<?php

defined('ABSPATH') || exit;

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

    public function __construct($namespace = 'insightpress/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') || current_user_can('manage_woocommerce');
    }

    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('insightpress_usage_tracking', 'pending');
            update_option('insightpress_usage_tracking', $params['usage_tracking']);
            self::$settings_cache = null; // Clear cache

            if ($params['usage_tracking'] === 'yes' && $prev_value !== 'yes') {
                if (class_exists('InsightPress_Event_Tracker')) {
                    delete_option('insightpress_install_tracked');
                    InsightPress_Event_Tracker::track_install();
                    InsightPress_Event_Tracker::track_activation();
                }
            }
        }

        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 = [
            'usage_tracking' => get_option('insightpress_usage_tracking', 'pending'),
        ];

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