<?php
/**
 * Admin: dish click and order statistics.
 *
 * @package Maca_Menu_List
 */

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

require_once MACA_MENULIST_PLUGIN_DIR . 'includes/db-dish-stats.php';

/**
 * Dish statistics admin screen.
 */
class Maca_MenuList_Admin_Dish_Stats {

    /**
     * Constructor.
     */
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'), 22);
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
    }

    /**
     * Register submenu in dish mode.
     */
    public function add_admin_menu() {
        if (!maca_menulist_is_dishes_mode()) {
            return;
        }

        add_submenu_page(
            null,
            __('Rättstatistik', 'maca-restu-pro'),
            __('Rättstatistik', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu-dish-stats',
            array($this, 'render_page')
        );
    }

    /**
     * @param string $hook Hook suffix.
     */
    public function enqueue_scripts($hook) {
        if ($hook !== 'maca-restu_page_maca-restu-dish-stats') {
            return;
        }

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

    /**
     * Parse filters from request.
     *
     * @return array{date_from: string, date_to: string, orderby: string}
     */
    private function get_filters_from_request() {
        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only filter UI.
        $date_from = isset($_GET['date_from']) ? sanitize_text_field(wp_unslash($_GET['date_from'])) : '';
        $date_to = isset($_GET['date_to']) ? sanitize_text_field(wp_unslash($_GET['date_to'])) : '';
        $preset = isset($_GET['preset']) ? sanitize_key(wp_unslash($_GET['preset'])) : '';
        $orderby = isset($_GET['orderby']) ? sanitize_key(wp_unslash($_GET['orderby'])) : 'clicks';
        // phpcs:enable WordPress.Security.NonceVerification.Recommended

        $today = wp_date('Y-m-d');

        if ($date_from === '' && $date_to === '' && $preset !== '') {
            switch ($preset) {
                case 'yesterday':
                    $yesterday = maca_menulist_wp_now_modify('-1 day');
                    $date_from = $yesterday;
                    $date_to = $yesterday;
                    break;
                case '7days':
                    $date_from = maca_menulist_wp_now_modify('-6 days');
                    $date_to = $today;
                    break;
                case '30days':
                    $date_from = maca_menulist_wp_now_modify('-29 days');
                    $date_to = $today;
                    break;
                case 'today':
                default:
                    $date_from = $today;
                    $date_to = $today;
                    break;
            }
        }

        $range = maca_menulist_normalize_stats_date_range($date_from, $date_to);

        $allowed_orderby = array('clicks', 'orders', 'revenue', 'title');
        if (!in_array($orderby, $allowed_orderby, true)) {
            $orderby = 'clicks';
        }

        return array(
            'date_from' => $range['date_from'],
            'date_to' => $range['date_to'],
            'period_label' => $range['label'],
            'orderby' => $orderby,
        );
    }

    /**
     * Build filtered admin URL.
     *
     * @param array<string, string> $extra Extra query args.
     * @return string
     */
    private function stats_url($extra = array()) {
        $filters = $this->get_filters_from_request();
        $args = array_merge(
            array(
                'page' => 'maca-restu-dish-stats',
                'date_from' => $filters['date_from'],
                'date_to' => $filters['date_to'],
                'orderby' => $filters['orderby'],
            ),
            $extra
        );

        return add_query_arg($args, admin_url('admin.php'));
    }

    /**
     * Render statistics page.
     */
    public function render_page() {
        if (!maca_menulist_user_can_manage_plugin()) {
            return;
        }

        $filters = $this->get_filters_from_request();
        $rows = maca_menulist_db_get_dish_statistics_rows(
            $filters['date_from'],
            $filters['date_to'],
            $filters['orderby']
        );
        $total_clicks = maca_menulist_db_count_dish_clicks_in_range($filters['date_from'], $filters['date_to']);
        $orders_enabled = maca_menulist_table_order_enabled();

        ?>
        <div class="wrap maca-dashboard-wrap maca-dish-stats-wrap">
            <h1><?php esc_html_e('Dish statistics', 'maca-restu-pro'); ?></h1>
            <p class="description">
                <?php
                echo esc_html(
                    sprintf(
                        /* translators: %s: formatted date range */
                        __('Guest clicks and orders for %s.', 'maca-restu-pro'),
                        $filters['period_label']
                    )
                );
                ?>
            </p>

            <form method="get" action="<?php echo esc_url(admin_url('admin.php')); ?>" class="maca-dashboard-history-form maca-dish-stats-filters">
                <input type="hidden" name="page" value="maca-restu-dish-stats">

                <div class="maca-dashboard-history-presets" role="group" aria-label="<?php esc_attr_e('Quick period', 'maca-restu-pro'); ?>">
                    <?php
                    $presets = array(
                        'today' => __('Today', 'maca-restu-pro'),
                        'yesterday' => __('Yesterday', 'maca-restu-pro'),
                        '7days' => __('Last 7 days', 'maca-restu-pro'),
                        '30days' => __('Last 30 days', 'maca-restu-pro'),
                    );
                    foreach ($presets as $key => $label) :
                        $url = add_query_arg(
                            array(
                                'page' => 'maca-restu-dish-stats',
                                'preset' => $key,
                                'orderby' => $filters['orderby'],
                            ),
                            admin_url('admin.php')
                        );
                        ?>
                        <a href="<?php echo esc_url($url); ?>" class="button"><?php echo esc_html($label); ?></a>
                    <?php endforeach; ?>
                </div>

                <div class="maca-dashboard-history-dates">
                    <label>
                        <?php esc_html_e('From', 'maca-restu-pro'); ?>
                        <input type="date" name="date_from" value="<?php echo esc_attr($filters['date_from']); ?>">
                    </label>
                    <label>
                        <?php esc_html_e('To', 'maca-restu-pro'); ?>
                        <input type="date" name="date_to" value="<?php echo esc_attr($filters['date_to']); ?>">
                    </label>
                    <label>
                        <?php esc_html_e('Sort by', 'maca-restu-pro'); ?>
                        <select name="orderby">
                            <option value="clicks" <?php selected($filters['orderby'], 'clicks'); ?>><?php esc_html_e('Clicks', 'maca-restu-pro'); ?></option>
                            <?php if ($orders_enabled) : ?>
                                <option value="orders" <?php selected($filters['orderby'], 'orders'); ?>><?php esc_html_e('Quantity ordered', 'maca-restu-pro'); ?></option>
                                <option value="revenue" <?php selected($filters['orderby'], 'revenue'); ?>><?php esc_html_e('Revenue', 'maca-restu-pro'); ?></option>
                            <?php endif; ?>
                            <option value="title" <?php selected($filters['orderby'], 'title'); ?>><?php esc_html_e('Name', 'maca-restu-pro'); ?></option>
                        </select>
                    </label>
                    <?php submit_button(__('Apply', 'maca-restu-pro'), 'secondary', '', false); ?>
                </div>
            </form>

            <div class="maca-dashboard-metrics maca-dish-stats-summary">
                <div class="maca-dashboard-metric">
                    <span class="maca-dashboard-metric-value"><?php echo esc_html((string) $total_clicks); ?></span>
                    <span class="maca-dashboard-metric-label"><?php esc_html_e('Total clicks', 'maca-restu-pro'); ?></span>
                </div>
                <div class="maca-dashboard-metric">
                    <span class="maca-dashboard-metric-value"><?php echo esc_html((string) count($rows)); ?></span>
                    <span class="maca-dashboard-metric-label"><?php esc_html_e('Dishes with activity', 'maca-restu-pro'); ?></span>
                </div>
            </div>

            <table class="widefat striped maca-dish-stats-table">
                <thead>
                    <tr>
                        <th scope="col"><?php esc_html_e('Dish', 'maca-restu-pro'); ?></th>
                        <th scope="col"><?php esc_html_e('Clicks', 'maca-restu-pro'); ?></th>
                        <?php if ($orders_enabled) : ?>
                            <th scope="col"><?php esc_html_e('Qty ordered', 'maca-restu-pro'); ?></th>
                            <th scope="col"><?php esc_html_e('Orders', 'maca-restu-pro'); ?></th>
                            <th scope="col"><?php esc_html_e('Revenue', 'maca-restu-pro'); ?></th>
                        <?php endif; ?>
                        <th scope="col"><?php esc_html_e('Status', 'maca-restu-pro'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($rows)) : ?>
                        <tr>
                            <td colspan="<?php echo $orders_enabled ? 6 : 3; ?>">
                                <?php esc_html_e('No dish activity recorded for this period yet. Clicks are tracked when guests tap a dish or enlarge its image.', 'maca-restu-pro'); ?>
                            </td>
                        </tr>
                    <?php else : ?>
                        <?php foreach ($rows as $row) : ?>
                            <tr>
                                <td>
                                    <a href="<?php echo esc_url($row['edit_url']); ?>"><strong><?php echo esc_html($row['title']); ?></strong></a>
                                </td>
                                <td><?php echo esc_html((string) $row['clicks']); ?></td>
                                <?php if ($orders_enabled) : ?>
                                    <td><?php echo esc_html((string) $row['qty_sold']); ?></td>
                                    <td><?php echo esc_html((string) $row['order_count']); ?></td>
                                    <td><?php echo esc_html($row['revenue_label']); ?></td>
                                <?php endif; ?>
                                <td>
                                    <?php
                                    echo $row['is_active']
                                        ? '<span class="status-active">' . esc_html__('Active', 'maca-restu-pro') . '</span>'
                                        : '<span class="status-inactive">' . esc_html__('Inactive', 'maca-restu-pro') . '</span>';
                                    ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>

            <p>
                <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-dashboard')); ?>" class="button">
                    <?php esc_html_e('Back to overview', 'maca-restu-pro'); ?>
                </a>
            </p>
        </div>
        <?php
    }
}
