<?php

/**
 * Settings page template
 *
 * @package ContentPerformanceAnalyzer
 * @since 1.0.0
 */
// Prevent direct access
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Read current provider at top of template. Hosted AI is only selectable in
// the premium package while a valid Pro license or Pro trial is active.
$cpanalyzer_hosted_ai_available = false;
$cpanalyzer_provider = get_option( 'cpanalyzer_ai_provider', 'openai' );
if ( 'hosted' === $cpanalyzer_provider && !$cpanalyzer_hosted_ai_available ) {
    $cpanalyzer_provider = 'openai';
}
?>

<div class="wrap">
<h1><?php 
echo esc_html( get_admin_page_title() );
?></h1>

<!-- Welcome Setup Instructions -->
<div class="notice notice-success" style="border-left-color: #00a32a; background-color: #f0f8f0; padding: 15px; margin: 20px 0;">
    <div style="display: flex; align-items: flex-start; gap: 10px;">
        <span style="font-size: 18px; color: #00a32a;">🚀</span>
        <div>
            <h3 style="margin: 0 0 8px 0; color: #00a32a; font-size: 16px;">
                <?php 
esc_html_e( 'Welcome! Let\'s Set Up Your Content Performance Analyzer', 'content-performance-analyzer' );
?>
            </h3>
            <p style="margin: 0 0 10px 0; line-height: 1.5; color: #2c3e50;">
                <?php 
esc_html_e( 'Three steps to your first analysis:', 'content-performance-analyzer' );
?>
            </p>
            <ol style="margin: 10px 0 0 20px; line-height: 1.6; color: #2c3e50;">
                <li><?php 
esc_html_e( 'Click "Connect with Google" below and pick your GA4 property and Search Console site from the dropdowns.', 'content-performance-analyzer' );
?></li>
                <?php 
if ( $cpanalyzer_hosted_ai_available ) {
    ?>
                    <li><?php 
    esc_html_e( 'AI recommendations are already on — your Pro plan runs them, so there is no key to set up.', 'content-performance-analyzer' );
    ?></li>
                <?php 
} else {
    ?>
                    <li><?php 
    esc_html_e( 'Optional: choose an AI provider and paste its API key for AI recommendations — Groq and Gemini have free tiers.', 'content-performance-analyzer' );
    ?></li>
                <?php 
}
?>
                <li><?php 
esc_html_e( 'Go to URL Management, click "Load Pages From Your Site", and start the scan.', 'content-performance-analyzer' );
?></li>
            </ol>
        </div>
    </div>
</div>

<form method="post" action="options.php" enctype="multipart/form-data">
    <?php 
settings_fields( 'cpanalyzer_settings' );
do_settings_sections( 'cpanalyzer_settings' );
wp_nonce_field( 'cpanalyzer_settings', 'cpanalyzer_settings_nonce' );
?>
    
    <table class="form-table">
        <?php 
