<?php
/**
 * GFB Location Handler Class
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'APBGF_Location' ) ) {

	class APBGF_Location {

		private static $instance = null;

		private function __construct() {
			add_action( 'init', array( $this, 'register_location_posttype' ), 20 );
			
			add_filter( 'manage_apbgf-location_posts_columns', array( $this, 'apbgf_modify_column_names' ) );
			add_action( 'manage_apbgf-location_posts_custom_column', array( $this, 'apbgf_add_custom_column' ), 9, 2 );
			add_action( 'admin_footer', array( $this, 'highlight_menu' ) );
			add_action( 'manage_posts_extra_tablenav', array( $this, 'apbgf_manage_posts_extra_tablenav' ) );

			add_action( 'wp_ajax_apbgf_add_location', array( $this, 'apbgf_add_location' ) );
			add_action( 'wp_ajax_apbgf_edit_location', array( $this, 'apbgf_edit_location' ) );
			add_action( 'wp_ajax_apbgf_delete_location', array( $this, 'apbgf_delete_location' ) );
			add_action( 'wp_ajax_apbgf_show_location_data', array( $this, 'apbgf_show_location_data' ) );
		}

		/**
		 * Register Location Post Type
		 */
		public function register_location_posttype() {

			
			$labels = array(
				'name'               => esc_html__( 'Locations', 'appointment-and-booking-for-gravity-forms' ),
				'singular_name'      => esc_html__( 'Location', 'appointment-and-booking-for-gravity-forms' ),
				'menu_name'          => esc_html__( 'Locations', 'appointment-and-booking-for-gravity-forms' ),
				'add_new'            => esc_html__( 'Add New', 'appointment-and-booking-for-gravity-forms' ),
				'add_new_item'       => esc_html__( 'Add New Location', 'appointment-and-booking-for-gravity-forms' ),
				'edit_item'          => esc_html__( 'Edit Location', 'appointment-and-booking-for-gravity-forms' ),
				'new_item'           => esc_html__( 'New Location', 'appointment-and-booking-for-gravity-forms' ),
				'view_item'          => esc_html__( 'View Location', 'appointment-and-booking-for-gravity-forms' ),
				'search_items'       => esc_html__( 'Search Locations', 'appointment-and-booking-for-gravity-forms' ),
				'not_found'          => esc_html__( 'No locations found', 'appointment-and-booking-for-gravity-forms' ),
				'not_found_in_trash' => esc_html__( 'No locations found in trash', 'appointment-and-booking-for-gravity-forms' ),
			);

			$args = array(
				'labels'             => $labels,
				'public'             => false,
				'publicly_queryable' => false,
				'show_ui'            => true,
				'show_in_menu'       => 'appointment-and-booking-for-gravity-forms',
				'show_in_rest'       => true,
				'query_var'          => true,
				'rewrite'            => array( 'slug' => 'apbgf-location' ),
				'capability_type'    => 'post',
				'has_archive'        => true,
				'hierarchical'       => false,
				'supports'           => array( 'title' ),
			);

			register_post_type( 'apbgf-location', $args );
		}

		public function apbgf_modify_column_names( $columns ) {
			unset($columns['date']);
			unset($columns['title']);

			$columns['id']      = __('&nbsp;&nbsp;Location ID', 'appointment-and-booking-for-gravity-forms');
			$columns['name']    = __('Name', 'appointment-and-booking-for-gravity-forms');
			$columns['phone']   = __('Phone', 'appointment-and-booking-for-gravity-forms');
			$columns['address'] = __('Address', 'appointment-and-booking-for-gravity-forms');
			$columns['actions'] = __('Actions', 'appointment-and-booking-for-gravity-forms');

			return $columns;
		}

		public function apbgf_add_custom_column( $column, $post_id ) {
			switch ($column) {
				case 'id':
					echo '&nbsp;&nbsp;' . esc_attr($post_id);
					break;
				case 'name':
					echo esc_attr(get_the_title($post_id));
					break;
				case 'phone':
					echo esc_attr(get_post_meta($post_id, 'phone', true));
					break;
				case 'address':
					echo esc_attr(get_post_meta($post_id, 'address', true));
					break;
				case 'actions':
					echo '<a href="#" data-type="location" data-id="apbgf-location-modal" data-post_id="' . esc_attr( $post_id ) . '" class="wc-dashicons apbgf-edit"> <i class="fa fa-edit customer--icon"></i> </a>';
					if ( 'publish' == get_post_status($post_id) ) {
						echo '<a href="#" data-type="location" data-post_id="' . esc_attr( $post_id ) . '" class="wc-dashicons apbgf-delete" title="Delete"> <i class="fa fa-trash customer--icon"></i></a>';
					}
					break;
			}
		}

		public function apbgf_manage_posts_extra_tablenav( $which ) {
			if ( 'top' === $which ) {
				$screen = get_current_screen();
				if ( isset($screen->post_type) && 'apbgf-location' === $screen->post_type ) {
					printf(
						'<a href="#" data-id="apbgf-location-pro-modal" class="apbgf-add-button apbgf-location-add-disabled" aria-disabled="true" title="%2$s"><i class="fa fa-plus-circle"></i>%1$s</a>',
						esc_html__( 'Add Location', 'appointment-and-booking-for-gravity-forms' ),
						esc_attr__( 'Upgrade to Pro to add more locations', 'appointment-and-booking-for-gravity-forms' )
					);
				}
			}
		}

		public function highlight_menu() {
			$screen = get_current_screen();
			if ( isset($screen->post_type) && 'apbgf-location' === $screen->post_type ) {
				require_once APBGF_ADMIN_VIEW_PATH . 'modal/location-modal.php';

				$popup_img = defined( 'APBGF_IMAGE_URL' ) ? APBGF_IMAGE_URL . 'ProPopup.svg' : '';
				$popup_url = 'https://gravitybooking.com/pricing/?utm_source=plugin&utm_medium=location';
				if ( $popup_img ) {
					?>
					<div id="apbgf-location-pro-modal" class="modal" role="dialog" aria-modal="true" aria-label="<?php esc_attr_e( 'Upgrade to Pro', 'appointment-and-booking-for-gravity-forms' ); ?>" style="position:fixed;inset:0;align-items:center;justify-content:center;">
						<div class="apbgf-location-pro-modal__inner" style="position:relative;max-width:640px;width:100%;margin:auto;">
							<div class="apbgf-location-pro-modal__content" style="position:relative;border-radius:8px;overflow:hidden;">
								<img src="<?php echo esc_url( $popup_img ); ?>" alt="<?php esc_attr_e( 'Upgrade to Pro', 'appointment-and-booking-for-gravity-forms' ); ?>" style="display:block;width:100%;height:auto;" />
								<a href="<?php echo esc_url( $popup_url ); ?>" target="_blank" rel="noopener noreferrer"
								   aria-label="<?php esc_attr_e( 'Buy Gravity Bookings', 'appointment-and-booking-for-gravity-forms' ); ?>"
								   style="position:absolute;left:31%;top:69%;width:38%;height:15%;background:transparent;border:none;outline:none;box-shadow:none;cursor:pointer;text-indent:-9999px;overflow:hidden;">
									<?php esc_html_e( 'Buy Gravity Bookings', 'appointment-and-booking-for-gravity-forms' ); ?>
								</a>
								<button type="button" class="modal__close apbgf-location-pro-modal-close" aria-label="<?php esc_attr_e( 'Close', 'appointment-and-booking-for-gravity-forms' ); ?>" style="position:absolute;top:0;right:0;width:15%;height:12%;background:transparent;border:none;outline:none;box-shadow:none;cursor:pointer;z-index:2;"></button>
							</div>
						</div>
					</div>
					<script type="text/javascript">
						(function() {
							function apbgfLocationPopupReady(fn) {
								if (document.readyState === 'loading') {
									document.addEventListener('DOMContentLoaded', fn);
								} else {
									fn();
								}
							}
							apbgfLocationPopupReady(function() {
								var modal = document.getElementById('apbgf-location-pro-modal');
								if (!modal) { return; }
								function closeLocationProModalOnly() {
									modal.classList.remove('apbgf-modal-show');
									var locationModal = document.getElementById('apbgf-location-modal');
									if (locationModal && locationModal.classList.contains('apbgf-modal-show')) {
										document.body.classList.add('apbgf-modal-open');
									} else {
										document.body.classList.remove('apbgf-modal-open');
									}
								}
								modal.addEventListener('click', function(e) {
									if (e.target === modal) {
										closeLocationProModalOnly();
									}
								});
								var closeBtn = modal.querySelector('.apbgf-location-pro-modal-close');
								if (closeBtn) {
									closeBtn.addEventListener('click', function(e) {
										e.stopPropagation();
										closeLocationProModalOnly();
									});
								}
							});
						})();
					</script>
					<?php
				}

				// Register and enqueue the menu highlight script
				wp_register_script('apbgf-location-menu-highlight', false, array( 'jquery' ));
				wp_enqueue_script('apbgf-location-menu-highlight');
				
				wp_add_inline_script('apbgf-location-menu-highlight', '
					jQuery(document).ready(function($) {
						$("#toplevel_page_gfb li, #toplevel_page_gfb li > a").removeClass("current");
						$("#toplevel_page_gfb a[href=\"edit.php?post_type=apbgf-location\"]").addClass("current");
						$("#toplevel_page_gfb a[href=\"edit.php?post_type=apbgf-location\"]").parent("li").addClass("current");
					});
				');
			}
		}

		public function apbgf_add_location() {
			check_ajax_referer( 'appointment-and-booking-for-gravity-forms', 'nonce' );

			$response = array(
				'message' => esc_html__( 'Please fill all required fields.', 'appointment-and-booking-for-gravity-forms' ),
				'status'  => 'error'
			);

			$name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
			$phone = isset( $_POST['phone'] ) ? sanitize_text_field( wp_unslash( $_POST['phone'] ) ) : '';
			$address = isset( $_POST['address'] ) ? sanitize_textarea_field( wp_unslash( $_POST['address'] ) ) : '';
			$description = isset( $_POST['description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['description'] ) ) : '';

			if ( ! empty( $name ) ) {
				$args = array(
					'post_title'   => $name,
					'post_content' => $description,
					'post_type'    => 'apbgf-location',
					'post_status'  => 'publish',
					'meta_input'   => array(
						'phone'   => $phone,
						'address' => $address,
					),
				);

				$location_id = wp_insert_post( $args );

				if ( ! is_wp_error( $location_id ) ) {
					update_post_meta( $location_id, 'phone', $phone );
					update_post_meta( $location_id, 'address', $address );
					$response['message'] = esc_html__( 'Location created successfully.', 'appointment-and-booking-for-gravity-forms' );
					$response['status']  = 'success';
					$response['post_id'] = $location_id;
				} else {
					$response['message'] = $location_id->get_error_message();
				}
			}

			echo wp_json_encode( $response );
			wp_die();
		}

		public function apbgf_edit_location() {
			check_ajax_referer( 'appointment-and-booking-for-gravity-forms', 'nonce' );

			$response = array(
				'message' => esc_html__( 'Please fill all required fields.', 'appointment-and-booking-for-gravity-forms' ),
				'status'  => 'error'
			);

			$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
			$name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
			$phone = isset( $_POST['phone'] ) ? sanitize_text_field( wp_unslash( $_POST['phone'] ) ) : '';
			$address = isset( $_POST['address'] ) ? sanitize_textarea_field( wp_unslash( $_POST['address'] ) ) : '';
			$description = isset( $_POST['description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['description'] ) ) : '';

			if ( ! empty( $post_id ) && ! empty( $name ) ) {
				$post = get_post( $post_id );
				if ( ! $post || 'apbgf-location' !== $post->post_type ) {
					echo wp_json_encode( $response );
					wp_die();
				}

				$update = wp_update_post(
					array(
						'ID'           => $post_id,
						'post_title'   => $name,
						'post_content' => $description,
						'post_status'  => 'publish',
					),
					true
				);

				if ( ! is_wp_error( $update ) ) {
					update_post_meta( $post_id, 'phone', $phone );
					update_post_meta( $post_id, 'address', $address );
					$response['message']  = esc_html__( 'Location updated successfully.', 'appointment-and-booking-for-gravity-forms' );
					$response['status']   = 'success';
					$response['post_id']  = $post_id;
					$response['name']     = $name;
					$response['phone']    = $phone;
					$response['address']  = $address;
					$response['description'] = $description;
				} else {
					$response['message'] = $update->get_error_message();
				}
			}

			echo wp_json_encode( $response );
			wp_die();
		}

		public function apbgf_delete_location() {
			check_ajax_referer( 'appointment-and-booking-for-gravity-forms', 'nonce' );

			$response = array(
				'message' => esc_html__( 'Location not deleted.', 'appointment-and-booking-for-gravity-forms' ),
				'status'  => 'error'
			);

			$post_id = isset( $_REQUEST['post_id'] ) ? absint( $_REQUEST['post_id'] ) : 0;

			if ( $post_id ) {
				$post = get_post( $post_id );
				if ( $post && 'apbgf-location' === $post->post_type ) {
					wp_delete_post( $post_id, true );
					$response['message'] = esc_html__( 'Location deleted successfully.', 'appointment-and-booking-for-gravity-forms' );
					$response['status'] = 'success';
				}
			}

			echo wp_json_encode( $response );
			wp_die();
		}

		public function apbgf_show_location_data() {
			check_ajax_referer( 'appointment-and-booking-for-gravity-forms', 'nonce' );

			$response = array(
				'status' => 'error'
			);

			$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;

			if ( $post_id ) {
				$post = get_post( $post_id );
				if ( $post && 'apbgf-location' === $post->post_type ) {
					$response['status'] = 'success';
					$response['name'] = $post->post_title;
					$response['description'] = $post->post_content;
					$response['phone'] = get_post_meta( $post_id, 'phone', true );
					$response['address'] = get_post_meta( $post_id, 'address', true );
				}
			}

			echo wp_json_encode( $response );
			wp_die();
		}

		/**
		 * Retrieve only the default location post
		 */
		public static function all_location() {
			$posts = get_posts(array(
				'post_type'   => 'apbgf-location',
				'meta_key'    => '_apbgf_default_location',
				'meta_value'  => '1',
				'numberposts' => 1
			));

			return !empty($posts) ? $posts[0] : false;
		}

		/**
		 * Get the singleton instance
		 */
		public static function get_instance() {
			if (self::$instance === null) {
				self::$instance = new APBGF_Location();
			}
			return self::$instance;
		}
	}

	// Instantiate the class
	APBGF_Location::get_instance();
}
