<?php
/**
 * Email Verification Endpoint
 * Location: public_html/verify_email.php
 */

require_once __DIR__ . '/connections/connect.php';
require_once __DIR__ . '/includes/functions.php';

$token = $_GET['token'] ?? '';
$status_message = '';
$is_success = false;

if (empty($token)) {
    $status_message = "Invalid or missing verification token.";
} else {
    $stmt = $pdo->prepare("SELECT * FROM email_verifications WHERE token = ? AND expires_at > NOW()");
    $stmt->execute([$token]);
    $verification = $stmt->fetch();

    if (!$verification) {
        $status_message = "This verification link is invalid or has expired.";
    } else {
        try {
            $pdo->beginTransaction();

            $stmt_user = $pdo->prepare("UPDATE users SET is_verified = 1 WHERE id = ?");
            $stmt_user->execute([$verification['user_id']]);

            $stmt_del = $pdo->prepare("DELETE FROM email_verifications WHERE id = ?");
            $stmt_del->execute([$verification['id']]);

            $pdo->commit();

            $is_success = true;
            $status_message = "Your email address has been successfully verified! You can now log in to your account.";
        } catch (Exception $e) {
            $pdo->rollBack();
            $status_message = "Error verifying email: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Email Verification - MiBuildqc</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-slate-100 min-h-screen flex items-center justify-center p-4">

    <div class="bg-white rounded-2xl max-w-md w-full p-8 shadow-xl text-center space-y-5 border border-slate-200">
        <div class="bg-[#E8E5FF] rounded-xl py-3 px-6 inline-block">
            <span class="text-2xl font-extrabold text-slate-900">MiBuild<span class="text-[#635BFF]">qc</span></span>
        </div>

        <h2 class="text-xl font-bold text-slate-800">Account Email Verification</h2>

        <?php if ($is_success): ?>
            <div class="p-4 rounded-xl bg-emerald-50 border border-emerald-200 text-emerald-800 text-sm">
                <?php echo $status_message; ?>
            </div>
            <a href="login.php" class="inline-block px-6 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-xs uppercase tracking-wider">
                Log In to Your Account
            </a>
        <?php else: ?>
            <div class="p-4 rounded-xl bg-rose-50 border border-rose-200 text-rose-800 text-sm">
                <?php echo $status_message; ?>
            </div>
            <a href="register.php" class="inline-block px-6 py-2.5 rounded-xl bg-slate-700 text-white font-bold text-xs">
                Back to Registration
            </a>
        <?php endif; ?>
    </div>

</body>
</html>