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

/**
 * Admin Settings Handler
 *
 * Handles settings-related AJAX requests.
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/admin
 */
class Kitsune_AI_Platform_Admin_Settings extends Kitsune_AI_Platform_Admin_Ajax_Base {

    /**
     * Register AJAX hooks.
     */
    public function register_hooks() {
        add_action('wp_ajax_kitsune_ai_platform_save_settings', array($this, 'save_settings'));
        add_action('wp_ajax_kitsune_ai_platform_get_settings', array($this, 'ajax_get_plugin_settings'));
        add_action('wp_ajax_kitsune_ai_platform_get_api_keys', array($this, 'ajax_get_api_keys'));
        add_action('wp_ajax_kitsune_ai_platform_create_api_key', array($this, 'ajax_create_api_key'));
        add_action('wp_ajax_kitsune_ai_platform_delete_api_key', array($this, 'ajax_delete_api_key'));
        add_action('wp_ajax_kitsune_ai_platform_complete_onboarding', array($this, 'ajax_complete_onboarding'));
        add_action('wp_ajax_kitsune_ai_platform_get_system_status', array($this, 'ajax_get_system_status'));
        add_action('wp_ajax_kitsune_ai_platform_run_diagnostics', array($this, 'ajax_run_diagnostics'));
        // Access Control
        add_action('wp_ajax_kitsune_ai_platform_get_access_control', array($this, 'ajax_get_access_control'));
        add_action('wp_ajax_kitsune_ai_platform_save_access_control', array($this, 'ajax_save_access_control'));
        // Notification Settings
        add_action('wp_ajax_kitsune_ai_platform_get_notification_settings', array($this, 'ajax_get_notification_settings'));
        add_action('wp_ajax_kitsune_ai_platform_save_notification_settings', array($this, 'ajax_save_notification_settings'));
        // Advanced Settings (exported fields handled via save_settings, but also separately)
        add_action('wp_ajax_kitsune_ai_platform_export_settings', array($this, 'ajax_export_settings'));
        add_action('wp_ajax_kitsune_ai_platform_import_settings', array($this, 'ajax_import_settings'));
    }

    /**
     * Save settings
     */
    public function save_settings() {
        if (!$this->verify_admin_request('settings')) {
            return;
        }

        $settings = isset($_POST['settings']) ? wp_unslash($_POST['settings']) : array();
        if ( ! is_array($settings) ) {
            $settings = is_string($settings)
                ? ( json_decode( $settings, true ) ?: array() )
                : array();
        }

        // Sanitize settings
        $allowed_languages = array('en', 'es_ES', 'de_DE', 'fr_FR', 'pt_BR', 'ja', 'it_IT', 'zh_CN');

        $sanitized_language = $settings['language'] ?? 'en';
        if (!in_array($sanitized_language, $allowed_languages, true)) {
            $sanitized_language = 'en';
        }

        $existing_settings = $this->get_plugin_settings(false);

        $sanitized_settings = array(
            'openai_api_key'    => sanitize_text_field($settings['openai_api_key'] ?? ''),
            'claude_api_key'    => sanitize_text_field($settings['claude_api_key'] ?? ''),
            'gemini_api_key'    => sanitize_text_field($settings['gemini_api_key'] ?? ''),
            'mistral_api_key'   => sanitize_text_field($settings['mistral_api_key'] ?? ''),
            'default_model'     => sanitize_text_field($settings['default_model'] ?? KITSUNE_AI_PLATFORM_DEFAULT_MODEL),
            'budget_limit'      => absint($settings['budget_limit'] ?? 500),
            'token_limit'       => absint($settings['token_limit'] ?? 100000),
            'budget_period'     => sanitize_text_field($settings['budget_period'] ?? 'monthly'),
            'enable_analytics'  => (bool)($settings['enable_analytics'] ?? true),
            'cache_enabled'     => (bool)($settings['cache_enabled'] ?? true),
            'cache_duration'    => absint($settings['cache_duration'] ?? 3600),
            'debug_mode'        => (bool)($settings['debug_mode'] ?? false),
            'show_branding'     => (bool)($settings['show_branding'] ?? false),
            'request_timeout'   => min(max(absint($settings['request_timeout'] ?? 60), 10), 120),
            'gdpr_enabled'      => (bool)($settings['gdpr_enabled'] ?? true),
            'data_retention'    => absint($settings['data_retention'] ?? 90),
            'enable_in_editor'  => (bool)($settings['enable_in_editor'] ?? true),
            'default_tone'      => sanitize_text_field($settings['default_tone'] ?? 'Neutral'),
            'language'          => sanitize_text_field($sanitized_language),
            'welcome_dismissed' => isset($settings['welcome_dismissed']) ? (bool)$settings['welcome_dismissed'] : ($existing_settings['welcome_dismissed'] ?? false),
        );

        // Keep existing key values when UI sends masked placeholders
        $sensitive_keys = array('openai_api_key', 'claude_api_key', 'gemini_api_key', 'mistral_api_key');
        foreach ($sensitive_keys as $key) {
            if (!array_key_exists($key, $settings) || $this->is_masked_api_key($settings[$key])) {
                $sanitized_settings[$key] = $existing_settings[$key] ?? '';
            }
        }

        // Merge with existing settings
        $final_settings = array_merge($existing_settings, $sanitized_settings);

        // Update settings
        update_option('kitsune_ai_platform_settings', $final_settings);

        wp_send_json_success(array(
            'message' => __('Settings saved successfully', 'kitsune-ai-platform'),
            'settings' => $final_settings
        ));
    }

