<?php
/**
 * AI tab — bring-your-own Mistral AI API key (EU-based provider).
 *
 * @package Brainwerk SEO Suite
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }

// Save handler — own form, own nonce. We never round-trip the key through GET.
if ( ! empty( $_POST['seoforge_ai_save'] ) && check_admin_referer( 'seoforge_ai_save' ) ) {
    $new_key = isset( $_POST['ai_key'] ) ? sanitize_text_field( wp_unslash( $_POST['ai_key'] ) ) : '';
    if ( '' !== $new_key && '__keep__' !== $new_key ) {
        Seoforge_AI::set_key( $new_key );
    }
    $patch = array();
    if ( isset( $_POST['ai_provider'] ) ) {
        $pv = sanitize_text_field( wp_unslash( $_POST['ai_provider'] ) );
        $patch['provider'] = array_key_exists( $pv, Seoforge_AI::providers() ) ? $pv : 'mistral';
    }
    $sel_provider = isset( $patch['provider'] ) ? $patch['provider'] : Seoforge_AI::get()['provider'];
    if ( isset( $_POST['ai_model'] ) ) {
        $allowed = array_keys( Seoforge_AI::model_options( $sel_provider ) );
        $val = sanitize_text_field( wp_unslash( $_POST['ai_model'] ) );
        $patch['model'] = in_array( $val, $allowed, true ) ? $val : Seoforge_AI::default_model( $sel_provider );
    }
    if ( isset( $_POST['ai_cap'] ) ) {
        $patch['monthly_call_cap'] = max( 0, min( 100000, (int) $_POST['ai_cap'] ) );
    }
    $patch['enabled'] = ! empty( $_POST['ai_enabled'] );
    if ( $patch ) {
        $existing = Seoforge_AI::get();
        $merged   = array_replace( $existing, $patch );
        if ( is_multisite() ) { update_site_option( 'seoforge_ai', $merged ); } else { update_option( 'seoforge_ai', $merged ); }
    }
    echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'AI settings saved.', 'brainwerk-seo-suite' ) . '</p></div>';
}
if ( ! empty( $_POST['seoforge_ai_clear'] ) && check_admin_referer( 'seoforge_ai_clear' ) ) {
    Seoforge_AI::clear_key();
    echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'API key removed.', 'brainwerk-seo-suite' ) . '</p></div>';
}

// A stored key that no longer decrypts (e.g. after the WordPress salts were
// rotated, or a DB restore without the matching wp-config.php). Prompt a
// re-entry instead of silently behaving as "not configured".
if ( Seoforge_AI::key_decrypt_failed() ) {
    echo '<div class="notice notice-error"><p>' . esc_html__( 'The stored AI API key could not be decrypted (for example after a change to the WordPress salts). Please enter it again.', 'brainwerk-seo-suite' ) . '</p></div>';
}

$state    = Seoforge_AI::get();
$has_key  = '' !== Seoforge_AI::get_key();
$provider = $state['provider'];
$models   = Seoforge_AI::model_options( $provider );
$prov_meta = array(
    'mistral' => array( 'name' => 'Mistral AI', 'console' => 'https://console.mistral.ai/api-keys/', 'console_label' => 'console.mistral.ai', 'host' => 'api.mistral.ai', 'placeholder' => 'xxxxxxxxxxxxxxxx', 'eu' => true ),
);
$pm = isset( $prov_meta[ $provider ] ) ? $prov_meta[ $provider ] : $prov_meta['mistral'];
?>

<div class="seoforge-card">
    <div class="seoforge-row-spread">
        <h2 style="margin:0;">✨ <?php esc_html_e( 'AI-powered SEO suggestions', 'brainwerk-seo-suite' ); ?></h2>
        <span class="seoforge-pill seoforge-pill-<?php echo $state['enabled'] && $has_key ? 'good' : 'unscored'; ?>">
            <?php echo $state['enabled'] && $has_key ? esc_html__( 'on', 'brainwerk-seo-suite' ) : esc_html__( 'off', 'brainwerk-seo-suite' ); ?>
        </span>
    </div>

    <div class="seoforge-callout seoforge-callout-info">
        <strong><?php
            /* translators: %s provider name */
            printf( esc_html__( 'Bring your own %s key', 'brainwerk-seo-suite' ), esc_html( $pm['name'] ) );
        ?></strong>
        <p><?php
            printf(
                /* translators: 1: provider name, 2: link to the provider's API-key console */
                esc_html__( 'Brainwerk SEO Suite talks to %1$s using YOUR personal API key — usage is billed directly to you. Get a key at %2$s.', 'brainwerk-seo-suite' ),
                esc_html( $pm['name'] ),
                '<a href="' . esc_url( $pm['console'] ) . '" target="_blank" rel="noopener">' . esc_html( $pm['console_label'] ) . '</a>'
            );
            ?>
            <?php if ( ! empty( $pm['eu'] ) ) : ?>
                <br><strong>🇪🇺 <?php esc_html_e( 'EU-based AI provider — your content stays in the EU.', 'brainwerk-seo-suite' ); ?></strong>
            <?php endif; ?>
        </p>
    </div>

    <form method="post" action="">
        <?php wp_nonce_field( 'seoforge_ai_save' ); ?>
        <input type="hidden" name="seoforge_ai_save" value="1">

        <table class="form-table">
            <tr>
                <th><label for="ai_provider"><?php esc_html_e( 'AI provider', 'brainwerk-seo-suite' ); ?></label></th>
                <td>
                    <select id="ai_provider" name="ai_provider">
                        <?php foreach ( Seoforge_AI::providers() as $pid => $plabel ) : ?>
                            <option value="<?php echo esc_attr( $pid ); ?>" <?php selected( $provider, $pid ); ?>><?php echo esc_html( $plabel ); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="description"><?php esc_html_e( 'Mistral is EU-based — on-brand for a privacy-first suite with EU-based processing. Your content stays within the EU.', 'brainwerk-seo-suite' ); ?></p>
                </td>
            </tr>
            <tr>
                <th><label for="ai_key"><?php esc_html_e( 'API key', 'brainwerk-seo-suite' ); ?></label></th>
                <td>
                    <?php if ( $has_key ) : ?>
                        <code style="padding:6px 10px;background:#f3f4f6;border-radius:4px;"><?php echo esc_html( Seoforge_Crypto::mask( Seoforge_AI::get_key() ) ); ?></code>
                        <input type="text" id="ai_key" name="ai_key" value="__keep__" style="display:none;">
                        <p class="description"><?php esc_html_e( 'Saved + encrypted at rest. To replace, paste a new one below.', 'brainwerk-seo-suite' ); ?></p>
                        <input type="password" name="ai_key" placeholder="<?php echo esc_attr( $pm['placeholder'] ); ?>" class="regular-text" autocomplete="off">
                    <?php else : ?>
                        <input type="password" id="ai_key" name="ai_key" placeholder="<?php echo esc_attr( $pm['placeholder'] ); ?>" class="regular-text" autocomplete="off">
                        <p class="description"><?php esc_html_e( 'Stored encrypted at rest using your WP AUTH_KEY. Never sent anywhere except your chosen AI provider.', 'brainwerk-seo-suite' ); ?></p>
                    <?php endif; ?>
                </td>
            </tr>
            <tr>
                <th><label><?php esc_html_e( 'Enabled', 'brainwerk-seo-suite' ); ?></label></th>
                <td>
                    <label class="seoforge-switch">
                        <input type="checkbox" name="ai_enabled" value="1" <?php checked( $state['enabled'] ); ?>>
                        <span></span>
                    </label>
                </td>
            </tr>
            <tr>
                <th><label for="ai_model"><?php esc_html_e( 'Model', 'brainwerk-seo-suite' ); ?></label></th>
                <td>
                    <select id="ai_model" name="ai_model">
                        <?php foreach ( $models as $id => $label ) : ?>
                            <option value="<?php echo esc_attr( $id ); ?>" <?php selected( $state['model'], $id ); ?>><?php echo esc_html( $label ); ?></option>
                        <?php endforeach; ?>
                    </select>
                </td>
            </tr>
            <tr>
                <th><label for="ai_cap"><?php esc_html_e( 'Monthly call cap', 'brainwerk-seo-suite' ); ?></label></th>
                <td>
                    <input type="number" id="ai_cap" name="ai_cap" min="0" max="100000" value="<?php echo (int) $state['monthly_call_cap']; ?>" class="small-text">
                    <p class="description"><?php
                        printf(
                            /* translators: %d count */
                            esc_html__( 'Soft client-side cap so you never wake up to a surprise bill. Used so far this month: %d.', 'brainwerk-seo-suite' ),
                            (int) $state['calls_this_month']
                        );
                    ?> <?php esc_html_e( '(0 = unlimited)', 'brainwerk-seo-suite' ); ?></p>
                </td>
            </tr>
        </table>

        <p>
            <?php submit_button( __( 'Save', 'brainwerk-seo-suite' ), 'primary', 'submit', false ); ?>
            <?php if ( $has_key ) : ?>
                <button type="button" class="button" id="sf-ai-test"><?php esc_html_e( 'Test connection', 'brainwerk-seo-suite' ); ?></button>
                <span id="sf-ai-test-result"></span>
            <?php endif; ?>
        </p>
    </form>

    <?php if ( $has_key ) : ?>
        <form method="post" action="" style="margin-top:6px;">
            <?php wp_nonce_field( 'seoforge_ai_clear' ); ?>
            <input type="hidden" name="seoforge_ai_clear" value="1">
            <button class="button button-link-delete" type="submit" onclick="return confirm('<?php echo esc_js( __( 'Remove the saved API key?', 'brainwerk-seo-suite' ) ); ?>')">
                <?php esc_html_e( 'Remove API key', 'brainwerk-seo-suite' ); ?>
            </button>
        </form>
    <?php endif; ?>

    <?php if ( ! empty( $state['last_error'] ) ) : ?>
        <p class="notice notice-error" style="padding:8px 12px;margin-top:14px;">
            <?php echo esc_html( $state['last_error'] ); ?>
        </p>
    <?php endif; ?>