if ( $cpanalyzer_hosted_ai_available ) {
    ?>
        <tr>
            <th scope="row">
                <label><?php 
    esc_html_e( 'AI Engine', 'content-performance-analyzer' );
    ?></label>
            </th>
            <td>
                <?php 
    // Pro runs on the hosted relay. There is no provider to choose
    // and no key to paste, so the selector is not rendered at all —
    // the hidden field keeps the saved value correct on submit.
    ?>
                <input type="hidden" name="cpanalyzer_ai_provider" value="hosted" />
                <div class="cpanalyzer-field cpanalyzer-pro-ai-panel" style="border-left:4px solid #0073aa; background:#f6fbfe; padding:12px 14px; max-width:760px;">
                    <p style="margin:0 0 6px 0; font-weight:600; color:#1d2327;">
                        <?php 
    esc_html_e( 'Content Performance AI — included with Pro', 'content-performance-analyzer' );
    ?>
                    </p>
                    <p class="description" style="margin:0;">
                        <?php 
    esc_html_e( 'Recommendations run on our servers using your Pro plan. There is no API key to manage and no provider account to set up.', 'content-performance-analyzer' );
    ?>
                        <a href="https://cpanalyzer.com/privacy" target="_blank" rel="noopener noreferrer"><?php 
    esc_html_e( 'Privacy details', 'content-performance-analyzer' );
    ?></a>
                    </p>
                    <?php 
    $cpanalyzer_quota = null;
    if ( function_exists( 'cpanalyzer_get_ai_quota__premium_only' ) ) {
        $cpanalyzer_quota = cpanalyzer_get_ai_quota__premium_only();
    }
    if ( is_array( $cpanalyzer_quota ) && isset( $cpanalyzer_quota['remaining'] ) ) {
        ?>
                        <p style="margin:8px 0 0 0; color:#1d2327;">
                            <?php 
        printf( 
            /* translators: %d: number of AI generations left this month. */
            esc_html__( '%d generations left this month.', 'content-performance-analyzer' ),
            (int) $cpanalyzer_quota['remaining']
         );
        ?>
                        </p>
                    <?php 
    } else {
        ?>
                        <p class="description" style="margin:8px 0 0 0;">
                            <?php 
        esc_html_e( 'Your monthly allowance appears here after the first generation.', 'content-performance-analyzer' );
        ?>
                        </p>
                    <?php 
    }
    ?>
                </div>
            </td>
        </tr>
        <?php 
} else {
    ?>
        <tr>
            <th scope="row">
                <label><?php 
    esc_html_e( 'AI Provider', 'content-performance-analyzer' );
    ?></label>
            </th>
            <td>
                <div class="cpanalyzer-field">
                    <p class="description" style="margin-bottom: 10px;">
                        <?php 
    esc_html_e( 'Choose who powers your AI recommendations, then paste that provider\'s API key below. Groq and Gemini both offer free tiers.', 'content-performance-analyzer' );
    ?>
                    </p>

                    <label style="margin-right: 20px;">
                        <input type="radio" name="cpanalyzer_ai_provider" value="openai" <?php 
    checked( $cpanalyzer_provider, 'openai' );
    ?> />
                        <?php 
    esc_html_e( 'OpenAI (gpt-5.4)', 'content-performance-analyzer' );
    ?>
                        <span style="color: #0073aa; font-weight: 600; margin-left: 8px;">
                            <?php 
    esc_html_e( '(Highest quality)', 'content-performance-analyzer' );
    ?>
                        </span>
                    </label>

                    <label style="margin-right: 20px;">
                        <input type="radio" name="cpanalyzer_ai_provider" value="groq" <?php 
    checked( $cpanalyzer_provider, 'groq' );
    ?> />
                        <?php 
    esc_html_e( 'Groq (openai/gpt-oss-120b)', 'content-performance-analyzer' );
    ?>
                        <span style="color: #00a32a; font-weight: 600; margin-left: 8px;">
                            <?php 
    esc_html_e( '(Recommended — Free)', 'content-performance-analyzer' );
    ?>
                        </span>
                    </label>

                    <label>
                        <input type="radio" name="cpanalyzer_ai_provider" value="gemini" <?php 
    checked( $cpanalyzer_provider, 'gemini' );
    ?> />
                        <?php 
    esc_html_e( 'Google Gemini (gemini-2.5-flash)', 'content-performance-analyzer' );
    ?>
                        <span style="color: #00a32a; font-weight: 600; margin-left: 8px;">
                            <?php 
    esc_html_e( '(Free tier)', 'content-performance-analyzer' );
    ?>
                        </span>
                    </label>

                    <p class="description" style="margin-top: 10px;">
                        <strong><?php 
    esc_html_e( 'Groq (Recommended):', 'content-performance-analyzer' );
    ?></strong>
                        <?php 
    esc_html_e( 'Free, fast, and runs a large 120B model that produces the most specific recommendations in our testing. Generous rate limits make it the best default for most sites.', 'content-performance-analyzer' );
    ?>
                        <br>
                        <strong><?php 
    esc_html_e( 'OpenAI:', 'content-performance-analyzer' );
    ?></strong>
                        <?php 
    esc_html_e( 'Runs OpenAI\'s flagship model for the highest-quality recommendations — the premium choice, billed to your OpenAI API credits.', 'content-performance-analyzer' );
    ?>
                        <br>
                        <strong><?php 
    esc_html_e( 'Google Gemini:', 'content-performance-analyzer' );
    ?></strong>
                        <?php 
    esc_html_e( 'Strong quality with a free tier, but tight rate limits (about 10 requests per minute) — large scans run slowly. The plugin paces itself automatically.', 'content-performance-analyzer' );
    ?>
                    </p>
                </div>
            </td>
        </tr>

        <tr class="cpanalyzer-byo-key-setting">
            <th scope="row">
                <label for="cpanalyzer_ai_model"><?php 
    esc_html_e( 'Model Override (optional)', 'content-performance-analyzer' );
    ?></label>
            </th>
            <td>
                <?php 
    $cpanalyzer_current_model = (string) get_option( 'cpanalyzer_ai_model', '' );
    $cpanalyzer_model_groups = array(
        'openai' => array(
            'label'  => 'OpenAI',
            'models' => array(
                'gpt-5.6-terra'          => 'gpt-5.6-terra',
                'gpt-5.6-sol'            => 'gpt-5.6-sol',
                'gpt-5.6-luna'           => 'gpt-5.6-luna',
                'gpt-5.5'                => 'gpt-5.5',
                'gpt-5.4'                => 'gpt-5.4 — ' . __( 'flagship', 'content-performance-analyzer' ),
                'gpt-5.4-mini'           => 'gpt-5.4-mini — ' . __( 'lower cost', 'content-performance-analyzer' ),
                'gpt-5.4-nano'           => 'gpt-5.4-nano — ' . __( 'lowest cost', 'content-performance-analyzer' ),
                'gpt-5.2-pro-2025-12-11' => 'gpt-5.2-pro-2025-12-11 — ' . __( 'premium', 'content-performance-analyzer' ),
                'gpt-5.2-2025-12-11'     => 'gpt-5.2-2025-12-11',
                'gpt-5.1'                => 'gpt-5.1',
                'gpt-5.1-mini'           => 'gpt-5.1-mini — ' . __( 'lower cost', 'content-performance-analyzer' ),
            ),
        ),
        'groq'   => array(
            'label'  => 'Groq',
            'models' => array(
                'openai/gpt-oss-120b'     => 'openai/gpt-oss-120b',
                'llama-3.3-70b-versatile' => 'llama-3.3-70b-versatile',
            ),
        ),
        'gemini' => array(
            'label'  => 'Google Gemini',
            'models' => array(
                'gemini-2.5-flash' => 'gemini-2.5-flash',
                'gemini-2.0-flash' => 'gemini-2.0-flash',
            ),
        ),
    );
    ?>
                <select id="cpanalyzer_ai_model" name="cpanalyzer_ai_model">
                    <option value=""><?php 
    esc_html_e( 'Automatic (recommended default for the provider)', 'content-performance-analyzer' );
    ?></option>
                    <?php 
    foreach ( $cpanalyzer_model_groups as $cpanalyzer_group_key => $cpanalyzer_group ) {
        ?>
                        <optgroup label="<?php 
        echo esc_attr( $cpanalyzer_group['label'] );
        ?>" data-provider="<?php 
        echo esc_attr( $cpanalyzer_group_key );
        ?>">
                            <?php 
        foreach ( $cpanalyzer_group['models'] as $cpanalyzer_model_id => $cpanalyzer_model_label ) {
            ?>
                                <option value="<?php 
            echo esc_attr( $cpanalyzer_model_id );
            ?>" <?php 
            selected( $cpanalyzer_current_model, $cpanalyzer_model_id );
            ?>><?php 
            echo esc_html( $cpanalyzer_model_label );
            ?></option>
                            <?php 
        }
        ?>
                        </optgroup>
                    <?php 
    }
    ?>
                </select>
                <p class="description">
                    <?php 
    esc_html_e( 'Pick the exact model to control quality and cost — the list follows your selected provider. Automatic uses the recommended default with sensible fallbacks. If your API project restricts allowed models, choose the allowed one here.', 'content-performance-analyzer' );
    ?>
                </p>
            </td>
        </tr>

        <tr class="cpanalyzer-byo-key-setting">
            <th scope="row">
                <label for="cpanalyzer_openai_key"><?php 
    esc_html_e( 'API Key', 'content-performance-analyzer' );
    ?></label>
            </th>
            <td>
                <input type="password" 
                        id="cpanalyzer_openai_key"
                        name="cpanalyzer_openai_key" 
                        value="<?php 
    echo esc_attr( get_option( 'cpanalyzer_openai_key' ) );
    ?>" 
                        size="50" 
                        autocomplete="off" />
                <p class="description">
                    <?php 
    esc_html_e( 'Paste your API secret key here. OpenAI keys (sk-…) from', 'content-performance-analyzer' );
    ?>
                    <a href="https://platform.openai.com/api-keys" target="_blank"><?php 
    esc_html_e( 'OpenAI Platform', 'content-performance-analyzer' );
    ?></a>,
                    <?php 
    esc_html_e( 'Groq keys (gsk_…) from', 'content-performance-analyzer' );
    ?>
                    <a href="https://console.groq.com/keys" target="_blank"><?php 
    esc_html_e( 'Groq Console', 'content-performance-analyzer' );
    ?></a>,
                    <?php 
    esc_html_e( 'or Gemini keys (AIza…) from', 'content-performance-analyzer' );
    ?>
                    <a href="https://aistudio.google.com/apikey" target="_blank"><?php 
    esc_html_e( 'Google AI Studio', 'content-performance-analyzer' );
    ?></a>.
                </p>
            </td>
        </tr>
        <?php 
}
?>

        <?php 
