<?php

namespace EstatebudConnect\Services;

if (!defined('WPINC')) {
    die();
}

use EstatebudConnect\Configs\App;
use EstatebudConnect\Traits\Singleton;
use EstatebudConnect\Models\Settings;
use EstatebudConnect\Utilities\Helper;

class Captcha
{
    use Singleton;

    protected $captcha_services = [
        'recaptcha' => 'https://recaptcha.net/recaptcha/api/siteverify',
        'hcaptcha' => 'https://api.hcaptcha.com/siteverify',
        'turnstile' => 'https://challenges.cloudflare.com/turnstile/v0/siteverify',
    ];

    public function __construct() {}

    public function post_captcha_response()
    {
        $settings_data = Settings::instance()->get_data();
        $captcha_provider = $settings_data['captcha_provider'];
        $captcha_site_key = $settings_data['captcha_site_key'];
        $captcha_secret_key = $settings_data['captcha_secret_key'];

        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'estatebud-nonce')) {
            return [
                'success' => false,
                'error' => 'Nonce verification failed',
            ];
        }

        $captcha_token = isset($_POST['captcha_token']) ? sanitize_text_field(wp_unslash($_POST['captcha_token'])) : null;

        if (empty($captcha_provider) || empty($captcha_site_key) || empty($captcha_secret_key)) {
            return [
                'success' => null,
            ];
        }

        if (!isset($this->captcha_services[$captcha_provider])) {
            return [
                'success' => false,
                'error' => 'Invalid captcha provider',
            ];
        }

        if (empty($captcha_token)) {
            return [
                'success' => false,
                'error' => 'Captcha token not provided',
            ];
        }

        $captcha_validation_url = $this->captcha_services[$captcha_provider];
        $remoteIp = Helper::get_user_ip();
        
        $payload = [
            'secret' => $captcha_secret_key,
            'response' => $captcha_token,
        ];

        if (!empty($remoteIp)) {
            $payload['remoteip'] = $remoteIp;
        }

        $result = $this->post($captcha_validation_url, $payload);

        if ($captcha_provider == 'recaptcha' && $result['score'] < 0.5) {
            $result['success'] = false;
        }

        return $result;
    }

    protected function post(string $url, array $payload = [])
    {
        return $this->call('POST', $url, $payload);
    }

    protected function call(string $method, string $url, array $payload = [])
    {
        $args = [
            'headers' => [
                'Accept' => 'application/json',
                'Content-Type' => 'application/x-www-form-urlencoded',
            ],
            'user-agent' => sprintf('WordPress/%s; %s', App::NAME, App::VERSION),
            'method' => $method,
            'timeout' => 30,
            'body' => http_build_query($payload),
        ];

        $response = wp_remote_request($url, $args);

        if (is_wp_error($response)) {
            return [
                'success' => false,
                'score' => null,
                'http_code' => $code,
                'response' => $response->get_error_message(),
            ];
        }

        $code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);

        $result = $this->parse($body);

        return [
            'success' => $result['success'] ?? false,
            'score' => $result['score'] ?? false,
            'http_code' => $code,
            'response' => $body,
        ];
    }

    protected function parse(string $json)
    {
        return json_decode($json, true);
    }
}
