<?php

defined('ABSPATH') || exit;

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

    public function __construct($namespace = 'bundlepress/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)
    {
        global $wpdb;
        $table_settings = $wpdb->prefix . 'bundlepress_settings';

        $params = $request->get_json_params();

        if (!isset($params['settings'])) {
            return new WP_Error('missing_settings', 'Settings data is required', ['status' => 400]);
        }

        $settings = $params['settings'];

        // Validate settings
        $valid_keys = [
            'usage_tracking',
            'product_bundles',
            'bundle_placement',
            'card_style',
            'product_alignment'
        ];
        foreach ($settings as $key => $value) {
            if (!in_array($key, $valid_keys)) {
                return new WP_Error('invalid_setting', "Invalid setting key: $key", ['status' => 400]);
            }
        }

        // Update or insert settings
        $existing = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->prefix}bundlepress_settings WHERE setting_key = %s",
                'feature_settings'
            )
        );

        $settings_json = json_encode($settings);

        if ($existing > 0) {
            // Update
            $result = $wpdb->update(
                $table_settings,
                ['setting_value' => $settings_json],
                ['setting_key' => 'feature_settings'],
                ['%s'],
                ['%s']
            );
        } else {
            // Insert
            $result = $wpdb->insert(
                $table_settings,
                [
                    'setting_key' => 'feature_settings',
                    'setting_value' => $settings_json
                ],
                ['%s', '%s']
            );
        }

        if ($result !== false) {
            // Clear cache to reflect new settings
            self::$settings_cache = null;

            // Send usage data only if tracking is enabled
            if (isset($settings['usage_tracking']) && $settings['usage_tracking']) {
                $this->send_usage_data($settings);
            }

            return rest_ensure_response([
                'success' => true,
                'message' => 'Settings updated successfully',
                'data' => $settings
            ]);
        }

        return new WP_Error('update_failed', 'Failed to update settings', ['status' => 500]);
    }

    private function send_usage_data($settings)
    {
        $body = [
            'site_url' => get_site_url(),
            'timestamp' => current_time('mysql'),
            'settings' => $settings,
            'plugin_version' => BUNDLEPRESS_VERSION,
            'php_version' => PHP_VERSION,
            'wp_version' => get_bloginfo('version'),
        ];

        BundlePress_Remote_API::post('features/usages', $body);
    }

    public static function get_feature_settings()
    {
        if (self::$settings_cache !== null) {
            return self::$settings_cache;
        }

        $defaults = [
            'usage_tracking'    => true,
            'product_bundles'   => true,
            'bundle_placement'  => 'woocommerce_after_add_to_cart_form',
            'card_style'        => 'card',
            'product_alignment' => 'horizontal',
        ];

        global $wpdb;
        $table_settings = $wpdb->prefix . 'bundlepress_settings';

        $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_settings));
        if (!$table_exists) {
            self::$settings_cache = $defaults;
            return self::$settings_cache;
        }

        $result = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT setting_value FROM {$wpdb->prefix}bundlepress_settings WHERE setting_key = %s",
                'feature_settings'
            )
        );

        if ($result && !empty($result->setting_value)) {
            $decoded = json_decode($result->setting_value, true);
            if (is_array($decoded)) {
                self::$settings_cache = array_merge($defaults, $decoded);
                return self::$settings_cache;
            }
        }

        self::$settings_cache = $defaults;
        return self::$settings_cache;
    }

    public static function is_feature_enabled($feature_key)
    {
        $settings = self::get_feature_settings();
        return isset($settings[$feature_key]) && $settings[$feature_key] === true;
    }
}