<?php
/**
 * Admin schedule preview for website menu and QR menu.
 *
 * @package Maca_Menu_List_Pro
 */

if (!defined('ABSPATH')) {
    exit;
}

class Maca_MenuList_Admin_Menu_Preview {

    /**
     * @var self|null
     */
    private static $instance = null;

    /**
     * Bootstrap hooks once.
     *
     * @return self
     */
    public static function bootstrap() {
        if (self::$instance === null) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * Constructor.
     */
    private function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'), 20);
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        add_action('wp_ajax_maca_menu_schedule_preview', array($this, 'ajax_schedule_preview'));
    }

    /**
     * Whether the site uses the online dish menu preview.
     *
     * @return bool
     */
    private function is_dish_preview_mode() {
        return maca_menulist_is_dishes_mode();
    }

    /**
     * Register the preview page for PDF/image and dish modes.
     */
    public function add_admin_menu() {
        add_submenu_page(
            'maca-restu',
            __('Menu preview', 'maca-restu-pro'),
            __('Menu preview', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu-menu-preview',
            array($this, 'render_page')
        );
    }

    /**
     * Enqueue styles and scripts for the preview page.
     *
     * @param string $hook Admin page hook suffix.
     */
    public function enqueue_admin_scripts($hook) {
        if ($hook !== 'maca-restu_page_maca-restu-menu-preview') {
            return;
        }

        wp_enqueue_style(
            'maca-menulist-admin-menu-preview',
            MACA_MENULIST_PLUGIN_URL . 'assets/css/admin-menu-preview.css',
            array('maca-menulist-admin'),
            MACA_MENULIST_VERSION
        );

        $script_deps = array('jquery');

        if ($this->is_dish_preview_mode()) {
            wp_enqueue_style(
                'maca-menulist-style',
                MACA_MENULIST_PLUGIN_URL . 'assets/css/style.css',
                array(),
                MACA_MENULIST_VERSION
            );
            wp_enqueue_style(
                'maca-menulist-dish-menu-themes',
                MACA_MENULIST_PLUGIN_URL . 'assets/css/dish-menu-themes.css',
                array('maca-menulist-style'),
                MACA_MENULIST_VERSION
            );
            wp_enqueue_script(
                'maca-menulist-dish-menu',
                MACA_MENULIST_PLUGIN_URL . 'assets/js/dish-menu.js',
                array(),
                MACA_MENULIST_VERSION,
                true
            );
            $script_deps[] = 'maca-menulist-dish-menu';
        }

        wp_enqueue_script(
            'maca-menulist-admin-menu-preview',
            MACA_MENULIST_PLUGIN_URL . 'assets/js/admin-menu-preview.js',
            $script_deps,
            MACA_MENULIST_VERSION,
            true
        );
        wp_localize_script(
            'maca-menulist-admin-menu-preview',
            'macaMenulistMenuPreview',
            array(
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('maca_menu_schedule_preview'),
                'loading' => __('Updating preview…', 'maca-restu-pro'),
                'error' => __('Could not load preview. Check the date and time.', 'maca-restu-pro'),
                /* translators: %s: formatted date and time */
                'activeLabel' => __('Showing menu as of %s.', 'maca-restu-pro'),
                'previewMode' => $this->is_dish_preview_mode() ? 'dishes' : 'files',
                'exclusiveCampaignNote' => __(
                    'Exclusive campaign mode is on and at least one campaign is active now, so regular categories are hidden on the guest menu.',
                    'maca-restu-pro'
                ),
            )
        );
    }

    /**
     * AJAX: render website and QR menu HTML for a chosen datetime.
     */
    public function ajax_schedule_preview() {
        check_ajax_referer('maca_menu_schedule_preview', 'nonce');

        if (!current_user_can(maca_menulist_admin_required_cap())) {
            wp_send_json_error(array('message' => __('Permission denied.', 'maca-restu-pro')), 403);
        }

        $use_now = isset($_POST['use_now']) && sanitize_text_field(wp_unslash($_POST['use_now'])) === '1';

        if ($use_now) {
            $timestamp = maca_menulist_wp_mysql_to_timestamp(maca_menulist_wp_now_mysql());
            if ($timestamp === false) {
                $timestamp = current_time('timestamp');
            }
        } else {
            $datetime = isset($_POST['datetime']) ? sanitize_text_field(wp_unslash($_POST['datetime'])) : '';
            $timestamp = maca_menulist_wp_datetime_local_to_timestamp($datetime);

            if ($timestamp === false) {
                wp_send_json_error(array('message' => __('Invalid date or time.', 'maca-restu-pro')), 400);
            }
        }

        wp_send_json_success($this->build_preview_payload((int) $timestamp));
    }

    /**
     * Build preview HTML and labels for a timestamp.
     *
     * @param int $timestamp Unix timestamp in site timezone context.
     * @return array<string, mixed>
     */
    private function build_preview_payload($timestamp) {
        if ($this->is_dish_preview_mode()) {
            return $this->build_dish_preview_payload($timestamp);
        }

        return maca_menulist_build_schedule_preview($timestamp);
    }

    /**
     * Build preview payload for online dish menus.
     *
     * @param int $timestamp Unix timestamp.
     * @return array<string, mixed>
     */
    private function build_dish_preview_payload($timestamp) {
        $mysql = maca_menulist_unix_to_site_mysql((int) $timestamp);

        return array(
            'website' => maca_menulist_capture_dish_menu_html('inline', (int) $timestamp),
            'qr' => maca_menulist_capture_dish_menu_html('qr', (int) $timestamp),
            'label' => maca_menulist_format_wp_datetime($mysql),
            'datetime_local' => maca_menulist_wp_timestamp_to_datetime_local((int) $timestamp),
            'schedule_mysql' => $mysql,
            'diagnostics' => $this->build_dish_category_diagnostics((int) $timestamp),
            'preview_mode' => 'dishes',
        );
    }

    /**
     * Explain dish category visibility for website vs QR at a preview moment.
     *
     * @param int $timestamp Unix timestamp.
     * @return array<string, mixed>
     */
    private function build_dish_category_diagnostics($timestamp) {
        $categories = maca_menulist_db_get_dish_categories(false);
        $exclusive_campaign_mode = maca_menulist_campaign_exclusive_mode_enabled();
        $campaigns_active = !empty(
            maca_menulist_get_grouped_campaigns(
                array(
                    'qr_schedule' => true,
                    'timestamp' => $timestamp,
                )
            )
        );

        $rows = array();

        foreach ($categories as $category) {
            $dishes = maca_menulist_db_get_dishes_by_category((int) $category->id, true);
            $website_reason = maca_menulist_explain_dish_category_visibility($category, $timestamp, false);
            $qr_reason = maca_menulist_explain_dish_category_visibility($category, $timestamp, true);

            if ($website_reason === 'visible' && empty($dishes)) {
                $website_reason = 'no_dishes';
            }

            if ($qr_reason === 'visible' && empty($dishes)) {
                $qr_reason = 'no_dishes';
            }

            if ($exclusive_campaign_mode && $campaigns_active) {
                if ($website_reason === 'visible') {
                    $website_reason = 'exclusive_campaign';
                }
                if ($qr_reason === 'visible') {
                    $qr_reason = 'exclusive_campaign';
                }
            }

            $rows[] = array(
                'id' => (int) $category->id,
                'name' => maca_menulist_get_dish_category_display_name($category),
                'website' => $website_reason,
                'website_label' => maca_menulist_dish_category_visibility_reason_label($website_reason),
                'qr' => $qr_reason,
                'qr_label' => maca_menulist_dish_category_visibility_reason_label($qr_reason),
            );
        }

        return array(
            'categories' => $rows,
            'exclusive_campaign_mode' => $exclusive_campaign_mode,
            'campaigns_active' => $campaigns_active,
        );
    }

    /**
     * Render category visibility diagnostics table.
     *
     * @param array<string, mixed> $diagnostics Diagnostics payload.
     * @return void
     */
    private function render_category_diagnostics($diagnostics) {
        if (empty($diagnostics['categories']) || !is_array($diagnostics['categories'])) {
            return;
        }

        $exclusive = !empty($diagnostics['exclusive_campaign_mode']);
        $campaigns_active = !empty($diagnostics['campaigns_active']);
        ?>
        <details class="maca-menu-preview-diagnostics" id="maca-menu-preview-diagnostics" open>
            <summary><?php esc_html_e('Category visibility at this time', 'maca-restu-pro'); ?></summary>
            <?php if ($exclusive && $campaigns_active) : ?>
                <p class="description maca-menu-preview-diagnostics-note">
                    <?php esc_html_e('Exclusive campaign mode is on and at least one campaign is active now, so regular categories are hidden on the guest menu.', 'maca-restu-pro'); ?>
                </p>
            <?php endif; ?>
            <table class="widefat striped maca-menu-preview-diagnostics-table">
                <thead>
                    <tr>
                        <th scope="col"><?php esc_html_e('Category', 'maca-restu-pro'); ?></th>
                        <th scope="col"><?php esc_html_e('Website menu', 'maca-restu-pro'); ?></th>
                        <th scope="col"><?php esc_html_e('QR menu', 'maca-restu-pro'); ?></th>
                    </tr>
                </thead>
                <tbody id="maca-menu-preview-diagnostics-body">
                    <?php foreach ($diagnostics['categories'] as $row) : ?>
                        <tr>
                            <td><?php echo esc_html($row['name']); ?></td>
                            <td>
                                <span class="maca-menu-preview-status maca-menu-preview-status--<?php echo esc_attr($row['website']); ?>">
                                    <?php echo esc_html($row['website_label']); ?>
                                </span>
                                <?php if (!empty($row['website_menu'])) : ?>
                                    <br><span class="maca-menu-preview-menu-ref"><?php echo esc_html($row['website_menu']); ?></span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="maca-menu-preview-status maca-menu-preview-status--<?php echo esc_attr($row['qr']); ?>">
                                    <?php echo esc_html($row['qr_label']); ?>
                                </span>
                                <?php if (!empty($row['qr_menu'])) : ?>
                                    <br><span class="maca-menu-preview-menu-ref"><?php echo esc_html($row['qr_menu']); ?></span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </details>
        <?php
    }

    /**
     * Render the admin preview page.
     */
    public function render_page() {
        if (!current_user_can(maca_menulist_admin_required_cap())) {
            wp_die(esc_html__('You do not have permission to access this page.', 'maca-restu-pro'));
        }

        $default_datetime = maca_menulist_wp_timestamp_to_datetime_local();
        $timestamp = maca_menulist_wp_datetime_local_to_timestamp($default_datetime);
        if ($timestamp === false) {
            $timestamp = current_time('timestamp');
            $default_datetime = maca_menulist_wp_timestamp_to_datetime_local($timestamp);
        }

        $preview = $this->build_preview_payload((int) $timestamp);
        $timezone = wp_timezone_string();
        $is_dish_mode = $this->is_dish_preview_mode();
        ?>
        <div class="wrap maca-menu-preview-page">
            <h1><?php esc_html_e('Menu preview', 'maca-restu-pro'); ?></h1>
            <p class="description">
                <?php
                if ($is_dish_mode) {
                    esc_html_e(
                        'Choose a date and time to see which dishes, categories, and campaigns appear on the website menu versus the QR menu at that moment.',
                        'maca-restu-pro'
                    );
                } else {
                    esc_html_e(
                        'Choose a date and time to see which categories and menus appear on the website versus the QR menu at that moment.',
                        'maca-restu-pro'
                    );
                }
                ?>
            </p>

            <div class="maca-menu-preview-controls">
                <label for="maca-menu-preview-datetime" class="maca-menu-preview-datetime-label">
                    <?php esc_html_e('Preview date and time', 'maca-restu-pro'); ?>
                </label>
                <div class="maca-menu-preview-datetime-row">
                    <input
                        type="datetime-local"
                        id="maca-menu-preview-datetime"
                        class="maca-menu-preview-datetime"
                        value="<?php echo esc_attr($default_datetime); ?>"
                        step="60"
                    >
                    <button type="button" class="button" id="maca-menu-preview-now">
                        <?php esc_html_e('Use current time', 'maca-restu-pro'); ?>
                    </button>
                    <button type="button" class="button button-primary" id="maca-menu-preview-update">
                        <?php esc_html_e('Update preview', 'maca-restu-pro'); ?>
                    </button>
                </div>
                <p class="description maca-menu-preview-timezone">
                    <?php
                    printf(
                        /* translators: %s: WordPress site timezone name */
                        esc_html__('Times use your site timezone (%s).', 'maca-restu-pro'),
                        esc_html($timezone !== '' ? $timezone : __('WordPress default', 'maca-restu-pro'))
                    );
                    ?>
                </p>
                <p class="maca-menu-preview-active-label" id="maca-menu-preview-active-label" aria-live="polite">
                    <?php
                    printf(
                        /* translators: %s: formatted datetime */
                        esc_html__('Showing menu as of %s.', 'maca-restu-pro'),
                        esc_html($preview['label'])
                    );
                    ?>
                </p>
            </div>

            <?php $this->render_category_diagnostics($preview['diagnostics']); ?>

            <div class="maca-menu-preview-grid" id="maca-menu-preview-grid">
                <section class="maca-menu-preview-panel" aria-labelledby="maca-menu-preview-qr-title">
                    <header class="maca-menu-preview-panel-header">
                        <h2 id="maca-menu-preview-qr-title"><?php esc_html_e('QR menu', 'maca-restu-pro'); ?></h2>
                        <p class="description">
                            <?php esc_html_e('Full schedule: start/end dates, weekdays, and daily serving times.', 'maca-restu-pro'); ?>
                        </p>
                    </header>
                    <div class="maca-menu-preview-frame maca-menu-preview-frame--qr" id="maca-menu-preview-qr" data-context="qr">
                        <?php echo $preview['qr']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped in helper. ?>
                    </div>
                </section>

                <section class="maca-menu-preview-panel" aria-labelledby="maca-menu-preview-website-title">
                    <header class="maca-menu-preview-panel-header">
                        <h2 id="maca-menu-preview-website-title"><?php esc_html_e('Website menu', 'maca-restu-pro'); ?></h2>
                        <p class="description">
                            <?php
                            if ($is_dish_mode) {
                                esc_html_e(
                                    'Active items within start/end dates. Weekdays and daily times are ignored.',
                                    'maca-restu-pro'
                                );
                            } else {
                                esc_html_e(
                                    'Categories within start/end dates. Guests can browse menus outside live hours; a serving-hours notice may appear.',
                                    'maca-restu-pro'
                                );
                            }
                            ?>
                        </p>
                    </header>
                    <div class="maca-menu-preview-frame" id="maca-menu-preview-website" data-context="website">
                        <?php echo $preview['website']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped in helper. ?>
                    </div>
                </section>
            </div>
        </div>
        <?php
    }
}
