<?php
if (!defined('ABSPATH')) die('Restricted Access');

class AIFLT_Settings_Logic {

    /**
     * Handles the AJAX request to save plugin settings.
     */
    public static function save_settings_callback() {
        check_ajax_referer('aiflt-save-settings-nonce', '_ajax_nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('You do not have permission to perform this action.', 'ai-flash-tune'));
        }

        // Core options are updated only when General Settings tab is submitted.
        if (isset($_POST['aiflt_ai_provider']) || isset($_POST['aiflt_ai_api_key'])) {
            $allowed_providers = ['local', 'openai', 'zywrap'];
            $provider = isset($_POST['aiflt_ai_provider']) ? sanitize_key(wp_unslash($_POST['aiflt_ai_provider'])) : 'local';
            if (!in_array($provider, $allowed_providers, true)) {
                $provider = 'local';
            }

            update_option('aiflt_ai_provider', $provider);
            $external_consent = ($provider !== 'local' && isset($_POST['aiflt_ai_external_consent'])) ? '1' : '0';
            update_option('aiflt_ai_external_consent', $external_consent);
            update_option('aiflt_ai_aggregate_only', isset($_POST['aiflt_ai_aggregate_only']) ? '1' : '0');
            update_option('aiflt_free_ai_monthly_limit', isset($_POST['aiflt_free_ai_monthly_limit']) ? absint($_POST['aiflt_free_ai_monthly_limit']) : 20);

            update_option('aiflt_ai_api_key', isset($_POST['aiflt_ai_api_key']) ? sanitize_text_field(wp_unslash($_POST['aiflt_ai_api_key'])) : '');
            update_option('aiflt_zywrap_api_key', isset($_POST['aiflt_zywrap_api_key']) ? sanitize_text_field(wp_unslash($_POST['aiflt_zywrap_api_key'])) : '');
            update_option('aiflt_zywrap_endpoint', 'https://api.zywrap.com/v1/proxy');
            $old_license_key = get_option('aiflt_pro_license_key', '');
            $new_license_key = isset($_POST['aiflt_pro_license_key']) ? sanitize_text_field(wp_unslash($_POST['aiflt_pro_license_key'])) : '';
            update_option('aiflt_pro_license_key', $new_license_key);
            if ($old_license_key !== $new_license_key && class_exists('AIFLT_License_Manager')) {
                AIFLT_License_Manager::clear_activation_records(__('License key changed. Please reactivate installed modules for this domain.', 'ai-flash-tune'));
            }
            // Always clear license cache when the settings form submits a license field.
            // This prevents Addon Manager from showing stale "needs license" state after a key is saved/re-saved.
            delete_transient('aiflt_license_status_cache');
            delete_transient('aiflt_license_data_cache');
            update_option('aiflt_ai_model', isset($_POST['aiflt_ai_model']) ? sanitize_text_field(wp_unslash($_POST['aiflt_ai_model'])) : 'gpt-4o-mini');
            update_option('aiflt_ai_response_language', isset($_POST['aiflt_ai_response_language']) ? sanitize_text_field(wp_unslash($_POST['aiflt_ai_response_language'])) : 'auto');
            update_option('aiflt_data_retention', isset($_POST['aiflt_data_retention']) ? sanitize_text_field(wp_unslash($_POST['aiflt_data_retention'])) : '30');

            update_option('aiflt_delete_data_on_uninstall', isset($_POST['aiflt_delete_data_on_uninstall']) ? '1' : '0');
            update_option('aiflt_anonymize_ip', isset($_POST['aiflt_anonymize_ip']) ? '1' : '0');
            update_option('aiflt_enable_tracking', isset($_POST['aiflt_enable_tracking']) ? '1' : '0');

            $excluded_roles = [];
            if (isset($_POST['aiflt_excluded_roles']) && is_array($_POST['aiflt_excluded_roles'])) {
                foreach ($_POST['aiflt_excluded_roles'] as $role) {
                    $excluded_roles[] = sanitize_key($role);
                }
            }
            update_option('aiflt_excluded_roles', $excluded_roles);

            if (isset($_POST['aiflt_excluded_ips'])) {
                $ips_array = explode("\n", trim((string) wp_unslash($_POST['aiflt_excluded_ips'])));
                $sanitized_ips = [];
                foreach ($ips_array as $ip) {
                    $trimmed_ip = trim($ip);
                    if (!empty($trimmed_ip)) {
                        $sanitized_ips[] = sanitize_text_field($trimmed_ip);
                    }
                }
                update_option('aiflt_excluded_ips', implode("\n", $sanitized_ips));
            }
        }

        do_action('aiflt_save_addon_settings', $_POST);

        wp_send_json_success(__('Settings saved successfully!', 'ai-flash-tune'));
    }

    public static function get_settings() {
        return [
            'ai_provider' => get_option('aiflt_ai_provider', 'local'),
            'ai_external_consent' => get_option('aiflt_ai_external_consent', '0'),
            'ai_aggregate_only' => get_option('aiflt_ai_aggregate_only', '1'),
            'free_ai_monthly_limit' => get_option('aiflt_free_ai_monthly_limit', 20),
            'ai_api_key' => get_option('aiflt_ai_api_key', ''),
            'zywrap_api_key' => get_option('aiflt_zywrap_api_key', ''),
            'zywrap_endpoint' => class_exists('AIFLT_AI_Service') ? AIFLT_AI_Service::get_zywrap_proxy_endpoint() : 'https://api.zywrap.com/v1/proxy',
            'pro_license_key' => get_option('aiflt_pro_license_key', ''),
            'ai_model' => get_option('aiflt_ai_model', 'gpt-4o-mini'),
            'ai_response_language' => get_option('aiflt_ai_response_language', 'auto'),
            'data_retention' => get_option('aiflt_data_retention', '30'),
            'delete_data_on_uninstall' => get_option('aiflt_delete_data_on_uninstall', '0'),
            'anonymize_ip' => get_option('aiflt_anonymize_ip', '1'),
            'enable_tracking' => get_option('aiflt_enable_tracking', '1'),
            'excluded_roles' => get_option('aiflt_excluded_roles', ['administrator', 'shop_manager']),
            'excluded_ips' => get_option('aiflt_excluded_ips', ''),
        ];
    }
}
