<?php
session_start();
require_once 'config/database.php';

$email = filter_input(INPUT_GET, 'email', FILTER_VALIDATE_EMAIL);
$code = filter_input(INPUT_GET, 'code');

if (!$email || !$code) {
    $_SESSION['error'] = "Invalid verification link.";
    header('Location: login.php');
    exit;
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Check if the verification code is valid and not expired
    $stmt = $db->prepare("
        SELECT id FROM users 
        WHERE email = ? AND verification_code = ? AND verification_expiry > NOW()
    ");
    $stmt->execute([$email, $code]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        $_SESSION['error'] = "Invalid or expired verification link.";
        header('Location: login.php');
        exit;
    }
    
    // Update user status to active
    $stmt = $db->prepare("
        UPDATE users 
        SET status = 'active', email_verified = 1, verification_code = NULL 
        WHERE id = ?
    ");
    $stmt->execute([$user['id']]);
    
    // Set success message using the existing 'success' session variable
    $_SESSION['success'] = "Your email has been verified successfully. You can now log in to your account.";
    
    // Also set a URL parameter to ensure the message is displayed
    header('Location: login.php?verified=true');
    exit;
    
} catch (Exception $e) {
    error_log("Email verification error: " . $e->getMessage());
    $_SESSION['error'] = "An error occurred during verification. Please try again or contact support.";
    header('Location: login.php');
    exit;
}
?>
