<?php
/**
 * Admin UI for daily manager report settings, preview, and manual send.
 *
 * @package Maca_Menu_List
 */

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

require_once MACA_MENULIST_PLUGIN_DIR . 'includes/daily-report.php';

/**
 * Daily report admin screen.
 */
class Maca_MenuList_Admin_Daily_Report {

    /**
     * Constructor.
     */
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'), 16);
        add_action('admin_init', array($this, 'handle_actions'));
        add_action('admin_init', array($this, 'maybe_render_preview'));
    }

    /**
     * Register submenu page.
     *
     * @return void
     */
    public function add_admin_menu() {
        add_submenu_page(
            'maca-restu',
            __('Dagsrapport', 'maca-restu-pro'),
            __('Dagsrapport', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu-daily-report',
            array($this, 'render_page')
        );
    }

    /**
     * Handle save / send actions.
     *
     * @return void
     */
    public function handle_actions() {
        if (!is_admin() || !isset($_POST['maca_daily_report_action'])) {
            return;
        }

        if (!maca_menulist_user_can_manage_plugin() || !maca_menulist_daily_report_is_available()) {
            return;
        }

        check_admin_referer('maca_daily_report', 'maca_daily_report_nonce');

        $action = sanitize_key(wp_unslash($_POST['maca_daily_report_action']));

        if ($action === 'save') {
            $this->save_settings();
            return;
        }

        if ($action === 'send_test') {
            $this->send_test();
        }
    }

    /**
     * Save report email settings.
     *
     * @return void
     */
    private function save_settings() {
        // phpcs:disable WordPress.Security.NonceVerification.Missing
        $enabled = isset($_POST['maca_daily_report_enabled']) ? '1' : '0';
        $send_time = isset($_POST['maca_daily_report_send_time'])
            ? sanitize_text_field(wp_unslash($_POST['maca_daily_report_send_time']))
            : '22:00';
        $recipients = isset($_POST['maca_daily_report_recipients'])
            ? sanitize_textarea_field(wp_unslash($_POST['maca_daily_report_recipients']))
            : '';
        $date_mode = isset($_POST['maca_daily_report_date_mode'])
            ? sanitize_key(wp_unslash($_POST['maca_daily_report_date_mode']))
            : 'auto';
        // phpcs:enable WordPress.Security.NonceVerification.Missing

        if (!preg_match('/^\d{2}:\d{2}$/', $send_time)) {
            $send_time = '22:00';
        }

        if (!in_array($date_mode, array('auto', 'same_day', 'previous_day'), true)) {
            $date_mode = 'auto';
        }

        update_option('maca_menulist_daily_report_enabled', $enabled, false);
        update_option('maca_menulist_daily_report_send_time', $send_time, false);
        update_option('maca_menulist_daily_report_recipients', $recipients, false);
        update_option('maca_menulist_daily_report_date_mode', $date_mode, false);

        maca_menulist_daily_report_schedule_cron();

        add_settings_error(
            'maca_daily_report',
            'settings_saved',
            __('Dagsrapportinställningar sparade.', 'maca-restu-pro'),
            'updated'
        );
    }

    /**
     * Send a test report to configured recipients.
     *
     * @return void
     */
    private function send_test() {
        // phpcs:disable WordPress.Security.NonceVerification.Missing
        $date = isset($_POST['maca_daily_report_preview_date'])
            ? sanitize_text_field(wp_unslash($_POST['maca_daily_report_preview_date']))
            : maca_menulist_daily_report_resolve_report_date();
        // phpcs:enable WordPress.Security.NonceVerification.Missing

        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
            $date = wp_date('Y-m-d');
        }

        $result = maca_menulist_daily_report_send(
            $date,
            maca_menulist_daily_report_get_recipients(),
            true
        );

        if (is_wp_error($result)) {
            add_settings_error(
                'maca_daily_report',
                'send_failed',
                $result->get_error_message(),
                'error'
            );
            return;
        }

        add_settings_error(
            'maca_daily_report',
            'send_ok',
            __('Dagsrapporten skickades.', 'maca-restu-pro'),
            'updated'
        );
    }

    /**
     * Render HTML preview in browser.
     *
     * @return void
     */
    public function maybe_render_preview() {
        if (!isset($_GET['maca_daily_report_preview'])) {
            return;
        }

        if (!maca_menulist_user_can_manage_plugin() || !maca_menulist_daily_report_is_available()) {
            wp_die(esc_html__('Forbidden', 'maca-restu-pro'));
        }

        check_admin_referer('maca_daily_report_preview');

        $date = isset($_GET['date']) ? sanitize_text_field(wp_unslash($_GET['date'])) : wp_date('Y-m-d');
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
            $date = wp_date('Y-m-d');
        }

        $rendered = maca_menulist_daily_report_render($date);
        $html = $rendered['html'];

        header('Content-Type: text/html; charset=utf-8');
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- trusted HTML email template.
        echo $html;
        exit;
    }

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

        if (!maca_menulist_daily_report_is_available()) {
            echo maca_menulist_pro_locked_notice('daily_report'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            return;
        }

        $enabled = maca_menulist_daily_report_is_enabled();
        $send_time = maca_menulist_daily_report_get_send_time();
        $date_mode = maca_menulist_daily_report_get_date_mode();
        $recipients = get_option('maca_menulist_daily_report_recipients', '');
        if (!is_string($recipients) || trim($recipients) === '') {
            $recipients = (string) get_option('admin_email');
        }

        $preview_date = maca_menulist_daily_report_resolve_report_date();
        $preview_url = wp_nonce_url(
            add_query_arg(
                array(
                    'maca_daily_report_preview' => '1',
                    'date' => $preview_date,
                ),
                admin_url('admin.php')
            ),
            'maca_daily_report_preview'
        );

        $next_cron = wp_next_scheduled(MACA_MENULIST_DAILY_REPORT_CRON_HOOK);
        $last_run = (int) get_option('maca_menulist_daily_report_last_run', 0);
        $last_report_date = get_option('maca_menulist_daily_report_last_report_date', '');

        ?>
        <div class="wrap">
            <h1><?php esc_html_e('Dagsrapport', 'maca-restu-pro'); ?></h1>
            <p><?php esc_html_e('En sammanfattning av dagens verksamhet — omsättning, ordrar, betalningar, bokningar och topprätter — skickas som snygg HTML-e-post till vald mottagare.', 'maca-restu-pro'); ?></p>

            <?php settings_errors('maca_daily_report'); ?>

            <form method="post" action="">
                <?php wp_nonce_field('maca_daily_report', 'maca_daily_report_nonce'); ?>
                <input type="hidden" name="maca_daily_report_action" value="save">

                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row"><?php esc_html_e('Automatiskt utskick', 'maca-restu-pro'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="maca_daily_report_enabled" value="1" <?php checked($enabled); ?>>
                                <?php esc_html_e('Skicka dagsrapport automatiskt varje dag', 'maca-restu-pro'); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="maca_daily_report_send_time"><?php esc_html_e('Tidpunkt', 'maca-restu-pro'); ?></label></th>
                        <td>
                            <input type="time" id="maca_daily_report_send_time" name="maca_daily_report_send_time" value="<?php echo esc_attr($send_time); ?>">
                            <p class="description"><?php esc_html_e('Sajtens tidszon. T.ex. 22:00 efter service.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="maca_daily_report_date_mode"><?php esc_html_e('Rapporten avser', 'maca-restu-pro'); ?></label></th>
                        <td>
                            <select id="maca_daily_report_date_mode" name="maca_daily_report_date_mode">
                                <option value="auto" <?php selected($date_mode, 'auto'); ?>>
                                    <?php esc_html_e('Automatiskt (samma dag vid kvällstid, annars gårdagen)', 'maca-restu-pro'); ?>
                                </option>
                                <option value="same_day" <?php selected($date_mode, 'same_day'); ?>>
                                    <?php esc_html_e('Samma kalenderdag som utskicket', 'maca-restu-pro'); ?>
                                </option>
                                <option value="previous_day" <?php selected($date_mode, 'previous_day'); ?>>
                                    <?php esc_html_e('Föregående kalenderdag', 'maca-restu-pro'); ?>
                                </option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="maca_daily_report_recipients"><?php esc_html_e('Mottagare', 'maca-restu-pro'); ?></label></th>
                        <td>
                            <textarea id="maca_daily_report_recipients" name="maca_daily_report_recipients" rows="4" class="large-text code"><?php echo esc_textarea($recipients); ?></textarea>
                            <p class="description"><?php esc_html_e('En eller flera e-postadresser, separerade med komma, semikolon eller radbrytning.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                </table>

                <?php submit_button(__('Spara inställningar', 'maca-restu-pro')); ?>
            </form>

            <?php if ($next_cron) : ?>
                <p class="description">
                    <?php
                    printf(
                        /* translators: %s: formatted date/time */
                        esc_html__('Nästa schemalagda utskick: %s', 'maca-restu-pro'),
                        esc_html(wp_date(get_option('date_format') . ' ' . get_option('time_format'), $next_cron))
                    );
                    ?>
                </p>
            <?php endif; ?>

            <?php if ($last_run > 0) : ?>
                <p class="description">
                    <?php
                    printf(
                        /* translators: 1: date/time, 2: report date */
                        esc_html__('Senaste utskick: %1$s (rapport för %2$s)', 'maca-restu-pro'),
                        esc_html(wp_date(get_option('date_format') . ' ' . get_option('time_format'), $last_run)),
                        esc_html($last_report_date !== '' ? $last_report_date : '—')
                    );
                    ?>
                </p>
            <?php endif; ?>

            <hr>

            <h2><?php esc_html_e('Förhandsgranska och testa', 'maca-restu-pro'); ?></h2>
            <p>
                <a href="<?php echo esc_url($preview_url); ?>" class="button" target="_blank" rel="noopener noreferrer">
                    <?php esc_html_e('Förhandsgranska HTML-rapport', 'maca-restu-pro'); ?>
                </a>
            </p>

            <form method="post" action="" style="margin-top:12px;">
                <?php wp_nonce_field('maca_daily_report', 'maca_daily_report_nonce'); ?>
                <input type="hidden" name="maca_daily_report_action" value="send_test">
                <p>
                    <label for="maca_daily_report_preview_date"><?php esc_html_e('Datum för testutskick', 'maca-restu-pro'); ?></label><br>
                    <input type="date" id="maca_daily_report_preview_date" name="maca_daily_report_preview_date" value="<?php echo esc_attr($preview_date); ?>">
                </p>
                <?php submit_button(__('Skicka testrapport nu', 'maca-restu-pro'), 'secondary'); ?>
            </form>
        </div>
        <?php
    }
}

new Maca_MenuList_Admin_Daily_Report();