    /**
     * AJAX: Get plugin settings
     */
    public function ajax_get_plugin_settings() {
        if (!$this->verify_admin_request('settings')) {
            return;
        }

        wp_send_json_success($this->get_plugin_settings());
    }

    /**
     * Get plugin settings
     */
    public function get_plugin_settings($mask_sensitive = true) {
        $defaults = array(
            'openai_api_key'    => '',
            'claude_api_key'    => '',
            'gemini_api_key'    => '',
            'default_model'     => KITSUNE_AI_PLATFORM_DEFAULT_MODEL,
            'budget_limit'      => 500,
            'token_limit'       => 100000,
            'budget_period'     => 'monthly',
            'enable_analytics'  => true,
            'cache_enabled'     => true,
            'cache_duration'    => 3600,
            'debug_mode'        => false,
            'show_branding'     => false,
            'request_timeout'   => 60,
            'enable_in_editor'  => true,
            'default_tone'      => 'Neutral',
            'gdpr_enabled'      => true,
            'data_retention'    => 90,
            'language'          => 'en',
        );

        $settings = get_option('kitsune_ai_platform_settings', array());
        if (!is_array($settings)) {
            $settings = array();
        }

        $settings = array_merge($defaults, $settings);

        if ($mask_sensitive) {
            $settings = $this->mask_sensitive_settings($settings);
        }

        return $settings;
    }

    /**
     * Mask sensitive API key fields
     */
    public function mask_sensitive_settings($settings) {
        $sensitive_keys = array('openai_api_key', 'claude_api_key', 'gemini_api_key', 'mistral_api_key');

        foreach ($sensitive_keys as $key) {
            if (!isset($settings[$key]) || !is_string($settings[$key]) || $settings[$key] === '') {
                continue;
            }

            if (strpos($settings[$key], '********') === 0) {
                continue;
            }

            $settings[$key] = '********' . substr($settings[$key], -4);
        }

        return $settings;
    }

