<?php

/**
 * AI Magic Settings Handler
 *
 * @link       https://insya.com/ai-magic
 * @since      1.0.7
 *
 * @package    Ai_Magic
 * @subpackage Ai_Magic/admin
 */
class AI_Magic_Settings
{
    public function __construct()
    {
        add_action('admin_menu', array($this, 'add_settings_page'));
        add_action('wp_ajax_ai_magic_save_settings', array($this, 'save_settings'));
        add_action('wp_ajax_ai_magic_test_api', array($this, 'handle_test_api'));
        add_action('wp_ajax_ai_magic_get_models', array($this, 'get_models'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_settings_styles'));
    }

    /**
     * Enqueue settings page styles
     */
    public function enqueue_settings_styles($hook)
    {
        // Pages that need our modern styles
        $allowed_pages = array(
            'toplevel_page_ai-magic-settings',
            'ai-magic_page_ai-magic-history',
            'ai-magic_page_ai-magic-analytics'
        );

        if (!in_array($hook, $allowed_pages)) {
            return;
        }

        wp_enqueue_style(
            'ai-magic-settings',
            plugin_dir_url(__FILE__) . 'css/ai-magic-settings.css',
            array(),
            '1.0.7'
        );

        // Load theme wizard CSS for shared modern components
        wp_enqueue_style(
            'ai-magic-theme-wizard',
            plugin_dir_url(__FILE__) . 'css/ai-magic-theme-wizard.css',
            array(),
            AI_MAGIC_VERSION
        );
    }

    /**
     * Add settings page to WordPress admin menu
     */
    public function add_settings_page()
    {
        // Main menu with dashicon
        // Main menu with custom icon (Sparkles SVG)
        add_menu_page(
            'AI Magic',
            'AI Magic',
            'manage_options',
            'ai-magic-settings',
            array($this, 'render_settings_page'),
            'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0iY3VycmVudENvbG9yIj48cGF0aCBkPSJNMTUgNGwyLjUgNS41TDIzIDEybC01LjUgMi41TDE1IDIwbC0yLjUtNS41TDcgMTJsNS41LTIuNUwxNSA0em0tOSA0bDEuMjUgMi43NUwxMCAxMmwtMi43NSAxLjI1TDYgMTZsLTEuMjUtMi43NUwyIDEybDIuNzUtMS4yNUw2IDh6Ii8+PC9zdmc+',
            80
        );

        // Settings submenu (rename main page)
        add_submenu_page(
            'ai-magic-settings',
            'Settings',
            'Settings',
            'manage_options',
            'ai-magic-settings',
            array($this, 'render_settings_page')
        );



        // History submenu
        add_submenu_page(
            'ai-magic-settings',
            'Content History',
            'History',
            'edit_posts',
            'ai-magic-history',
            array($this, 'render_history_page')
        );

        // Analytics submenu
        add_submenu_page(
            'ai-magic-settings',
            'Analytics',
            'Analytics',
            'manage_options',
            'ai-magic-analytics',
            array($this, 'render_analytics_page')
        );
    }

    /**
     * Render history page
     */
    public function render_history_page()
    {
        if (!current_user_can('edit_posts')) {
            return;
        }

        include plugin_dir_path(__FILE__) . 'partials/ai-magic-history-page.php';
    }

    /**
     * Render analytics page
     */
    public function render_analytics_page()
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        include plugin_dir_path(__FILE__) . 'partials/ai-magic-analytics-page.php';
    }



    /**
     * Render modern settings page
     */
    public function render_settings_page()
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        include plugin_dir_path(__FILE__) . 'partials/ai-magic-settings-page-modern.php';
    }

