<?php
	namespace Main\Libs;
	
	class reCAPTCHA
	{
		private $siteKey;
		private $secretKey;
		
		public function __construct($siteKey, $secretKey)
		{
			$this->siteKey = $siteKey;
			$this->secretKey = $secretKey;
		}
		
		public function getHTML(): string
		{
			return '<div class="cf-turnstile" data-sitekey="' . $this->siteKey . '"></div>';
		}
		
		public function getScript(): string
		{
			return '<script src="https://challenges.cloudflare.com/turnstile/v0/api.js?onload=_turnstileCb" defer></script>';
		}
		
		public function verify()
		{
			$ch = curl_init("https://challenges.cloudflare.com/turnstile/v0/siteverify");
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, [
				"secret" => $this->secretKey,
				"response" => $_POST['cf-turnstile-response'],
				"remoteip" => $_SERVER['CF_CONNECTING_IP'] ?? getIP(),
			]);
			$response = curl_exec($ch);
			curl_close($ch);
			
			$response = json_decode($response);
			
			return $response->success;
		}
		
		public function isEnabled($action): bool
		{
			if (!modules('recaptcha')->isActive()) return false;
			
			$recaptchaPagesStatusJSON = modules('recaptcha')->settings('pagesStatus');
			$recaptchaPagesStatus = json_decode($recaptchaPagesStatusJSON, true);
			
			return $recaptchaPagesStatus[$action] == 1;
		}
	}