<?php
/**
 * Table Reservation settings (admin UI + save).
 *
 * @package Maca_MenuList
 */

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

/**
 * Render table reservation settings tab on the bookings admin page.
 */
function maca_menulist_render_table_booking_settings_tab() {
    $table_booking = get_option('maca_menulist_table_booking', '0') === '1';
    $table_booking_slot_duration = maca_menulist_table_booking_slot_duration();
    $table_booking_hold_minutes = maca_menulist_get_table_booking_hold_minutes();
    $table_booking_arrival_notice = get_option('maca_menulist_table_booking_arrival_notice', '');
    $table_booking_arrival_notice_en = get_option('maca_menulist_table_booking_arrival_notice_en', '');
    $table_booking_advance_days = maca_menulist_table_booking_advance_days();
    $table_booking_assignment_mode = maca_menulist_get_table_booking_assignment_mode();
    $table_booking_guest_cancel = get_option('maca_menulist_table_booking_guest_cancel', '1') === '1';
    $table_booking_cancel_slug = maca_menulist_get_table_booking_cancel_slug();
    $table_booking_captcha_provider = maca_menulist_get_table_booking_captcha_provider();
    $table_booking_captcha_site_key = maca_menulist_get_table_booking_captcha_site_key();
    $table_booking_captcha_secret_key_set = maca_menulist_get_table_booking_captcha_secret_key() !== '';
    $table_booking_captcha_v3_score = maca_menulist_get_table_booking_captcha_v3_score();
    $table_booking_button_text = get_option('maca_menulist_table_booking_button_text', '');
    $table_booking_button_text_en = get_option('maca_menulist_table_booking_button_text_en', '');
    $table_booking_title_text = get_option('maca_menulist_table_booking_title_text', '');
    $table_booking_title_text_en = get_option('maca_menulist_table_booking_title_text_en', '');
    $table_booking_notification_email = get_option('maca_menulist_table_booking_notification_email', '');
    $table_booking_waitlist = get_option('maca_menulist_table_booking_waitlist', '1') === '1';
    $table_bookings_pro_active = maca_menulist_pro_has_feature('table_bookings');
    ?>
    <form method="post" class="maca-table-booking-settings-form">
        <?php wp_nonce_field('maca_bookings', 'maca_bookings_nonce'); ?>
        <input type="hidden" name="maca_bookings_action" value="save_booking_settings">

        <table class="form-table" role="presentation">
            <?php if ($table_bookings_pro_active) : ?>
            <tr>
                <th scope="row">
                    <label for="maca_table_booking_button_text"><?php echo esc_html(maca_menulist_admin_primary_field_label(__('Booking button text', 'maca-restu-pro'))); ?></label>
                </th>
                <td>
                    <input type="text" id="maca_table_booking_button_text" name="maca_table_booking_button_text" value="<?php echo esc_attr($table_booking_button_text); ?>" class="regular-text" placeholder="<?php echo esc_attr(maca_menulist_get_table_booking_button_default_label()); ?>">
                    <p class="description"><?php esc_html_e('Text on the button that opens the booking form. Follows the guest’s menu language (local or English).', 'maca-restu-pro'); ?></p>
                </td>
            </tr>
            <?php if (maca_menulist_admin_show_local_content_fields()) : ?>
            <tr>
                <th scope="row">
                    <label for="maca_table_booking_button_text_en"><?php echo esc_html(maca_menulist_bilingual_field_label(__('Booking button text', 'maca-restu-pro'), true)); ?></label>
                </th>
                <td>
                    <input type="text" id="maca_table_booking_button_text_en" name="maca_table_booking_button_text_en" value="<?php echo esc_attr($table_booking_button_text_en); ?>" class="regular-text" placeholder="<?php echo esc_attr__('Book a table', 'maca-restu-pro'); ?>">
                </td>
            </tr>
            <?php endif; ?>
            <tr>
                <th scope="row">
                    <label for="maca_table_booking_title_text"><?php echo esc_html(maca_menulist_admin_primary_field_label(__('Booking form title', 'maca-restu-pro'))); ?></label>
                </th>
                <td>
                    <input type="text" id="maca_table_booking_title_text" name="maca_table_booking_title_text" value="<?php echo esc_attr($table_booking_title_text); ?>" class="regular-text" placeholder="<?php echo esc_attr(maca_menulist_get_table_booking_title_default_label()); ?>">
                    <p class="description"><?php esc_html_e('Heading inside the booking popup.', 'maca-restu-pro'); ?></p>
                </td>
            </tr>
            <?php if (maca_menulist_admin_show_local_content_fields()) : ?>
            <tr>
                <th scope="row">
                    <label for="maca_table_booking_title_text_en"><?php echo esc_html(maca_menulist_bilingual_field_label(__('Booking form title', 'maca-restu-pro'), true)); ?></label>
                </th>
                <td>
                    <input type="text" id="maca_table_booking_title_text_en" name="maca_table_booking_title_text_en" value="<?php echo esc_attr($table_booking_title_text_en); ?>" class="regular-text" placeholder="<?php echo esc_attr__('Table Reservation', 'maca-restu-pro'); ?>">
                </td>
            </tr>
            <?php endif; ?>
            <?php endif; ?>
            <tr>
                <th scope="row">
                    <label for="maca_table_booking"><?php esc_html_e('Table Reservation', 'maca-restu-pro'); ?></label>
                </th>
                <td>
                    <?php if (!$table_bookings_pro_active) : ?>
                        <?php echo wp_kses_post(maca_menulist_pro_locked_notice('table_bookings')); ?>
                    <?php else : ?>
                        <input type="checkbox" id="maca_table_booking" name="maca_table_booking" value="1" <?php checked($table_booking); ?>>
                        <label for="maca_table_booking"><?php esc_html_e('Enable table reservation on the website (shortcode or block)', 'maca-restu-pro'); ?></label>
                        <p class="description">
                            <?php esc_html_e('Shortcode:', 'maca-restu-pro'); ?> <code>[maca_table_booking]</code>
                            <?php esc_html_e('Optional override:', 'maca-restu-pro'); ?> <code>[maca_table_booking button="Reserve now"]</code>.
                            <?php esc_html_e('Configure tables under the Tables tab here. Weekly opening hours and date exceptions are under maca Restu → Settings → Opening hours and Exceptions.', 'maca-restu-pro'); ?>
                        </p>
                        <p style="margin-top:10px;">
                            <label for="maca_table_booking_slot_duration"><strong><?php esc_html_e('Booking duration (minutes)', 'maca-restu-pro'); ?></strong></label><br>
                            <input type="number" id="maca_table_booking_slot_duration" name="maca_table_booking_slot_duration" min="30" max="480" step="30" value="<?php echo esc_attr((string) $table_booking_slot_duration); ?>" class="small-text">
                        </p>
                        <p>
                            <label for="maca_table_booking_advance_days"><strong><?php esc_html_e('Book ahead (days)', 'maca-restu-pro'); ?></strong></label><br>
                            <input type="number" id="maca_table_booking_advance_days" name="maca_table_booking_advance_days" min="1" max="365" value="<?php echo esc_attr((string) $table_booking_advance_days); ?>" class="small-text">
                        </p>
                        <p>
                            <label for="maca_table_booking_hold_minutes"><strong><?php esc_html_e('Table hold after booked time (minutes)', 'maca-restu-pro'); ?></strong></label><br>
                            <input type="number" id="maca_table_booking_hold_minutes" name="maca_table_booking_hold_minutes" min="0" max="120" value="<?php echo esc_attr((string) $table_booking_hold_minutes); ?>" class="small-text">
                            <span class="description"><?php esc_html_e('Shown in the booking confirmation email to the guest (not waitlist). Use 0 to hide the message.', 'maca-restu-pro'); ?></span>
                        </p>
                        <p>
                            <label for="maca_table_booking_arrival_notice"><strong><?php echo esc_html(maca_menulist_admin_primary_field_label(__('Arrival notice text', 'maca-restu-pro'))); ?></strong></label><br>
                            <textarea id="maca_table_booking_arrival_notice" name="maca_table_booking_arrival_notice" rows="2" class="large-text" placeholder="<?php echo esc_attr('Bordet kommer att reserveras upp till %d minuter efter den tid och bokningsdag du valt. Vi uppskattar att du kommer i tid.'); ?>"><?php echo esc_textarea($table_booking_arrival_notice); ?></textarea>
                            <span class="description"><?php
                            /* translators: %d: placeholder for hold minutes in the notice text */
                            esc_html_e('Optional. Use %d for hold minutes. Leave empty for the default Swedish text.', 'maca-restu-pro');
                            ?></span>
                        </p>
                        <p>
                            <label for="maca_table_booking_arrival_notice_en"><strong><?php echo esc_html(maca_menulist_bilingual_field_label(__('Arrival notice text', 'maca-restu-pro'), true)); ?></strong></label><br>
                            <textarea id="maca_table_booking_arrival_notice_en" name="maca_table_booking_arrival_notice_en" rows="2" class="large-text" placeholder="<?php echo esc_attr('The table will be reserved for up to %d minutes after the date and time you selected. We appreciate you arriving on time.'); ?>"><?php echo esc_textarea($table_booking_arrival_notice_en); ?></textarea>
                            <span class="description"><?php
                            /* translators: %d: placeholder for hold minutes in the notice text */
                            esc_html_e('Optional. Use %d for hold minutes. Leave empty for the default English text.', 'maca-restu-pro');
                            ?></span>
                        </p>
                        <p style="margin-top:14px;">
                            <label for="maca_table_booking_notification_email"><strong><?php esc_html_e('Booking email address', 'maca-restu-pro'); ?></strong></label><br>
                            <input type="email" id="maca_table_booking_notification_email" name="maca_table_booking_notification_email" value="<?php echo esc_attr($table_booking_notification_email); ?>" class="regular-text" placeholder="bokning@example.com">
                        </p>
                        <p class="description">
                            <?php esc_html_e('All guest booking notifications are sent to this address, and outgoing booking emails to guests use it as the sender (From). Delivery uses your WordPress mail setup (e.g. SMTP plugin). If empty, the email under maca Restu → Settings → Restaurant is used.', 'maca-restu-pro'); ?>
                        </p>
                        <fieldset style="margin-top:14px;">
                            <legend><strong><?php esc_html_e('Table assignment', 'maca-restu-pro'); ?></strong></legend>
                            <p>
                                <label>
                                    <input type="radio" name="maca_table_booking_assignment_mode" value="standard" <?php checked($table_booking_assignment_mode, 'standard'); ?>>
                                    <?php esc_html_e('Standard — guest chooses from available tables', 'maca-restu-pro'); ?>
                                </label>
                            </p>
                            <p>
                                <label>
                                    <input type="radio" name="maca_table_booking_assignment_mode" value="best_fit" <?php checked($table_booking_assignment_mode, 'best_fit'); ?>>
                                    <?php esc_html_e('Best-fit — assign smallest available table automatically', 'maca-restu-pro'); ?>
                                </label>
                            </p>
                            <p class="description"><?php esc_html_e('Best-fit also hides booking times with no free suitable table.', 'maca-restu-pro'); ?></p>
                        </fieldset>
                        <fieldset style="margin-top:14px;">
                            <legend><strong><?php esc_html_e('Waitlist', 'maca-restu-pro'); ?></strong></legend>
                            <label>
                                <input type="checkbox" name="maca_table_booking_waitlist" value="1" <?php checked($table_booking_waitlist); ?>>
                                <?php esc_html_e('Allow waitlist sign-ups on the website and in admin (email notification; no table until confirmed)', 'maca-restu-pro'); ?>
                            </label>
                        </fieldset>
                        <fieldset style="margin-top:14px;">
                            <legend><strong><?php esc_html_e('Guest cancellation', 'maca-restu-pro'); ?></strong></legend>
                            <label>
                                <input type="checkbox" name="maca_table_booking_guest_cancel" value="1" <?php checked($table_booking_guest_cancel); ?>>
                                <?php esc_html_e('Allow guests to cancel via link in booking emails', 'maca-restu-pro'); ?>
                            </label>
                            <p style="margin:8px 0 0;">
                                <label for="maca_table_booking_cancel_slug"><strong><?php esc_html_e('Cancellation page slug', 'maca-restu-pro'); ?></strong></label><br>
                                <input type="text" id="maca_table_booking_cancel_slug" name="maca_table_booking_cancel_slug" value="<?php echo esc_attr($table_booking_cancel_slug); ?>" class="regular-text">
                                <span class="description"><?php esc_html_e('Example URL:', 'maca-restu-pro'); ?> <code><?php echo esc_html(home_url('/' . $table_booking_cancel_slug . '/')); ?></code></span>
                            </p>
                        </fieldset>
                        <fieldset style="margin-top:14px;">
                            <legend><strong><?php esc_html_e('Security check (CAPTCHA)', 'maca-restu-pro'); ?></strong></legend>
                            <p>
                                <label for="maca_table_booking_captcha_provider"><strong><?php esc_html_e('Provider', 'maca-restu-pro'); ?></strong></label><br>
                                <select id="maca_table_booking_captcha_provider" name="maca_table_booking_captcha_provider">
                                    <option value="none" <?php selected($table_booking_captcha_provider, 'none'); ?>><?php esc_html_e('None', 'maca-restu-pro'); ?></option>
                                    <option value="recaptcha_v2" <?php selected($table_booking_captcha_provider, 'recaptcha_v2'); ?>><?php esc_html_e('Google reCAPTCHA v2 (checkbox)', 'maca-restu-pro'); ?></option>
                                    <option value="recaptcha_v3" <?php selected($table_booking_captcha_provider, 'recaptcha_v3'); ?>><?php esc_html_e('Google reCAPTCHA v3 (invisible)', 'maca-restu-pro'); ?></option>
                                    <option value="turnstile" <?php selected($table_booking_captcha_provider, 'turnstile'); ?>><?php esc_html_e('Cloudflare Turnstile', 'maca-restu-pro'); ?></option>
                                </select>
                            </p>
                            <p>
                                <label for="maca_table_booking_captcha_site_key"><strong><?php esc_html_e('Site key', 'maca-restu-pro'); ?></strong></label><br>
                                <input type="text" id="maca_table_booking_captcha_site_key" name="maca_table_booking_captcha_site_key" value="<?php echo esc_attr($table_booking_captcha_site_key); ?>" class="large-text">
                            </p>
                            <p>
                                <label for="maca_table_booking_captcha_secret_key"><strong><?php esc_html_e('Secret key', 'maca-restu-pro'); ?></strong></label><br>
                                <?php
                                $captcha_secret_attrs = maca_menulist_admin_secret_input_attrs(
                                    $table_booking_captcha_secret_key_set,
                                    array(
                                        'id' => 'maca_table_booking_captcha_secret_key',
                                        'name' => 'maca_table_booking_captcha_secret_key',
                                        'class' => 'large-text',
                                    )
                                );
                                ?>
                                <input <?php echo maca_menulist_admin_secret_field_attr_string($captcha_secret_attrs); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
                            </p>
                            <p>
                                <label for="maca_table_booking_captcha_v3_score"><strong><?php esc_html_e('reCAPTCHA v3 minimum score', 'maca-restu-pro'); ?></strong></label><br>
                                <input type="number" id="maca_table_booking_captcha_v3_score" name="maca_table_booking_captcha_v3_score" min="0.1" max="1" step="0.1" value="<?php echo esc_attr((string) $table_booking_captcha_v3_score); ?>" class="small-text">
                                <span class="description"><?php esc_html_e('Only used for reCAPTCHA v3 (0.1–1.0).', 'maca-restu-pro'); ?></span>
                            </p>
                        </fieldset>
                    <?php endif; ?>
                </td>
            </tr>
        </table>

        <?php if ($table_bookings_pro_active && maca_menulist_user_can_manage_plugin()) : ?>
        <h2><?php esc_html_e('Staff access to bookings', 'maca-restu-pro'); ?></h2>
        <p class="description">
            <?php esc_html_e('Create a user under Users → Add New and assign the role “Booking host”. They see all table reservation tabs except Table settings (including confirm, move, cancel, delete bookings, floor overview, and split tables), plus opening hours and exceptions.', 'maca-restu-pro'); ?>
        </p>
        <?php endif; ?>

        <?php submit_button(__('Save table reservation settings', 'maca-restu-pro')); ?>
    </form>
    <?php
}

