<?php
/**
 * Admin settings page for GistMag Alt Text Generator
 *
 * @package GistMag_ATG
 */

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

class GistMag_ATG_Admin {
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'register_settings'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
    }

    /**
     * Enqueue admin scripts and styles for settings page
     *
     * @param string $hook Current admin page hook.
     */
    public function enqueue_admin_scripts($hook) {
        // Only load on our settings page
        if ('toplevel_page_gistmag-atg' !== $hook) {
            return;
        }

        $script_url = GISTMAG_ATG_PLUGIN_URL . 'assets/js/admin-settings.js';
        
        wp_enqueue_script(
            'gistmag-atg-admin-settings',
            $script_url,
            array('jquery'),
            GISTMAG_ATG_VERSION,
            true
        );

        wp_localize_script('gistmag-atg-admin-settings', 'gistmag_atg_settings', array(
            'nonce' => wp_create_nonce('gistmag_atg_nonce'),
        ));
    }

    public function add_admin_menu() {
        add_menu_page(
            __('GistMag Alt Text Generator', 'gistmag-alt-text-generator'),
            __('GistMag ATG', 'gistmag-alt-text-generator'),
            'manage_options',
            'gistmag-atg',
            array($this, 'render_settings_page'),
            'dashicons-format-image',
            30
        );
    }

    public function register_settings() {
        register_setting(
            'gistmag_atg_settings',
            'gistmag_atg_api_key',
            array(
                'sanitize_callback' => 'sanitize_text_field',
            )
        );

        register_setting(
            'gistmag_atg_settings',
            'gistmag_atg_auto_generate',
            array(
                'sanitize_callback' => 'absint',
            )
        );

        register_setting(
            'gistmag_atg_settings',
            'gistmag_atg_default_mode',
            array(
                'sanitize_callback' => array($this, 'sanitize_mode'),
            )
        );
    }

    /**
     * Sanitize default mode value.
     *
     * @param string $value Mode value.
     * @return string
     */
    public function sanitize_mode($value) {
        $value = sanitize_text_field($value);
        $allowed = array('short', 'long', 'seo');
        if (!in_array($value, $allowed, true)) {
            return 'short';
        }
        return $value;
    }

    public function render_settings_page() {
        if (!current_user_can('manage_options')) {
            return;
        }

        $api = new GistMag_ATG_API();
        $api_key = get_option('gistmag_atg_api_key', '');
        $usage_stats = null;

        // Handle usage stats check with nonce verification.
        if (
            ! empty( $api_key )
            && isset( $_POST['check_usage'], $_POST['gistmag_atg_check_usage_nonce'] )
        ) {
            $raw_nonce = wp_unslash( $_POST['gistmag_atg_check_usage_nonce'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            $nonce     = sanitize_text_field( $raw_nonce );

            if ( wp_verify_nonce( $nonce, 'gistmag_atg_check_usage' ) ) {
                $usage_stats = $api->get_usage_stats( $api_key );
            }
        }

        ?>
        <div class="wrap">
            <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
            
            <form action="options.php" method="post">
                <?php
                settings_fields('gistmag_atg_settings');
                do_settings_sections('gistmag_atg_settings');
                ?>
                
                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="gistmag_atg_api_key"><?php esc_html_e('API Key', 'gistmag-alt-text-generator'); ?></label>
                        </th>
                        <td>
                            <input type="text" 
                                   id="gistmag_atg_api_key" 
                                   name="gistmag_atg_api_key" 
                                   value="<?php echo esc_attr($api_key); ?>" 
                                   class="regular-text" 
                                   placeholder="atg_...">
                            <p class="description">
                                <?php
                                printf(
                                    wp_kses(
                                        /* translators: %s: GistMag dashboard URL. */
                                        __('Enter your GistMag API key. Get one from <a href="%s" target="_blank">your dashboard</a>.', 'gistmag-alt-text-generator'),
                                        array(
                                            'a' => array(
                                                'href' => array(),
                                                'target' => array(),
                                            ),
                                        )
                                    ),
                                    esc_url('https://gistmag.co.uk/dashboard/api-key')
                                );
                                ?>
                            </p>
                            <?php if (!empty($api_key)): ?>
                                <p>
                                    <button type="button" 
                                            class="button" 
                                            id="verify-api-key">
                                        <?php esc_html_e('Verify API Key', 'gistmag-alt-text-generator'); ?>
                                    </button>
                                </p>
                            <?php endif; ?>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="gistmag_atg_auto_generate"><?php esc_html_e('Auto-generate on Upload', 'gistmag-alt-text-generator'); ?></label>
                        </th>
                        <td>
                            <input type="checkbox" 
                                   id="gistmag_atg_auto_generate" 
                                   name="gistmag_atg_auto_generate" 
                                   value="1" 
                                   <?php checked(get_option('gistmag_atg_auto_generate', true)); ?>>
                            <label for="gistmag_atg_auto_generate">
                                <?php esc_html_e('Automatically generate alt text when images are uploaded', 'gistmag-alt-text-generator'); ?>
                            </label>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="gistmag_atg_default_mode"><?php esc_html_e('Default Mode', 'gistmag-alt-text-generator'); ?></label>
                        </th>
                        <td>
                            <select id="gistmag_atg_default_mode" name="gistmag_atg_default_mode">
                                <option value="short" <?php selected(get_option('gistmag_atg_default_mode', 'short'), 'short'); ?>>
                                    <?php esc_html_e('Short', 'gistmag-alt-text-generator'); ?>
                                </option>
                                <option value="long" <?php selected(get_option('gistmag_atg_default_mode', 'short'), 'long'); ?>>
                                    <?php esc_html_e('Long', 'gistmag-alt-text-generator'); ?>
                                </option>
                                <option value="seo" <?php selected(get_option('gistmag_atg_default_mode', 'short'), 'seo'); ?>>
                                    <?php esc_html_e('SEO', 'gistmag-alt-text-generator'); ?>
                                </option>
                            </select>
                            <p class="description">
                                <?php esc_html_e('Default mode for auto-generated alt text.', 'gistmag-alt-text-generator'); ?>
                            </p>
                        </td>
                    </tr>
                </table>
                
                <?php submit_button(); ?>
            </form>

            <?php if (!empty($api_key)): ?>
                <hr>
                <h2><?php esc_html_e('Usage Statistics', 'gistmag-alt-text-generator'); ?></h2>
                <form method="post">
                    <?php wp_nonce_field('gistmag_atg_check_usage', 'gistmag_atg_check_usage_nonce'); ?>
                    <button type="submit" name="check_usage" class="button">
                        <?php esc_html_e('Check Usage', 'gistmag-alt-text-generator'); ?>
                    </button>
                </form>
                
                <?php if ($usage_stats): ?>
                    <table class="widefat" style="margin-top: 20px;">
                        <thead>
                            <tr>
                                <th><?php esc_html_e('Current Month', 'gistmag-alt-text-generator'); ?></th>
                                <th><?php esc_html_e('Monthly Limit', 'gistmag-alt-text-generator'); ?></th>
                                <th><?php esc_html_e('Remaining', 'gistmag-alt-text-generator'); ?></th>
                                <th><?php esc_html_e('Plan', 'gistmag-alt-text-generator'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><?php echo esc_html($usage_stats['current_month'] ?? 0); ?></td>
                                <td><?php echo esc_html($usage_stats['monthly_limit'] ?? 0); ?></td>
                                <td><?php echo esc_html($usage_stats['remaining'] ?? 0); ?></td>
                                <td><?php echo esc_html(ucfirst($usage_stats['subscription_tier'] ?? 'free')); ?></td>
                            </tr>
                        </tbody>
                    </table>
                <?php endif; ?>
            <?php endif; ?>
        </div>
        <?php
    }
}
