<?php
declare(strict_types=1);
defined('ABSPATH') || exit;

class DSProofwp_Form_Settings_Controller
{
    private const ROUTE_NAMESPACE = 'dsproofwp/v1';

    private DSProofwp_Form_Settings_Repository $repository;

    public function __construct(DSProofwp_Form_Settings_Repository $repository)
    {
        $this->repository = $repository;
    }

    public function register_routes(): void
    {
        register_rest_route(
            self::ROUTE_NAMESPACE,
            '/form-settings',
            [
                [
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => [$this, 'get_settings'],
                    'permission_callback' => '__return_true',
                ],
                [
                    'methods'             => WP_REST_Server::EDITABLE,
                    'callback'            => [$this, 'update_settings'],
                    'permission_callback' => [$this, 'manage_permission'],
                ],
            ]
        );
    }

    public function get_settings(): WP_REST_Response
    {
        $settings = $this->repository->get();
        return rest_ensure_response([
            'form_settings' => $settings,
        ]);
    }

    public function update_settings(WP_REST_Request $request): WP_REST_Response
    {
        $params = $request->get_params();
        $form_settings = isset($params['form_settings']) ? $params['form_settings'] : [];
        if (is_string($form_settings)) {
            $form_settings = json_decode($form_settings, true);
        }
        if (! is_array($form_settings)) {
            $form_settings = [];
        }

        // Handle secret key inside form_settings or at the top level
        $secret_key = null;
        if (isset($form_settings['recaptcha_secret_key'])) {
            $secret_key = $form_settings['recaptcha_secret_key'];
        } elseif (isset($params['recaptcha_secret_key'])) {
            $secret_key = $params['recaptcha_secret_key'];
        }

        if ($secret_key !== null) {
            $form_settings['recaptcha_secret_key'] = $secret_key;
        }

        $updated = $this->repository->update($form_settings);
        return rest_ensure_response([
            'form_settings' => $updated,
        ]);
    }

    public function manage_permission(): bool
    {
        return current_user_can('manage_options');
    }
}
