<?php
/**
 * Product layout admin page handler.
 *
 * @package FoodOrd
 */

defined('ABSPATH') || exit;

/**
 * Class Foodord_Product_Layout
 */
class Foodord_Product_Layout
{

	/**
	 * Hook assets for the layout page.
	 */
	public function __construct()
	{
		add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));
	}

	/**
	 * Enqueue admin assets when on the layout page.
	 *
	 * @param string $hook Current screen hook.
	 */
	public function enqueue_assets($hook)
	{
		if (!$this->is_layout_screen($hook)) {
			return;
		}

		wp_enqueue_style(
			'foodord-products-shortcode',
			FOODORD_URL . 'public/css/shortcode-products.css',
			array(),
			FOODORD_VERSION
		);

		wp_enqueue_style(
			'foodord-product-layout-admin',
			FOODORD_URL . 'admin/css/foodord-product-layout.css',
			array('foodord-products-shortcode'),
			FOODORD_VERSION
		);

		wp_enqueue_script(
			'foodord-product-layout-admin',
			FOODORD_URL . 'admin/js/foodord-product-layout.js',
			array(),
			FOODORD_VERSION,
			true
		);
	}

	/**
	 * Determine if the current page matches the layout settings screen.
	 *
	 * @param string $hook Current screen hook.
	 */
	private function is_layout_screen($hook): bool
	{
		if ('' === (string) $hook) {
			return false;
		}

		$slugs = function_exists('foodord_get_settings_page_slugs')
			? foodord_get_settings_page_slugs('layout')
			: array('foodord-theme-settings-layout', 'foodord-layout');

		foreach ($slugs as $slug) {
			if ('' !== $slug && false !== strpos((string) $hook, $slug)) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Retrieve layout choices.
	 */
	private function get_layout_choices(): array
	{
		return array(
			'classic' => array(
				'label' => __('Signature Classic', 'foodord'),
				'description' => __('The timeless FoodOrd experience. Balanced, efficient, and perfectly optimized for high-volume menu scanning.', 'foodord'),
			),
			'grid' => array(
				'label' => __('Modern Grid', 'foodord'),
				'description' => __('Elevate your menu with immersive visuals and a bold, contemporary structure designed to captivate.', 'foodord'),
			),
			'streamline' => array(
				'label' => __('Mobile Streamline', 'foodord'),
				'description' => __('Swift, focused, and app-native in feel. Precision-engineered for the modern mobile-first diner.', 'foodord'),
			),
			'frosted' => array(
				'label' => __('Frosted Flow', 'foodord'),
				'description' => __('A translucent, layered card style with soft depth, bright edges, and a premium lightweight feel.', 'foodord'),
			),
		);
	}

	/**
	 * Render the layout admin page.
	 */
	public function render_page()
	{
		if (!current_user_can('manage_options')) {
			return;
		}

		$choices = $this->get_layout_choices();
		$current_layout = foodord_get_product_card_layout();
		$notice_message = '';
		$request_method = isset($_SERVER['REQUEST_METHOD']) ? strtoupper(sanitize_text_field(wp_unslash($_SERVER['REQUEST_METHOD']))) : '';

		if ('POST' === $request_method && isset($_POST['foodord_product_layout_nonce'])) {
			check_admin_referer('foodord_save_product_layout', 'foodord_product_layout_nonce');
			$requested_layout = isset($_POST['foodord_product_card_layout']) ? sanitize_text_field(wp_unslash($_POST['foodord_product_card_layout'])) : 'streamline';
			if (!isset($choices[$requested_layout])) {
				$requested_layout = 'streamline';
			}
			update_option('foodord_product_card_layout', $requested_layout);
			$current_layout = $requested_layout;
			$notice_message = __('Layout preference saved.', 'foodord');
		}

		?>
		<div class="wrap foodord-layout-settings">
			<h1 class="wp-heading-inline"><?php esc_html_e('Product Card Layout', 'foodord'); ?></h1>
			<hr class="wp-header-end">

			<p class="description">
				<?php esc_html_e('Choose how FoodOrd product cards are rendered on the storefront.', 'foodord'); ?>
			</p>
			<?php
			if ( function_exists( 'foodord_admin_render_horizontal_menu' ) ) {
				foodord_admin_render_horizontal_menu();
			}
			?>

			<?php if ('' !== $notice_message): ?>
				<div class="notice notice-success is-dismissible">
					<p class="foodord-layout-notice__message"><?php echo esc_html($notice_message); ?></p>
				</div>
			<?php endif; ?>

			<form method="post"
				action="<?php echo esc_url(admin_url('admin.php?page=' . foodord_get_settings_page_slug('layout'))); ?>">
				<?php wp_nonce_field('foodord_save_product_layout', 'foodord_product_layout_nonce'); ?>

				<div class="foodord-layout-grid">
					<?php
					foreach ($choices as $layout_key => $layout_meta):
						$preview = $this->get_preview_markup($layout_key);
						$card_classes = array('foodord-layout-card');
						if ($current_layout === $layout_key) {
							$card_classes[] = 'is-active';
						}
						?>
						<div class="<?php echo esc_attr(implode(' ', $card_classes)); ?>"
							data-foodord-layout-card="<?php echo esc_attr($layout_key); ?>">
							<div class="foodord-layout-card__header">
								<div class="foodord-layout-card__info">
									<h2 class="foodord-layout-card__title"><?php echo esc_html($layout_meta['label']); ?></h2>
									<p class="foodord-layout-card__description">
										<?php echo esc_html($layout_meta['description']); ?>
									</p>
								</div>
								<div class="foodord-layout-card__choice">
									<input type="radio" name="foodord_product_card_layout"
										value="<?php echo esc_attr($layout_key); ?>" <?php checked($current_layout, $layout_key); ?> aria-label="<?php echo esc_attr($layout_meta['label']); ?>" />
								</div>
							</div>
							<div class="foodord-layout-card__preview">
								<div class="foodord-products-shortcode">
									<?php
									$preview_allowed = wp_kses_allowed_html('post');
									$preview_allowed['svg'] = array(
										'viewbox' => true,
										'fill' => true,
										'stroke' => true,
										'stroke-width' => true,
										'stroke-linecap' => true,
										'stroke-linejoin' => true,
										'class' => true,
										'aria-hidden' => true,
									);
									$preview_allowed['circle'] = array(
										'cx' => true,
										'cy' => true,
										'r' => true,
									);
									$preview_allowed['line'] = array(
										'x1' => true,
										'y1' => true,
										'x2' => true,
										'y2' => true,
									);
									$preview_allowed['path'] = array('d' => true);

									echo wp_kses($preview, $preview_allowed);
									?>
								</div>
							</div>
						</div>
					<?php endforeach; ?>
				</div>

				<?php submit_button(__('Save Changes', 'foodord')); ?>
			</form>
		</div>
		<?php
	}

	/**
	 * Provide preview markup for the requested layout.
	 *
	 * @param string $layout_key Layout identifier.
	 */
	private function get_preview_markup(string $layout_key): string
	{
		$sample_price = '<span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">$</span>14.50</bdi></span>';
		$description = esc_html__('Premium grilled beef patty with aged cheddar and caramelized onions.', 'foodord');
		$image = '<img src="' . esc_url(FOODORD_URL . 'public/images/preview-pizza.jpg') . '" class="product-image" alt="' . esc_attr__('Sample product image', 'foodord') . '" />';
		$button = '<button class="button add_to_cart_button" type="button" aria-label="' . esc_attr__('Add to cart', 'foodord') . '"><span class="screen-reader-text">' . esc_html__('Add to cart', 'foodord') . '</span></button>';

		ob_start();
		if ('grid' === $layout_key) {
			?>
			<div class="foodord-product-card foodord-product-card--grid foodord-product-card-alt" data-foodord-available="1"
				data-product-id="demo-grid" data-foodord-direct-add="0">
				<div class="card-image-wrap">
					<div class="product-image-container">
						<div class="product-image-wrapper">
							<?php echo wp_kses_post($image); ?>
						</div>
					</div>
				</div>
				<div class="card-content">
					<div class="product-info">
						<div class="product-top">
							<div class="product-title-row card-header">
								<h3 class="product-title card-title"><?php esc_html_e('Beef Deluxe', 'foodord'); ?></h3>
								<button type="button" class="foodord-allergy-trigger"
									aria-label="<?php esc_attr_e('Open Allergy Info', 'foodord'); ?>">
									<span class="foodord-allergy-trigger__icon" aria-hidden="true">
										<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"
											stroke-linecap="round" stroke-linejoin="round">
											<circle cx="12" cy="12" r="10"></circle>
											<line x1="12" y1="16" x2="12" y2="12"></line>
											<line x1="12" y1="8" x2="12.01" y2="8"></line>
										</svg>
									</span>
								</button>
							</div>
							<div class="product-description">
								<p class="product-description-text card-description"><?php echo esc_html($description); ?></p>
							</div>
						</div>
						<div class="product-bottom card-footer">
							<div class="product-price-container card-price">
								<span class="price-label"><?php esc_html_e('Price from', 'foodord'); ?></span>
								<div class="product-price price-value">
									<?php echo wp_kses_post($sample_price); ?>
								</div>
							</div>
							<div class="product-actions">
								<?php echo wp_kses_post($button); ?>
							</div>
						</div>
					</div>
				</div>
			</div>
			<?php
		} elseif ('streamline' === $layout_key) {
			?>
			<div class="foodord-product-card foodord-product-card--streamline" data-foodord-available="1"
				data-product-id="demo-streamline" data-foodord-direct-add="0">
				<div class="foodord-card-count">2</div>
				<div class="product-info">
					<div class="product-top">
						<div class="product-title-row">
							<h3 class="product-title"><?php esc_html_e('Beef Deluxe', 'foodord'); ?></h3>
							<button type="button" class="foodord-allergy-trigger"
								aria-label="<?php esc_attr_e('Open Allergy Info', 'foodord'); ?>">
								<span class="foodord-allergy-trigger__icon" aria-hidden="true">
									<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"
										stroke-linecap="round" stroke-linejoin="round">
										<circle cx="12" cy="12" r="10"></circle>
										<line x1="12" y1="16" x2="12" y2="12"></line>
										<line x1="12" y1="8" x2="12.01" y2="8"></line>
									</svg>
								</span>
							</button>
						</div>
						<div class="product-description">
							<p class="product-description-text"><?php echo esc_html($description); ?></p>
						</div>
					</div>
					<div class="product-bottom">
						<div class="product-price-container">
							<div class="product-price">
								<span class="foodord-price-prefix"><?php esc_html_e('from: ', 'foodord'); ?></span>
								<?php echo wp_kses_post($sample_price); ?>
							</div>
						</div>
					</div>
				</div>
				<div class="product-image-container">
					<div class="product-image-wrapper">
						<?php echo wp_kses_post($image); ?>
					</div>
				</div>
				<div class="product-actions">
					<?php echo wp_kses_post($button); ?>
				</div>
			</div>
			<?php
		} elseif ('frosted' === $layout_key) {
			?>
			<div class="foodord-product-card foodord-product-card--frosted" data-foodord-card-layout="frosted"
				data-foodord-available="1" data-product-id="demo-frosted" data-foodord-direct-add="0">
				<div class="foodord-product-card__surface" aria-hidden="true"></div>
				<div class="product-image-container">
					<div class="product-image-wrapper">
						<?php echo wp_kses_post($image); ?>
					</div>
				</div>
				<div class="product-info">
					<div class="product-top">
						<div class="product-title-row">
							<h3 class="product-title"><?php esc_html_e('Beef Deluxe', 'foodord'); ?></h3>
							<button type="button" class="foodord-allergy-trigger"
								aria-label="<?php esc_attr_e('Open Allergy Info', 'foodord'); ?>">
								<span class="foodord-allergy-trigger__icon" aria-hidden="true">
									<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"
										stroke-linecap="round" stroke-linejoin="round">
										<circle cx="12" cy="12" r="10"></circle>
										<line x1="12" y1="16" x2="12" y2="12"></line>
										<line x1="12" y1="8" x2="12.01" y2="8"></line>
									</svg>
								</span>
							</button>
						</div>
						<div class="product-description">
							<p class="product-description-text"><?php echo esc_html($description); ?></p>
						</div>
					</div>
					<div class="product-bottom">
						<div class="product-price-container">
							<div class="product-price">
								<span class="foodord-price-prefix"><?php esc_html_e('from: ', 'foodord'); ?></span>
								<?php echo wp_kses_post($sample_price); ?>
							</div>
						</div>
						<div class="product-actions">
							<?php echo wp_kses_post($button); ?>
						</div>
					</div>
				</div>
			</div>
			<?php
		} else {
			?>
			<div class="foodord-product-card" data-foodord-available="1" data-product-id="demo-classic" data-foodord-direct-add="0">
				<div class="product-image-container">
					<div class="product-image-wrapper">
						<?php echo wp_kses_post($image); ?>
					</div>
				</div>
				<div class="product-info">
					<div class="product-top">
						<div class="product-title-row">
							<h3 class="product-title"><?php esc_html_e('Beef Deluxe', 'foodord'); ?></h3>
							<button type="button" class="foodord-allergy-trigger"
								aria-label="<?php esc_attr_e('Open Allergy Info', 'foodord'); ?>">
								<span class="foodord-allergy-trigger__icon" aria-hidden="true">
									<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"
										stroke-linecap="round" stroke-linejoin="round">
										<circle cx="12" cy="12" r="10"></circle>
										<line x1="12" y1="16" x2="12" y2="12"></line>
										<line x1="12" y1="8" x2="12.01" y2="8"></line>
									</svg>
								</span>
							</button>
						</div>
						<div class="product-description">
							<p class="product-description-text"><?php echo esc_html($description); ?></p>
						</div>
					</div>
					<div class="product-bottom">
						<div class="product-price-container">
							<div class="product-price">
								<?php echo wp_kses_post($sample_price); ?>
							</div>
						</div>
						<div class="product-actions">
							<?php echo wp_kses_post($button); ?>
						</div>
					</div>
				</div>
			</div>
			<?php
		}

		$content = ob_get_clean();
		return is_string($content) ? $content : '';
	}
}
