<?php
/**
 * Resend 2FA Code 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.']
    ]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    $user_email = $_SESSION['pending_user_email'];
    $user_name = $_SESSION['pending_user_name'];
    
    // Check rate limiting - max 3 codes per 15 minutes
    $rate_check = $connect->prepare("
        SELECT COUNT(*) as code_count 
        FROM verification_codes 
        WHERE user_email = :user_email 
        AND created_at > DATE_SUB(NOW(), INTERVAL 15 MINUTE)
    ");
    $rate_check->execute([':user_email' => $user_email]);
    $rate_result = $rate_check->fetch();
    
    if ($rate_result['code_count'] >= 3) {
        echo json_encode([
            'success' => false,
            'errors' => ['Too many requests. Please wait 15 minutes before requesting a new code.']
        ]);
        exit;
    }
    
    // Generate new 6-digit verification code
    $verification_code = str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT);
    
    // Store verification code in database
    $expires_at = date('Y-m-d H:i:s', strtotime('+10 minutes'));
    $ip_address = getClientIp(1);
    
    $stmt = $connect->prepare("INSERT INTO verification_codes (user_email, verification_code, expires_at, ip_address) VALUES (:user_email, :verification_code, :expires_at, :ip_address)");
    $stmt->execute([
        ':user_email' => $user_email,
        ':verification_code' => $verification_code,
        ':expires_at' => $expires_at,
        ':ip_address' => $ip_address
    ]);
    
    // Send verification code via email
    $array_content = array(
        "{LOGO_URL}" => $urlPath->image($theme['th_logo']),
        "{SITE_DOMAIN}" => $urlPath->home(),
        "{SITE_NAME}" => $translation['tr_1'],
        "{USER_NAME}" => $user_name,
        "{VERIFICATION_CODE}" => $verification_code
    );
    
    $emailTemplate = getEmailTemplate($connect, 3); // 2FA template ID
    
    if ($emailTemplate) {
        $emailContent = json_decode($emailTemplate['email_content'], true);
        $emailSent = @sendMail(
            $array_content,
            $emailContent[0]['message'],
            $user_email,
            $emailTemplate['email_fromname'],
            $emailContent[0]['subject'],
            $emailTemplate['email_plaintext']
        );
        
        if ($emailSent === 'TRUE') {
            echo json_encode([
                'success' => true,
                'message' => 'A new verification code has been sent to your email.'
            ]);
            exit;
        } else {
            echo json_encode([
                'success' => false,
                'errors' => ['Failed to send email. Please try again.']
            ]);
            exit;
        }
    } else {
        echo json_encode([
            'success' => false,
            'errors' => ['Email template not found. Please contact support.']
        ]);
        exit;
    }
}

echo json_encode([
    'success' => false,
    'errors' => ['Invalid request method.']
]);
exit;
