<?php
// File: resend_code.php
// Resend verification code

require_once 'config.php';
require_once 'send_email.php';

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Method not allowed', null, 405);
}

$input = getJsonInput();

// Validate input
if (empty($input['email'])) {
    sendResponse(false, 'Email is required');
}

$email = sanitizeInput($input['email']);

// Validate email format
if (!validateEmail($email)) {
    sendResponse(false, 'Invalid email format');
}

try {
    $conn = getDBConnection();
    if (!$conn) {
        sendResponse(false, 'Database connection failed', null, 500);
    }
    
    // Check if user exists
    $stmt = $conn->prepare("SELECT id, is_verified, is_deleted FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();
    
    if (!$user) {
        sendResponse(false, 'Email not found. Please register first.');
    }
    
    if ($user['is_deleted'] == 1) {
        sendResponse(false, 'This account has been deleted.');
    }
    
    if ($user['is_verified'] == 1) {
        sendResponse(false, 'Email already verified. Please login.');
    }
    
    // Check rate limiting (max 3 codes per 10 minutes)
    $stmt = $conn->prepare("
        SELECT COUNT(*) as count 
        FROM verification_codes 
        WHERE email = ? 
        AND purpose = 'registration' 
        AND created_at > DATE_SUB(NOW(), INTERVAL 10 MINUTE)
    ");
    $stmt->execute([$email]);
    $result = $stmt->fetch();
    
    if ($result['count'] >= 3) {
        sendResponse(false, 'Too many requests. Please wait 10 minutes before requesting another code.');
    }
    
    // Generate new verification code
    $code = generateVerificationCode();
    $expiresAt = date('Y-m-d H:i:s', strtotime('+15 minutes'));
    
    // Delete old unused codes
    $stmt = $conn->prepare("DELETE FROM verification_codes WHERE email = ? AND purpose = 'registration' AND is_used = 0");
    $stmt->execute([$email]);
    
    // Insert new verification code
    $stmt = $conn->prepare("INSERT INTO verification_codes (email, code, purpose, expires_at) VALUES (?, ?, 'registration', ?)");
    $stmt->execute([$email, $code, $expiresAt]);
    
    // Send email
    $subject = "ensi.lk - New Verification Code";
    $bodyHTML = "
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: linear-gradient(135deg, #6C63FF 0%, #FF6584 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
                .content { background: #f8f9fa; padding: 30px; border-radius: 0 0 10px 10px; }
                .code { font-size: 32px; font-weight: bold; color: #6C63FF; text-align: center; letter-spacing: 10px; padding: 20px; background: white; border-radius: 10px; margin: 20px 0; }
                .footer { text-align: center; color: #636E72; padding: 20px; font-size: 12px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>New Verification Code 🎓</h1>
                </div>
                <div class='content'>
                    <h2>Your New Verification Code</h2>
                    <p>Here is your new verification code:</p>
                    <div class='code'>$code</div>
                    <p><strong>This code will expire in 15 minutes.</strong></p>
                    <p>If you didn't request this code, please ignore this email.</p>
                </div>
                <div class='footer'>
                    <p>&copy; 2025 ensi.lk - Master English with Fun!</p>
                </div>
            </div>
        </body>
        </html>
    ";
    
    $emailSent = sendIdeasEmail($email, $subject, $bodyHTML);
    
    if ($emailSent) {
        logActivity("Verification code resent to: $email");
        sendResponse(true, 'New verification code sent to your email.');
    } else {
        logActivity("Failed to resend verification email to: $email");
        sendResponse(false, 'Failed to send verification email. Please try again later.', null, 500);
    }
    
} catch (Exception $e) {
    logActivity("Resend code error: " . $e->getMessage());
    sendResponse(false, 'An error occurred. Please try again later.', null, 500);
}
?>