    /**
     * Save settings via AJAX
     */
    public function save_settings()
    {
        check_ajax_referer('ai_magic_settings_nonce', 'ai_magic_nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }

        // Get providers from centralized manager if available, fallback to hardcoded list
        if (class_exists('AI_Magic_Provider_Manager')) {
            $provider_list = AI_Magic_Provider_Manager::get_providers();
            $providers = array_keys($provider_list);
        } else {
            $providers = array('openai', 'anthropic', 'google', 'openrouter');
        }

        foreach ($providers as $provider) {
            // API Key
            if (isset($_POST["ai_magic_api_key_{$provider}"])) {
                update_option("ai_magic_api_key_{$provider}", sanitize_text_field($_POST["ai_magic_api_key_{$provider}"]));

                // Backward compatibility for OpenAI
                if ($provider === 'openai') {
                    update_option('ai_magic_api_key', sanitize_text_field($_POST["ai_magic_api_key_{$provider}"]));
                }
            }

            // Active Status
            $is_active = isset($_POST["ai_magic_{$provider}_active"]) && $_POST["ai_magic_{$provider}_active"] === 'yes' ? 'yes' : 'no';
            update_option("ai_magic_{$provider}_active", $is_active);

            // Provider-specific Model
            if (isset($_POST["ai_magic_{$provider}_model"])) {
                update_option("ai_magic_{$provider}_model", sanitize_text_field($_POST["ai_magic_{$provider}_model"]));
            }

            // Provider-specific Max Tokens
            if (isset($_POST["ai_magic_{$provider}_max_tokens"])) {
                update_option("ai_magic_{$provider}_max_tokens", absint($_POST["ai_magic_{$provider}_max_tokens"]));
            }

            // Provider-specific Temperature
            if (isset($_POST["ai_magic_{$provider}_temperature"])) {
                update_option("ai_magic_{$provider}_temperature", floatval($_POST["ai_magic_{$provider}_temperature"]));
            }

            // Provider-specific Top P
            if (isset($_POST["ai_magic_{$provider}_top_p"])) {
                update_option("ai_magic_{$provider}_top_p", floatval($_POST["ai_magic_{$provider}_top_p"]));
            }

            // Writing Preferences
            if (isset($_POST["ai_magic_{$provider}_language"])) {
                update_option("ai_magic_{$provider}_language", sanitize_text_field($_POST["ai_magic_{$provider}_language"]));
            }

            if (isset($_POST["ai_magic_{$provider}_style"])) {
                update_option("ai_magic_{$provider}_style", sanitize_text_field($_POST["ai_magic_{$provider}_style"]));
            }

            if (isset($_POST["ai_magic_{$provider}_tone"])) {
                update_option("ai_magic_{$provider}_tone", sanitize_text_field($_POST["ai_magic_{$provider}_tone"]));
            }

            // Provider-specific Custom Model
            if (isset($_POST["ai_magic_{$provider}_custom_model"])) {
                update_option("ai_magic_{$provider}_custom_model", sanitize_text_field($_POST["ai_magic_{$provider}_custom_model"]));
            }
        }

        // Global Model (for backward compatibility)
        if (isset($_POST['ai_magic_model'])) {
            $model = sanitize_text_field($_POST['ai_magic_model']);
            update_option('ai_magic_model', $model);

            // If custom model, save the custom model name
            if ($model === 'custom' && isset($_POST['ai_magic_custom_model'])) {
                update_option('ai_magic_custom_model', sanitize_text_field($_POST['ai_magic_custom_model']));
            }
        }

        // Content Settings
        if (isset($_POST['ai_magic_min_content_length'])) {
            update_option('ai_magic_min_content_length', intval($_POST['ai_magic_min_content_length']));
        }

        if (isset($_POST['ai_magic_max_keywords'])) {
            update_option('ai_magic_max_keywords', intval($_POST['ai_magic_max_keywords']));
        }

        // Advanced Settings (global defaults)
        if (isset($_POST['ai_magic_temperature'])) {
            update_option('ai_magic_temperature', floatval($_POST['ai_magic_temperature']));
        }

        if (isset($_POST['ai_magic_max_tokens'])) {
            update_option('ai_magic_max_tokens', intval($_POST['ai_magic_max_tokens']));
        }

        if (isset($_POST['ai_magic_top_p'])) {
            update_option('ai_magic_top_p', floatval($_POST['ai_magic_top_p']));
        }

        if (isset($_POST['ai_magic_frequency_penalty'])) {
            update_option('ai_magic_frequency_penalty', floatval($_POST['ai_magic_frequency_penalty']));
        }

        if (isset($_POST['ai_magic_presence_penalty'])) {
            update_option('ai_magic_presence_penalty', floatval($_POST['ai_magic_presence_penalty']));
        }

        // Base Prompt / Company Context Profile
        if (isset($_POST['ai_magic_base_prompt'])) {
            // Load context class if not already loaded
            if (!class_exists('AI_Magic_Context')) {
                require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-ai-magic-context.php';
            }
            AI_Magic_Context::save_base_prompt($_POST['ai_magic_base_prompt']);
        }

        // Active Provider
        if (isset($_POST['ai_magic_active_provider'])) {
            update_option('ai_magic_active_provider', sanitize_text_field($_POST['ai_magic_active_provider']));
        }

        wp_send_json_success('Settings saved successfully');
    }

    /**
     * Handle Test API generation
     */
    public function handle_test_api()
    {
        check_ajax_referer('ai_magic_settings_nonce', 'nonce');

        if (!current_user_can('edit_posts')) {
            wp_send_json_error('Insufficient permissions');
        }

        $prompt = isset($_POST['prompt']) ? sanitize_textarea_field($_POST['prompt']) : '';
        $provider = isset($_POST['provider']) ? sanitize_text_field($_POST['provider']) : 'openai';

        if (empty($prompt)) {
            wp_send_json_error('Prompt is required');
        }

        $ai = null;

        if (class_exists('AI_Magic_Provider_Manager')) {
            $ai = AI_Magic_Provider_Manager::get_provider_instance($provider);
        }

        if (!$ai) {
            wp_send_json_error('Failed to initialize AI provider');
        }

        $response = $ai->generateText($prompt);

        if ($response['type'] === 'success') {
            // Normalize response structure
            $text = isset($response['data']['post_content']) ? $response['data']['post_content'] : '';
            if (empty($text) && isset($response['data']['text'])) {
                $text = $response['data']['text'];
            }

            wp_send_json_success(['text' => $text]);
        } else {
            wp_send_json_error($response['message']);
        }
    }

    /**
     * Get models for a provider
     */
    public function get_models()
    {
        check_ajax_referer('ai_magic_settings_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }

        $provider = isset($_POST['provider']) ? sanitize_text_field($_POST['provider']) : 'openai';
        $api_key = isset($_POST['api_key']) ? sanitize_text_field($_POST['api_key']) : '';

        $ai = null;

        if (class_exists('AI_Magic_Provider_Manager')) {
            $ai = AI_Magic_Provider_Manager::get_provider_instance($provider);
        }

        if (!$ai) {
            wp_send_json_error('Failed to initialize AI provider');
        }

        // If API key is provided, set it temporarily for this request
        if (!empty($api_key) && method_exists($ai, 'setApiKey')) {
            $ai->setApiKey($api_key);
        }

        if (method_exists($ai, 'getModels')) {
            $models = $ai->getModels();
            wp_send_json_success($models);
        } else {
            wp_send_json_error('Provider does not support fetching models');
        }
    }
}

new AI_Magic_Settings();
