<?php
if (!defined('ABSPATH')) exit;


function acwbsrh_api_page() {
 	// Handle form submission
	if (isset($_POST['acwbsrh_api_key_submit']) && check_admin_referer('acwbsrh_api_key_form')) {
		$acwbsrh_api_key = isset($_POST['acwbsrh_api_key']) ? sanitize_text_field(wp_unslash($_POST['acwbsrh_api_key'])) : '';
		update_option('acwbsrh_api_key', $acwbsrh_api_key);
		echo '<div class="notice notice-success is-dismissible"><p><strong>API Key saved successfully.</strong></p></div>';
	}

    $saved_key = get_option('acwbsrh_api_key', '');
    ?>
    <div class="wrap">
        <h1>🔑 Connect Gemini API</h1>
        <p>Enter your Gemini API key below to enable blog generation with Google's Gemini AI models.</p>

        <div class="notice notice-info" style="margin-top: 20px;">
            <p><strong>Note:</strong> You must be logged in with your Google account to access your API key.</p>
        </div>

        <form method="post" style="margin-top: 20px;">
            <?php wp_nonce_field('acwbsrh_api_key_form'); ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row"><label for="acwbsrh_api_key">Your Gemini API Key</label></th>
                    <td>
                        <input type="text" id="acwbsrh_api_key" name="acwbsrh_api_key" value="<?php echo esc_attr($saved_key); ?>" class="regular-text code" placeholder="Enter your API key here..." />
                        <p class="description">Paste the API key you copied from Google AI Studio.</p>
                    </td>
                </tr>
            </table>
            <?php submit_button('Save API Key', 'primary', 'acwbsrh_api_key_submit'); ?>
        </form>

        <hr style="margin: 40px 0;">

        <h2>🧭 How to Get Your Gemini API Key</h2>
        <ol style="line-height: 1.8; padding-left: 20px;">
            <li>Go to <a href="https://aistudio.google.com/app/apikey" target="_blank" rel="noopener noreferrer">https://aistudio.google.com/app/apikey</a></li>
            <li>Log in with your Google account.</li>
            <li>Click <strong>“Get API Key”</strong> in the popup.</li>
            <li>Accept the terms by checking both boxes and clicking <strong>“I accept”</strong></li>
            <li>Click <strong>“+ Create API Key”</strong> in the dashboard.</li>
            <li>Choose <strong>“Create API Key in new project”</strong>.</li>
            <li>Once the key is generated, click <strong>“Copy”</strong>.</li>
            <li>Paste it in the field above and click <strong>Save API Key</strong>.</li>
        </ol>

        <div class="notice notice-warning" style="margin-top: 20px;">
            <p><strong>Security Tip:</strong> Treat your API key like a password. Never share or expose it publicly.</p>
        </div>
    </div>
    <?php
}