<?php
/**
 * reCAPTCHA Service - Standard v2 API Implementation
 */
require_once 'config_loader.php';
require_once 'Logger.php';

class RecaptchaService {
    private $siteKey;
    private $secretKey;
    
    public function __construct() {
        $this->siteKey = env('RECAPTCHA_SITE_KEY');
        $this->secretKey = env('RECAPTCHA_SECRET_KEY');
        
        if (empty($this->siteKey) || empty($this->secretKey)) {
            throw new Exception('reCAPTCHA configuration missing. Please check environment variables.');
        }
        
        Logger::debug('RecaptchaService initialized', [
            'site_key' => $this->siteKey
        ]);
    }
    
    public function verifyToken($token, $action = 'submit') {
        if (empty($token)) {
            Logger::warning('Empty reCAPTCHA token provided');
            return ['success' => false, 'message' => 'reCAPTCHA token is missing'];
        }
        
        try {
            Logger::debug('Verifying reCAPTCHA token', ['action' => $action]);
            
            // Use standard reCAPTCHA v2 verification API
            $url = 'https://www.google.com/recaptcha/api/siteverify';
            $data = [
                'secret' => $this->secretKey,
                'response' => $token,
                'remoteip' => $_SERVER['REMOTE_ADDR'] ?? null
            ];
            
            $options = [
                'http' => [
                    'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                    'method' => 'POST',
                    'content' => http_build_query($data)
                ]
            ];
            
            $context = stream_context_create($options);
            $response = file_get_contents($url, false, $context);
            $result = json_decode($response, true);
            
            if (!$result['success']) {
                $errorCodes = $result['error-codes'] ?? [];
                Logger::warning('reCAPTCHA verification failed', ['errors' => $errorCodes]);
                return ['success' => false, 'message' => 'reCAPTCHA verification failed'];
            }
            
            Logger::info('reCAPTCHA verification successful', ['action' => $action]);
            
            return [
                'success' => true,
                'message' => 'reCAPTCHA verification successful'
            ];
            
        } catch (Exception $e) {
            Logger::error('reCAPTCHA Error', [
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            return ['success' => false, 'message' => 'An error occurred during verification.'];
        }
    }
    
    public function getSiteKey() {
        return $this->siteKey;
    }
}