<?php
// File: verify_email.php
// Verify the 4-digit code sent to email

require_once 'config.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']) || empty($input['code'])) {
    sendResponse(false, 'Email and code are required');
}

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

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

// Validate code format (4 digits)
if (!preg_match('/^\d{4}$/', $code)) {
    sendResponse(false, 'Invalid code format');
}

try {
    $conn = getDBConnection();
    if (!$conn) {
        sendResponse(false, 'Database connection failed', null, 500);
    }
    
    // Find valid verification code
    $stmt = $conn->prepare("
        SELECT id, purpose 
        FROM verification_codes 
        WHERE email = ? 
        AND code = ? 
        AND is_used = 0 
        AND expires_at > NOW()
        ORDER BY created_at DESC 
        LIMIT 1
    ");
    $stmt->execute([$email, $code]);
    $verificationCode = $stmt->fetch();
    
    if (!$verificationCode) {
        logActivity("Invalid or expired verification code for: $email");
        sendResponse(false, 'Invalid or expired verification code');
    }
    
    // Handle different purposes
    $purpose = $verificationCode['purpose'];
    
    if ($purpose === 'registration') {
        // Mark code as used for registration
        $stmt = $conn->prepare("UPDATE verification_codes SET is_used = 1 WHERE id = ?");
        $stmt->execute([$verificationCode['id']]);
        
        // Mark email as verified (but don't complete registration yet)
        $stmt = $conn->prepare("UPDATE users SET is_verified = 1 WHERE email = ?");
        $stmt->execute([$email]);
        
        logActivity("Email verified successfully for registration: $email");
        sendResponse(true, 'Email verified successfully. Please complete your registration.');
        
    } elseif ($purpose === 'password_reset') {
        // DON'T mark code as used - reset_password.php will do that
        // Just verify the code is valid
        logActivity("Email verified successfully for password reset: $email");
        sendResponse(true, 'Code verified. You can now reset your password.');
        
    } elseif ($purpose === 'delete_account') {
        // Mark code as used
        $stmt = $conn->prepare("UPDATE verification_codes SET is_used = 1 WHERE id = ?");
        $stmt->execute([$verificationCode['id']]);
        
        // Mark account as deleted
        $stmt = $conn->prepare("UPDATE users SET is_deleted = 1, updated_at = NOW() WHERE email = ?");
        $stmt->execute([$email]);
        
        logActivity("Account marked as deleted: $email");
        sendResponse(true, 'Account has been deleted successfully.');
        
    } else {
        sendResponse(false, 'Invalid verification purpose');
    }
    
} catch (Exception $e) {
    logActivity("Verification error: " . $e->getMessage());
    sendResponse(false, 'An error occurred. Please try again later.', null, 500);
}
?>
