<?php
/**
 * 2FA Verification Controller
 */

// Suppress errors for clean JSON output
@ini_set('display_errors', '0');
@error_reporting(0);

// Start output buffering
ob_start();

// Mark as API endpoint
define('IS_API_ENDPOINT', true);

try {
    require '../core.php';
} catch (Exception $e) {
    ob_end_clean();
    header('Content-Type: application/json');
    http_response_code(200);
    echo json_encode(['success' => false, 'errors' => ['System error. Please try again.']]);
    exit;
}

// Clear buffer
ob_end_clean();

// Set JSON header
header('Content-Type: application/json');
http_response_code(200);

$errors = array();

// Check if user has pending 2FA
if (!isset($_SESSION['pending_2fa']) || $_SESSION['pending_2fa'] !== true) {
    echo json_encode([
        'success' => false,
        'errors' => ['Invalid session. Please login again.'],
        'redirect' => SITE_URL . '/signin.php'
    ]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    $verification_code = isset($_POST['verification_code']) ? trim($_POST['verification_code']) : '';
    $user_email = $_SESSION['pending_user_email'];
    
    // Validate verification code
    if (empty($verification_code)) {
        $errors[] = 'Please enter the verification code.';
    } elseif (!preg_match('/^\d{6}$/', $verification_code)) {
        $errors[] = 'Verification code must be 6 digits.';
    }
    
    if (empty($errors)) {
        
        // Check verification code in database
        $statement = $connect->prepare("
            SELECT * FROM verification_codes 
            WHERE user_email = :user_email 
            AND verification_code = :verification_code 
            AND is_used = 0 
            AND expires_at > NOW() 
            ORDER BY created_at DESC 
            LIMIT 1
        ");
        
        $statement->execute([
            ':user_email' => $user_email,
            ':verification_code' => $verification_code
        ]);
        
        $result = $statement->fetch();
        
        if ($result !== false) {
            
            // Mark code as used
            $update_stmt = $connect->prepare("UPDATE verification_codes SET is_used = 1 WHERE id = :id");
            $update_stmt->execute([':id' => $result['id']]);
            
            // Create actual session
            $_SESSION['signedin'] = true;
            $_SESSION['user_email'] = $_SESSION['pending_user_email'];
            $_SESSION['user_name'] = $_SESSION['pending_user_name'];
            $_SESSION['user_id'] = $_SESSION['pending_user_id'];
            
            // Remember me cookie (30 days)
            if (isset($_SESSION['pending_remember_me']) && $_SESSION['pending_remember_me']) {
                $token = bin2hex(random_bytes(32));
                setcookie('remember_token', $token, time() + (30 * 24 * 60 * 60), '/');
            }
            
            // Clear pending session data
            unset($_SESSION['pending_2fa']);
            unset($_SESSION['pending_user_email']);
            unset($_SESSION['pending_user_name']);
            unset($_SESSION['pending_user_id']);
            unset($_SESSION['pending_remember_me']);
            
            echo json_encode([
                'success' => true,
                'message' => 'Verification successful!',
                'redirect' => SITE_URL
            ]);
            exit;
            
        } else {
            $errors[] = 'Invalid or expired verification code.';
        }
    }
}

// Return errors
echo json_encode([
    'success' => false,
    'errors' => $errors
]);
exit;
