<?php
// phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Yatoon App Shell (v3.5.0)
 *
 * Renders an independent left navigation rail + top bar on Yatoon admin
 * screens, replacing the default WordPress chrome there only. Inspired by
 * the "looks and feels like a SaaS app, not a WP submenu list" pattern
 * used by best-in-class booking products. Every link still points at the
 * existing admin.php?page=... URLs registered in YATOON_Admin::add_admin_menu,
 * so no routing/capability logic changes — this is presentation only.
 */
class YATOON_App_Shell {

	public function __construct() {
		add_filter( 'admin_body_class', array( $this, 'maybe_add_body_class' ) );
		add_action( 'in_admin_header', array( $this, 'render' ) );
	}

	public static function is_booking_admin_page() {
		$page_slug = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
		if ( '' === $page_slug ) {
			return false;
		}

		if ( strpos( $page_slug, 'sbs-' ) === 0 ) {
			return true;
		}

		$booking_slugs = array(
			'yatoon-booking-system',
			'yatoon-dashboard',
			'yatoon-calendar',
			'yatoon-clients',
			'yatoon-reports',
			'yatoon-automations',
			'yatoon-loyalty',
			'yatoon-broadcasts',
			'yatoon-packages',
			'yatoon-gift-cards',
			'yatoon-service-menu',
			'yatoon-catalog-settings',
			'yatoon-reviews',
			'yatoon-recurring',
			'yatoon-addons',
			'yatoon-form-fields',
			'yatoon-closed-dates',
			'yatoon-setup-wizard',
			'yatoon-ai-assistant',
			'yatoon-resources',
			'yatoon-service-menu',
			'yatoon-locations',
			'yatoon-orders',
			'yatoon-operations',
			'yatoon-performance',
			'yatoon-growth-modules',
			'yatoon-deposit-pro',
			'yatoon-noshow-pro',
			'yatoon-waitlist-pro',
		);

		if ( in_array( $page_slug, $booking_slugs, true ) ) {
			return true;
		}

		if ( strpos( $page_slug, 'yatoon-booking-system-' ) === 0 ) {
			return true;
		}

		if ( strpos( $page_slug, 'yatoon_booking_system' ) === 0 ) {
			return true;
		}

		return false;
	}

	private function is_yatoon_screen() {
		if ( self::is_booking_admin_page() ) {
			return true;
		}

		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( ! $screen ) {
			return false;
		}
		return ( strpos( $screen->id, 'sbs-' ) !== false || strpos( $screen->id, 'yatoon-booking-system' ) !== false );
	}

	public function maybe_add_body_class( $classes ) {
		if ( $this->is_yatoon_screen() ) {
			$classes .= ' yatoon-app-shell-on';
		}
		return $classes;
	}