if ( $cpanalyzer_hosted_ai_available ) {
    ?>
        <tr>
            <th scope="row">
                <label><?php 
    esc_html_e( 'Competitor Analysis', 'content-performance-analyzer' );
    ?></label>
            </th>
            <td>
                <?php 
    // The relay provides the searches on Pro, so there is no key
    // to collect. The hidden field carries any previously saved
    // key through the save so it is not silently wiped — a saved
    // personal key still takes precedence over the relay.
    ?>
                <input type="hidden" name="cpanalyzer_serper_api_key" value="<?php 
    echo esc_attr( get_option( 'cpanalyzer_serper_api_key', '' ) );
    ?>" />
                <div class="cpanalyzer-field cpanalyzer-pro-ai-panel" style="border-left:4px solid #0073aa; background:#f6fbfe; padding:12px 14px; max-width:760px;">
                    <p style="margin:0 0 6px 0; font-weight:600; color:#1d2327;">
                        <?php 
    esc_html_e( 'Competitor gap analysis — included with Pro', 'content-performance-analyzer' );
    ?>
                    </p>
                    <p class="description" style="margin:0;">
                        <?php 
    esc_html_e( 'The plugin searches Google for each page\'s primary keyword, fetches the top competitor pages, and compares their structure against yours. Searches run through your Pro plan — 600 a month, no key to set up.', 'content-performance-analyzer' );
    ?>
                    </p>
                </div>
            </td>
        </tr>
        <?php 
} else {
    ?>
        <tr>
            <th scope="row">
                <label for="cpanalyzer_serper_api_key">
                    <?php 
    esc_html_e( 'Serper.dev API Key', 'content-performance-analyzer' );
    ?>
                    <span style="display:inline-block; background:#0073aa; color:#fff; font-size:10px; font-weight:700; padding:1px 6px; border-radius:3px; margin-left:6px; text-transform:uppercase; letter-spacing:.5px;">Pro</span>
                </label>
            </th>
            <td>
                <input
                    type="password"
                    id="cpanalyzer_serper_api_key"
                    name="cpanalyzer_serper_api_key"
                    value="<?php 
    echo esc_attr( get_option( 'cpanalyzer_serper_api_key', '' ) );
    ?>"
                    class="regular-text"
                    autocomplete="new-password"
                    placeholder="<?php 
    esc_attr_e( 'Enter your Serper.dev API key', 'content-performance-analyzer' );
    ?>"
                />
                <p class="description">
                    <?php 
    printf( 
        /* translators: %s: URL to serper.dev */
        wp_kses( __( 'Enables <strong>real competitor gap analysis</strong>. The plugin will search Google for each page\'s primary keyword, fetch the top 3 competitor pages, and compare their structure against yours — giving the AI actual data instead of guesses. Get a free key (2,500 searches/mo) at <a href="%s" target="_blank" rel="noopener noreferrer">serper.dev</a>.', 'content-performance-analyzer' ), array(
            'strong' => array(),
            'a'      => array(
                'href'   => array(),
                'target' => array(),
                'rel'    => array(),
            ),
        ) ),
        'https://serper.dev'
     );
    ?>
                </p>
                <?php 
    $serper_key = get_option( 'cpanalyzer_serper_api_key', '' );
    if ( !empty( $serper_key ) && strlen( trim( $serper_key ) ) > 10 ) {
        ?>
                    <p style="color:#46b450; font-weight:600; margin-top:4px;">
                        <?php 
        esc_html_e( 'Serper API key saved — competitor analysis is active.', 'content-performance-analyzer' );
        ?>
                    </p>
                    <?php 
    } else {
        ?>
                    <p style="color:#999; margin-top:4px; font-style:italic;">
                        <?php 
        esc_html_e( 'Without this key, AI suggestions use internal data only (no competitor comparison).', 'content-performance-analyzer' );
        ?>
                    </p>
                    <?php 
    }
    ?>
            </td>
        </tr>
        <?php 
}
?>


        <tr>
            <th scope="row">
                <label for="cpanalyzer_property_id"><?php 
