<?php
/**
 * Browser-based Live Orders admin screen.
 *
 * @package FoodOrd
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class Foodord_Live_Orders_Admin
 */
final class Foodord_Live_Orders_Admin {
	/**
	 * Cached central entitlement for this request.
	 *
	 * @var array<string,mixed>|null
	 */
	private $quota_status = null;

	/**
	 * Register admin hooks.
	 */
	public function init(): void {
		add_action( 'admin_menu', array( $this, 'register_submenu' ), 18 );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_filter( 'admin_body_class', array( $this, 'filter_admin_body_class' ) );
	}

	/**
	 * Register the operational Live Orders screen.
	 */
	public function register_submenu(): void {
		$page_hook = add_submenu_page(
			$this->get_parent_slug(),
			__( 'Live Orders', 'foodord' ),
			__( 'Live Orders', 'foodord' ),
			'edit_shop_orders',
			$this->get_page_slug(),
			array( $this, 'render_page' )
		);

		if ( $page_hook ) {
			add_action( 'load-' . $page_hook, array( $this, 'remove_contextual_help' ) );
		}
	}

	/**
	 * Remove WordPress contextual help from the operational screen.
	 */
	public function remove_contextual_help(): void {
		$screen = get_current_screen();

		if ( $screen ) {
			$screen->remove_help_tabs();
			$screen->set_help_sidebar( '' );
		}
	}

