<?php
// phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

$ai_available = class_exists( 'YATOON_AI' ) && YATOON_AI::is_text_available();
$ai_status    = class_exists( 'YATOON_AI' ) ? YATOON_AI::status_message() : __( 'AI requires WordPress 7.0 or newer.', 'yatoon-booking-system' );
$is_pro       = function_exists( 'yatoon_is_pro' ) && yatoon_is_pro();
$connector_url = admin_url( 'options-connectors.php' );
$frontend_title_value = trim( (string) get_option( 'yatoon_ai_frontend_title', __( 'Not sure what to book?', 'yatoon-booking-system' ) ) );
// Exact historical option values: keep untranslated so previously saved English defaults can be upgraded safely.
if ( in_array( $frontend_title_value, array( 'AI Style Assistant', 'Need help choosing?', 'Need Help Booking? Let AI Help' ), true ) || $frontend_title_value === '' ) {
    $frontend_title_value = __( 'Not sure what to book?', 'yatoon-booking-system' );
}
$privacy_note_value = trim( (string) get_option( 'yatoon_ai_privacy_note', __( 'Please do not include medical, payment, or other sensitive information.', 'yatoon-booking-system' ) ) );
// Exact historical option values: these are comparison keys, not text rendered to the user.
if ( in_array( $privacy_note_value, array( 'Privacy note: Please avoid sensitive, medical, or payment details.', 'For your privacy, please avoid sharing sensitive or payment information.' ), true ) || $privacy_note_value === '' ) {
    $privacy_note_value = __( 'Please do not include medical, payment, or other sensitive information.', 'yatoon-booking-system' );
}
$provider_labels = array(
    'google'    => 'Google Gemini',
    'openai'    => 'OpenAI',
    'anthropic' => 'Anthropic Claude',
);
$provider_order = get_option( 'yatoon_ai_provider_order', array( 'google', 'openai', 'anthropic' ) );
if ( is_string( $provider_order ) ) {
    $decoded = json_decode( $provider_order, true );
    $provider_order = is_array( $decoded ) ? $decoded : explode( ',', $provider_order );
}
$provider_order = array_values( array_unique( array_intersect( array_map( 'sanitize_key', (array) $provider_order ), array_keys( $provider_labels ) ) ) );
foreach ( array_keys( $provider_labels ) as $provider_key ) {
    if ( ! in_array( $provider_key, $provider_order, true ) ) {
        $provider_order[] = $provider_key;
    }
}
$model_choices = array(
    'google' => array(
        'gemini-3.7-flash'      => 'Gemini 3.7 Flash — recommended, latest stable',
        'gemini-3.6-flash'      => 'Gemini 3.6 Flash — stable',
        'gemini-3.5-flash'      => 'Gemini 3.5 Flash — stable',
        'gemini-3.5-flash-lite' => 'Gemini 3.5 Flash-Lite — lowest cost',
        'gemini-2.5-flash'      => 'Gemini 2.5 Flash — compatibility, proven stable',
        'gemini-2.5-flash-lite' => 'Gemini 2.5 Flash-Lite — compatibility, low cost',
        'gemini-2.0-flash'      => 'Gemini 2.0 Flash — original compatibility',
        'gemini-2.0-flash-lite' => 'Gemini 2.0 Flash-Lite — original compatibility',
        'gemini-1.5-flash'      => 'Gemini 1.5 Flash — legacy fallback',
        'gemini-1.5-flash-8b'   => 'Gemini 1.5 Flash-8B — legacy fallback',
    ),
    'openai' => array(
        'gpt-5.6-luna'  => 'GPT-5.6 Luna — recommended, lowest cost',
        'gpt-5.6-terra' => 'GPT-5.6 Terra — balanced',
        'gpt-5.6-sol'   => 'GPT-5.6 Sol — highest quality',
        'gpt-5-mini'    => 'GPT-5 Mini — compatibility, balanced',
        'gpt-4.1-mini'  => 'GPT-4.1 Mini — compatibility, fast',
        'gpt-4o-mini'   => 'GPT-4o Mini — legacy compatibility',
        'gpt-4.1-nano'  => 'GPT-4.1 Nano — legacy compatibility',
        'gpt-5-nano'    => 'GPT-5 Nano — compatibility',
    ),
    'anthropic' => array(
        'claude-haiku-4-5' => 'Claude Haiku 4.5 — fastest, lowest cost',
        'claude-sonnet-5'  => 'Claude Sonnet 5 — recommended balance',
        'claude-opus-5'    => 'Claude Opus 5 — premium',
        'claude-fable-5'   => 'Claude Fable 5 — highest capability',
        'claude-3-5-haiku-20241022'  => 'Claude 3.5 Haiku — legacy compatibility',
        'claude-3-7-sonnet-20250219' => 'Claude 3.7 Sonnet — legacy compatibility',
        'claude-3-5-sonnet-20241022' => 'Claude 3.5 Sonnet — legacy fallback',
        'claude-3-haiku-20240307'    => 'Claude 3 Haiku — legacy fallback',
    ),
);
$model_defaults = array(
    'google'    => 'gemini-3.7-flash',
    'openai'    => 'gpt-5.6-luna',
    'anthropic' => 'claude-haiku-4-5',
);
?>
<div class="wrap sbs-admin-page yatoon-settings-page yatoon-ai-admin-page">
    <style>
        .yatoon-ai-hero {
            margin: 18px 0 20px;
            padding: 22px;
            border-radius: 8px;
            background: linear-gradient(135deg, #eef2ff 0%, #fdf2f8 100%);
            border: 1px solid #dbe4ef;
        }
        .yatoon-ai-hero h1 { margin: 0 0 8px; }
        .yatoon-ai-hero p { max-width: 760px; font-size: 15px; }
        .yatoon-ai-grid {
            display: grid;
            grid-template-columns: minmax(0, 1.1fr) minmax(280px, .9fr);
            gap: 16px;
        }
        .yatoon-ai-panel {
            background: #fff;
            border: 1px solid #dcdcde;
            border-radius: 8px;
            padding: 18px;
        }
        .yatoon-ai-status {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 7px 10px;
            border-radius: 999px;
            font-weight: 700;
            background: <?php echo $ai_available ? '#ecfdf5' : '#fffbeb'; ?>;
            color: <?php echo $ai_available ? '#166534' : '#92400e'; ?>;
        }
        .yatoon-ai-dot {
            width: 8px;
            height: 8px;
            border-radius: 999px;
            background: <?php echo $ai_available ? '#22c55e' : '#f59e0b'; ?>;
        }
        .yatoon-ai-feature {
            margin: 12px 0;
            padding: 12px;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            background: #f9fafb;
        }
        .yatoon-ai-feature strong { display: block; margin-bottom: 4px; }
        .yatoon-ai-feature p { margin: 0; color: #646970; }
        .yatoon-ai-actions { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 14px; }
        .yatoon-ai-provider-row {
            display: grid;
            grid-template-columns: 42px minmax(150px, .8fr) minmax(210px, 1fr);
            gap: 10px;
            align-items: center;
            margin: 8px 0;
        }
        .yatoon-ai-provider-row select { width: 100%; max-width: 100%; }
        .yatoon-ai-provider-rank {
            width: 32px;
            height: 32px;
            border-radius: 999px;
            background: #eef2ff;
            color: #3730a3;
            font-weight: 700;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
        @media (max-width: 700px) { .yatoon-ai-provider-row { grid-template-columns: 1fr; } }
        @media (max-width: 900px) { .yatoon-ai-grid { grid-template-columns: 1fr; } }
    </style>

    <?php if ( isset( $_GET['saved'] ) ) : ?>
        <div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'AI Assistant settings saved.', 'yatoon-booking-system' ); ?></p></div>
    <?php endif; ?>

    <div class="yatoon-ai-hero">
        <h1><?php esc_html_e( 'Yatoon AI Assistant', 'yatoon-booking-system' ); ?></h1>
        <p><?php esc_html_e( 'Make AI obvious to salon owners and useful for customers: service recommendations on the booking page, service description writing in the admin, plus staff-reviewed reply drafts in Pro.', 'yatoon-booking-system' ); ?></p>
        <span class="yatoon-ai-status"><span class="yatoon-ai-dot"></span><?php echo esc_html( $ai_status ); ?></span>
    </div>

    <div class="yatoon-ai-grid">
        <div class="yatoon-ai-panel">
            <h2><?php esc_html_e( 'AI Feature Switches', 'yatoon-booking-system' ); ?></h2>
            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
                <?php wp_nonce_field( 'yatoon_save_ai_settings' ); ?>
                <input type="hidden" name="action" value="yatoon_save_ai_settings">

                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Customer Service Helper', 'yatoon-booking-system' ); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="yatoon_ai_service_helper_enabled" value="1" <?php checked( get_option( 'yatoon_ai_service_helper_enabled', '1' ), '1' ); ?>>
                                <?php esc_html_e( 'Show the AI Style Assistant on the booking form.', 'yatoon-booking-system' ); ?>
                            </label>
                            <p class="description"><?php esc_html_e( 'Customers describe their desired look, length, occasion, budget, or concerns; AI suggests matching services from your real service list.', 'yatoon-booking-system' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'AI Reschedule Assistant', 'yatoon-booking-system' ); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="yatoon_ai_reschedule_assistant_enabled" value="1" <?php checked( get_option( 'yatoon_ai_reschedule_assistant_enabled', '1' ), '1' ); ?>>
                                <?php esc_html_e( 'Let customers describe a new time in their own words when rescheduling.', 'yatoon-booking-system' ); ?>
                            </label>
                            <p class="description"><?php esc_html_e( 'In "My Appointments", customers can type something like "next Thursday afternoon" instead of using the date picker. AI only reads off your real open time slots and never invents availability — the customer still confirms the exact time before anything changes.', 'yatoon-booking-system' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Frontend Assistant Text', 'yatoon-booking-system' ); ?></th>
                        <td>
                            <input type="text" class="regular-text" name="yatoon_ai_frontend_title" value="<?php echo esc_attr( $frontend_title_value ); ?>" placeholder="<?php esc_attr_e( 'Not sure what to book?', 'yatoon-booking-system' ); ?>">
                            <p class="description"><?php esc_html_e( 'This text appears on the collapsed AI button and the expanded assistant title.', 'yatoon-booking-system' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Privacy Note Text', 'yatoon-booking-system' ); ?></th>
                        <td>
                            <input type="text" class="regular-text" name="yatoon_ai_privacy_note" value="<?php echo esc_attr( $privacy_note_value ); ?>" placeholder="<?php esc_attr_e( 'Please do not include medical, payment, or other sensitive information.', 'yatoon-booking-system' ); ?>">
                            <p class="description"><?php esc_html_e( 'Small text shown under the AI input box. Keep it short so the customer form stays clean.', 'yatoon-booking-system' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Frontend Assistant Style', 'yatoon-booking-system' ); ?></th>
                        <td>
                            <label>
                                <?php esc_html_e( 'Text size', 'yatoon-booking-system' ); ?>
                                <input type="number" name="yatoon_ai_frontend_font_size" value="<?php echo esc_attr( get_option( 'yatoon_ai_frontend_font_size', '14' ) ); ?>" min="11" max="24" step="1" style="width:80px;"> px
                            </label>
                            <label style="margin-left:14px;">
                                <?php esc_html_e( 'Text color', 'yatoon-booking-system' ); ?>
                                <input type="color" name="yatoon_ai_frontend_text_color" value="<?php echo esc_attr( get_option( 'yatoon_ai_frontend_text_color', '#111827' ) ); ?>">
                            </label>
                            <label style="margin-left:14px;">
                                <?php esc_html_e( 'Background', 'yatoon-booking-system' ); ?>
                                <input type="color" name="yatoon_ai_frontend_bg_color" value="<?php echo esc_attr( get_option( 'yatoon_ai_frontend_bg_color', '#f8fafc' ) ); ?>">
                            </label>
                            <p class="description"><?php esc_html_e( 'Controls the collapsed AI button style. Text size and color also apply to the expanded assistant title.', 'yatoon-booking-system' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Service Description Helper', 'yatoon-booking-system' ); ?></th>
                        <td>
                            <strong><?php esc_html_e( 'Available in Services.', 'yatoon-booking-system' ); ?></strong>
                            <p class="description"><?php esc_html_e( 'Use AI to turn short service notes into clearer customer-facing descriptions, based on the service name, category, duration, price, and current text.', 'yatoon-booking-system' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Frontend AI Performance', 'yatoon-booking-system' ); ?></th>
                        <td>
                            <select name="yatoon_ai_frontend_profile">
                                <option value="fast" <?php selected( get_option( 'yatoon_ai_frontend_profile', 'fast' ), 'fast' ); ?>><?php esc_html_e( 'Fast & free-tier friendly (recommended)', 'yatoon-booking-system' ); ?></option>
                                <option value="balanced" <?php selected( get_option( 'yatoon_ai_frontend_profile', 'fast' ), 'balanced' ); ?>><?php esc_html_e( 'Balanced', 'yatoon-booking-system' ); ?></option>
                                <option value="quality" <?php selected( get_option( 'yatoon_ai_frontend_profile', 'fast' ), 'quality' ); ?>><?php esc_html_e( 'Quality first (slower, more usage)', 'yatoon-booking-system' ); ?></option>
                            </select>
                            <label style="margin-left:14px;">
                                <?php esc_html_e( 'Reuse identical answers for', 'yatoon-booking-system' ); ?>
                                <input type="number" name="yatoon_ai_cache_minutes" value="<?php echo esc_attr( get_option( 'yatoon_ai_cache_minutes', 30 ) ); ?>" min="5" max="120" step="5" style="width:76px;"> <?php esc_html_e( 'minutes', 'yatoon-booking-system' ); ?>
                            </label>
                            <p class="description"><?php esc_html_e( 'Fast mode limits front-desk waiting, skips schedule calculations unless the customer asks about availability, and falls back to clickable menu matches instead of showing a dead-end busy error. Repeated identical questions reuse a recent answer and do not consume another AI request.', 'yatoon-booking-system' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'AI Providers & Models', 'yatoon-booking-system' ); ?></th>
                        <td>
                            <p class="description" style="margin-top:0;"><?php esc_html_e( 'Choose the provider fallback order and model for each provider. Yatoon tries row 1 first, then row 2, then row 3 when available through WordPress Connectors. Catalog verified against provider documentation on August 21, 2026.', 'yatoon-booking-system' ); ?></p>
                            <p class="notice notice-warning inline" style="padding:10px 12px;"><?php esc_html_e( 'Data flow: after the customer checks the consent box, their AI-helper text and a limited service/availability snapshot may be sent to the first available configured provider. Yatoon does not send customer contact details and does not store the raw request; providers may retain data under their own terms. Do not enable this feature until your privacy notice identifies the providers and applicable retention terms.', 'yatoon-booking-system' ); ?></p>
                            <?php for ( $i = 0; $i < 3; $i++ ) : ?>
                                <?php $current_provider = $provider_order[ $i ] ?? array_keys( $provider_labels )[ $i ]; ?>
                                <div class="yatoon-ai-provider-row">
                                    <span class="yatoon-ai-provider-rank"><?php echo esc_html( (string) ( $i + 1 ) ); ?></span>
                                    <select name="yatoon_ai_provider_order[]">
                                        <?php foreach ( $provider_labels as $provider_key => $provider_label ) : ?>
                                            <option value="<?php echo esc_attr( $provider_key ); ?>" <?php selected( $current_provider, $provider_key ); ?>><?php echo esc_html( $provider_label ); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <span class="description"><?php esc_html_e( 'Fallback priority', 'yatoon-booking-system' ); ?></span>
                                </div>
                            <?php endfor; ?>
                            <div style="height:8px;"></div>
                            <?php foreach ( $provider_labels as $provider_key => $provider_label ) : ?>
                                <div class="yatoon-ai-provider-row">
                                    <span class="yatoon-ai-provider-rank">*</span>
                                    <strong><?php echo esc_html( $provider_label ); ?></strong>
                                    <select name="yatoon_ai_model_<?php echo esc_attr( $provider_key ); ?>">
                                        <?php
                                        $selected_model = get_option( 'yatoon_ai_model_' . $provider_key, $model_defaults[ $provider_key ] );
                                        if ( ! isset( $model_choices[ $provider_key ][ $selected_model ] ) ) {
                                            $selected_model = $model_defaults[ $provider_key ];
                                        }
                                        foreach ( $model_choices[ $provider_key ] as $model_key => $model_label ) :
                                        ?>
                                            <option value="<?php echo esc_attr( $model_key ); ?>" <?php selected( $selected_model, $model_key ); ?>><?php echo esc_html( $model_label . ' (' . $model_key . ')' ); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            <?php endforeach; ?>
                            <p class="description"><?php esc_html_e( 'For the lowest practical cost, put Google Gemini first and keep Gemini 2.0 Flash if it is the model proven to work with your Connector. Flash-Lite can be faster and cheaper when your connected account supports it. A provider-wide rate limit now moves directly to the next provider instead of retrying several models on the same exhausted quota.', 'yatoon-booking-system' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Frontend Display', 'yatoon-booking-system' ); ?></th>
                        <td>
                            <select name="yatoon_ai_display_mode">
                                <option value="collapsed" <?php selected( get_option( 'yatoon_ai_display_mode', 'collapsed' ), 'collapsed' ); ?>><?php esc_html_e( 'Collapsed button', 'yatoon-booking-system' ); ?></option>
                                <option value="expanded" <?php selected( get_option( 'yatoon_ai_display_mode', 'collapsed' ), 'expanded' ); ?>><?php esc_html_e( 'Expanded panel', 'yatoon-booking-system' ); ?></option>
                            </select>
                            <p class="description"><?php esc_html_e( 'Choose whether the AI Style Assistant opens visibly or starts as a compact button customers can expand.', 'yatoon-booking-system' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Text Us Reply Drafts', 'yatoon-booking-system' ); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="yatoon_ai_reply_drafts_enabled" value="1" <?php checked( get_option( 'yatoon_ai_reply_drafts_enabled', '1' ), '1' ); ?> <?php disabled( ! $is_pro ); ?>>
                                <?php esc_html_e( 'Generate AI reply drafts for customer messages.', 'yatoon-booking-system' ); ?>
                            </label>
                            <p class="description"><?php echo esc_html( $is_pro ? __( 'Drafts are shown to staff for review before sending.', 'yatoon-booking-system' ) : __( 'Requires an active Pro license. Customer service helper stays available.', 'yatoon-booking-system' ) ); ?></p>
                        </td>
                    </tr>
                </table>

                <?php submit_button( __( 'Save AI Settings', 'yatoon-booking-system' ) ); ?>
            </form>
        </div>

        <div class="yatoon-ai-panel">
            <h2><?php esc_html_e( 'Setup Checklist', 'yatoon-booking-system' ); ?></h2>
            <div class="yatoon-ai-feature">
                <strong><?php esc_html_e( '1. WordPress 7.0 AI Client', 'yatoon-booking-system' ); ?></strong>
                <p><?php esc_html_e( 'WordPress 6.9 remains supported. AI appears as a visible feature panel, but generation requires WordPress 7.0 AI Client support.', 'yatoon-booking-system' ); ?></p>
            </div>
            <div class="yatoon-ai-feature">
                <strong><?php esc_html_e( '2. Connect an AI provider', 'yatoon-booking-system' ); ?></strong>
                <p><?php esc_html_e( 'Use WordPress Settings > Connectors. Yatoon does not store AI API keys or charge for AI usage.', 'yatoon-booking-system' ); ?></p>
            </div>
            <div class="yatoon-ai-feature">
                <strong><?php esc_html_e( '3. Provider priority', 'yatoon-booking-system' ); ?></strong>
                <p><?php esc_html_e( 'Yatoon follows the provider order shown on the left. Temporary overloads and rate limits automatically fall through to another current model or connected provider.', 'yatoon-booking-system' ); ?></p>
            </div>
            <div class="yatoon-ai-feature">
                <strong><?php esc_html_e( '4. Improve service descriptions', 'yatoon-booking-system' ); ?></strong>
                <p><?php esc_html_e( 'Open Services, edit a service, and use Improve with AI so customers and the AI Style Assistant have better service details.', 'yatoon-booking-system' ); ?></p>
            </div>
            <div class="yatoon-ai-feature">
                <strong><?php esc_html_e( '5. Preview the booking page', 'yatoon-booking-system' ); ?></strong>
                <p><?php esc_html_e( 'The AI Style Assistant appears above the service list when the switch is on.', 'yatoon-booking-system' ); ?></p>
            </div>
            <div class="yatoon-ai-actions">
                <a class="button button-primary" href="<?php echo esc_url( $connector_url ); ?>"><?php esc_html_e( 'Open Connectors', 'yatoon-booking-system' ); ?></a>
                <a class="button" href="<?php echo esc_url( admin_url( 'admin.php?page=yatoon-booking-system' ) ); ?>"><?php esc_html_e( 'General Settings', 'yatoon-booking-system' ); ?></a>
            </div>
        </div>
    </div>
</div>
