<?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
        }


        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;
        }

        self::$settings_cache = [
            'store_manager' => true,
            'usage_tracking' => get_option('shopcentral_usage_tracking', 'pending'),
            'auto_sync' => get_option('shopcentral_auto_sync', 'no') === 'yes',
        ];


        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;
    }
}