    /**
     * AJAX: Get API keys
     */
    public function ajax_get_api_keys() {
        if (!$this->verify_admin_request('settings')) {
            return;
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-api-key-model.php';
        $model = new Kitsune_AI_Platform_API_Key_Model();

        wp_send_json_success($model->get_all());
    }

    /**
     * AJAX: Create API key
     */
    public function ajax_create_api_key() {
        if (!$this->verify_admin_request('settings')) {
            return;
        }

        $name = sanitize_text_field(wp_unslash($_POST['name'] ?? ''));

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-api-key-model.php';
        $model = new Kitsune_AI_Platform_API_Key_Model();

        $result = $model->create($name);
        if (is_wp_error($result)) {
            wp_send_json_error(array('message' => $result->get_error_message()));
            return;
        }

        wp_send_json_success(array(
            'id' => $result['id'] ?? 0,
            'name' => $result['name'] ?? '',
            'prefix' => $result['prefix'] ?? '',
            'created' => $result['created'] ?? '',
            'last_used' => $result['last_used'] ?? '',
        ));
    }

    /**
     * AJAX: Delete API key
     */
    public function ajax_delete_api_key() {
        if (!$this->verify_admin_request('settings')) {
            return;
        }

        $id = isset($_POST['id']) ? intval(wp_unslash($_POST['id'])) : 0;
        if (!$id) {
            wp_send_json_error(array('message' => __('ID required', 'kitsune-ai-platform')));
            return;
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-api-key-model.php';
        $model = new Kitsune_AI_Platform_API_Key_Model();

        if ($model->delete($id)) {
            wp_send_json_success(array('message' => __('API key deleted', 'kitsune-ai-platform')));
        } else {
            wp_send_json_error(array('message' => __('Failed to delete API key', 'kitsune-ai-platform')));
        }
    }

    /**
     * AJAX: Complete onboarding
     */
    public function ajax_complete_onboarding() {
        if (!$this->verify_admin_request('settings')) {
            return;
        }

        update_option('kitsune_ai_platform_onboarding_complete', true);
        wp_send_json_success(array('message' => __('Onboarding completed', 'kitsune-ai-platform')));
    }

    /**
     * AJAX: Get system status info
     */
    public function ajax_get_system_status() {
        if (!$this->verify_admin_request('settings')) {
            return;
        }

        global $wpdb;

        $status = array(
            'wordpress_version' => get_bloginfo('version'),
            'php_version'       => PHP_VERSION,
            'plugin_version'    => KITSUNE_AI_PLATFORM_VERSION,
            'server_memory'     => ini_get('memory_limit'),
            'max_upload'        => ini_get('upload_max_filesize'),
            'db_prefix'         => $wpdb->prefix,
            'site_url'          => get_site_url(),
        );

        wp_send_json_success($status);
    }

    /**
     * AJAX: Run system diagnostics
     */
    public function ajax_run_diagnostics() {
        if (!$this->verify_admin_request('settings')) {
            return;
        }

        global $wpdb;

        $checks = array();

        // WordPress version check
        $wp_version = get_bloginfo('version');
        $checks[] = array(
            'name'    => __('WordPress Version', 'kitsune-ai-platform'),
            'status'  => version_compare($wp_version, '6.0', '>=') ? 'pass' : 'warn',
            /* translators: %s: WordPress version */
            'message' => sprintf(__('WordPress %s', 'kitsune-ai-platform'), $wp_version),
        );

        // PHP version check
        $php_version = PHP_VERSION;
        $checks[] = array(
            'name'    => __('PHP Version', 'kitsune-ai-platform'),
            'status'  => version_compare($php_version, '8.0', '>=') ? 'pass' : 'warn',
            /* translators: %s: PHP version */
            'message' => sprintf(__('PHP %s', 'kitsune-ai-platform'), $php_version),
        );

        // Database tables check
        $required_tables = array(
            $wpdb->prefix . 'kitsune_ai_platform_chatbots',
            $wpdb->prefix . 'kitsune_ai_platform_conversations',
            $wpdb->prefix . 'kitsune_ai_platform_messages',
            $wpdb->prefix . 'kitsune_ai_platform_api_keys',
        );
        $missing_tables = array();
        foreach ($required_tables as $table) {
            // Using prepare is safer even if the table name is built from $wpdb->prefix
            if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) !== $table) {
                $missing_tables[] = $table;
            }
        }
        $checks[] = array(
            'name'    => __('Database', 'kitsune-ai-platform'),
            'status'  => empty($missing_tables) ? 'pass' : 'fail',
            'message' => empty($missing_tables)
                ? __('All tables present', 'kitsune-ai-platform')
                : sprintf(__('Missing tables: %s', 'kitsune-ai-platform'), implode(', ', $missing_tables)),
        );

        // Write permissions check
        $upload_dir = wp_upload_dir();
        $checks[] = array(
            'name'    => __('Write Permissions', 'kitsune-ai-platform'),
            'status'  => is_writable($upload_dir['basedir']) ? 'pass' : 'fail',
            'message' => is_writable($upload_dir['basedir'])
                ? __('Upload directory writable', 'kitsune-ai-platform')
                : __('Upload directory not writable', 'kitsune-ai-platform'),
        );

        // API connections check
        $settings     = get_option('kitsune_ai_platform_settings', array());
        $has_api_key  = !empty($settings['openai_api_key']) || !empty($settings['claude_api_key']) || !empty($settings['gemini_api_key']);
        $checks[] = array(
            'name'    => __('API Connections', 'kitsune-ai-platform'),
            'status'  => $has_api_key ? 'pass' : 'warn',
            'message' => $has_api_key
                ? __('At least one provider connected', 'kitsune-ai-platform')
                : __('No AI provider API keys configured', 'kitsune-ai-platform'),
        );

        wp_send_json_success(array(
            'checks'            => $checks,
            'wordpress_version' => $wp_version,
            'php_version'       => $php_version,
            'plugin_version'    => KITSUNE_AI_PLATFORM_VERSION,
            'server_memory'     => ini_get('memory_limit'),
            'max_upload'        => ini_get('upload_max_filesize'),
        ));
    }