esc_html_e( 'GA4 Property ID', 'content-performance-analyzer' );
?></label>
            </th>
            <td>
                <input type="text"
                        id="cpanalyzer_property_id"
                        name="cpanalyzer_property_id"
                        value="<?php 
echo esc_attr( get_option( 'cpanalyzer_property_id' ) );
?>"
                        autocomplete="off" />
                <?php 
if ( ( new CPAP_Google_OAuth() )->is_connected() ) {
    ?>
                    <button type="button" id="cpanalyzer-load-properties" class="button">
                        <?php 
    esc_html_e( 'Choose from your Google account', 'content-performance-analyzer' );
    ?>
                    </button>
                    <span id="cpanalyzer-properties-status" role="status"></span>
                    <div id="cpanalyzer-property-picker" style="margin-top:8px; display:none;">
                        <select id="cpanalyzer-property-select" style="max-width:100%;"></select>
                    </div>
                <?php 
}
?>
                <p class="description">
                    <?php 
esc_html_e( 'e.g. 123456789 - Find this in your GA4 property settings.', 'content-performance-analyzer' );
?>
                </p>
            </td>
        </tr>

        <tr>
            <th scope="row">
                <label for="cpanalyzer_site_url"><?php 
esc_html_e( 'Search Console Site URL', 'content-performance-analyzer' );
?></label>
            </th>
            <td>
                <input type="text"
                        id="cpanalyzer_site_url"
                        name="cpanalyzer_site_url"
                        value="<?php 
echo esc_attr( get_option( 'cpanalyzer_site_url' ) );
?>"
                        autocomplete="off" />
                <?php 
if ( ( new CPAP_Google_OAuth() )->is_connected() ) {
    ?>
                    <div id="cpanalyzer-site-picker" style="margin-top:8px; display:none;">
                        <select id="cpanalyzer-site-select" style="max-width:100%;"></select>
                    </div>
                <?php 
}
?>
                <p class="description">
                    <?php 
esc_html_e( 'e.g. sc-domain:yoursite.com or https://yoursite.com/', 'content-performance-analyzer' );
?>
                </p>
            </td>
        </tr>

        <tr>
            <th scope="row">
                <label for="cpanalyzer_conversion_events"><?php 
esc_html_e( 'Conversion Events (optional)', 'content-performance-analyzer' );
?></label>
            </th>
            <td>
                <input type="text"
                        id="cpanalyzer_conversion_events"
                        name="cpanalyzer_conversion_events"
                        value="<?php 
echo esc_attr( get_option( 'cpanalyzer_conversion_events', '' ) );
?>"
                        placeholder="<?php 
esc_attr_e( 'e.g. demo_submit, trial_registration', 'content-performance-analyzer' );
?>"
                        autocomplete="off" />
                <p class="description">
                    <?php 
esc_html_e( 'Leave empty to use the key events marked in your GA4 property (recommended). If no key events are set up, the built-in form_submit event is used. Enter comma-separated GA4 event names to override.', 'content-performance-analyzer' );
?>
                </p>
            </td>
        </tr>
        
        <?php 
