<?php
/**
 * AgentForms WordPress Plugin — Admin Settings Page
 *
 * Settings:
 *   - Default theme (light/dark)
 *   - Default success message
 *   - API base URL (defaults to https://agentforms.io)
 *   - Clear config cache button
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Add top-level menu item.
 */
function agentforms_add_menu() {
    add_menu_page(
        'AgentForms',
        'AgentForms',
        'manage_options',
        'agentforms',
        'agentforms_settings_page',
        'dashicons-admin-generic',
        100
    );
}
add_action( 'admin_menu', 'agentforms_add_menu' );

/**
 * Register plugin settings.
 */
function agentforms_register_settings() {
    register_setting( 'agentforms_settings_group', 'agentforms_settings', array(
        'type'              => 'array',
        'sanitize_callback' => 'agentforms_sanitize_settings',
        'default'           => array(
            'default_theme'           => 'light',
            'default_success_message' => 'Thank you! We will be in touch.',
            'api_base_url'            => 'https://agentforms.io',
        ),
    ) );
}
add_action( 'init', 'agentforms_register_settings' );

/**
 * Sanitize settings input.
 *
 * @param array $input Raw settings array.
 * @return array       Sanitized settings.
 */
function agentforms_sanitize_settings( $input ) {
    $sanitized = array();

    $sanitized['default_theme'] = isset( $input['default_theme'] ) ? sanitize_text_field( $input['default_theme'] ) : 'light';
    if ( ! in_array( $sanitized['default_theme'], array( 'light', 'dark' ), true ) ) {
        $sanitized['default_theme'] = 'light';
    }

    $sanitized['default_success_message'] = isset( $input['default_success_message'] ) ? sanitize_textarea_field( $input['default_success_message'] ) : '';

    $sanitized['api_base_url'] = isset( $input['api_base_url'] ) ? esc_url_raw( $input['api_base_url'] ) : 'https://agentforms.io';

    return $sanitized;
}

/**
 * Render settings page.
 */
function agentforms_settings_page() {
    // Handle cache clear action
    if ( isset( $_GET['action'] ) && $_GET['action'] === 'clear_cache' && isset( $_GET['_wpnonce'] ) ) {
        if ( wp_verify_nonce( $_GET['_wpnonce'], 'agentforms_clear_cache' ) ) {
            agentforms_clear_all_caches();
            wp_safe_redirect( admin_url( 'admin.php?page=agentforms&cleared=1' ) );
            exit;
        }
    }

    $settings = get_option( 'agentforms_settings', array() );
    ?>
    <div class="wrap agentforms-settings-wrap">
        <h1>AgentForms Settings</h1>

        <?php if ( isset( $_GET['cleared'] ) ) : ?>
            <div class="notice notice-success is-dismissible">
                <p>All cached form configurations have been cleared.</p>
            </div>
        <?php endif; ?>

        <div class="agentforms-settings-grid">
            <form method="post" action="options.php" class="agentforms-settings-form">
                <?php wp_nonce_field( 'update_options_' . 'agentforms_settings_group' ); ?>
                <?php settings_fields( 'agentforms_settings_group' ); ?>
                <?php $opts = get_option( 'agentforms_settings', array() ); ?>

                <table class="form-table">
                    <tr>
                        <th scope="row"><label for="af_default_theme">Default Theme</label></th>
                        <td>
                            <select name="agentforms_settings[default_theme]" id="af_default_theme">
                                <option value="light"<?php selected( isset( $opts['default_theme'] ) ? $opts['default_theme'] : 'light', 'light' ); ?>>Light</option>
                                <option value="dark"<?php selected( isset( $opts['default_theme'] ) ? $opts['default_theme'] : 'light', 'dark' ); ?>>Dark</option>
                            </select>
                            <p class="description">Default theme for embedded forms. Can be overridden per-form via shortcode: [agentforms token="..." theme="dark"].</p>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row"><label for="af_success_message">Default Success Message</label></th>
                        <td>
                            <input type="text" name="agentforms_settings[default_success_message]" id="af_success_message"
                                   value="<?php echo esc_attr( isset( $opts['default_success_message'] ) ? $opts['default_success_message'] : 'Thank you! We will be in touch.' ); ?>"
                                   class="regular-text" />
                            <p class="description">Message shown after successful form submission. Can be overridden per-form.</p>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row"><label for="af_api_base_url">API Base URL</label></th>
                        <td>
                            <input type="url" name="agentforms_settings[api_base_url]" id="af_api_base_url"
                                   value="<?php echo esc_url( isset( $opts['api_base_url'] ) ? $opts['api_base_url'] : 'https://agentforms.io' ); ?>"
                                   class="regular-text" />
                            <p class="description">AgentForms API endpoint. Only change if using a custom domain.</p>
                        </td>
                    </tr>
                </table>

                <?php submit_button( 'Save Settings' ); ?>
            </form>

            <div class="agentforms-settings-actions">
                <h2>Cache Management</h2>
                <p>Form configurations are cached for 24 hours. Clear the cache to force a fresh fetch from the API.</p>
                <a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=agentforms&action=clear_cache' ), 'agentforms_clear_cache' ) ); ?>"
                   class="button button-secondary">Clear All Caches</a>
            </div>
        </div>

        <div class="agentforms-docs-section">
            <h2>Usage</h2>
            <h3>Shortcode</h3>
            <pre><code>[agentforms token="your-form-token"]</code></pre>
            <pre><code>[agentforms token="your-form-token" theme="dark"]</code></pre>
            <pre><code>[agentforms token="your-form-token" success="Thanks for signing up!"]</code></pre>

            <h3>Gutenberg Block</h3>
            <p>Add the "AgentForms" block from the block inserter. Enter your form token in the block sidebar.</p>

            <h3>Embed in Theme</h3>
            <pre><code>&lt;?php echo do_shortcode('[agentforms token="your-form-token"]'); ?&gt;</code></pre>
        </div>
    </div>
    <?php
}