	/**
	 * Load assets only on the Live Orders screen.
	 *
	 * @param string $hook Current admin hook.
	 */
	public function enqueue_assets( $hook ): void {
		if ( ! $this->is_current_screen( $hook ) ) {
			return;
		}

		wp_enqueue_style(
			'foodord-live-orders-admin',
			plugin_dir_url( __FILE__ ) . 'css/foodord-live-orders-admin.css',
			array( 'dashicons' ),
			FOODORD_VERSION
		);

		wp_enqueue_script(
			'foodord-live-orders-receipt',
			plugin_dir_url( __FILE__ ) . 'js/foodord-live-orders-receipt.js',
			array(),
			FOODORD_VERSION,
			true
		);

		wp_enqueue_script(
			'foodord-live-orders-admin',
			plugin_dir_url( __FILE__ ) . 'js/foodord-live-orders-admin.js',
			array( 'foodord-live-orders-receipt' ),
			FOODORD_VERSION,
			true
		);

		wp_localize_script(
			'foodord-live-orders-admin',
			'foodordLiveOrdersAdmin',
			array(
				'restBase'        => esc_url_raw( rest_url( 'foodord/v1/admin/live-orders' ) ),
				'nonce'           => wp_create_nonce( 'wp_rest' ),
				'refreshInterval' => 30000,
				'hiddenInterval'  => 30000,
				'alertInterval'   => 5000,
				'currencyLocale'  => str_replace( '_', '-', get_user_locale() ),
				'currencyFormat'  => array(
					'currency'          => function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : '',
					'symbol'            => function_exists( 'get_woocommerce_currency_symbol' ) ? html_entity_decode( get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8' ) : '',
					'position'          => get_option( 'woocommerce_currency_pos', 'left' ),
					'thousandSeparator' => function_exists( 'wc_get_price_thousand_separator' ) ? wc_get_price_thousand_separator() : ',',
					'decimalSeparator'  => function_exists( 'wc_get_price_decimal_separator' ) ? wc_get_price_decimal_separator() : '.',
					'decimals'          => function_exists( 'wc_get_price_decimals' ) ? wc_get_price_decimals() : 2,
				),
				'soundUrl'        => esc_url_raw( plugin_dir_url( __FILE__ ) . 'audio/sound5.mp3' ),
				'receiptStylesUrl' => esc_url_raw( plugin_dir_url( __FILE__ ) . 'css/foodord-live-orders-receipt.css' ),
				'groupLabels'      => get_option( 'foodord_show_topping_group_label', 'yes' ),
				'direction'       => is_rtl() ? 'rtl' : 'ltr',
				'language'        => str_replace( '_', '-', determine_locale() ),
				'emptyStateImages' => array(
					'new'      => esc_url_raw( plugin_dir_url( __FILE__ ) . 'images/live-orders/no-orders.svg' ),
					'kitchen'  => esc_url_raw( plugin_dir_url( __FILE__ ) . 'images/live-orders/preparing-order.svg' ),
					'ontheway' => esc_url_raw( plugin_dir_url( __FILE__ ) . 'images/live-orders/courier-delivery.svg' ),
				),
				'strings'         => array(
					'new'                  => __( 'New', 'foodord' ),
					'kitchen'              => __( 'Kitchen', 'foodord' ),
					'onTheWay'             => __( 'On the Way', 'foodord' ),
					'noNewOrders'          => __( 'New orders will appear here automatically.', 'foodord' ),
					'noKitchenOrders'      => __( 'Orders being prepared will appear here.', 'foodord' ),
					'noOnTheWayOrders'     => __( 'Orders ready for delivery will appear here.', 'foodord' ),
					'loading'              => __( 'Loading live orders...', 'foodord' ),
					'loadError'            => __( 'Live orders could not be loaded. Please check your connection and try again.', 'foodord' ),
					'updateError'          => __( 'The order could not be updated. Please try again.', 'foodord' ),
					'detailsError'         => __( 'Order details could not be loaded.', 'foodord' ),
					'moveToKitchen'        => __( 'Send to kitchen', 'foodord' ),
					'moveToOnTheWay'       => __( 'Mark as on the way', 'foodord' ),
					'moveBackToKitchen'    => __( 'Move back to kitchen', 'foodord' ),
					'delivery'             => __( 'Delivery', 'foodord' ),
					'pickup'               => __( 'Pickup', 'foodord' ),
					'items'                => __( 'Items', 'foodord' ),
					'customer'             => __( 'Customer', 'foodord' ),
					'payment'              => __( 'Payment', 'foodord' ),
					'orderNote'            => __( 'Order note', 'foodord' ),
					'deliveryDetails'      => __( 'Delivery details', 'foodord' ),
					'contact'              => __( 'Contact', 'foodord' ),
					'name'                 => __( 'Name', 'foodord' ),
					'phone'                => __( 'Phone', 'foodord' ),
					'notes'                => __( 'Notes', 'foodord' ),
					'subtotal'             => __( 'Subtotal', 'foodord' ),
					'deliveryFee'          => __( 'Delivery fee', 'foodord' ),
					'tip'                  => __( 'Tip', 'foodord' ),
					'deposit'              => __( 'Deposit', 'foodord' ),
					'discount'             => __( 'Discount', 'foodord' ),
					'onlinePaid'           => __( 'Online paid', 'foodord' ),
					'notPaid'              => __( 'Not paid', 'foodord' ),
					'preparationTime'      => __( 'Preparation time', 'foodord' ),
					'decreasePreparation'  => __( 'Decrease preparation time', 'foodord' ),
					'increasePreparation'  => __( 'Increase preparation time', 'foodord' ),
					'minutes'              => __( 'minutes', 'foodord' ),
					'acceptOrder'          => __( 'Confirm', 'foodord' ),
					'close'                => __( 'Close', 'foodord' ),
					'quantity'             => __( 'Qty', 'foodord' ),
					'total'                => __( 'Total', 'foodord' ),
					'address'              => __( 'Address', 'foodord' ),
					'requestedTime'        => __( 'Requested time', 'foodord' ),
					'notAvailable'         => __( 'Not available', 'foodord' ),
					'deliveryTimingLabel'  => __( 'Customer preferred delivery time:', 'foodord' ),
					'pickupTimingLabel'    => __( 'Customer preferred pickup time:', 'foodord' ),
					/* translators: %s: Order number. */
					'orderNumber'          => __( 'Order #%s', 'foodord' ),
					'confirming'           => __( 'Accepting order...', 'foodord' ),
					'updating'             => __( 'Updating order...', 'foodord' ),
					'printReceipt'         => esc_html__( 'Print receipt', 'foodord' ),
					'printError'           => esc_html__( 'The receipt could not be prepared for printing.', 'foodord' ),
					'placed'               => __( 'Placed', 'foodord' ),
					'customerTime'         => __( 'Customer time', 'foodord' ),
					'restaurantTime'       => __( 'Restaurant confirmed time', 'foodord' ),
					'pending'              => __( 'Pending', 'foodord' ),
					'noItems'              => __( 'No items', 'foodord' ),
					'item'                 => __( 'Item', 'foodord' ),
					'toppings'             => __( 'Toppings', 'foodord' ),
					'note'                 => __( 'Note', 'foodord' ),
					'tax'                  => __( 'VAT', 'foodord' ),
				),
			)
		);
	}

	/**
	 * Add a page-specific body class.
	 *
	 * @param string $classes Existing classes.
	 */
	public function filter_admin_body_class( $classes ): string {
		if ( ! $this->is_current_screen() ) {
			return (string) $classes;
		}

		return trim( (string) $classes . ' foodord-live-orders-screen' );
	}

	/**
	 * Render the Live Orders application shell.
	 */
	public function render_page(): void {
		if ( ! current_user_can( 'manage_woocommerce' ) && ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( esc_html__( 'You do not have permission to manage live orders.', 'foodord' ) );
		}
		$quota                = $this->get_quota_status();
		$show_quota_header    = ! empty( $quota['known'] ) && empty( $quota['licensed'] );
		$stage_image_base_url = plugin_dir_url( __FILE__ ) . 'images/live-orders/';
		?>
		<div class="wrap foodord-live-orders-admin" data-foodord-live-orders>
			<?php if ( $show_quota_header ) : ?>
				<?php $this->render_quota_header( $quota ); ?>
			<?php endif; ?>

			<nav class="foodord-live-orders-admin__mobile-tabs" aria-label="<?php esc_attr_e( 'Order stages', 'foodord' ); ?>">
				<button type="button" class="foodord-live-orders-admin__mobile-tab is-active" data-live-tab="new" aria-pressed="true">
					<span><?php esc_html_e( 'New', 'foodord' ); ?></span>
					<span data-live-tab-count="new">0</span>
				</button>
				<button type="button" class="foodord-live-orders-admin__mobile-tab" data-live-tab="kitchen" aria-pressed="false">
					<span><?php esc_html_e( 'Kitchen', 'foodord' ); ?></span>
					<span data-live-tab-count="kitchen">0</span>
				</button>
				<button type="button" class="foodord-live-orders-admin__mobile-tab" data-live-tab="ontheway" aria-pressed="false">
					<span><?php esc_html_e( 'On the Way', 'foodord' ); ?></span>
					<span data-live-tab-count="ontheway">0</span>
				</button>
			</nav>

			<div class="foodord-live-orders-admin__notice" data-live-notice role="status" aria-live="polite" hidden></div>

			<main class="foodord-live-orders-board" data-live-board aria-busy="true">
				<?php $this->render_column( 'new', __( 'New', 'foodord' ) ); ?>
				<?php $this->render_column( 'kitchen', __( 'Kitchen', 'foodord' ) ); ?>
				<?php $this->render_column( 'ontheway', __( 'On the Way', 'foodord' ) ); ?>
			</main>
		</div>

		<div class="foodord-live-order-modal" data-live-modal hidden>
			<div class="foodord-live-order-modal__backdrop" data-live-modal-close></div>
			<section class="foodord-live-order-modal__dialog" role="dialog" aria-modal="true"
				aria-labelledby="foodord-live-order-modal-title">
				<header class="foodord-live-order-modal__header">
					<h2 id="foodord-live-order-modal-title" data-live-modal-title></h2>
					<div class="foodord-live-order-modal__header-actions">
						<button type="button" class="foodord-live-order-modal__close" data-live-modal-close
							aria-label="<?php esc_attr_e( 'Close', 'foodord' ); ?>">
							<span class="dashicons dashicons-no-alt" aria-hidden="true"></span>
						</button>
					</div>
				</header>
				<button type="button" class="foodord-live-order-modal__print" data-live-modal-print aria-label="<?php esc_attr_e( 'Print receipt', 'foodord' ); ?>"
					title="<?php esc_attr_e( 'Print receipt', 'foodord' ); ?>" hidden>
					<span class="<?php echo esc_attr( 'dashicons dashicons-printer' ); ?>" aria-hidden="true"></span>
				</button>
				<div class="foodord-live-order-modal__status-strip" data-live-modal-status hidden>
					<span class="foodord-live-order-modal__status" data-live-modal-fulfillment></span>
					<span class="foodord-live-order-modal__status" data-live-modal-payment></span>
				</div>
				<nav class="foodord-live-order-modal__stage-controls" data-live-modal-stage-controls
					aria-label="<?php esc_attr_e( 'Order stages', 'foodord' ); ?>" hidden>
					<button type="button" class="foodord-live-order-modal__stage-control" data-live-modal-stage="new" aria-pressed="false">
						<img class="foodord-live-order-modal__stage-image"
							src="<?php echo esc_url( $stage_image_base_url . 'no-orders.svg' ); ?>" alt="" aria-hidden="true">
						<span><?php esc_html_e( 'New', 'foodord' ); ?></span>
					</button>
					<button type="button" class="foodord-live-order-modal__stage-control" data-live-modal-stage="kitchen" aria-pressed="false">
						<img class="foodord-live-order-modal__stage-image"
							src="<?php echo esc_url( $stage_image_base_url . 'preparing-order.svg' ); ?>" alt="" aria-hidden="true">
						<span><?php esc_html_e( 'Kitchen', 'foodord' ); ?></span>
					</button>
					<button type="button" class="foodord-live-order-modal__stage-control" data-live-modal-stage="ontheway" aria-pressed="false">
						<img class="foodord-live-order-modal__stage-image"
							src="<?php echo esc_url( $stage_image_base_url . 'courier-delivery.svg' ); ?>" alt="" aria-hidden="true">
						<span><?php esc_html_e( 'On the Way', 'foodord' ); ?></span>
					</button>
				</nav>
				<div class="foodord-live-order-modal__body" data-live-modal-body></div>
				<footer class="foodord-live-order-modal__footer" data-live-modal-footer></footer>
			</section>
		</div>

		<?php
	}

	/**
	 * Render the compact monthly allowance header for unlicensed installations.
	 *
	 * @param array<string,mixed> $quota Current central quota snapshot.
	 */
	private function render_quota_header( array $quota ): void {
		$remaining    = isset( $quota['remaining'] ) ? absint( $quota['remaining'] ) : 0;
		$header_class = 'foodord-live-orders-quota';
		if ( $remaining <= 10 ) {
			$header_class .= ' is-low';
		}
		?>
		<header class="<?php echo esc_attr( $header_class ); ?>" data-live-quota-header>
			<span class="foodord-live-orders-quota__icon dashicons dashicons-chart-bar" aria-hidden="true"></span>
			<span class="foodord-live-orders-quota__label"><?php esc_html_e( 'Monthly allowance', 'foodord' ); ?></span>
			<span class="foodord-live-orders-quota__divider" aria-hidden="true"></span>
			<strong class="foodord-live-orders-quota__remaining" data-live-quota-remaining>
				<?php echo esc_html( Foodord_Live_Orders_Quota::get_remaining_message( $remaining ) ); ?>
			</strong>
			<button type="button" class="foodord-live-orders-quota__upgrade" data-live-quota-upgrade
				data-upgrade-url="<?php echo esc_url( 'https://www.foodord.com/pricing/' ); ?>">
				<?php esc_html_e( 'Upgrade', 'foodord' ); ?>
			</button>
		</header>
		<?php
	}

	/**
	 * Render one operational order column.
	 *
	 * @param string $stage Stage identifier.
	 * @param string $label Column label.
	 */
	private function render_column( string $stage, string $label ): void {
		?>
		<section class="foodord-live-orders-column" data-live-column="<?php echo esc_attr( $stage ); ?>">
			<header class="foodord-live-orders-column__header">
				<div class="foodord-live-orders-column__title-wrap">
					<h2 class="foodord-live-orders-column__title"><?php echo esc_html( $label ); ?></h2>
				</div>
				<span class="foodord-live-orders-column__count is-loading" data-live-count="<?php echo esc_attr( $stage ); ?>" aria-hidden="true"></span>
			</header>
			<div class="foodord-live-orders-column__content" data-live-column-content="<?php echo esc_attr( $stage ); ?>"></div>
		</section>
		<?php
	}

	/**
	 * Get the central entitlement once per admin request.
	 *
	 * @return array<string,mixed>
	 */
	private function get_quota_status(): array {
		if ( is_array( $this->quota_status ) ) {
			return $this->quota_status;
		}

		$this->quota_status = class_exists( 'Foodord_Live_Orders_Quota' )
			? Foodord_Live_Orders_Quota::get_status()
			: array(
				'known'    => false,
				'allowed'  => true,
				'licensed' => false,
			);

		return $this->quota_status;
	}

	/**
	 * Get the current page slug.
	 */
	private function get_page_slug(): string {
		return function_exists( 'foodord_get_settings_page_slug' )
			? foodord_get_settings_page_slug( 'live_orders' )
			: 'foodord-live-orders';
	}

	/**
	 * Get the FoodOrd parent menu slug.
	 */
	private function get_parent_slug(): string {
		return function_exists( 'foodord_get_admin_parent_slug' )
			? (string) foodord_get_admin_parent_slug()
			: 'foodord-settings';
	}

	/**
	 * Determine whether the current request targets this screen.
	 *
	 * @param string $hook Optional hook suffix.
	 */
	private function is_current_screen( $hook = '' ): bool {
		$page_raw = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$page     = is_string( $page_raw ) ? sanitize_key( $page_raw ) : '';

		if ( $this->get_page_slug() === $page ) {
			return true;
		}

		return is_string( $hook ) && '' !== $hook && false !== strpos( $hook, $this->get_page_slug() );
	}
}