    /**
     * AJAX: Get access control roles
     */
    public function ajax_get_access_control() {
        if (!$this->verify_admin_request('settings')) {
            return;
        }

        // Build a keyed map of saved permissions
        $saved = get_option('kitsune_ai_platform_access_control', array());
        $saved_map = array();
        foreach ( (array) $saved as $row ) {
            if ( isset($row['slug']) ) {
                $saved_map[ $row['slug'] ] = $row;
            }
        }

        // Always grant full permissions to Administrator regardless of saved value
        $admin_defaults = array(
            'models'         => true,
            'chatbots'       => true,
            'content'        => true,
            'knowledge_base' => true,
            'automation'     => true,
            'analytics'      => true,
            'integrations'   => true,
            'settings'       => true,
        );

        // Merge real WP roles with saved prefs; new roles get sensible defaults
        $roles = array();
        foreach ( get_editable_roles() as $slug => $role_data ) {
            $is_admin = ( $slug === 'administrator' );
            $saved_row = $saved_map[ $slug ] ?? null;

            if ( $is_admin ) {
                $perms = $admin_defaults;
            } else {
                // Default: editors/contributors get content; lower roles get nothing
                $has_edit_cap = ! empty( $role_data['capabilities']['edit_posts'] );
                $perms = array(
                    'models'         => $saved_row['models']         ?? false,
                    'chatbots'       => $saved_row['chatbots']       ?? false,
                    'content'        => $saved_row['content']        ?? $has_edit_cap,
                    'knowledge_base' => $saved_row['knowledge_base'] ?? false,
                    'automation'     => $saved_row['automation']     ?? false,
                    'analytics'      => $saved_row['analytics']      ?? false,
                    'integrations'   => $saved_row['integrations']   ?? false,
                    'settings'       => $saved_row['settings']       ?? false,
                );
            }

            $roles[] = array(
                'slug'           => $slug,
                'name'           => translate_user_role( $role_data['name'] ),
                'models'         => (bool) $perms['models'],
                'chatbots'       => (bool) $perms['chatbots'],
                'content'        => (bool) $perms['content'],
                'knowledge_base' => (bool) $perms['knowledge_base'],
                'automation'     => (bool) $perms['automation'],
                'analytics'      => (bool) $perms['analytics'],
                'integrations'   => (bool) $perms['integrations'],
                'settings'       => (bool) $perms['settings'],
            );
        }

        wp_send_json_success($roles);
    }

    /**
     * AJAX: Save access control roles
     */
    public function ajax_save_access_control() {
        if (!$this->verify_admin_request('settings')) {
            return;
        }

        $roles = isset($_POST['roles']) ? wp_unslash($_POST['roles']) : array();
        if ( ! is_array($roles) ) {
            $roles = is_string($roles)
                ? ( json_decode( $roles, true ) ?: array() )
                : array();
        }
        if ( ! is_array($roles) ) {
            wp_send_json_error(array('message' => __('Invalid data', 'kitsune-ai-platform')));
            return;
        }

        $valid_slugs = array_keys( get_editable_roles() );
        $sanitized   = array();

        foreach ($roles as $role) {
            $slug = sanitize_key($role['slug'] ?? '');
            // Only save roles that actually exist in this WP installation
            if ( ! in_array($slug, $valid_slugs, true) ) {
                continue;
            }
            // Administrator permissions are always forced to true
            $is_admin = ( $slug === 'administrator' );
            $sanitized[] = array(
                'slug'           => $slug,
                'name'           => sanitize_text_field($role['name'] ?? $slug),
                'models'         => $is_admin ? true : (bool)($role['models'] ?? false),
                'chatbots'       => $is_admin ? true : (bool)($role['chatbots'] ?? false),
                'content'        => $is_admin ? true : (bool)($role['content'] ?? false),
                'knowledge_base' => $is_admin ? true : (bool)($role['knowledge_base'] ?? false),
                'automation'     => $is_admin ? true : (bool)($role['automation'] ?? false),
                'analytics'      => $is_admin ? true : (bool)($role['analytics'] ?? false),
                'integrations'   => $is_admin ? true : (bool)($role['integrations'] ?? false),
                'settings'       => $is_admin ? true : (bool)($role['settings'] ?? false),
            );
        }

        update_option('kitsune_ai_platform_access_control', $sanitized);

        wp_send_json_success(array(
            'message' => __('Permissions saved successfully', 'kitsune-ai-platform'),
            'roles'   => $sanitized,
        ));
    }

