<?php
/**
 * Public read-only management overview page (chef PIN).
 *
 * @package Maca_MenuList
 */

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

require_once MACA_MENULIST_PLUGIN_DIR . 'includes/management-overview.php';
require_once MACA_MENULIST_PLUGIN_DIR . 'includes/dashboard-data.php';
require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-dashboard.php';

/**
 * Front-end management overview (read-only).
 */
class Maca_MenuList_Public_Management_Overview {

    /**
     * @var Maca_MenuList_Admin_Dashboard|null
     */
    private $dashboard_renderer = null;

    /**
     * Constructor.
     */
    public function __construct() {
        add_action('template_redirect', array($this, 'handle_page'), 0);
        add_action('wp_ajax_maca_management_dashboard_refresh', array($this, 'ajax_refresh'));
        add_action('wp_ajax_nopriv_maca_management_dashboard_refresh', array($this, 'ajax_refresh'));
        add_action('wp_ajax_maca_management_dashboard_history', array($this, 'ajax_history'));
        add_action('wp_ajax_nopriv_maca_management_dashboard_history', array($this, 'ajax_history'));
    }

    /**
     * Dashboard renderer without admin hooks.
     *
     * @return Maca_MenuList_Admin_Dashboard
     */
    private function get_renderer() {
        if ($this->dashboard_renderer === null) {
            $this->dashboard_renderer = new Maca_MenuList_Admin_Dashboard(false);
        }

        return $this->dashboard_renderer;
    }

    /**
     * Verify PIN from AJAX request.
     *
     * @return bool
     */
    private function verify_ajax_pin() {
        $pin = isset($_POST['pin']) ? sanitize_text_field(wp_unslash($_POST['pin'])) : '';

        return maca_menulist_verify_management_overview_pin($pin);
    }

    /**
     * AJAX: refresh metrics (read-only payload).
     */
    public function ajax_refresh() {
        maca_menulist_ensure_dashboard_locale();

        check_ajax_referer('maca_management_dashboard', 'nonce');

        if (!maca_menulist_management_overview_enabled()) {
            wp_send_json_error(array('message' => __('Overview unavailable.', 'maca-restu-pro')), 403);
        }

        if (!$this->verify_ajax_pin()) {
            $feedback = maca_menulist_get_management_pin_attempt_feedback();
            $message = maca_menulist_is_management_pin_locked()
                ? __('PIN locked. Try again later.', 'maca-restu-pro')
                : __('Invalid PIN.', 'maca-restu-pro');
            wp_send_json_error(
                array(
                    'message' => $message,
                    'pin_feedback' => $feedback,
                ),
                403
            );
        }

        $date_from = isset($_POST['date_from']) ? sanitize_text_field(wp_unslash($_POST['date_from'])) : '';
        $date_to = isset($_POST['date_to']) ? sanitize_text_field(wp_unslash($_POST['date_to'])) : '';

        $payload = maca_menulist_get_dashboard_payload($date_from, $date_to);
        wp_send_json_success(maca_menulist_sanitize_dashboard_payload_readonly($payload));
    }

    /**
     * AJAX: load history for period (read-only).
     */
    public function ajax_history() {
        maca_menulist_ensure_dashboard_locale();

        check_ajax_referer('maca_management_dashboard', 'nonce');

        if (!maca_menulist_management_overview_enabled()) {
            wp_send_json_error(array('message' => __('Overview unavailable.', 'maca-restu-pro')), 403);
        }

        if (!$this->verify_ajax_pin()) {
            wp_send_json_error(array('message' => __('Invalid PIN.', 'maca-restu-pro')), 403);
        }

        $date_from = isset($_POST['date_from']) ? sanitize_text_field(wp_unslash($_POST['date_from'])) : '';
        $date_to = isset($_POST['date_to']) ? sanitize_text_field(wp_unslash($_POST['date_to'])) : '';

        $history = maca_menulist_get_dashboard_history($date_from, $date_to);
        wp_send_json_success(
            maca_menulist_sanitize_dashboard_payload_readonly(
                array('history' => $history)
            )['history']
        );
    }

