<?php
// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

use Automattic\WooCommerce\Admin\Features\Navigation\Menu;
use Automattic\WooCommerce\Admin\Features\Navigation\Screen;

/**
 * WC_Appointments_Admin_Menus.
 */
class WC_Appointments_Admin_Menus {

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'current_screen', [ $this, 'buffer' ] );
		add_filter( 'woocommerce_screen_ids', [ $this, 'woocommerce_screen_ids' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'admin_scripts' ] );
		add_action( 'admin_menu', [ $this, 'remove_default_appointments_menu_links' ], 10, 0 );
		add_action( 'admin_menu', [ $this, 'admin_menu' ], 49, 0 );
		add_filter( 'menu_order', [ $this, 'menu_order' ], 20 );
		add_action( 'load-wc_appointment_page_appointment_calendar', [ $this, 'calendar_screen_options' ] );
		add_filter( 'screen_settings', [ $this, 'calendar_screen_settings' ], 10, 2 );
		add_filter( 'screen_options_show_screen', [ $this, 'show_calendar_screen_options' ] );
		add_action( 'load-post-new.php', [ $this, 'maybe_redirect_add_new_screen' ] );
	}

	/**
	 * output buffer.
	 */
	public function buffer(): void {
		// Get current screen.
		$screen    = function_exists( 'get_current_screen' ) ? get_current_screen() : '';
		$screen_id = $screen ? $screen->id : '';

		if ( 'wc_appointment_page_add_appointment' === $screen_id ) {
			ob_start();
		}
	}

	/**
     * Screen IDS.
     *
     * @param  array  $ids
     */
    public function woocommerce_screen_ids( $ids ): array {
		return array_merge(
		    $ids,
		    [
				'edit-wc_appointment',
				'wc_appointment',
				'wc_appointment_page_appointment_calendar',
				'wc_appointment_page_appointment_notification',
				'wc_appointment_page_add_appointment',
				'wc_appointment_page_wc_appointments_global_availability',
			],
		);
	}

	/**
	 * Add appointment scripts in admin pages.
	 *
	 * @param  string $hook
	 * @return void meta in header
	 */
	public function admin_scripts( $hook ): void {

		// Admin calendar page scripts.
		if ( 'wc_appointment_page_appointment_calendar' == $hook ) {
			// Enqueue common dependencies
			wp_enqueue_script( 'wc-enhanced-select' );
			wp_enqueue_script( 'jquery-ui-datepicker' );

			// Check if React calendar mode is enabled
			$react_mode = (bool) apply_filters( 'wc_appointments_admin_enable_react_calendar', true );
			$legacy_toggle = get_user_meta( get_current_user_id(), 'wc_appointments_legacy_calendar', true );
			if ( '1' === $legacy_toggle ) {
				$react_mode = false;
			}
			if ( $react_mode ) {
				// Load calendar class and delegate script enqueuing to it
				if ( ! class_exists( 'WC_Appointments_Admin_Calendar' ) ) {
					require_once __DIR__ . '/class-wc-appointments-admin-calendar.php';
				}
				WC_Appointments_Admin_Calendar::enqueue_react_calendar_scripts();
			}

			// Auto-submit Screen Options form when legacy calendar checkbox changes
			wp_enqueue_script( 'jquery' );
			$auto_submit_script = "
			jQuery( document ).ready( function( $ ) {
				$( '#screen-options-wrap input[name=\"wca_legacy_calendar\"]' ).on( 'change', function() {
					var \$form = $( this ).closest( 'form' );
					if ( \$form.length ) {
						\$form.submit();
					}
				} );
			} );
			";
			wp_add_inline_script( 'jquery', $auto_submit_script );

		// Admin add new appointment page scripts.
		} elseif ( 'wc_appointment_page_add_appointment' == $hook ) {
			WC_Appointments_Init::appointment_form_styles();
		}

	}

	/**
	 * Register and handle Screen Options for the calendar screen.
	 */
	public function calendar_screen_options(): void {
		if ( isset( $_POST['screenoptionnonce'] ) ) {
			check_admin_referer( 'screen-options-nonce', 'screenoptionnonce' );
			$value = isset( $_POST['wca_legacy_calendar'] ) ? '1' : '0';
			update_user_meta( get_current_user_id(), 'wc_appointments_legacy_calendar', $value );
		}
	}

	/**
	 * Ensure Screen Options tab is visible on the calendar screen.
	 *
	 * @param bool $show
	 * @return bool
	 */
	public function show_calendar_screen_options( $show ) {
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( $screen && 'wc_appointment_page_appointment_calendar' === $screen->id ) {
			return true;
		}
		return $show;
	}

	/**
	 * Add a simple checkbox to Screen Options to toggle legacy calendar.
	 *
	 * @param string $status
	 * @param object $args
	 * @return string
	 */
	public function calendar_screen_settings( $settings, $screen ) {
		if ( ! $screen || 'wc_appointment_page_appointment_calendar' !== $screen->id ) {
			return $settings;
		}

		$legacy_enabled = get_user_meta( get_current_user_id(), 'wc_appointments_legacy_calendar', true ) === '1';
		$checked = $legacy_enabled ? ' checked="checked"' : '';
		$settings .= '<h5>' . esc_html__( 'Calendar Options', 'woocommerce-appointments' ) . '</h5>';

		return $settings . ('<div class="metabox-prefs"><label><input type="checkbox" name="wca_legacy_calendar" value="1"' . $checked . ' /> ' . esc_html__( 'Use legacy calendar temporarily', 'woocommerce-appointments' ) . '</label>' . '</div>');
	}

	/**
	 * Removes the default appointments menu links from the main admin menu.
	 */
	public function remove_default_appointments_menu_links()
    {
    }

	/**
	 * Add a submenu for managing appointments pages.
	 */
	public function admin_menu(): void {
		// Only ensure Calendar submenu exists; keep WP's default "Add New" so core can render it.
		add_submenu_page(
		    'edit.php?post_type=wc_appointment',
		    __( 'Calendar', 'woocommerce-appointments' ),
		    __( 'Calendar', 'woocommerce-appointments' ),
		    'manage_appointments',
		    'appointment_calendar',
		    [
				$this,
				'calendar_page',
			],
		);

		// Register legacy "Add Appointment" page so direct URL still works, but hide it from the menu.
		add_submenu_page(
		    'edit.php?post_type=wc_appointment',
		    __( 'Add New Appointment (Legacy)', 'woocommerce-appointments' ),
		    __( 'Add New (Legacy)', 'woocommerce-appointments' ),
		    'edit_appointments',
		    'add_appointment',
		    [ $this, 'add_appointment_page' ],
		);
		remove_submenu_page( 'edit.php?post_type=wc_appointment', 'add_appointment' );
	}

	/**
	 * Create appointment page
	 */
	public function add_appointment_page(): void {
		require_once __DIR__ . '/class-wc-appointments-admin-add.php';
		$page = new WC_Appointments_Admin_Add();
		$page->output();
	}

	/**
	 * Output the calendar page
	 */
	public function calendar_page(): void {
		require_once __DIR__ . '/class-wc-appointments-admin-calendar.php';
		$page = new WC_Appointments_Admin_Calendar();
		$page->output();
	}

	/**
     * Reorder the WC menu items in admin.
     *
     * @param mixed $menu_order
     */
    public function menu_order( array $menu_order ): array {
		// Initialize our custom order array
		$new_menu_order = [];

		// Get index of product menu
		$appointment_menu = array_search( 'edit.php?post_type=wc_appointment', $menu_order );

		// Loop through menu order and do some rearranging
		foreach ( $menu_order as $item ) :
			if ( ( ( 'edit.php?post_type=product' ) == $item ) ) :
				$new_menu_order[] = $item;
				$new_menu_order[] = 'edit.php?post_type=wc_appointment';
				unset( $menu_order[ $appointment_menu ] );
			else :
				$new_menu_order[] = $item;
			endif;
		endforeach;

		// Return order
		return $new_menu_order;
	}

	/**
	 * Filters the add new appointment url to point to our custom page.
	 *
	 * @param string $url original url
	 * @param string $path requested path that we can match against
	 * @return string new url
	 */
	public function add_new_appointment_url( $url, $path ) {
		if ( 'post-new.php?post_type=wc_appointment' == $path ) {
			return admin_url( 'edit.php?post_type=wc_appointment&open_modal=1' );
		}

		return $url;
	}

	public function maybe_redirect_add_new_screen(): void {
		if ( ! is_admin() ) {
			return;
		}

		$post_type = isset( $_GET['post_type'] ) ? sanitize_key( wp_unslash( $_GET['post_type'] ) ) : '';
		if ( 'wc_appointment' !== $post_type ) {
			return;
		}

		wp_safe_redirect( admin_url( 'edit.php?post_type=wc_appointment&open_modal=1' ) );
		exit;
	}
}

$GLOBALS['wc_appointment_admin_menus'] = new WC_Appointments_Admin_Menus();
