<?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' );
$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-1.5-flash'      => 'Gemini 1.5 Flash',
        'gemini-1.5-flash-8b'   => 'Gemini 1.5 Flash-8B',
        'gemini-2.0-flash'      => 'Gemini 2.0 Flash',
        'gemini-2.0-flash-lite' => 'Gemini 2.0 Flash-Lite',
        'gemini-2.5-flash'      => 'Gemini 2.5 Flash',
        'gemini-2.5-flash-lite' => 'Gemini 2.5 Flash-Lite',
    ),
    'openai' => array(
        'gpt-4o-mini' => 'GPT-4o mini',
        'gpt-4.1-mini' => 'GPT-4.1 mini',
        'gpt-4.1-nano' => 'GPT-4.1 nano',
        'gpt-5-mini' => 'GPT-5 mini',
        'gpt-5-nano' => 'GPT-5 nano',
    ),
    'anthropic' => array(
        'claude-3-5-haiku-20241022' => 'Claude 3.5 Haiku',
        'claude-3-haiku-20240307' => 'Claude 3 Haiku',
        'claude-3-5-sonnet-20241022' => 'Claude 3.5 Sonnet',
        'claude-3-7-sonnet-20250219' => 'Claude 3.7 Sonnet',
    ),
);
$model_defaults = array(
    'google'    => 'gemini-1.5-flash',
    'openai'    => 'gpt-4o-mini',
    'anthropic' => 'claude-3-5-haiku-20241022',
);
?>
<div class="wrap sbs-admin-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( 'Frontend Assistant Text', 'yatoon-booking-system' ); ?></th>
                        <td>
                            <input type="text" class="regular-text" name="yatoon_ai_frontend_title" value="<?php echo esc_attr( get_option( 'yatoon_ai_frontend_title', __( 'AI Style Assistant', 'yatoon-booking-system' ) ) ); ?>" placeholder="<?php esc_attr_e( 'AI Style Assistant', '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( get_option( 'yatoon_ai_privacy_note', __( 'Privacy note: Please avoid sensitive, medical, or payment details.', 'yatoon-booking-system' ) ) ); ?>" placeholder="<?php esc_attr_e( 'Privacy note: Please avoid sensitive, medical, or payment details.', '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( '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.', '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 ] );
                                        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 low cost, put Google Gemini first. For OpenAI compatibility, put OpenAI first. For a softer premium tone, put Anthropic first.', '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( 'If multiple AI providers are connected, Yatoon prefers OpenAI/GPT first, then Google/Gemini, then Anthropic/Claude when fallback is needed.', '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>
