<?php

defined('ABSPATH') || exit;

class ShopCentral_Settings_API
{
    private $namespace;
    private static $settings_cache = null;

    public function __construct($namespace = 'shopcentral/v1')
    {
        $this->namespace = $namespace;
        add_action('rest_api_init', [$this, 'register_routes']);
    }

    public function register_routes()
    {
        // Get settings
        register_rest_route($this->namespace, '/settings', [
            'methods' => 'GET',
            'callback' => [$this, 'get_settings'],
            'permission_callback' => [$this, 'check_permission']
        ]);

        // Update settings
        register_rest_route($this->namespace, '/settings', [
            'methods' => 'POST',
            'callback' => [$this, 'update_settings'],
            'permission_callback' => [$this, 'check_permission']
        ]);
    }

    public function check_permission()
    {
        return current_user_can('manage_options');
    }

    public function get_settings($request)
    {
        $settings = self::get_feature_settings();
        return rest_ensure_response([
            'success' => true,
            'data' => $settings
        ]);
    }

    public function update_settings($request)
    {
        $params = $request->get_params();
        
        if (isset($params['usage_tracking'])) {
            $prev_value = get_option('shopcentral_usage_tracking', 'pending');
            update_option('shopcentral_usage_tracking', $params['usage_tracking']);
            self::$settings_cache = null; // Clear cache

            if ($params['usage_tracking'] === 'yes' && $prev_value !== 'yes') {
                if (class_exists('ShopCentral_Event_Tracker')) {
                    // Reset tracked flag so track_install actually sends the event
                    delete_option('shopcentral_install_tracked');
                    ShopCentral_Event_Tracker::track_install();
                    ShopCentral_Event_Tracker::track_activation();
                }
            }
        }

        if (isset($params['auto_sync'])) {
            update_option('shopcentral_auto_sync', $params['auto_sync'] ? 'yes' : 'no');
            self::$settings_cache = null; // Clear cache
        }

        if (isset($params['order_push_enabled'])) {
            update_option('shopcentral_order_push_enabled', $params['order_push_enabled'] ? 'yes' : 'no');
            self::$settings_cache = null;
        }

        if (isset($params['hub_url'])) {
            update_option('shopcentral_hub_url', esc_url_raw($params['hub_url']));
            self::$settings_cache = null;
        }

        if (isset($params['hub_import_key'])) {
            update_option('shopcentral_hub_import_key', sanitize_text_field($params['hub_import_key']));
            self::$settings_cache = null;
        }

        if ($params['regenerate_import_key'] ?? false) {
            if (class_exists('ShopCentral_Order_Import_Manager')) {
                ShopCentral_Order_Import_Manager::regenerate_import_key();
            }
            self::$settings_cache = null;
        }

        return rest_ensure_response([
            'success' => true,
            'message' => 'Settings updated',
            'data' => self::get_feature_settings()
        ]);
    }

    /**
     * Get feature settings as a PHP array
     */
    public static function get_feature_settings()
    {
        if (self::$settings_cache !== null) {
            return self::$settings_cache;
        }

        $import_key = get_option('shopcentral_import_key');
        if (empty($import_key) && class_exists('ShopCentral_Order_Import_Manager')) {
            $import_key = ShopCentral_Order_Import_Manager::get_import_key();
        }

        self::$settings_cache = [
            'store_manager' => true,
            'usage_tracking' => get_option('shopcentral_usage_tracking', 'pending'),
            'auto_sync' => get_option('shopcentral_auto_sync', 'no') === 'yes',
            'order_push_enabled' => get_option('shopcentral_order_push_enabled', 'no') === 'yes',
            'hub_url' => get_option('shopcentral_hub_url', ''),
            'hub_import_key' => get_option('shopcentral_hub_import_key', ''),
            'import_key' => $import_key ?: '',
        ];


        return self::$settings_cache;
    }

    /**
     * Check if a specific feature is enabled
     */
    public static function is_feature_enabled($feature_key)
    {
        $settings = self::get_feature_settings();
        
        if ($feature_key === 'usage_tracking') {
            return isset($settings['usage_tracking']) && $settings['usage_tracking'] === 'yes';
        }

        return isset($settings[$feature_key]) && $settings[$feature_key] === true;
    }
}