/* ---------- OAuth Connection Status Banner ---------- */
$cpanalyzer_oauth = new CPAP_Google_OAuth();
$cpanalyzer_oauth_connected = $cpanalyzer_oauth->is_connected();
$cpanalyzer_oauth_email = $cpanalyzer_oauth->get_connected_email();
// Show feedback from the OAuth callback redirect.
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( !empty( $_GET['cpanalyzer_oauth_success'] ) ) {
    echo '<div class="notice notice-success is-dismissible" style="margin-bottom:16px;"><p><strong>' . esc_html__( '✓ Google account connected successfully!', 'content-performance-analyzer' ) . '</strong></p></div>';
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( !empty( $_GET['cpanalyzer_oauth_error'] ) ) {
    echo '<div class="notice notice-error is-dismissible" style="margin-bottom:16px;"><p><strong>' . esc_html__( 'Google connection failed: ', 'content-performance-analyzer' ) . esc_html( urldecode( sanitize_text_field( wp_unslash( $_GET['cpanalyzer_oauth_error'] ) ) ) ) . '</strong></p></div>';
}
?>

        <!-- Section heading: Google Connection -->
        <tr>
            <th colspan="2" style="background:#f8f9fa; padding:15px; border-left:4px solid #4285f4;">
                <h3 style="margin:0; color:#4285f4;">
                    🔗 <?php 
esc_html_e( 'Google Connection', 'content-performance-analyzer' );
?>
                </h3>
                <p style="margin:5px 0 0; font-weight:normal; font-size:13px; color:#666;">
                    <?php 
esc_html_e( 'One click connects GA4 and Search Console. No Google Cloud setup needed — the credential fields below are only for advanced users who prefer their own OAuth client.', 'content-performance-analyzer' );
?>
                </p>
            </th>
        </tr>

        <!-- One-click hosted connect -->
        <?php 
if ( !$cpanalyzer_oauth_connected ) {
    ?>
        <tr>
            <th scope="row"><?php 
    esc_html_e( 'Quick Connect', 'content-performance-analyzer' );
    ?></th>
            <td>
                <a href="<?php 
    echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=cpanalyzer-settings&cpanalyzer_hosted_start=1' ), 'cpanalyzer_hosted_start' ) );
    ?>"
                   class="button button-primary"
                   style="display:inline-flex; align-items:center; gap:6px; font-size:14px; padding:8px 18px; height:auto; line-height:1.4;">
                    <span style="font-size:16px;">🔗</span>
                    <?php 
    esc_html_e( 'Connect with Google', 'content-performance-analyzer' );
    ?>
                </a>
                <p class="description" style="margin-top:8px;">
                    <?php 
    esc_html_e( 'Sign in, pick your Google account, done. Read-only access to Analytics and Search Console — you can disconnect anytime.', 'content-performance-analyzer' );
    ?>
                    <a href="https://cpanalyzer.com/privacy" target="_blank" rel="noopener noreferrer"><?php 
    esc_html_e( 'Privacy Policy', 'content-performance-analyzer' );
    ?></a>
                </p>
            </td>
        </tr>
        <?php 
}
?>

        <?php 
// BYO OAuth credentials are legacy: hosted "Connect with Google" is
// the path now. Show these fields only when credentials are already
// saved (so existing users keep control), or when explicitly enabled
// via the cpanalyzer_show_byo_oauth_fields filter.
$cpanalyzer_show_byo_oauth = '' !== get_option( 'cpanalyzer_oauth_client_id', '' ) || '' !== get_option( 'cpanalyzer_oauth_client_secret', '' ) || apply_filters( 'cpanalyzer_show_byo_oauth_fields', false );
?>
        <?php 
if ( $cpanalyzer_show_byo_oauth ) {
    ?>
        <!-- OAuth Client ID (advanced / BYO credentials) -->
        <tr>
            <th scope="row">
                <label for="cpanalyzer_oauth_client_id"><?php 
    esc_html_e( 'OAuth Client ID (advanced)', 'content-performance-analyzer' );
    ?></label>
            </th>
            <td>
                <input type="text"
                       id="cpanalyzer_oauth_client_id"
                       name="cpanalyzer_oauth_client_id"
                       value="<?php 
    echo esc_attr( get_option( 'cpanalyzer_oauth_client_id', '' ) );
    ?>"
                       size="60"
                       autocomplete="off" />
                <p class="description">
                    <?php 
    esc_html_e( 'From Google Cloud Console → APIs & Services → Credentials → OAuth 2.0 Client ID.', 'content-performance-analyzer' );
    ?>
                </p>
            </td>
        </tr>

        <!-- OAuth Client Secret -->
        <tr>
            <th scope="row">
                <label for="cpanalyzer_oauth_client_secret"><?php 
    esc_html_e( 'OAuth Client Secret', 'content-performance-analyzer' );
    ?></label>
            </th>
            <td>
                <input type="password"
                       id="cpanalyzer_oauth_client_secret"
                       name="cpanalyzer_oauth_client_secret"
                       value="<?php 
    echo esc_attr( get_option( 'cpanalyzer_oauth_client_secret', '' ) );
    ?>"
                       size="60"
                       autocomplete="off" />
                <p class="description">
                    <?php 
    esc_html_e( 'Keep this secret. Never commit it to version control.', 'content-performance-analyzer' );
    ?>
                </p>
            </td>
        </tr>
        <?php 
}
?>

        <!-- Connection Status + Connect / Disconnect button -->
        <tr>
            <th scope="row"><?php 
esc_html_e( 'Google Account', 'content-performance-analyzer' );
?></th>
            <td>
                <?php 
if ( $cpanalyzer_oauth_connected ) {
    ?>
                    <div id="cpanalyzer-oauth-status" style="display:flex; align-items:center; gap:12px; background:#f0f8f0; border:1px solid #00a32a; border-radius:6px; padding:12px 16px; max-width:520px;">
                        <span style="font-size:20px;">✅</span>
                        <div>
                            <strong style="color:#00a32a;"><?php 
    esc_html_e( 'Connected', 'content-performance-analyzer' );
    ?></strong>
                            <?php 
    if ( $cpanalyzer_oauth_email ) {
        ?>
                                <br><small style="color:#555;"><?php 
        echo esc_html( $cpanalyzer_oauth_email );
        ?></small>
                            <?php 
    }
    ?>
                        </div>
                        <button type="button" id="cpanalyzer-oauth-disconnect" class="button" style="margin-left:auto; color:#d63638; border-color:#d63638;">
                            <?php 
    esc_html_e( 'Disconnect', 'content-performance-analyzer' );
    ?>
                        </button>
                    </div>
                <?php 
} else {
    ?>
                    <div id="cpanalyzer-oauth-status" style="display:flex; align-items:center; gap:12px; background:#fff8f0; border:1px solid #dba617; border-radius:6px; padding:12px 16px; max-width:520px;">
                        <span style="font-size:20px;">⚠️</span>
                        <div>
                            <strong style="color:#856404;"><?php 
    esc_html_e( 'Not Connected', 'content-performance-analyzer' );
    ?></strong>
                            <br><small style="color:#555;"><?php 
    echo esc_html( ( $cpanalyzer_show_byo_oauth ? __( 'Use the "Connect with Google" button above — or save your own Client ID & Secret and connect below.', 'content-performance-analyzer' ) : __( 'Use the "Connect with Google" button above to link GA4 and Search Console in one click.', 'content-performance-analyzer' ) ) );
    ?></small>
                        </div>
                    </div>
                    <br>
                    <?php 
    $cpanalyzer_auth_url = '';
    if ( !empty( get_option( 'cpanalyzer_oauth_client_id', '' ) ) && !empty( get_option( 'cpanalyzer_oauth_client_secret', '' ) ) ) {
        $cpanalyzer_auth_url = $cpanalyzer_oauth->get_authorization_url();
    }
    ?>
                    <?php 
    if ( $cpanalyzer_auth_url ) {
        ?>
                        <a href="<?php 
        echo esc_url( $cpanalyzer_auth_url );
        ?>"
                           class="button"
                           style="display:inline-flex; align-items:center; gap:6px; font-size:14px; padding:8px 18px; height:auto; line-height:1.4;">
                            <span style="font-size:16px;">🔗</span>
                            <?php 
        esc_html_e( 'Connect with your own OAuth client', 'content-performance-analyzer' );
        ?>
                        </a>
                    <?php 
    }
    ?>
                <?php 
}
?>

                <?php 
if ( !empty( get_option( 'cpanalyzer_oauth_client_id', '' ) ) ) {
    ?>
                <p class="description" style="margin-top:10px;">
                    <?php 
    esc_html_e( 'Using your own OAuth client? Set its Authorized Redirect URI in Google Cloud Console to:', 'content-performance-analyzer' );
    ?>
                    <br>
                    <code><?php 
    echo esc_html( $cpanalyzer_oauth->get_redirect_uri() );
    ?></code>
                </p>
                <?php 
}
?>
            </td>
        </tr>
        <tr>
<th scope="row">
    <label for="cpanalyzer_batch_size"><?php 
esc_html_e( 'Batch Size', 'content-performance-analyzer' );
?></label>
</th>
<td>
    <input type="number" 
            id="cpanalyzer_batch_size"
            name="cpanalyzer_batch_size" 
            value="<?php 
echo esc_attr( get_option( 'cpanalyzer_batch_size', 10 ) );
?>" 
            min="1" 
            max="50" />
    <p class="description">
        <?php 
esc_html_e( 'Number of URLs to process per batch (1-50)', 'content-performance-analyzer' );
?>
    </p>
</td>
</tr>

<tr>
<th scope="row">
    <label for="cpanalyzer_off_peak_hour"><?php 
esc_html_e( 'Off-Peak Hour', 'content-performance-analyzer' );
?></label>
</th>
<td>
    <select id="cpanalyzer_off_peak_hour" name="cpanalyzer_off_peak_hour">
        <?php 
$cpanalyzer_current_hour = get_option( 'cpanalyzer_off_peak_hour', 2 );
for ($cpanalyzer_iter = 0; $cpanalyzer_iter < 24; $cpanalyzer_iter++) {
    ?>
            <option value="<?php 
    echo esc_attr( $cpanalyzer_iter );
    ?>" <?php 
    selected( $cpanalyzer_current_hour, $cpanalyzer_iter );
    ?>>
                <?php 
    echo esc_html( sprintf( '%02d:00', $cpanalyzer_iter ) );
    ?>
            </option>
        <?php 
}
?>
    </select>
    <p class="description">
        <?php 
printf( 
    /* translators: %s: WordPress site timezone string e.g. "America/Chicago" */
    esc_html__( 'Hour to run automatic full scan (site timezone: %s)', 'content-performance-analyzer' ),
    esc_html( wp_timezone_string() )
 );
?>
    </p>
</td>
</tr>

<tr>
<th scope="row">
    <label for="cpanalyzer_enable_auto_scan"><?php 
esc_html_e( 'Enable Auto Scan', 'content-performance-analyzer' );
?></label>
</th>
<td>
    <label>
        <input type="checkbox" 
                id="cpanalyzer_enable_auto_scan"
                name="cpanalyzer_enable_auto_scan" 
                value="yes" 
                <?php 
checked( get_option( 'cpanalyzer_enable_auto_scan', 'no' ), 'yes' );
?> />
        <?php 
esc_html_e( 'Enable automatic daily scanning during off-peak hours', 'content-performance-analyzer' );
?>
    </label>
</td>
</tr>
<tr>
  <th scope="row">
    <label for="cpanalyzer_verify_ssl"><?php 
esc_html_e( 'Verify SSL (scraper)', 'content-performance-analyzer' );
?></label>
  </th>
  <td>
    <label>
      <!-- Hidden field to ensure 'no' is sent when unchecked -->
      <input type="hidden" name="cpanalyzer_verify_ssl" value="no" />
      <input type="checkbox"
             id="cpanalyzer_verify_ssl"
             name="cpanalyzer_verify_ssl"
             value="yes"
             <?php 
checked( get_option( 'cpanalyzer_verify_ssl', 'yes' ), 'yes' );
?> />
      <?php 
esc_html_e( 'Enable SSL verification (recommended for production)', 'content-performance-analyzer' );
?>
    </label>
  </td>
</tr>

<!-- AI Visibility Section -->
<tr>
    <th colspan="2" style="background-color: #f8f9fa; padding: 15px; border-left: 4px solid #7c3aed;">
        <h3 style="margin: 0; color: #7c3aed;">
            🤖 <?php 
esc_html_e( 'AI Visibility', 'content-performance-analyzer' );
?>
        </h3>
        <p style="margin: 5px 0 0 0; font-weight: normal; font-size: 13px; color: #666;">
            <?php 
esc_html_e( 'Help AI assistants understand and cite your site', 'content-performance-analyzer' );
?>
        </p>
    </th>
</tr>

<tr>
    <th scope="row">
        <label for="cpanalyzer_llms_txt_enable"><?php 
esc_html_e( 'Publish llms.txt', 'content-performance-analyzer' );
?></label>
    </th>
    <td>
        <label>
            <input type="checkbox"
                    id="cpanalyzer_llms_txt_enable"
                    name="cpanalyzer_llms_txt_enable"
                    value="yes"
                    <?php 
checked( get_option( 'cpanalyzer_llms_txt_enable', 'no' ), 'yes' );
?> />
            <?php 
esc_html_e( 'Serve a machine-readable site guide for AI crawlers at /llms.txt', 'content-performance-analyzer' );
?>
        </label>
        <p class="description">
            <?php 
esc_html_e( 'Generated automatically from your analyzed pages (titles and descriptions). Leave off if another plugin already provides llms.txt.', 'content-performance-analyzer' );
?>
            <?php 
if ( 'yes' === get_option( 'cpanalyzer_llms_txt_enable', 'no' ) ) {
    ?>
                <a href="<?php 
    echo esc_url( home_url( '/llms.txt' ) );
    ?>" target="_blank"><?php 
    esc_html_e( 'View your llms.txt', 'content-performance-analyzer' );
    ?></a>
            <?php 
}
?>
        </p>
    </td>
</tr>

<!-- PageSpeed Insights Settings Section -->
<tr>
    <th colspan="2" style="background-color: #f8f9fa; padding: 15px; border-left: 4px solid #4285f4;">
        <h3 style="margin: 0; color: #4285f4;">
            📊 <?php 
esc_html_e( 'PageSpeed Insights Configuration', 'content-performance-analyzer' );
?>
        </h3>
        <p style="margin: 5px 0 0 0; font-weight: normal; font-size: 13px; color: #666;">
            <?php 
esc_html_e( 'Optional: Add performance metrics to your content analysis', 'content-performance-analyzer' );
?>
        </p>
    </th>
</tr>

<tr>
    <th scope="row">
        <label for="cpanalyzer_pagespeed_enable"><?php 
esc_html_e( 'Enable PageSpeed Analysis', 'content-performance-analyzer' );
?></label>
    </th>
    <td>
        <label>
            <input type="checkbox"
                    id="cpanalyzer_pagespeed_enable"
                    name="cpanalyzer_pagespeed_enable"
                    value="yes"
                    <?php 
checked( get_option( 'cpanalyzer_pagespeed_enable', 'no' ), 'yes' );
?> />
            <?php 
esc_html_e( 'Enable PageSpeed Insights analysis', 'content-performance-analyzer' );
?>
        </label>
        <p class="description">
            <?php 
esc_html_e( 'Analyzes Core Web Vitals and performance scores through the free hosted service — no API key or setup needed. Off by default.', 'content-performance-analyzer' );
?>
        </p>
    </td>
</tr>

<?php 
// PSI sub-settings only matter once the feature is on — hidden otherwise.
// admin.js toggles them live when the checkbox changes.
$cpanalyzer_psi_row_attr = ( 'yes' === get_option( 'cpanalyzer_pagespeed_enable', 'no' ) ? '' : ' style="display:none;"' );
?>
<tr class="cpanalyzer-psi-setting"<?php 
echo $cpanalyzer_psi_row_attr;
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Static attribute string defined above.
?>>
    <th scope="row">
        <?php 
esc_html_e( 'Pages to Analyze', 'content-performance-analyzer' );
?>
    </th>
    <td>
        <?php 
$cpanalyzer_psi_selected = array_map( 'strval', (array) get_option( 'cpanalyzer_psi_pages', array() ) );
$cpanalyzer_psi_page_query = new WP_Query(array(
    'post_type'              => array_values( array_diff( get_post_types( array(
        'public' => true,
    ), 'names' ), array('attachment') ) ),
    'post_status'            => 'publish',
    'posts_per_page'         => 200,
    'orderby'                => array(
        'type'  => 'ASC',
        'title' => 'ASC',
    ),
    'fields'                 => 'ids',
    'no_found_rows'          => true,
    'update_post_meta_cache' => false,
    'update_post_term_cache' => false,
));
$cpanalyzer_psi_choices = array(
    '/' => __( 'Homepage', 'content-performance-analyzer' ),
);
foreach ( $cpanalyzer_psi_page_query->posts as $cpanalyzer_psi_post_id ) {
    if ( !is_post_publicly_viewable( $cpanalyzer_psi_post_id ) ) {
        continue;
    }
    $cpanalyzer_psi_path = cpanalyzer_normalize_path( (string) get_permalink( $cpanalyzer_psi_post_id ) );
    if ( '' !== $cpanalyzer_psi_path && !isset( $cpanalyzer_psi_choices[$cpanalyzer_psi_path] ) ) {
        $cpanalyzer_psi_choices[$cpanalyzer_psi_path] = get_the_title( $cpanalyzer_psi_post_id );
    }
}
?>
        <!-- Empty marker so clearing every checkbox still saves an empty list. -->
        <input type="hidden" name="cpanalyzer_psi_pages[]" value="" />
        <p style="margin-top:0;">
            <input type="search"
                    id="cpanalyzer-psi-page-search"
                    placeholder="<?php 
esc_attr_e( 'Search pages by title or path…', 'content-performance-analyzer' );
?>"
                    style="width: 320px; max-width: 100%;" />
        </p>
        <div class="cpanalyzer-site-pages-list" id="cpanalyzer-psi-pages-list" style="max-width:640px;">
            <?php 
foreach ( $cpanalyzer_psi_choices as $cpanalyzer_psi_path => $cpanalyzer_psi_title ) {
    ?>
                <label class="cpanalyzer-page-row">
                    <input type="checkbox"
                            class="cpanalyzer-psi-page-checkbox"
                            name="cpanalyzer_psi_pages[]"
                            value="<?php 
    echo esc_attr( $cpanalyzer_psi_path );
    ?>"
                            <?php 
    checked( in_array( $cpanalyzer_psi_path, $cpanalyzer_psi_selected, true ) );
    ?> />
                    <span class="cpanalyzer-page-title"><?php 
    echo esc_html( ( '' !== $cpanalyzer_psi_title ? $cpanalyzer_psi_title : __( '(no title)', 'content-performance-analyzer' ) ) );
    ?></span>
                    <code class="cpanalyzer-page-path"><?php 
    echo esc_html( $cpanalyzer_psi_path );
    ?></code>
                </label>
            <?php 
}
?>
        </div>
        <p class="description">
            <span id="cpanalyzer-psi-pages-count"></span>
            <?php 
printf( 
    /* translators: %d: maximum number of selectable pages. */
    esc_html__( 'Pick up to %d pages for PageSpeed analysis. Leave all unticked to let the plugin choose automatically (flagged and high-traffic pages).', 'content-performance-analyzer' ),
    (int) cpanalyzer_psi_page_limit()
 );
?>
        </p>
    </td>
</tr>

<tr class="cpanalyzer-psi-setting"<?php 
echo $cpanalyzer_psi_row_attr;
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Static attribute string defined above.
?>>
    <th scope="row">
        <label for="cpanalyzer_pagespeed_strategy"><?php 
esc_html_e( 'Analysis Strategy', 'content-performance-analyzer' );
?></label>
    </th>
    <td>
        <select id="cpanalyzer_pagespeed_strategy" name="cpanalyzer_pagespeed_strategy">
            <?php 
$cpanalyzer_current_strategy = get_option( 'cpanalyzer_pagespeed_strategy', 'mobile' );
$cpanalyzer_strategies = array(
    'mobile'  => __( 'Mobile Only', 'content-performance-analyzer' ),
    'desktop' => __( 'Desktop Only', 'content-performance-analyzer' ),
    'both'    => __( 'Both Mobile & Desktop', 'content-performance-analyzer' ),
);
foreach ( $cpanalyzer_strategies as $cpanalyzer_value => $cpanalyzer_label ) {
    ?>
                <option value="<?php 
    echo esc_attr( $cpanalyzer_value );
    ?>" <?php 
    selected( $cpanalyzer_current_strategy, $cpanalyzer_value );
    ?>>
                    <?php 
    echo esc_html( $cpanalyzer_label );
    ?>
                </option>
            <?php 
}
?>
        </select>
        <p class="description">
            <?php 
esc_html_e( 'Mobile is recommended for Core Web Vitals. "Both" uses 2x API quota.', 'content-performance-analyzer' );
?>
        </p>
    </td>
</tr>

<tr class="cpanalyzer-psi-setting"<?php 
echo $cpanalyzer_psi_row_attr;
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Static attribute string defined above.
?>>
    <th scope="row">
        <label for="cpanalyzer_pagespeed_rate_limit"><?php 
esc_html_e( 'Rate Limit', 'content-performance-analyzer' );
?></label>
    </th>
    <td>
        <input type="number" 
                id="cpanalyzer_pagespeed_rate_limit"
                name="cpanalyzer_pagespeed_rate_limit" 
                value="<?php 
echo esc_attr( get_option( 'cpanalyzer_pagespeed_rate_limit', 30 ) );
?>" 
                min="1" 
                max="60" />
        <label for="cpanalyzer_pagespeed_rate_limit"><?php 
esc_html_e( 'requests per minute', 'content-performance-analyzer' );
?></label>
        <p class="description">
            <?php 
esc_html_e( 'Recommended: 30/min. Lower if you hit rate limits.', 'content-performance-analyzer' );
?>
        </p>
    </td>
</tr>

<tr class="cpanalyzer-psi-setting"<?php 
echo $cpanalyzer_psi_row_attr;
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Static attribute string defined above.
?>>
    <th scope="row">
        <label for="cpanalyzer_pagespeed_categories"><?php 
esc_html_e( 'Analysis Categories', 'content-performance-analyzer' );
?></label>
    </th>
    <td>
        <?php 
$cpanalyzer_current_categories = get_option( 'cpanalyzer_pagespeed_categories', array('PERFORMANCE') );
$cpanalyzer_available_categories = array(
    'PERFORMANCE'    => __( 'Performance', 'content-performance-analyzer' ),
    'SEO'            => __( 'SEO', 'content-performance-analyzer' ),
    'ACCESSIBILITY'  => __( 'Accessibility', 'content-performance-analyzer' ),
    'BEST_PRACTICES' => __( 'Best Practices', 'content-performance-analyzer' ),
);
foreach ( $cpanalyzer_available_categories as $cpanalyzer_value => $cpanalyzer_label ) {
    ?>
            <label style="display: inline-block; margin-right: 15px; margin-bottom: 5px;">
                <input type="checkbox" 
                        name="cpanalyzer_pagespeed_categories[]" 
                        value="<?php 
    echo esc_attr( $cpanalyzer_value );
    ?>" 
                        <?php 
    checked( in_array( $cpanalyzer_value, $cpanalyzer_current_categories ) );
    ?> />
                <?php 
    echo esc_html( $cpanalyzer_label );
    ?>
            </label>
        <?php 
}
?>
        <p class="description">
            <?php 
esc_html_e( 'Performance is required for Core Web Vitals analysis.', 'content-performance-analyzer' );
?>
        </p>
    </td>
</tr>

<tr class="cpanalyzer-psi-setting"<?php 
echo $cpanalyzer_psi_row_attr;
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Static attribute string defined above.
?>>
    <th scope="row">
        <label for="cpanalyzer_pagespeed_cache_hours"><?php 
esc_html_e( 'Cache Duration', 'content-performance-analyzer' );
?></label>
    </th>
    <td>
        <input type="number" 
                id="cpanalyzer_pagespeed_cache_hours"
                name="cpanalyzer_pagespeed_cache_hours" 
                value="<?php 
echo esc_attr( get_option( 'cpanalyzer_pagespeed_cache_hours', 24 ) );
?>" 
                min="1" 
                max="168" />
        <label for="cpanalyzer_pagespeed_cache_hours"><?php 
esc_html_e( 'hours', 'content-performance-analyzer' );
?></label>
        <p class="description">
            <?php 
esc_html_e( 'How long to cache PSI results before re-analyzing. 24h recommended.', 'content-performance-analyzer' );
?>
        </p>
    </td>
</tr>
    </table>
    
    <?php 
submit_button();
?>
</form>

</div>