	/**
	 * Grouped nav structure. Kept in one place so the sidebar, the topbar
	 * search index, and (eventually) breadcrumbs all stay in sync.
	 */
	public static function get_nav_groups() {
		$is_pro = function_exists( 'ybs_is_pro' ) ? ybs_is_pro() : false;
		$customer_items = array(
			array( 'slug' => 'yatoon-clients', 'label' => 'Clients', 'icon' => 'dashicons-groups' ),
			array( 'slug' => 'sbs-messages', 'label' => 'Messages', 'icon' => 'dashicons-email' ),
			array( 'slug' => 'sbs-waitlist', 'label' => 'Waitlist', 'icon' => 'dashicons-clock' ),
			array( 'slug' => 'yatoon-reviews', 'label' => 'Reviews', 'icon' => 'dashicons-star-filled' ),
		);
		$business_items = array(
			array( 'slug' => 'sbs-services', 'label' => 'Services', 'icon' => 'dashicons-tag' ),
			array( 'slug' => 'sbs-staff', 'label' => 'Staff', 'icon' => 'dashicons-businessperson' ),
			array( 'slug' => 'yatoon-resources', 'label' => 'Resources', 'icon' => 'dashicons-screenoptions' ),
			array( 'slug' => 'yatoon-gift-cards', 'label' => 'Gift Cards', 'icon' => 'dashicons-tickets-alt' ),
			array( 'slug' => 'yatoon-catalog-settings', 'label' => 'Catalog', 'icon' => 'dashicons-format-gallery' ),
		);
		$growth_items = array(
			array( 'slug' => 'yatoon-reports', 'label' => 'Reports', 'icon' => 'dashicons-chart-bar' ),
			array( 'slug' => 'yatoon-recurring', 'label' => 'Recurring', 'icon' => 'dashicons-update' ),
			array( 'slug' => 'yatoon-ai-assistant', 'label' => 'AI Assistant', 'icon' => 'dashicons-superhero-alt' ),
		);
		$tool_items = array(
			array( 'slug' => 'yatoon-service-menu', 'label' => 'Service Menu', 'icon' => 'dashicons-list-view' ),
			array( 'slug' => 'yatoon-orders', 'label' => 'Orders & Invoices', 'icon' => 'dashicons-media-spreadsheet' ),
			array( 'slug' => 'yatoon-operations', 'label' => 'Operations', 'icon' => 'dashicons-clipboard' ),
			array( 'slug' => 'yatoon-performance', 'label' => 'Performance', 'icon' => 'dashicons-dashboard' ),
			array( 'slug' => 'yatoon-growth-modules', 'label' => 'Growth Modules', 'icon' => 'dashicons-chart-line' ),
			array( 'slug' => 'sbs-blacklist', 'label' => 'Blacklist', 'icon' => 'dashicons-shield' ),
		);
		if ( get_option( 'yatoon_multi_location_enabled', '0' ) === '1' ) {
			array_unshift( $tool_items, array( 'slug' => 'yatoon-locations', 'label' => 'Locations', 'icon' => 'dashicons-location-alt' ) );
		}
		$settings_items = array(
			array( 'slug' => 'yatoon-booking-system', 'label' => 'General', 'icon' => 'dashicons-admin-settings' ),
			array( 'slug' => 'sbs-brand', 'label' => 'Brand & Colors', 'icon' => 'dashicons-admin-customizer' ),
			array( 'slug' => 'sbs-notifications', 'label' => 'Notifications', 'icon' => 'dashicons-bell' ),
			array( 'slug' => 'yatoon-form-fields', 'label' => 'Form Fields', 'icon' => 'dashicons-feedback' ),
			array( 'slug' => 'yatoon-closed-dates', 'label' => 'Closed Dates', 'icon' => 'dashicons-no-alt' ),
			array( 'slug' => 'sbs-sync-log', 'label' => 'Sync & Logs', 'icon' => 'dashicons-update-alt' ),
			array( 'slug' => 'yatoon-setup-wizard', 'label' => 'Setup Wizard', 'icon' => 'dashicons-controls-play' ),
		);
		if ( $is_pro ) {
			$customer_items[] = array( 'slug' => 'yatoon-loyalty', 'label' => 'Loyalty', 'icon' => 'dashicons-awards' );
			$business_items[] = array( 'slug' => 'yatoon-packages', 'label' => 'Packages', 'icon' => 'dashicons-archive' );
			$growth_items[] = array( 'slug' => 'yatoon-automations', 'label' => 'Automation', 'icon' => 'dashicons-networking' );
			$growth_items[] = array( 'slug' => 'yatoon-broadcasts', 'label' => 'Broadcasts', 'icon' => 'dashicons-megaphone' );
			$settings_items[] = array( 'slug' => 'sbs-sms-pro', 'label' => 'SMS', 'icon' => 'dashicons-smartphone' );
			$settings_items[] = array( 'slug' => 'sbs-gcal-pro', 'label' => 'Google Calendar', 'icon' => 'dashicons-calendar' );
			$settings_items[] = array( 'slug' => 'yatoon-deposit-pro', 'label' => 'Deposits', 'icon' => 'dashicons-money-alt' );
			$settings_items[] = array( 'slug' => 'yatoon-noshow-pro', 'label' => 'No-show Rules', 'icon' => 'dashicons-dismiss' );
		} else {
			$growth_items[] = array( 'slug' => 'yatoon-addons', 'label' => 'Explore Pro', 'icon' => 'dashicons-star-filled' );
		}

		return array(
			array(
				'label' => 'Today',
				'items' => array(
					array( 'slug' => 'yatoon-dashboard', 'label' => 'Today', 'icon' => 'dashicons-admin-home' ),
					array( 'slug' => 'sbs-bookings', 'label' => 'Bookings', 'icon' => 'dashicons-calendar-alt' ),
					array( 'slug' => 'yatoon-calendar', 'label' => 'Calendar', 'icon' => 'dashicons-calendar' ),
				),
			),
			array( 'label' => 'Customers', 'items' => $customer_items ),
			array( 'label' => 'Business', 'items' => $business_items ),
			array( 'label' => 'Growth', 'items' => $growth_items ),
			array( 'label' => 'Tools', 'items' => $tool_items ),
			array(
				'label' => 'Settings',
				'items' => $settings_items,
			),
		);
	}