/**
 * Save table reservation options from POST.
 */
function maca_menulist_save_table_booking_settings_from_post() {
    $previous_cancel_slug = get_option('maca_menulist_table_booking_cancel_slug', 'bokning-avbryt');
    $previous_guest_cancel = get_option('maca_menulist_table_booking_guest_cancel', '1');

    $table_booking = isset($_POST['maca_table_booking']) ? '1' : '0';
    $table_booking_slot_duration = isset($_POST['maca_table_booking_slot_duration']) ? absint(wp_unslash($_POST['maca_table_booking_slot_duration'])) : 120;
    $table_booking_hold_minutes = isset($_POST['maca_table_booking_hold_minutes']) ? absint(wp_unslash($_POST['maca_table_booking_hold_minutes'])) : 15;
    $table_booking_advance_days = isset($_POST['maca_table_booking_advance_days']) ? absint(wp_unslash($_POST['maca_table_booking_advance_days'])) : 60;
    $table_booking_assignment_mode = isset($_POST['maca_table_booking_assignment_mode']) ? sanitize_key(wp_unslash($_POST['maca_table_booking_assignment_mode'])) : 'standard';
    $table_booking_waitlist = isset($_POST['maca_table_booking_waitlist']) ? '1' : '0';
    $table_booking_guest_cancel = isset($_POST['maca_table_booking_guest_cancel']) ? '1' : '0';
    $table_booking_cancel_slug = isset($_POST['maca_table_booking_cancel_slug']) ? sanitize_title(wp_unslash($_POST['maca_table_booking_cancel_slug'])) : 'bokning-avbryt';
    $table_booking_captcha_provider = isset($_POST['maca_table_booking_captcha_provider']) ? sanitize_key(wp_unslash($_POST['maca_table_booking_captcha_provider'])) : 'none';
    $table_booking_captcha_site_key = isset($_POST['maca_table_booking_captcha_site_key']) ? sanitize_text_field(wp_unslash($_POST['maca_table_booking_captcha_site_key'])) : '';
    $table_booking_captcha_secret_key = isset($_POST['maca_table_booking_captcha_secret_key']) ? sanitize_text_field(wp_unslash($_POST['maca_table_booking_captcha_secret_key'])) : '';
    $table_booking_captcha_v3_score = isset($_POST['maca_table_booking_captcha_v3_score']) ? (float) wp_unslash($_POST['maca_table_booking_captcha_v3_score']) : 0.5;
    $table_booking_button_text = isset($_POST['maca_table_booking_button_text']) ? sanitize_text_field(wp_unslash($_POST['maca_table_booking_button_text'])) : '';
    $table_booking_button_text_en = isset($_POST['maca_table_booking_button_text_en']) ? sanitize_text_field(wp_unslash($_POST['maca_table_booking_button_text_en'])) : '';
    $table_booking_title_text = isset($_POST['maca_table_booking_title_text']) ? sanitize_text_field(wp_unslash($_POST['maca_table_booking_title_text'])) : '';
    $table_booking_title_text_en = isset($_POST['maca_table_booking_title_text_en']) ? sanitize_text_field(wp_unslash($_POST['maca_table_booking_title_text_en'])) : '';
    $table_booking_notification_email = isset($_POST['maca_table_booking_notification_email'])
        ? sanitize_email(wp_unslash($_POST['maca_table_booking_notification_email']))
        : '';
    $table_booking_arrival_notice = isset($_POST['maca_table_booking_arrival_notice'])
        ? sanitize_textarea_field(wp_unslash($_POST['maca_table_booking_arrival_notice']))
        : '';
    $table_booking_arrival_notice_en = isset($_POST['maca_table_booking_arrival_notice_en'])
        ? sanitize_textarea_field(wp_unslash($_POST['maca_table_booking_arrival_notice_en']))
        : '';

    if ($table_booking === '1' && !maca_menulist_pro_has_feature('table_bookings')) {
        $table_booking = '0';
    }

    $table_booking_slot_duration = max(30, min(480, $table_booking_slot_duration));
    $table_booking_hold_minutes = min(120, $table_booking_hold_minutes);
    $table_booking_advance_days = max(1, min(365, $table_booking_advance_days));

    if (!in_array($table_booking_assignment_mode, maca_menulist_table_booking_assignment_modes(), true)) {
        $table_booking_assignment_mode = 'standard';
    }

    if ($table_booking_cancel_slug === '') {
        $table_booking_cancel_slug = 'bokning-avbryt';
    }

    if (!in_array($table_booking_captcha_provider, maca_menulist_table_booking_captcha_providers(), true)) {
        $table_booking_captcha_provider = 'none';
    }

    $table_booking_captcha_v3_score = max(0.1, min(1.0, $table_booking_captcha_v3_score));

    update_option('maca_menulist_table_booking', $table_booking);
    update_option('maca_menulist_table_booking_slot_duration', (string) $table_booking_slot_duration);
    update_option('maca_menulist_table_booking_hold_minutes', (string) $table_booking_hold_minutes);
    update_option('maca_menulist_table_booking_arrival_notice', $table_booking_arrival_notice);
    update_option('maca_menulist_table_booking_arrival_notice_en', $table_booking_arrival_notice_en);
    update_option('maca_menulist_table_booking_advance_days', (string) $table_booking_advance_days);
    update_option('maca_menulist_table_booking_assignment_mode', $table_booking_assignment_mode);
    update_option('maca_menulist_table_booking_waitlist', $table_booking_waitlist);
    update_option('maca_menulist_table_booking_guest_cancel', $table_booking_guest_cancel);
    update_option('maca_menulist_table_booking_cancel_slug', $table_booking_cancel_slug);
    update_option('maca_menulist_table_booking_captcha_provider', $table_booking_captcha_provider);
    update_option('maca_menulist_table_booking_captcha_site_key', $table_booking_captcha_site_key);
    if (maca_menulist_admin_secret_should_update($table_booking_captcha_secret_key)) {
        update_option('maca_menulist_table_booking_captcha_secret_key', $table_booking_captcha_secret_key);
    }
    update_option('maca_menulist_table_booking_captcha_v3_score', (string) $table_booking_captcha_v3_score);
    update_option('maca_menulist_table_booking_button_text', $table_booking_button_text);
    update_option('maca_menulist_table_booking_button_text_en', $table_booking_button_text_en);
    update_option('maca_menulist_table_booking_title_text', $table_booking_title_text);
    update_option('maca_menulist_table_booking_title_text_en', $table_booking_title_text_en);
    update_option('maca_menulist_table_booking_notification_email', $table_booking_notification_email);

    if (
        $table_booking_cancel_slug !== $previous_cancel_slug
        || $table_booking_guest_cancel !== $previous_guest_cancel
    ) {
        maca_menulist_flush_rewrite_rules();
    }

}
