<?php
/**
 * GFB Admin Class
 *
 * @package GFB.
 */

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

if ( ! class_exists( 'APBGF_Admin' ) ) {
	class APBGF_Admin {
		private static $instance = null;

		private function __construct() {
			add_action( 'admin_menu', array( $this, 'register_main_menu' ) );
			add_action( 'admin_enqueue_scripts', array( $this, 'register_admin_assets' ) );
			add_action( 'admin_init', array( $this, 'check_wizard_redirect' ) );
		}

		public function register_admin_assets( $hook ) {
			global $current_screen;

			$_posttypes = array(
				'apbgf-service',
				'apbgf-staff',
				'apbgf-customer',
				'apbgf-calendar',
				'apbgf-appointment',
				'apbgf-location'
			);

			$_pages = array(
				'gravity-booking_page_apbgf-report',
				'toplevel_page_gfb',
				'gravity-booking_page_apbgf-email',
				'gravity-booking_page_apbgf-account',
				'gravity-booking_page_apbgf-affiliation',
				'gravity-booking_page_apbgf-setting',
				'edit-apbgf-service-category',
				'gravity-booking_page_apbgf-calendar',
				'edit-apbgf-location'
			);

			$minimized = defined('APBGF_LIVE_MODE') && APBGF_LIVE_MODE ? '.min' : '';
			$clear_cache = !APBGF_LIVE_MODE ? '?t=' . gmdate('ymdhis') : '';

			// Always register and enqueue admin menu style to hide submenus when wizard not completed
			wp_register_style('apbgf-admin-menu', false);
			wp_enqueue_style('apbgf-admin-menu');
			
			$wizard_completed = get_option( 'apbgf_wizard_completed', false );
			$inline_css = '
				ul#adminmenu li > a[href="post-new.php?post_type=apbgf-appointment"], 
				ul#adminmenu li > a[href="post-new.php?post_type=apbgf-staff"] {
					display: none!important;
				}
			';
			
			// Always hide setup wizard from menu (it should not be visible)
			$inline_css .= '
				#toplevel_page_appointment-and-booking-for-gravity-forms .wp-submenu li a[href*="page=apbgf-setup-wizard"],
				#toplevel_page_appointment-and-booking-for-gravity-forms .wp-submenu li:has(a[href*="page=apbgf-setup-wizard"]) {
					display: none !important;
				}
			';
			
			// Hide all submenus if wizard not completed
			if ( ! $wizard_completed ) {
				$inline_css .= '
					#toplevel_page_appointment-and-booking-for-gravity-forms .wp-submenu,
					#toplevel_page_appointment-and-booking-for-gravity-forms .wp-submenu li {
						display: none !important;
					}
				';
			}
			
			wp_add_inline_style('apbgf-admin-menu', $inline_css);

			// Sanitize and retrieve $_GET values
			$page    = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
			$form_id = isset( $_GET['id'] ) ? sanitize_text_field( wp_unslash( $_GET['id'] ) ) : '';
			$subview = isset( $_GET['subview'] ) ? sanitize_text_field( wp_unslash( $_GET['subview'] ) ) : '';

			// Verify nonce if provided
			$valid_nonce = false;
			if ( isset( $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'apbgf_admin_assets_nonce' ) ) {
				$valid_nonce = true;
			}
			
			$cond1 =  isset( $current_screen->id ) && 'toplevel_page_gf_edit_forms' === $current_screen->id && $page === 'gf_edit_forms' && ! empty( $form_id );
			$cond2 = isset( $current_screen->id ) && in_array( $current_screen->id, $_pages, true );
			$cond3 = $valid_nonce && isset( $current_screen->id ) && 'toplevel_page_gf_edit_forms' === $current_screen->id && $subview === 'apbgf_settings_page';
			$cond4 = isset( $current_screen->post_type ) && in_array( $current_screen->post_type, $_posttypes, true );
			
			if ( $cond1 || $cond2 || $cond3 || $cond4 ) {
				
				wp_enqueue_style( 'apbgf-poppins-bold-font', esc_url( APBGF_FONT_URL ) . 'Poppins-Bold.ttf', array(), APBGF_VERSION . $clear_cache, 'all' );
				wp_enqueue_style( 'apbgf-poppins-light-font', esc_url( APBGF_FONT_URL ) . 'Poppins-Light.ttf', array(), APBGF_VERSION . $clear_cache, 'all' );
				wp_enqueue_style( 'apbgf-poppins-medium-font', esc_url( APBGF_FONT_URL ) . 'Poppins-Medium.ttf', array(), APBGF_VERSION . $clear_cache, 'all' );
				wp_enqueue_style( 'apbgf-poppins-regular-font', esc_url( APBGF_FONT_URL ) . 'Poppins-Regular.ttf', array(), APBGF_VERSION . $clear_cache, 'all' );
				wp_enqueue_style( 'apbgf-poppins-semiBold-font', esc_url( APBGF_FONT_URL ) . 'Poppins-SemiBold.ttf', array(), APBGF_VERSION . $clear_cache, 'all' );

				wp_enqueue_style( 'apbgf-font-awesome-style-min', esc_url( APBGF_ADMIN_CSS_URL ) . '/font-awesome/font-awesome.min.css', array(), APBGF_VERSION . $clear_cache, 'all' );
				wp_enqueue_style( 'apbgf-font-awesome-style', esc_url( APBGF_ADMIN_CSS_URL ) . '/font-awesome/font-awesome-fonts.css', array( 'apbgf-font-awesome-style-min' ), APBGF_VERSION . $clear_cache, 'all' );
				wp_enqueue_style( 'apbgf-posttype-style', esc_url( APBGF_ADMIN_CSS_URL ) . 'apbgf-posttype-style' . $minimized . '.css', array(), APBGF_VERSION . $clear_cache, 'all' );
				wp_enqueue_style( 'apbgf-admin-style', esc_url( APBGF_ADMIN_CSS_URL ) . 'apbgf-admin-style' . $minimized . '.css', array(), APBGF_VERSION . $clear_cache, 'all' );
				wp_enqueue_style( 'apbgf-daterangepicker', esc_url( APBGF_COMMON_URL ) . 'daterangepicker.css', array(), APBGF_VERSION . $clear_cache, 'all' );
				wp_enqueue_style( 'apbgf-sweetalert-style', esc_url( APBGF_COMMON_URL ) . 'sweetalert2.min.css', array(), APBGF_VERSION . $clear_cache, 'all' );
				wp_enqueue_style( 'apbgf-select2-style', esc_url( APBGF_COMMON_URL ) . 'select2.min.css', array(), APBGF_VERSION . $clear_cache, 'all' );

				wp_enqueue_script( 'apbgf-select2-script', esc_url( APBGF_COMMON_URL ) . 'select2.min.js', array( 'jquery' ), APBGF_VERSION . $clear_cache, true );
				wp_enqueue_script( 'apbgf-jquery-validation', esc_url( APBGF_ADMIN_JS_URL ) . 'apbgf-jquery-validate.min.js', array( 'jquery' ), APBGF_VERSION, true );

				if ( isset( $current_screen->id ) && ( 'gravity-booking_page_apbgf-report' === $current_screen->id || 'toplevel_page_gfb' === $current_screen->id ) ) {
					wp_enqueue_script( 'apbgf-chart', esc_url( APBGF_ADMIN_JS_URL ) . 'Chart.bundle.min.js', array( 'jquery' ), APBGF_VERSION . $clear_cache, true );
					wp_register_script( 'apbgf-report-script', esc_url( APBGF_ADMIN_JS_URL ) . 'apbgf-report-script' . $minimized . '.js', array( 'jquery', 'apbgf-chart' ), APBGF_VERSION . $clear_cache, true );

					wp_localize_script( 'apbgf-report-script', 'apbgf_report', array(
						'ajaxurl' => admin_url( 'admin-ajax.php' ),
						'nonce'   => wp_create_nonce( 'appointment-and-booking-for-gravity-forms' ),
					) );

					wp_enqueue_script( 'apbgf-report-script' );
				}

				wp_enqueue_script( 'apbgf-daterangepicker', esc_url( APBGF_COMMON_URL ) . 'daterangepicker.js', array( 'moment' ), APBGF_VERSION . $clear_cache, true );
				wp_enqueue_script( 'apbgf-sweetalert-script', esc_url( APBGF_COMMON_URL ) . 'sweetalert2.min.js', array( 'jquery' ), APBGF_VERSION . $clear_cache, true );
				wp_enqueue_script( 'apbgf-input-autofilter', esc_url( APBGF_ADMIN_JS_URL ) . 'apbgf-input-autofilter' . $minimized . '.js', array( 'jquery' ), APBGF_VERSION . $clear_cache, true );

				wp_register_script( 'apbgf-admin-script', esc_url( APBGF_ADMIN_JS_URL ) . 'apbgf-admin-script' . $minimized . '.js', array( 'jquery', 'jquery-ui-accordion', 'apbgf-sweetalert-script', 'apbgf-select2-script', 'apbgf-daterangepicker', 'apbgf-jquery-validation' ), APBGF_VERSION . $clear_cache, true );

				$general_settings = class_exists( 'APBGF_Setting' ) ? APBGF_Setting::get_settings() : array(
					'gbf_time_duration' => '',
					'gbf_time_interval' => ''
				);
				$staff_exists = class_exists( 'APBGF_Staff' ) ? APBGF_Staff::get_staff_exist() : false;

				wp_localize_script( 'apbgf-admin-script', 'apbgf_admin', array(
					'ajaxurl'         => admin_url( 'admin-ajax.php' ),
					'nonce'           => wp_create_nonce( 'appointment-and-booking-for-gravity-forms' ),
					'addBreakTxt'     => __( 'Add Break', 'appointment-and-booking-for-gravity-forms' ),
					'removeSlotTxt'   => __( 'Remove', 'appointment-and-booking-for-gravity-forms' ),
					'durationHelpTxt' => __( 'Time Duration. Default duration will be from general setting', 'appointment-and-booking-for-gravity-forms' ),
					'intervalHelpTxt' => __( 'Time Interval. Default interval will be from general setting', 'appointment-and-booking-for-gravity-forms' ),
					'time_duration'   => $general_settings['gbf_time_duration'] ?? '',
					'time_interval'   => $general_settings['gbf_time_interval'] ?? '',
					'startTimeLbl'    => __( 'Start Time', 'appointment-and-booking-for-gravity-forms' ),
					'endTimeLbl'      => __( 'End Time', 'appointment-and-booking-for-gravity-forms' ),
					'dateLbl'         => __( 'Date', 'appointment-and-booking-for-gravity-forms' ),
					'capacityLbl'     => __( 'Capacity', 'appointment-and-booking-for-gravity-forms' ),
					'staff_exists'    => $staff_exists,
				) );

				wp_enqueue_script( 'apbgf-admin-script' );

				wp_register_script( 'apbgf-common-script', esc_url( APBGF_COMMON_URL ) . 'apbgf-common-script' . $minimized . '.js', array( 'jquery' ), APBGF_VERSION . $clear_cache, true );
				wp_localize_script( 'apbgf-common-script', 'apbgf_common', array(
					'ajaxurl'               => admin_url( 'admin-ajax.php' ),
					'nonce'                 => wp_create_nonce( 'appointment-and-booking-for-gravity-forms' ),
					'form_id'               => $form_id,
					'is_admin'              => is_admin(),
					'loadingText'           => __( 'loading...', 'appointment-and-booking-for-gravity-forms' ),
					'all_service_text'      => __( 'All Service', 'appointment-and-booking-for-gravity-forms' ),
					'no_service_text'       => __( 'No Service Found', 'appointment-and-booking-for-gravity-forms' ),
					'all_location_text'     => __( 'All Location', 'appointment-and-booking-for-gravity-forms' ),
					'no_location_text'      => __( 'No Location Found', 'appointment-and-booking-for-gravity-forms' ),
					'all_staff_text'        => __( 'All Staff', 'appointment-and-booking-for-gravity-forms' ),
					'no_staff_text'         => __( 'No Staff Found', 'appointment-and-booking-for-gravity-forms' ),
					'all_service_category_text' => __( 'All Service Category', 'appointment-and-booking-for-gravity-forms' ),
					'no_service_category_text'  => __( 'No Service Category Found', 'appointment-and-booking-for-gravity-forms' ),
					'saved'                 => __( 'Setting Saved', 'appointment-and-booking-for-gravity-forms' ),
				) );

				wp_enqueue_script( 'apbgf-common-script' );
			}
		}

		public function register_main_menu() {
			if ( defined( 'GFB_VERSION' ) ) {
				return;
			}

			$wizard_completed = get_option( 'apbgf_wizard_completed', false );
			
			add_menu_page(
				__( 'Dashboard - Gravity Booking', 'appointment-and-booking-for-gravity-forms' ),
				__( 'Gravity Booking', 'appointment-and-booking-for-gravity-forms' ),
				'manage_options',
				'appointment-and-booking-for-gravity-forms',
				array( get_class( $this ), 'apbgf_dashboard_page' ),
				'dashicons-calendar-alt',
				10
			);

			// Only register submenus if wizard is completed
			if ( $wizard_completed ) {
				do_action( 'apbgf_after_menu_register' );
			}
		}

		public function check_wizard_redirect() {
			$wizard_completed = get_option( 'apbgf_wizard_completed', false );
			
			// If wizard is not completed, redirect away from Gravity Booking pages
			if ( ! $wizard_completed ) {
				$page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
				$post_type = isset( $_GET['post_type'] ) ? sanitize_text_field( wp_unslash( $_GET['post_type'] ) ) : '';
				
				// Allow access to wizard page
				if ( 'apbgf-setup-wizard' === $page ) {
					return;
				}
				
				// Redirect Gravity Booking related pages to wizard
				$apbgf_pages = array(
					'appointment-and-booking-for-gravity-forms',
					'apbgf-report',
					'apbgf-calendar',
					'apbgf-email',
					'apbgf-setting',
				);
				
				$apbgf_post_types = array(
					'apbgf-service',
					'apbgf-staff',
					'apbgf-customer',
					'apbgf-appointment',
					'apbgf-calendar',
					'apbgf-location',
				);
				
				if ( in_array( $page, $apbgf_pages, true ) || in_array( $post_type, $apbgf_post_types, true ) ) {
					wp_safe_redirect( admin_url( 'admin.php?page=apbgf-setup-wizard' ) );
					exit;
				}
			}
		}

	public static function apbgf_dashboard_page() {
		$wizard_completed = get_option( 'apbgf_wizard_completed', false );
		
		// Redirect to wizard if not completed
		if ( ! $wizard_completed ) {
			wp_safe_redirect( admin_url( 'admin.php?page=apbgf-setup-wizard' ) );
			exit;
		}
		
		// Redirect to report page if wizard is completed
		wp_safe_redirect( admin_url( 'admin.php?page=apbgf-report' ) );
		exit;
	}

		public static function get_instance() {
			if ( null === self::$instance ) {
				self::$instance = new APBGF_Admin();
			}
			return self::$instance;
		}
	}

	APBGF_Admin::get_instance();
}