	public function render() {
		if ( ! $this->is_yatoon_screen() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Inline, guaranteed-to-apply critical CSS. This duplicates rules already
		// in yatoon-app-shell.css, but is printed directly in the page (not as a
		// separate enqueued file), so it can't be dropped by asset-combining,
		// minification, or aggressive caching plugins/CDNs. If the external
		// stylesheet fails to load for any reason, the shell still works.
		echo '<style id="yatoon-app-shell-critical-css">
			body.yatoon-app-shell-on #adminmenumain,
			body.yatoon-app-shell-on #adminmenuwrap,
			body.yatoon-app-shell-on #adminmenuback,
			body.yatoon-app-shell-on #wpadminbar,
			body.yatoon-app-shell-on #wpfooter,
			body.yatoon-app-shell-on #screen-meta-links,
			body.yatoon-app-shell-on #screen-meta,
			body.yatoon-app-shell-on .update-nag,
			body.yatoon-app-shell-on .notice:not(.yatoon-keep-notice) { display: none !important; }
			html.wp-toolbar { padding-top: 0 !important; }
		</style>';

		$current_page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
		$groups       = self::get_nav_groups();
		$book_url     = get_option( 'yatoon_book_new_url', '' );
		if ( ! $book_url ) {
			$page_id = (int) get_option( 'yatoon_manage_booking_page_id', 0 );
			if ( $page_id ) {
				$book_url = get_permalink( $page_id );
			}
		}

		echo '<div class="yatoon-app-sidebar" id="yatoon-app-sidebar">';
		echo '<div class="yatoon-app-brand"><span class="dot"></span>' . esc_html( defined( 'YATOON_BRAND_NAME' ) ? YATOON_BRAND_NAME : 'Yatoon' ) . ' Booking</div>';
		echo '<nav class="yatoon-app-nav">';
		foreach ( $groups as $group ) {
			$group_active = false;
			foreach ( $group['items'] as $group_item ) {
				if ( $current_page === $group_item['slug'] ) {
					$group_active = true;
					break;
				}
			}
			echo '<div class="yatoon-app-nav-group' . ( $group_active ? ' has-active' : '' ) . '">';
			if ( ! empty( $group['label'] ) ) {
				echo '<button type="button" class="yatoon-app-nav-label" aria-expanded="true"><span>' . esc_html( $group['label'] ) . '</span><span class="dashicons dashicons-arrow-up-alt2" aria-hidden="true"></span></button>';
			}
			foreach ( $group['items'] as $item ) {
				$is_active = ( $current_page === $item['slug'] );
				$locked    = ! empty( $item['locked'] );
				$url       = admin_url( 'admin.php?page=' . $item['slug'] );
				printf(
					'<a href="%1$s" class="%2$s"><span class="dashicons %3$s"></span>%4$s%5$s</a>',
					esc_url( $url ),
					$is_active ? 'is-active' : ( $locked ? 'is-locked' : '' ),
					esc_attr( $item['icon'] ),
					esc_html( $item['label'] ),
					$locked ? '<span class="lock-badge">PRO</span>' : ''
				);
			}
			echo '</div>';
		}
		echo '</nav>';
		echo '<div class="yatoon-app-sidebar-footer">Yatoon Booking v' . esc_html( defined( 'YATOON_VERSION' ) ? YATOON_VERSION : '' ) . '</div>';
		echo '</div>';

		echo '<div class="yatoon-app-topbar">';
		echo '<button type="button" class="yatoon-app-menu-toggle" aria-label="Menu" aria-controls="yatoon-app-sidebar" aria-expanded="false"><span class="dashicons dashicons-menu"></span></button>';
		echo '<div class="yatoon-app-search">';
		echo '<span class="dashicons dashicons-search"></span>';
		echo '<input type="text" id="yatoon-app-search-input" placeholder="Search bookings, services, settings... (press /)" autocomplete="off" />';
		echo '<div class="yatoon-app-search-results" id="yatoon-app-search-results"></div>';
		echo '</div>';
		echo '<div class="yatoon-app-topbar-spacer"></div>';
		if ( $book_url ) {
			printf(
				'<a class="yatoon-app-quick-create" href="%s" target="_blank" rel="noreferrer"><span class="dashicons dashicons-plus-alt2"></span>New Booking</a>',
				esc_url( $book_url )
			);
		}
		printf(
			'<a class="yatoon-app-topbar-icon" href="%s" title="Sync Log"><span class="dashicons dashicons-update-alt"></span></a>',
			esc_url( admin_url( 'admin.php?page=sbs-sync-log' ) )
		);
		printf(
			'<a class="yatoon-app-topbar-icon" href="%s" title="Notifications"><span class="dashicons dashicons-bell"></span></a>',
			esc_url( admin_url( 'admin.php?page=sbs-notifications' ) )
		);
		printf(
			'<a class="yatoon-app-topbar-icon" href="%s" title="Back to WordPress Dashboard"><span class="dashicons dashicons-wordpress"></span></a>',
			esc_url( admin_url() )
		);
		printf(
			'<a class="yatoon-app-topbar-icon" href="%s" title="View Site" target="_blank" rel="noreferrer"><span class="dashicons dashicons-external"></span></a>',
			esc_url( home_url( '/' ) )
		);
		echo '</div>';
	}

	/**
	 * Flat searchable index of every nav item, localized to JS for the
	 * topbar quick-search box.
	 */
	public static function get_search_index() {
		$index = array();
		foreach ( self::get_nav_groups() as $group ) {
			foreach ( $group['items'] as $item ) {
				$index[] = array(
					'label'    => $item['label'],
					'url'      => admin_url( 'admin.php?page=' . $item['slug'] ),
					'icon'     => $item['icon'],
					'keywords' => strtolower( $item['label'] . ' ' . $item['slug'] ),
				);
			}
		}
		return $index;
	}
}