    /**
     * Render public management overview page.
     */
    public function handle_page() {
        if (!maca_menulist_is_management_overview_request()) {
            return;
        }

        if (!maca_menulist_management_overview_enabled()) {
            status_header(404);
            nocache_headers();
            exit;
        }

        maca_menulist_ensure_dashboard_locale();

        if (function_exists('maca_menulist_legal_blocks_frontend') && maca_menulist_legal_blocks_frontend()) {
            maca_menulist_legal_render_blocked_page();
        }

        if (maca_menulist_get_management_overview_pin() === '') {
            status_header(200);
            wp_die(
                esc_html__('Management overview PIN is not configured. Set it under maca Restu → Settings → Restaurant.', 'maca-restu-pro'),
                esc_html__('Overview unavailable', 'maca-restu-pro'),
                array('response' => 200)
            );
        }

        $pin_feedback = maca_menulist_get_management_pin_attempt_feedback();
        $today = maca_menulist_dashboard_today_date();
        $initial = maca_menulist_sanitize_dashboard_payload_readonly(maca_menulist_get_dashboard_payload());

        status_header(200);
        nocache_headers();

        $title = __('Översikt', 'maca-restu-pro');
        $css_ver = MACA_MENULIST_VERSION;
        $plugin_url = MACA_MENULIST_PLUGIN_URL;

        // phpcs:disable WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet, WordPress.WP.EnqueuedResources.NonEnqueuedScript, WordPress.Security.EscapeOutput.OutputNotEscaped
        echo '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <title>' . esc_html($title) . '</title>
    <link rel="stylesheet" href="' . esc_url($plugin_url . 'assets/css/admin-dashboard.css?ver=' . $css_ver) . '">
    <link rel="stylesheet" href="' . esc_url($plugin_url . 'assets/css/management-overview-public.css?ver=' . $css_ver) . '">
</head>
<body class="maca-management-overview-page">
    <div id="maca-management-overview-app" class="maca-management-overview-app">
        <div id="maca-management-overview-pin" class="maca-management-overview-pin">
            <h1>' . esc_html($title) . '</h1>
            <p class="maca-management-overview-pin-desc">' . esc_html__('Enter the manager PIN to view live statistics (read-only).', 'maca-restu-pro') . '</p>
            <label for="maca-management-overview-pin-input">' . esc_html__('Manager PIN', 'maca-restu-pro') . '</label>
            <input type="password" id="maca-management-overview-pin-input" class="maca-management-overview-pin-input" inputmode="numeric" autocomplete="off" placeholder="' . esc_attr__('PIN', 'maca-restu-pro') . '">
            <p id="maca-management-overview-pin-info" class="maca-management-overview-pin-info">' . esc_html(
                $pin_feedback['is_locked']
                    ? sprintf(
                        /* translators: %d: lockout minutes remaining */
                        __('PIN locked. Try again in %d min.', 'maca-restu-pro'),
                        max(1, (int) ceil($pin_feedback['locked_seconds_remaining'] / 60))
                    )
                    : sprintf(
                        /* translators: 1: attempts left, 2: max attempts */
                        __('Attempts left: %1$d of %2$d', 'maca-restu-pro'),
                        (int) $pin_feedback['attempts_left'],
                        (int) $pin_feedback['max_attempts']
                    )
            ) . '</p>
            <button type="button" id="maca-management-overview-unlock" class="button button-primary maca-management-overview-unlock">' . esc_html__('Show overview', 'maca-restu-pro') . '</button>
            <p id="maca-management-overview-pin-error" class="maca-management-overview-pin-error" hidden></p>
        </div>
        <div id="maca-management-overview-dashboard" class="maca-management-overview-dashboard" hidden>';

        $this->get_renderer()->render_dashboard(true);

