<?php
/**
 * Admin functionality for Nemtly Booking
 *
 * @since   PBOOKING_SINCE
 * @package Nemtly_Booking
 */

namespace NemtlyBooking\Core;

use NemtlyBooking\Modules\Booking\Booking_Module;

/**
 * Admin class
 *
 * Handles WordPress admin functionality including menu creation,
 * page rendering, and script/style enqueuing.
 *
 * @since PBOOKING_SINCE
 */
class Admin {

    /**
     * Booking module instance
     *
     * @var Booking_Module
     */
    private $booking_module;

    /**
     * Initialize admin functionality
     *
     * @since PBOOKING_SINCE
     */
    public function __construct() {
        add_action( 'admin_menu', [ $this, 'add_admin_menu' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_scripts' ] );
        add_action( 'admin_init', [ $this, 'maybe_redirect_to_setup' ] );
        add_action( 'admin_init', [ $this, 'set_setup_page_title' ] );
    }

    /**
     * Set the global $title for the hidden setup wizard page.
     *
     * Hidden pages (registered with an empty parent slug) are not indexed in
     * $menu or $submenu, so WordPress's get_admin_page_title() returns without
     * setting $title. This leaves admin-header.php passing null to strip_tags(),
     * which is deprecated on PHP 8.1+.
     *
     * @since PBOOKING_SINCE
     *
     * @return void
     */
    public function set_setup_page_title() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';

        if ( 'nemtly-booking-setup' !== $page ) {
            return;
        }

        global $title;
        $title = __( 'Nemtly Booking Setup', 'nemtly-booking' ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
    }

    /**
     * Set booking module instance
     *
     * @since PBOOKING_SINCE
     *
     * @param Booking_Module $booking_module The booking module instance.
     */
    public function set_booking_module( Booking_Module $booking_module ) {
        $this->booking_module = $booking_module;
    }

    /**
     * Add admin menu pages
     *
     * @since PBOOKING_SINCE
     */
    public function add_admin_menu() {
        $menu_slug  = 'nemtly-booking';
        $capability = 'manage_options';

        // Main menu
        add_menu_page(
            __( 'Nemtly Booking', 'nemtly-booking' ),
            __( 'Nemtly Booking', 'nemtly-booking' ),
            $capability,
            $menu_slug,
            [ $this, 'render_main_page' ],
            'dashicons-calendar-alt',
            30
        );

        add_submenu_page(
            $menu_slug,
            __( 'Events', 'nemtly-booking' ),
            __( 'Events', 'nemtly-booking' ),
            $capability,
            $menu_slug
        );

        		// Bookings submenu
		add_submenu_page(
			'nemtly-booking',
			__( 'Bookings', 'nemtly-booking' ),
			__( 'Bookings', 'nemtly-booking' ),
			'manage_options',
			'nemtly-booking-bookings',
			[ $this, 'render_bookings_page' ]
		);

		// Payments submenu
		add_submenu_page(
			'nemtly-booking',
			__( 'Payments', 'nemtly-booking' ),
			__( 'Payments', 'nemtly-booking' ),
			'manage_options',
			'nemtly-booking-payments',
			[ $this, 'render_payments_page' ]
		);

		// Categories & Tags submenu
		add_submenu_page(
			'nemtly-booking',
			__( 'Categories & Tags', 'nemtly-booking' ),
			__( 'Categories & Tags', 'nemtly-booking' ),
			'manage_options',
			'nemtly-booking-taxonomies',
			[ $this, 'render_taxonomies_page' ]
		);

		// Settings submenu
		add_submenu_page(
			'nemtly-booking',
			__( 'Settings', 'nemtly-booking' ),
			__( 'Settings', 'nemtly-booking' ),
			'manage_options',
			'nemtly-booking-settings',
			[ $this, 'render_settings_page' ]
		);

		// Setup wizard — hidden page (no menu entry, but accessible via URL).
		// Empty parent slug keeps the page off the sidebar without passing null
		// (which is deprecated on PHP 8.1+ inside WP core).
		add_submenu_page(
			'',
			__( 'Nemtly Booking Setup', 'nemtly-booking' ),
			__( 'Setup', 'nemtly-booking' ),
			'manage_options',
			'nemtly-booking-setup',
			[ $this, 'render_setup_page' ]
		);
    }

    /**
     * Redirect to the setup wizard once after activation.
     *
     * Consumes the one-shot transient set during plugin activation. Skipped on
     * AJAX, bulk-activation, and for users without manage_options. The wizard
     * itself remains accessible at any time afterwards via its URL.
     *
     * @since PBOOKING_SINCE
     */
    public function maybe_redirect_to_setup() {
        if ( ! get_transient( 'nemtly_booking_activation_redirect' ) ) {
            return;
        }

        delete_transient( 'nemtly_booking_activation_redirect' );

        if ( wp_doing_ajax() || isset( $_GET['activate-multi'] ) ) {
            return;
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        wp_safe_redirect( admin_url( 'admin.php?page=nemtly-booking-setup' ) );
        exit;
    }

    /**
     * Enqueue admin scripts and styles
     *
     * @since PBOOKING_SINCE
     *
     * @param string $hook The current admin page hook.
     */
    public function enqueue_admin_scripts( $hook ) {
        // Only enqueue on our plugin pages
        if ( ! $this->is_nemtly_booking_page( $hook ) ) {
            return;
        }
        // Get the current screen
        $screen = get_current_screen();
        if ( ! $screen ) {
            return;
        }
        // Enqueue events app scripts on event-related pages
        if ( strpos( $hook, 'new-event' ) !== false ||
            ( strpos( $hook, 'nemtly-booking' ) !== false && ! strpos( $hook, 'bookings' ) && ! strpos( $hook, 'settings' ) && ! strpos( $hook, 'stats' ) && ! strpos( $hook, 'setup' ) ) ) {
            $this->enqueue_events_app_scripts();
        }

        // Enqueue setup wizard scripts on the setup page
        if ( strpos( $hook, 'nemtly-booking-setup' ) !== false ) {
            $this->enqueue_setup_wizard_scripts();
        }

        		// Enqueue booking admin scripts on booking-related pages
		if ( strpos( $hook, 'nemtly-booking-bookings' ) !== false || strpos( $hook, 'nemtly-booking-stats' ) !== false ) {
			if ( $this->booking_module ) {
				$this->booking_module->enqueue_admin_assets( $hook );
			}
		}

		// Enqueue payments app scripts on payments page
		if ( strpos( $hook, 'nemtly-booking-payments' ) !== false ) {
			$this->enqueue_payments_app_scripts();
		}

		// Enqueue taxonomies app scripts on categories & tags page
		if ( strpos( $hook, 'nemtly-booking-taxonomies' ) !== false ) {
			$this->enqueue_taxonomies_app_scripts();
		}

		// Enqueue settings app scripts on settings page
		if ( strpos( $hook, 'nemtly-booking-settings' ) !== false ) {
			$this->enqueue_settings_app_scripts();
		}
    }

    /**
     * Check if current page is a Pulse Booking admin page
     *
     * @since PBOOKING_SINCE
     *
     * @param string $hook The current admin page hook.
     *
     * @return bool True if it's a Pulse Booking page, false otherwise.
     */
    private function is_nemtly_booking_page( $hook ) {
        return strpos( $hook, 'nemtly' ) !== false;
    }

    /**
     * Enqueue events app React scripts and styles (handles both list and create/edit)
     *
     * @since PBOOKING_SINCE
     */
    private function enqueue_events_app_scripts() {
        wp_enqueue_media();

        $asset_file = include NEMTLY_BOOKING_PATH . 'assets/js/events-app.asset.php';
        wp_enqueue_script(
            'nemtly-events-app',
            NEMTLY_BOOKING_URL . 'assets/js/events-app.js',
            $asset_file['dependencies'],
            $asset_file['version'],
            true
        );
        wp_enqueue_style(
            'nemtly-events-app',
            NEMTLY_BOOKING_URL . 'assets/css/events-app.css',
            [ 'wp-components' ],
            $asset_file['version']
        );
        wp_enqueue_style(
            'nemtly-events-list',
            NEMTLY_BOOKING_URL . 'assets/css/event-list.css',
            [],
            $asset_file['version']
        );
        // Add RTL support - WordPress will automatically load the -rtl version if needed
        wp_style_add_data( 'nemtly-booking-events-app', 'rtl', 'replace' );
        $business_hours_default = [
            'mon' => [
				[
					'start' => '09:00',
					'end'   => '17:00',
				],
			],
            'tue' => [
				[
					'start' => '09:00',
					'end'   => '17:00',
				],
			],
            'wed' => [
				[
					'start' => '09:00',
					'end'   => '17:00',
				],
			],
            'thu' => [
				[
					'start' => '09:00',
					'end'   => '17:00',
				],
			],
            'fri' => [
				[
					'start' => '09:00',
					'end'   => '17:00',
				],
			],
            'sat' => [],
            'sun' => [],
        ];
        $plugin_settings        = get_option( 'nemtly_booking_settings', [] );

        // Localize script with REST API data
        wp_localize_script(
            'nemtly-events-app',
            'nemtlyCreateEvent',
            [
                'version'       => NEMTLY_BOOKING_VERSION,
                'restUrl'       => rest_url( 'nemtly-booking/v1' ),
                'nonce'         => wp_create_nonce( 'wp_rest' ),
                'pluginUrl'     => NEMTLY_BOOKING_URL,
                'siteTimezone'  => wp_timezone_string(),
                'timezones'     => \DateTimeZone::listIdentifiers( \DateTimeZone::ALL ),
                'templates'     => \NemtlyBooking\Core\Event_Templates::get_all(),
                'businessHours' => $plugin_settings['business_hours'] ?? $business_hours_default,
                'strings'       => [
                    'confirmDelete' => __( 'Are you sure you want to delete this event?', 'nemtly-booking' ),
                    'deleteError'   => __( 'Failed to delete event', 'nemtly-booking' ),
                    'loadError'     => __( 'Failed to load events', 'nemtly-booking' ),
                    'saveError'     => __( 'Failed to save event', 'nemtly-booking' ),
                    'createError'   => __( 'Failed to create event', 'nemtly-booking' ),
                    'validateError' => __( 'Please fill in all required fields', 'nemtly-booking' ),
                ],
            ]
        );
    }

    /**
     * Render the Event List page
     *
     * @since PBOOKING_SINCE
     */
    public function render_event_list_page() {
        ?>
        <div id="nemtly-booking-create-event-app" style="margin-left: -20px;"></div>
        <?php
    }

    	/**
         * Render the Bookings page - delegate to Booking_Module
         *
         * @since PBOOKING_SINCE
         */
	public function render_bookings_page() {
		if ( $this->booking_module ) {
			$this->booking_module->render_bookings_page();
		} else {
			?>
			<div class="wrap">
				<h1><?php esc_html_e( 'Bookings', 'nemtly-booking' ); ?></h1>
				<p><?php esc_html_e( 'Booking module not available.', 'nemtly-booking' ); ?></p>
			</div>
			<?php
		}
	}

	/**
	 * Render the Payments page
	 *
	 * @since PBOOKING_SINCE
	 */
	public function render_payments_page() {
		?>
        <div id="nemtly-payments-root" style="margin-left: -20px;"></div>
		<?php
	}
    /**
     * Render the Statistics page - delegate to Booking_Module
     *
     * @since PBOOKING_SINCE
     */
    public function render_statistics_page() {
        if ( $this->booking_module ) {
            $this->booking_module->render_statistics_page();
        } else {
            ?>
            <div class="wrap">
                <h1><?php esc_html_e( 'Booking Statistics', 'nemtly-booking' ); ?></h1>
                <p><?php esc_html_e( 'Booking module not available.', 'nemtly-booking' ); ?></p>
            </div>
            <?php
        }
    }

    	/**
         * Enqueue payments app React scripts and styles
         *
         * @since PBOOKING_SINCE
         */
	private function enqueue_payments_app_scripts() {
		$asset_file = include NEMTLY_BOOKING_DIR . 'assets/js/admin-payments.asset.php';

		wp_enqueue_script(
			'nemtly-payments-app',
			NEMTLY_BOOKING_URL . 'assets/js/admin-payments.js',
			$asset_file['dependencies'],
			$asset_file['version'],
			true
		);

		wp_enqueue_style(
			'nemtly-payments-app',
			NEMTLY_BOOKING_URL . 'assets/css/admin-payments-app.css',
			[ 'wp-components' ],
			$asset_file['version']
		);

		// Localize script with REST API data
		wp_localize_script(
			'nemtly-payments-app',
			'nemtlyPayments',
			[
				'version'   => NEMTLY_BOOKING_VERSION,
				'restUrl'   => rest_url( 'nemtly-booking/v1' ),
				'nonce'     => wp_create_nonce( 'wp_rest' ),
				'pluginUrl' => NEMTLY_BOOKING_URL,
				'strings'   => [
					'loadError' => __( 'Failed to load payments', 'nemtly-booking' ),
				],
			]
		);
	}

	/**
	 * Enqueue settings app React scripts and styles
	 *
	 * @since PBOOKING_SINCE
	 */
	private function enqueue_settings_app_scripts() {
        $asset_file = include NEMTLY_BOOKING_DIR . 'assets/js/settings-app.asset.php';

        wp_enqueue_script(
            'nemtly-settings-app',
            NEMTLY_BOOKING_URL . 'assets/js/settings-app.js',
            $asset_file['dependencies'],
            $asset_file['version'],
            true
        );

        wp_enqueue_style(
            'nemtly-settings-app',
            NEMTLY_BOOKING_URL . 'assets/css/settings-app.css',
            [ 'wp-components' ],
            $asset_file['version']
        );

        wp_enqueue_style(
            'nemtly-settings-app-css',
            NEMTLY_BOOKING_URL . 'assets/css/settings-app-css.css',
            [ 'wp-components' ],
            $asset_file['version']
        );

        // Localize script with REST API data
        wp_localize_script(
            'nemtly-settings-app',
            'nemtlySettings',
            [
                'version'   => NEMTLY_BOOKING_VERSION,
                'restUrl'   => rest_url( 'nemtly-booking/v1' ),
                'nonce'     => wp_create_nonce( 'wp_rest' ),
                'pluginUrl' => NEMTLY_BOOKING_URL,
                'strings'   => [
                    'saveError'   => __( 'Failed to save settings', 'nemtly-booking' ),
                    'loadError'   => __( 'Failed to load settings', 'nemtly-booking' ),
                    'deleteError' => __( 'Failed to delete template', 'nemtly-booking' ),
                    'createError' => __( 'Failed to create template', 'nemtly-booking' ),
                ],
            ]
        );
    }

    /**
     * Render the Categories & Tags page
     *
     * @since PBOOKING_SINCE
     *
     * @return void
     */
    public function render_taxonomies_page() {
        ?>
        <div id="nemtly-booking-taxonomies-app" style="margin-left: -20px;"></div>
        <?php
    }

    /**
     * Enqueue taxonomies app React scripts and styles
     *
     * @since PBOOKING_SINCE
     *
     * @return void
     */
    private function enqueue_taxonomies_app_scripts() {
        $asset_file = include NEMTLY_BOOKING_DIR . 'assets/js/taxonomies-app.asset.php';

        wp_enqueue_script(
            'nemtly-taxonomies-app',
            NEMTLY_BOOKING_URL . 'assets/js/taxonomies-app.js',
            $asset_file['dependencies'],
            $asset_file['version'],
            true
        );

        wp_enqueue_style(
            'nemtly-taxonomies-app',
            NEMTLY_BOOKING_URL . 'assets/css/taxonomies-app.css',
            [ 'wp-components' ],
            $asset_file['version']
        );

        wp_localize_script(
            'nemtly-taxonomies-app',
            'nemtlyTaxonomies',
            [
                'version'   => NEMTLY_BOOKING_VERSION,
                'restUrl'   => rest_url( 'wp/v2' ),
                'nonce'     => wp_create_nonce( 'wp_rest' ),
                'pluginUrl' => NEMTLY_BOOKING_URL,
                'strings'   => [
                    'loadError'     => __( 'Failed to load terms', 'nemtly-booking' ),
                    'saveError'     => __( 'Failed to save term', 'nemtly-booking' ),
                    'deleteError'   => __( 'Failed to delete term', 'nemtly-booking' ),
                    'confirmDelete' => __( 'Are you sure you want to delete this term?', 'nemtly-booking' ),
                ],
            ]
        );
    }

    /**
     * Render the Settings page
     *
     * @since PBOOKING_SINCE
     */
    public function render_settings_page() {
        ?>
        <div id="nemtly-booking-settings-app" style="margin-left: -20px;"></div>
        <?php
    }

    /**
     * Enqueue setup wizard React scripts and styles
     *
     * @since PBOOKING_SINCE
     */
    private function enqueue_setup_wizard_scripts() {
        $asset_file = include NEMTLY_BOOKING_DIR . 'assets/js/setup-wizard-app.asset.php';

        wp_enqueue_script(
            'nemtly-setup-wizard-app',
            NEMTLY_BOOKING_URL . 'assets/js/setup-wizard-app.js',
            $asset_file['dependencies'],
            $asset_file['version'],
            true
        );

        wp_enqueue_style(
            'nemtly-setup-wizard-css',
            NEMTLY_BOOKING_URL . 'assets/css/setup-wizard-app.css', // This will be generated by MiniCssExtractPlugin
            [ 'wp-components' ],
            $asset_file['version']
        );

        // Localize script
        wp_localize_script(
            'nemtly-setup-wizard-app',
            'nemtlyBookingSetup',
            [
                'restUrl'   => rest_url( 'nemtly-booking/v1' ),
                'nonce'     => wp_create_nonce( 'wp_rest' ),
                'pluginUrl' => NEMTLY_BOOKING_URL,
                'adminUrl'  => admin_url(),
                'siteUrl'   => home_url(),
            ]
        );

        wp_set_script_translations(
            'nemtly-setup-wizard-app',
            'nemtly-booking',
            NEMTLY_BOOKING_DIR . 'languages'
        );
    }

    /**
     * Render the Setup Wizard page
     *
     * @since PBOOKING_SINCE
     */
    public function render_setup_page() {
        ?>
        <style>
            /* Hide WP admin chrome — wizard owns the full viewport. */
            #wpcontent,
            #wpfooter { margin-left: 0 !important; padding-left: 0 !important; }
            #adminmenuwrap,
            #adminmenuback,
            #wpadminbar { display: none !important; }
            html.wp-toolbar { padding-top: 0 !important; }
            #wpwrap, #wpbody, #wpbody-content { min-height: 100vh; padding: 0 !important; }

        </style>
        <div id="nemtly-booking-setup-wizard"></div>
        <?php
    }

    /**
     * Render the main admin page
     *
     * @since PBOOKING_SINCE
     */
    public function render_main_page() {
        // Show the events list page directly
        $this->render_events_page();
    }

    /**
     * Render the Events page
     *
     * @since PBOOKING_SINCE
     */
    public function render_events_page() {
        ?>
        <div id="nemtly-booking-create-event-app" style="margin-left: -20px;"></div>
        <?php
    }
}