</div>

<div class="seoforge-card-grid">
    <div class="seoforge-card">
        <h3><?php esc_html_e( 'What this unlocks', 'brainwerk-seo-suite' ); ?></h3>
        <ul style="line-height:1.9">
            <li>✨ <?php esc_html_e( 'Three SEO-title alternatives per post, ranked', 'brainwerk-seo-suite' ); ?></li>
            <li>✨ <?php esc_html_e( 'Three meta descriptions with built-in CTAs', 'brainwerk-seo-suite' ); ?></li>
            <li>✨ <?php esc_html_e( 'Focus-keyword candidates with search intent', 'brainwerk-seo-suite' ); ?></li>
            <li>✨ <?php esc_html_e( 'Internal-linking opportunities from your own posts', 'brainwerk-seo-suite' ); ?></li>
        </ul>
    </div>
    <div class="seoforge-card">
        <h3><?php esc_html_e( 'Privacy', 'brainwerk-seo-suite' ); ?></h3>
        <p style="font-size:13px;line-height:1.7"><?php
            printf(
                /* translators: 1: API host (e.g. api.mistral.ai), 2: provider name */
                esc_html__( 'When you click an "Optimize" button, the post title + body content is sent to %1$s so %2$s can suggest improvements. Cached suggestions stay in your DB for 7 days. Disable the toggle above to switch off completely.', 'brainwerk-seo-suite' ),
                esc_html( $pm['host'] ),
                esc_html( $pm['name'] )
            );
        ?></p>
    </div>
</div>

<script>
( function () {
    var models = <?php echo wp_json_encode( array( 'mistral' => Seoforge_AI::model_options( 'mistral' ) ), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ); ?>;
    var prov = document.getElementById( 'ai_provider' );
    var sel  = document.getElementById( 'ai_model' );
    if ( ! prov || ! sel ) { return; }
    prov.addEventListener( 'change', function () {
        var list = models[ prov.value ] || {};
        sel.innerHTML = '';
        Object.keys( list ).forEach( function ( id ) {
            var o = document.createElement( 'option' );
            o.value = id;
            o.textContent = list[ id ];
            sel.appendChild( o );
        } );
    } );
} )();
</script>