    /**
     * AJAX: Get notification settings
     */
    public function ajax_get_notification_settings() {
        if (!$this->verify_admin_request('settings')) {
            return;
        }

        $defaults = array(
            'budgetWarning' => true,
            'budgetLimit'   => true,
            'apiErrors'     => true,
            'pluginUpdates' => false,
            'email'         => get_option('admin_email', ''),
        );

        $settings = get_option('kitsune_ai_platform_notification_settings', $defaults);
        if (!is_array($settings)) {
            $settings = $defaults;
        }
        $settings = array_merge($defaults, $settings);

        wp_send_json_success($settings);
    }

    /**
     * AJAX: Save notification settings
     */
    public function ajax_save_notification_settings() {
        if (!$this->verify_admin_request('settings')) {
            return;
        }

        $data = isset($_POST['settings']) ? wp_unslash($_POST['settings']) : array();
        if ( ! is_array($data) ) {
            $data = is_string($data)
                ? ( json_decode( $data, true ) ?: array() )
                : array();
        }

        $sanitized = array(
            'budgetWarning' => (bool)($data['budgetWarning'] ?? false),
            'budgetLimit'   => (bool)($data['budgetLimit'] ?? false),
            'apiErrors'     => (bool)($data['apiErrors'] ?? false),
            'pluginUpdates' => (bool)($data['pluginUpdates'] ?? false),
            'email'         => sanitize_email($data['email'] ?? ''),
        );

        update_option('kitsune_ai_platform_notification_settings', $sanitized);

        wp_send_json_success(array(
            'message'  => __('Notification preferences saved successfully', 'kitsune-ai-platform'),
            'settings' => $sanitized,
        ));
    }

    /**
     * AJAX: Export plugin settings as JSON download
     */
    public function ajax_export_settings() {
        if (!$this->verify_admin_request('settings')) {
            return;
        }

        $settings = $this->get_plugin_settings(false);

        // Strip sensitive keys from export
        $sensitive = array('openai_api_key', 'claude_api_key', 'gemini_api_key', 'mistral_api_key');
        foreach ($sensitive as $key) {
            unset($settings[$key]);
        }

        $export = array(
            'version'    => KITSUNE_AI_PLATFORM_VERSION,
            'exported'   => current_time('mysql'),
            'settings'   => $settings,
            'access'     => get_option('kitsune_ai_platform_access_control', array()),
            'notifications' => get_option('kitsune_ai_platform_notification_settings', array()),
        );

        wp_send_json_success($export);
    }

    /**
     * AJAX: Import plugin settings from JSON
     */
    public function ajax_import_settings() {
        if (!$this->verify_admin_request('settings')) {
            return;
        }

        $data = $this->get_post_payload('json');

        if (!is_array($data) || !isset($data['settings'])) {
            wp_send_json_error(array('message' => __('Invalid configuration file', 'kitsune-ai-platform')));
            return;
        }

        // Merge imported settings with existing (keeping existing API keys)
        $existing = $this->get_plugin_settings(false);
        $imported_settings = array_merge($existing, $data['settings']);
        update_option('kitsune_ai_platform_settings', $imported_settings);

        if (!empty($data['access']) && is_array($data['access'])) {
            update_option('kitsune_ai_platform_access_control', $data['access']);
        }

        if (!empty($data['notifications']) && is_array($data['notifications'])) {
            update_option('kitsune_ai_platform_notification_settings', $data['notifications']);
        }

        wp_send_json_success(array('message' => __('Settings imported successfully', 'kitsune-ai-platform')));
    }

    /**
     * Detect whether a key value is a masked placeholder
     */
    private function is_masked_api_key($value) {
        return is_string($value) && preg_match('/^\*{8}/', $value) === 1;
    }
}
