<?php

namespace CouponsPlus\App\Handlers;

use CouponsPlus\Original\Environment\Env;
use CouponsPlus\Original\Events\Handler\EventHandler;
use WP_REST_Request;
use WP_REST_Response;

class PreferencesAPIHandler extends EventHandler
{
    protected $numberOfArguments = 1;
    protected $priority = 10;

    public function execute()
    {
        register_rest_route('coupons-plus/v1', '/preferences', [
            'methods' => 'POST',
            'callback' => [$this, 'update_preference'],
            'permission_callback' => [$this, 'check_permissions'],
            'args' => [
                'key' => [
                    'type' => 'string',
                    'required' => true,
                    'description' => 'The preference key to update',
                    'sanitize_callback' => 'sanitize_text_field',
                ],
                'value' => [
                    'required' => true,
                    'description' => 'The preference value to set',
                ]
            ]
        ]);
    }

    public function update_preference(WP_REST_Request $request): WP_REST_Response
    {
        $key = $request->get_param('key');
        $value = $request->get_param('value');

        // Prefix the option name with the plugin prefix
        $option_name = Env::getWithPrefix($key);

        // Update the option in the database
        $updated = update_option($option_name, $value);

        if ($updated || get_option($option_name) === $value) {
            return new WP_REST_Response([
                'success' => true,
                'name' => $option_name,
                'value' => $value
            ], 200);
        }

        return new WP_REST_Response([
            'success' => false,
            'message' => 'Failed to update preference'
        ], 500);
    }

    public function check_permissions(): bool
    {
        return current_user_can('manage_woocommerce') || current_user_can('manage_options');
    }
}
