<?php
namespace OxygenApp\Common\Guards;

if ( ! defined( 'ABSPATH' ) ) exit;

use WP_REST_Request;
use OxygenApp\Common\Validation\FieldsValidator;
use OxygenApp\Utils\OptionUtils;

class SignupGuard extends BaseGuard implements GuardInterface {

    public static function check(WP_REST_Request $request): array {

        $fieldsRules = [
            [
                'field_name' => 'email',
                'required' => true,
                'type' => 'email',
            ],
            [
                'field_name' => 'password',
                'required' => true,
                'type' => 'password',
                'min_length' => 7,
            ],
            [
                'field_name' => 'terms',
                'required' => true,
                'type' => 'string',
                'min_length' => 2,
                'max_length' => 4,
            ]
        ];

        $recaptcha_site_key = trim(OptionUtils::getInstance()->getOption('recaptcha_site_key'));
        $recaptcha_site_secret = trim(OptionUtils::getInstance()->getOption('recaptcha_site_secret'));
        $isRecaptchaActive = OptionUtils::getInstance()->getOption('is_recaptcha_active');
        $isRecaptchaActive = $isRecaptchaActive && strlen($recaptcha_site_key) > 0 && strlen($recaptcha_site_secret) > 0;
        if ($isRecaptchaActive) {
            $fieldsRules[] = [
                'field_name' => 'token',
                'required' => true,
                'type' => 'string',
                'max_length' => 3000
            ];
        }

        $params = $request->get_params();
        $validatorResult = FieldsValidator::validate($params, $fieldsRules);

        if (!$validatorResult['status']) {
            return self::getFailedResponse($validatorResult['errorMessage'], 400);
        }

        if ($isRecaptchaActive) {
            $turnstileValidationResult = self::checkTurnstile($recaptcha_site_secret, $request->get_param('token'));
            if (!$turnstileValidationResult) {
                return [
                    'status'  => false,
                    'code'    => 400,
                    'message' => esc_html__('Turnstile verification failed', 'oxyleaf-app-working-and-relaxing-app')
                ];
            }
        }

        return self::getSuccessResponse();
    }

    private static function checkTurnstile(string $secretKey, string $token): bool {

        $verifyURL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';

        $data = [
            'secret' => $secretKey,
            'response' => $token
        ];

        $response = wp_remote_post($verifyURL, [
            'body' => $data,
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded'
            ]
        ]);

        if (is_wp_error($response)) {
            return false;
        }

        $responseData = json_decode(wp_remote_retrieve_body($response), true);

        if ($responseData['success']) {
            return true;
        } else {
            return false;
        }
    }
}