<?php
/**
 * Admin UI for dish campaigns (kampanjmenyer).
 *
 * @package Maca_Menu_List
 */

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

class Maca_MenuList_Admin_Campaigns {

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

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

        add_submenu_page(
            'maca-restu',
            __('Kampanjmenyer', 'maca-restu-pro'),
            __('Kampanjmenyer', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu-campaigns',
            array($this, 'render_campaigns_page')
        );
    }

    /**
     * Handle campaign form submissions.
     */
    public function handle_form_submission() {
        if (!isset($_POST['maca_action'])) {
            return;
        }

        if (!isset($_POST['maca_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['maca_nonce'])), 'maca_save')) {
            return;
        }

        if (!maca_menulist_user_can_manage_plugin()) {
            return;
        }

        $type = isset($_POST['maca_type']) ? sanitize_text_field(wp_unslash($_POST['maca_type'])) : '';

        if ($type !== 'campaign') {
            return;
        }

        if (!maca_menulist_pro_has_feature('dishes')) {
            return;
        }

        $action = sanitize_text_field(wp_unslash($_POST['maca_action']));

        if ($action === 'add' || $action === 'edit') {
            $this->save_campaign();
        } elseif ($action === 'delete') {
            $this->delete_campaign();
        }
    }

    /**
     * Save campaign.
     */
    private function save_campaign() {
        // phpcs:disable WordPress.Security.NonceVerification.Missing
        $name = sanitize_text_field(wp_unslash($_POST['campaign_name'] ?? ''));
        $name_en = sanitize_text_field(wp_unslash($_POST['campaign_name_en'] ?? ''));
        $sort_order = isset($_POST['sort_order']) ? intval(wp_unslash($_POST['sort_order'])) : 0;
        $is_active = isset($_POST['campaign_is_active']) ? 1 : 0;
        $campaign_id = isset($_POST['campaign_id']) ? intval(wp_unslash($_POST['campaign_id'])) : 0;
        $dish_ids = isset($_POST['campaign_dishes']) ? array_map('intval', (array) wp_unslash($_POST['campaign_dishes'])) : array();
        $schedule = maca_menulist_parse_schedule_from_request();
        // phpcs:enable WordPress.Security.NonceVerification.Missing

        if (maca_menulist_admin_content_field_missing($name, $name_en)) {
            add_settings_error(
                'maca_campaign',
                'error',
                maca_menulist_admin_show_local_content_fields()
                    ? __('Kampanjnamn krävs på engelska eller lokalt språk.', 'maca-restu-pro')
                    : __('Kampanjnamn krävs.', 'maca-restu-pro')
            );
            return;
        }

        $row = array(
            'name' => $name,
            'name_en' => $name_en,
            'sort_order' => $sort_order,
            'is_active' => $is_active,
            'start_date' => $schedule['start_date'],
            'end_date' => $schedule['end_date'],
            'time_start' => $schedule['time_start'],
            'time_end' => $schedule['time_end'],
            'days_of_week' => $schedule['days_of_week'],
        );

        if ($campaign_id > 0) {
            $result = maca_menulist_db_update_campaign($campaign_id, $row);
            $saved_campaign_id = $campaign_id;
        } else {
            $result = maca_menulist_db_insert_campaign($row);
            global $wpdb;
            $saved_campaign_id = (int) $wpdb->insert_id;
        }

        if ($result === false) {
            add_settings_error('maca_campaign', 'error', __('Kunde inte spara kampanjen.', 'maca-restu-pro'));
            return;
        }

        if ($saved_campaign_id > 0) {
            $existing_dishes = maca_menulist_db_get_dishes_for_campaign($saved_campaign_id, false);
            foreach ($existing_dishes as $dish) {
                $dish_id = (int) $dish->id;
                $dish_campaign_ids = maca_menulist_db_get_dish_campaign_ids($dish_id);
                $dish_campaign_ids = array_values(array_diff($dish_campaign_ids, array($saved_campaign_id)));
                maca_menulist_db_set_dish_campaigns($dish_id, $dish_campaign_ids);
            }

            $dish_ids = array_values(array_unique(array_filter(array_map('intval', $dish_ids))));
            foreach ($dish_ids as $dish_id) {
                if ($dish_id <= 0) {
                    continue;
                }

                $dish_campaign_ids = maca_menulist_db_get_dish_campaign_ids($dish_id);
                $dish_campaign_ids[] = $saved_campaign_id;
                maca_menulist_db_set_dish_campaigns($dish_id, array_values(array_unique($dish_campaign_ids)));
            }
        }

        add_settings_error('maca_campaign', 'success', __('Kampanjen sparades.', 'maca-restu-pro'), 'updated');
        do_action('maca_menulist_site_chat_content_changed');
    }

    /**
     * Delete campaign.
     */
    private function delete_campaign() {
        // phpcs:disable WordPress.Security.NonceVerification.Missing
        $campaign_id = isset($_POST['campaign_id']) ? intval(wp_unslash($_POST['campaign_id'])) : 0;
        // phpcs:enable WordPress.Security.NonceVerification.Missing

        if ($campaign_id <= 0) {
            return;
        }

        maca_menulist_db_delete_campaign($campaign_id);
        add_settings_error('maca_campaign', 'success', __('Kampanjen togs bort.', 'maca-restu-pro'), 'updated');
        do_action('maca_menulist_site_chat_content_changed');
    }

    /**
     * Render campaigns page.
     */
    public function render_campaigns_page() {
        if (!maca_menulist_pro_has_feature('dishes')) {
            ?>
            <div class="wrap">
                <h1><?php esc_html_e('Kampanjmenyer', 'maca-restu-pro'); ?></h1>
                <?php echo wp_kses_post(maca_menulist_pro_locked_notice('dishes')); ?>
            </div>
            <?php
            return;
        }

        // phpcs:disable WordPress.Security.NonceVerification.Recommended
        $action = isset($_GET['action']) ? sanitize_text_field(wp_unslash($_GET['action'])) : 'list';
        $campaign_id = isset($_GET['campaign_id']) ? intval($_GET['campaign_id']) : 0;
        // phpcs:enable WordPress.Security.NonceVerification.Recommended

        ?>
        <div class="wrap">
            <h1><?php esc_html_e('Kampanjmenyer', 'maca-restu-pro'); ?></h1>
            <p class="description"><?php esc_html_e('Skapa tidsstyrda kampanjer som Quizkväll eller Sommarmeny. Ställ in schema och välj vilka rätter som ingår.', 'maca-restu-pro'); ?></p>

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

            <?php if ($action === 'add' || $action === 'edit') : ?>
                <?php $this->render_campaign_form($action, $campaign_id); ?>
            <?php else : ?>
                <?php $this->render_campaigns_list(); ?>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Render campaign form.
     *
     * @param string $action      Action type.
     * @param int    $campaign_id Campaign ID.
     */
    private function render_campaign_form($action, $campaign_id) {
        $campaign = null;
        if ($action === 'edit' && $campaign_id > 0) {
            $campaign = maca_menulist_db_get_campaign($campaign_id);
        }

        $name = $campaign ? $campaign->name : '';
        $name_en = ($campaign && isset($campaign->name_en)) ? $campaign->name_en : '';
        $sort_order = $campaign ? $campaign->sort_order : 0;
        $is_active = $campaign ? (int) $campaign->is_active : 1;
        $start_date = $campaign ? maca_menulist_format_datetime_local_value($campaign->start_date) : '';
        $end_date = $campaign ? maca_menulist_format_datetime_local_value($campaign->end_date) : '';
        $time_start = ($campaign && !empty($campaign->time_start)) ? substr($campaign->time_start, 0, 5) : '';
        $time_end = ($campaign && !empty($campaign->time_end)) ? substr($campaign->time_end, 0, 5) : '';
        $selected_days = $campaign ? maca_menulist_parse_days_of_week($campaign->days_of_week ?? '') : array();
        $weekday_labels = maca_menulist_weekday_labels_ordered();
        $all_dishes = maca_menulist_db_get_dishes(false);
        $selected_dish_ids = ($campaign_id > 0) ? array_map('intval', wp_list_pluck(maca_menulist_db_get_dishes_for_campaign($campaign_id, false), 'id')) : array();

        ?>
        <h2><?php echo esc_html($action === 'add' ? __('Lägg till kampanj', 'maca-restu-pro') : __('Redigera kampanj', 'maca-restu-pro')); ?></h2>
        <?php if ($campaign_id > 0) : ?>
            <?php
            $campaign_print_url = wp_nonce_url(
                admin_url('admin.php?page=maca-restu-dishes&maca_menu_print=1&campaign_id=' . (int) $campaign_id),
                'maca_menu_print'
            );
            ?>
            <p>
                <a href="<?php echo esc_url($campaign_print_url); ?>" class="button">
                    <?php esc_html_e('Skriv ut kampanjmeny', 'maca-restu-pro'); ?>
                </a>
            </p>
        <?php endif; ?>
        <?php
        $campaign_nav = array(
            'action' => $action,
            'current_id' => $campaign_id,
            'records' => maca_menulist_db_get_campaigns(),
            'list_url' => admin_url('admin.php?page=maca-restu-campaigns'),
            'edit_page' => 'maca-restu-campaigns',
            'edit_id_param' => 'campaign_id',
        );
        maca_menulist_render_admin_record_navigation($campaign_nav);
        ?>

        <form method="post" action="" class="maca-admin-record-form">
            <?php wp_nonce_field('maca_save', 'maca_nonce'); ?>
            <input type="hidden" name="maca_action" value="<?php echo esc_attr($action); ?>">
            <input type="hidden" name="maca_type" value="campaign">
            <input type="hidden" name="campaign_id" value="<?php echo esc_attr($campaign_id); ?>">

            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="campaign_name"><?php echo esc_html(maca_menulist_admin_primary_field_label(__('Name', 'maca-restu-pro'))); ?></label>
                    </th>
                    <td>
                        <input type="text" id="campaign_name" name="campaign_name" value="<?php echo esc_attr($name); ?>" class="regular-text">
                        <p class="description"><?php esc_html_e('T.ex. Quizkväll, Sommarmeny, Happy hour', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>
                <?php if (maca_menulist_admin_show_local_content_fields()) : ?>
                <tr>
                    <th scope="row">
                        <label for="campaign_name_en"><?php echo esc_html(maca_menulist_bilingual_field_label(__('Name', 'maca-restu-pro'), true)); ?></label>
                    </th>
                    <td>
                        <input type="text" id="campaign_name_en" name="campaign_name_en" value="<?php echo esc_attr($name_en); ?>" class="regular-text">
                    </td>
                </tr>
                <?php endif; ?>
                <tr>
                    <th scope="row">
                        <label for="sort_order"><?php esc_html_e('Sortering', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="number" id="sort_order" name="sort_order" value="<?php echo esc_attr($sort_order); ?>" class="small-text" min="0">
                        <p class="description"><?php esc_html_e('Lägre nummer visas först. Kampanjer visas ovanför vanliga menykategorier.', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label><?php esc_html_e('Schema', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <p class="description" style="margin-top:0;">
                            <?php esc_html_e('När kampanjen ska vara synlig i menyn och QR-menyn. Utanför tiderna döljs kampanjen.', 'maca-restu-pro'); ?>
                        </p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="campaign_start_date"><?php esc_html_e('Startdatum', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="datetime-local" id="campaign_start_date" name="start_date" value="<?php echo esc_attr($start_date); ?>">
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="campaign_end_date"><?php esc_html_e('Slutdatum', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="datetime-local" id="campaign_end_date" name="end_date" value="<?php echo esc_attr($end_date); ?>">
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label><?php esc_html_e('Veckodagar', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><?php esc_html_e('Veckodagar', 'maca-restu-pro'); ?></legend>
                            <?php foreach ($weekday_labels as $day_num => $day_label) : ?>
                                <label style="display:inline-block;margin-right:12px;margin-bottom:6px;">
                                    <input type="checkbox" name="days_of_week[]" value="<?php echo esc_attr($day_num); ?>" <?php checked(in_array($day_num, $selected_days, true)); ?>>
                                    <?php echo esc_html($day_label); ?>
                                </label>
                            <?php endforeach; ?>
                        </fieldset>
                        <p class="description"><?php esc_html_e('Lämna alla omarkerade för alla dagar.', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="campaign_time_start"><?php esc_html_e('Daglig starttid', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="time" id="campaign_time_start" name="time_start" value="<?php echo esc_attr($time_start); ?>">
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="campaign_time_end"><?php esc_html_e('Daglig sluttid', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="time" id="campaign_time_end" name="time_end" value="<?php echo esc_attr($time_end); ?>">
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="campaign_is_active"><?php esc_html_e('Aktiv', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="checkbox" id="campaign_is_active" name="campaign_is_active" value="1" <?php checked($is_active, 1); ?>>
                        <label for="campaign_is_active"><?php esc_html_e('Aktivera kampanj', 'maca-restu-pro'); ?></label>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Rätter i kampanjen', 'maca-restu-pro'); ?></th>
                    <td>
                        <?php if (empty($all_dishes)) : ?>
                            <p class="description">
                                <?php esc_html_e('Inga rätter finns ännu.', 'maca-restu-pro'); ?>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-dishes&action=add')); ?>"><?php esc_html_e('Lägg till rätter först', 'maca-restu-pro'); ?></a>
                            </p>
                        <?php else : ?>
                            <fieldset class="maca-campaign-dish-checkboxes">
                                <legend class="screen-reader-text"><?php esc_html_e('Rätter i kampanjen', 'maca-restu-pro'); ?></legend>
                                <?php foreach ($all_dishes as $dish) : ?>
                                    <label style="display:block;margin-bottom:6px;">
                                        <input type="checkbox" name="campaign_dishes[]" value="<?php echo esc_attr($dish->id); ?>" <?php checked(in_array((int) $dish->id, $selected_dish_ids, true)); ?>>
                                        <?php
                                        echo esc_html(
                                            maca_menulist_get_admin_content_label(
                                                isset($dish->title) ? $dish->title : '',
                                                isset($dish->title_en) ? $dish->title_en : ''
                                            )
                                            . ' - '
                                            . (isset($dish->category_name) ? $dish->category_name : '')
                                        );
                                        ?>
                                    </label>
                                <?php endforeach; ?>
                            </fieldset>
                            <p class="description"><?php esc_html_e('Markerade rätter visas i kampanjen när schemat är aktivt.', 'maca-restu-pro'); ?></p>
                        <?php endif; ?>
                    </td>
                </tr>
            </table>

            <?php submit_button($action === 'add' ? __('Lägg till kampanj', 'maca-restu-pro') : __('Uppdatera kampanj', 'maca-restu-pro')); ?>
            <?php maca_menulist_render_admin_record_navigation(array_merge($campaign_nav, array('modifier' => 'bottom'))); ?>
        </form>
        <?php
    }

    /**
     * Render campaigns list.
     */
    private function render_campaigns_list() {
        $campaigns = maca_menulist_db_get_campaigns();

        ?>
        <p>
            <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-campaigns&action=add')); ?>" class="button button-primary">
                <?php esc_html_e('Lägg till kampanj', 'maca-restu-pro'); ?>
            </a>
        </p>

        <?php if (empty($campaigns)) : ?>
            <p><?php esc_html_e('Inga kampanjer ännu. Skapa en kampanj för att visa en tidsstyrd del av menyn.', 'maca-restu-pro'); ?></p>
        <?php else : ?>
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th><?php esc_html_e('Name', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Rätter', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Schema', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Status', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Åtgärder', 'maca-restu-pro'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($campaigns as $campaign) : ?>
                        <?php
                        $dish_count = count(maca_menulist_db_get_dishes_for_campaign((int) $campaign->id, false));
                        $status = maca_menulist_get_campaign_status($campaign);
                        $campaign_print_url = wp_nonce_url(
                            admin_url('admin.php?page=maca-restu-dishes&maca_menu_print=1&campaign_id=' . (int) $campaign->id),
                            'maca_menu_print'
                        );
                        $status_labels = array(
                            'active' => __('Aktiv nu', 'maca-restu-pro'),
                            'inactive' => __('Inaktiv', 'maca-restu-pro'),
                            'scheduled' => __('Schemalagd', 'maca-restu-pro'),
                            'expired' => __('Utgången', 'maca-restu-pro'),
                            'outside_hours' => __('Utanför tid', 'maca-restu-pro'),
                        );
                        ?>
                        <tr>
                            <td><strong><?php echo esc_html(maca_menulist_get_campaign_admin_label($campaign)); ?></strong></td>
                            <td><?php echo esc_html((string) $dish_count); ?></td>
                            <td><small><?php echo esc_html(maca_menulist_format_schedule_summary($campaign)); ?></small></td>
                            <td><?php echo esc_html(isset($status_labels[$status]) ? $status_labels[$status] : $status); ?></td>
                            <td>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-campaigns&action=edit&campaign_id=' . $campaign->id)); ?>" class="button button-small">
                                    <?php esc_html_e('Redigera', 'maca-restu-pro'); ?>
                                </a>
                                <a href="<?php echo esc_url($campaign_print_url); ?>" class="button button-small">
                                    <?php esc_html_e('Skriv ut', 'maca-restu-pro'); ?>
                                </a>
                                <form method="post" action="" style="display: inline;">
                                    <?php wp_nonce_field('maca_save', 'maca_nonce'); ?>
                                    <input type="hidden" name="maca_action" value="delete">
                                    <input type="hidden" name="maca_type" value="campaign">
                                    <input type="hidden" name="campaign_id" value="<?php echo esc_attr($campaign->id); ?>">
                                    <button type="submit" class="button button-small" onclick="return confirm('<?php echo esc_js(__('Är du säker? Rätter kopplas bort från kampanjen.', 'maca-restu-pro')); ?>');">
                                        <?php esc_html_e('Ta bort', 'maca-restu-pro'); ?>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
        <?php
    }
}