        echo '
        </div>
    </div>
    <script>
    window.macaMenulistManagementOverview = ' . wp_json_encode(
            array(
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('maca_management_dashboard'),
                'pollInterval' => 60000,
                'readonly' => true,
                'currency' => function_exists('maca_menulist_get_price_currency')
                    ? maca_menulist_get_price_currency()
                    : 'SEK',
                'today' => $today,
                'initial' => $initial,
                'pinFeedback' => $pin_feedback,
                'labels' => array(
                    'live' => __('Live', 'maca-restu-pro'),
                    'updating' => __('Uppdaterar…', 'maca-restu-pro'),
                    'updateError' => __('Kunde inte uppdatera data. Försöker igen…', 'maca-restu-pro'),
                    'lastUpdated' => __('Senast uppdaterad', 'maca-restu-pro'),
                    'noActions' => __('Inget behöver åtgärdas just nu.', 'maca-restu-pro'),
                    'historyTitle' => __('Historik', 'maca-restu-pro'),
                    'presetToday' => __('Idag', 'maca-restu-pro'),
                    'presetYesterday' => __('Igår', 'maca-restu-pro'),
                    'preset7days' => __('Senaste 7 dagarna', 'maca-restu-pro'),
                    'preset30days' => __('Senaste 30 dagarna', 'maca-restu-pro'),
                    'dateFrom' => __('Från', 'maca-restu-pro'),
                    'dateTo' => __('Till', 'maca-restu-pro'),
                    'applyPeriod' => __('Visa period', 'maca-restu-pro'),
                    'topDishes' => __('Topprätter (klick)', 'maca-restu-pro'),
                    'clicks' => __('klick', 'maca-restu-pro'),
                    'noDishStats' => __('Inga rättklick registrerade för perioden ännu.', 'maca-restu-pro'),
                    'periodOrders' => __('Ordrar i perioden', 'maca-restu-pro'),
                    'periodRevenue' => __('Intäkter i perioden', 'maca-restu-pro'),
                    'periodBookings' => __('Bokningar i perioden', 'maca-restu-pro'),
                    'periodPending' => __('väntande', 'maca-restu-pro'),
                    'totalClicks' => __('Totala klick', 'maca-restu-pro'),
                    'chartsTitle' => __('Diagram', 'maca-restu-pro'),
                    'noCharts' => __('Ingen diagramdata för perioden ännu. Prova ett längre intervall eller invänta gästaktivitet.', 'maca-restu-pro'),
                    'pinInvalid' => __('Invalid PIN.', 'maca-restu-pro'),
                    'pinLocked' => __('PIN locked. Try again later.', 'maca-restu-pro'),
                    /* translators: %d: minutes until PIN unlock */
                    'pinLockedMinutes' => __('PIN locked. Try again in %d min.', 'maca-restu-pro'),
                    /* translators: 1: remaining attempts, 2: max attempts */
                    'attemptsLeft' => __('Attempts left: %1$d of %2$d', 'maca-restu-pro'),
                ),
            )
        ) . ';
    (function () {
        var cfg = window.macaMenulistManagementOverview || {};
        window.macaMenulistDashboard = {
            ajaxUrl: cfg.ajaxUrl,
            nonce: cfg.nonce,
            pollInterval: cfg.pollInterval,
            readonly: true,
            refreshAction: "maca_management_dashboard_refresh",
            historyAction: "maca_management_dashboard_history",
            currency: cfg.currency,
            today: cfg.today,
            initial: cfg.initial,
            labels: cfg.labels,
            getPin: function () {
                try {
                    return window.sessionStorage.getItem("maca_menulist_management_pin") || "";
                } catch (e) {
                    return "";
                }
            }
        };
    })();
    </script>
    <script src="' . esc_url($plugin_url . 'assets/js/management-overview-public.js?ver=' . $css_ver) . '"></script>
    <script src="' . esc_url($plugin_url . 'assets/vendor/chartjs/chart.umd.min.js?ver=4.4.1') . '"></script>
    <script src="' . esc_url($plugin_url . 'assets/js/admin-dashboard-charts.js?ver=' . $css_ver) . '"></script>
    <script src="' . esc_url($plugin_url . 'assets/js/admin-dashboard.js?ver=' . $css_ver) . '"></script>
</body>
</html>';
        // phpcs:enable WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet, WordPress.WP.EnqueuedResources.NonEnqueuedScript, WordPress.Security.EscapeOutput.OutputNotEscaped
        exit;
    }
}
