<?php 
session_start();
require 'includes/db.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$error = "";

// ✅ MUST HAVE EMAIL SESSION
if (empty($_SESSION['verify_email_id'])) {
    header("Location: verify_details.php");
    exit;
}

$email_id = $_SESSION['verify_email_id'];

// 🔥 GET EMAIL
$emailRes = mysqli_query($conn, "
    SELECT * FROM user_emails 
    WHERE id='$email_id'
");

$emailData = mysqli_fetch_assoc($emailRes);

if (!$emailData) {
    header("Location: verify_details.php");
    exit;
}


// 🔐 VERIFY OTP
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $input_otp = $_POST['otp'];

    // ❌ OTP expired
    if (strtotime($emailData['otp_expires_at']) < time()) {
        $error = "OTP has expired.";

    // ❌ Wrong OTP
    } elseif ($input_otp != $emailData['otp']) {
        $error = "Invalid OTP.";

    } else {

        // ✅ MARK EMAIL VERIFIED
        mysqli_query($conn, "
            UPDATE user_emails 
            SET verified=1 
            WHERE id='$email_id'
        ");

        // 🔥 SAFE ACCOUNT SWITCH (VERY IMPORTANT)
        if (!empty($_SESSION['verify_email_owner'])) {

            $new_user_id = $_SESSION['verify_email_owner'];

            // 🔍 VERIFY USER EXISTS BEFORE SWITCH
            $checkUser = mysqli_query($conn, "
                SELECT id FROM users WHERE id='$new_user_id' LIMIT 1
            ");

            if (mysqli_num_rows($checkUser) > 0) {
                $_SESSION['user_id'] = $new_user_id;
            }
        }

        $user_id = $_SESSION['user_id'];

        // 🔍 ENSURE USER EXISTS (FINAL SAFETY)
        $checkFinalUser = mysqli_query($conn, "
            SELECT id FROM users WHERE id='$user_id' LIMIT 1
        ");

        if (mysqli_num_rows($checkFinalUser) == 0) {
            session_destroy();
            die("Invalid session user. Please login again.");
        }

        // ✅ MARK USER AS VERIFIED (FIXES LOOP)
        mysqli_query($conn, "
            UPDATE users 
            SET verified = 1 
            WHERE id='$user_id'
        ");

        // 🔥 SET PRIMARY EMAIL IF EMPTY
        $checkUserEmail = mysqli_query($conn, "
            SELECT email FROM users WHERE id='$user_id'
        ");
        $userRow = mysqli_fetch_assoc($checkUserEmail);

        if (empty($userRow['email'])) {
            mysqli_query($conn, "
                UPDATE users 
                SET email='{$emailData['email']}'
                WHERE id='$user_id'
            ");
        }

        // 🔥 CLEAR OTP AFTER USE
        mysqli_query($conn, "
            UPDATE user_emails 
            SET otp=NULL, otp_expires_at=NULL 
            WHERE id='$email_id'
        ");

        // 🧹 CLEAN SESSION
        unset($_SESSION['verify_email_owner']);
        unset($_SESSION['verify_email']);
        unset($_SESSION['verify_email_id']);

        // 🚀 FINAL REDIRECT
        header("Location: includes/auth_check.php");
        exit;
    }
}


// 🔁 RESEND OTP
if (isset($_GET['resend'])) {

    $otp = rand(100000, 999999);
    $expiry = date("Y-m-d H:i:s", time() + 300);

    mysqli_query($conn, "
        UPDATE user_emails 
        SET otp='$otp', 
            otp_expires_at='$expiry',
            verified=0
        WHERE id='$email_id'
    ");

    $subject = "Your Verification Code";
    $message = "<h2>Your OTP: $otp</h2><p>Expires in 5 minutes</p>";
    $headers = "Content-type:text/html;charset=UTF-8\r\n";

    mail($emailData['email'], $subject, $message, $headers);

    echo "<script>alert('New OTP sent'); window.location='verify.php';</script>";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Verification - Geneva & Exeter Coin</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #4f46e5 0%, #3730a3 100%);
            min-height: 100vh;
            position: relative;
            overflow-x: hidden;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        /* Animated crypto background */
        .crypto-bg {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            overflow: hidden;
            pointer-events: none;
            z-index: 0;
        }

        .crypto-icon {
            position: absolute;
            opacity: 0.05;
            color: white;
            font-size: 48px;
            font-weight: bold;
            animation: float 8s ease-in-out infinite;
        }

        .crypto-icon:nth-child(1) { top: 10%; left: 5%; transform: rotate(-15deg); font-size: 64px; animation-delay: 0s; }
        .crypto-icon:nth-child(2) { top: 70%; left: 15%; transform: rotate(10deg); font-size: 56px; animation-delay: 2s; }
        .crypto-icon:nth-child(3) { top: 30%; right: 10%; transform: rotate(-5deg); font-size: 72px; animation-delay: 4s; }
        .crypto-icon:nth-child(4) { bottom: 20%; right: 25%; transform: rotate(20deg); font-size: 48px; animation-delay: 1s; }
        .crypto-icon:nth-child(5) { top: 50%; left: 40%; transform: rotate(-10deg); font-size: 60px; animation-delay: 3s; }
        .crypto-icon:nth-child(6) { top: 20%; left: 25%; transform: rotate(5deg); font-size: 52px; animation-delay: 5s; }
        .crypto-icon:nth-child(7) { top: 60%; right: 5%; transform: rotate(-10deg); font-size: 60px; animation-delay: 6s; }
        .crypto-icon:nth-child(8) { bottom: 30%; left: 8%; transform: rotate(15deg); font-size: 44px; animation-delay: 7s; }

        @keyframes float {
            0%, 100% { transform: translateY(0) rotate(var(--rotation, 0deg)); }
            50% { transform: translateY(-20px) rotate(var(--rotation, 0deg)); }
        }

        /* Container */
        .container {
            position: relative;
            z-index: 10;
            width: 100%;
            max-width: 440px;
        }

        /* Logo Section */
        .logo-section {
            text-align: center;
            margin-bottom: 32px;
        }

        .logo {
            display: inline-flex;
            align-items: center;
            gap: 12px;
            color: white;
            font-size: 28px;
            font-weight: 700;
            text-decoration: none;
            margin-bottom: 16px;
        }

        /* Card */
        .card {
            background: white;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
        }

        .card-header {
            text-align: center;
            margin-bottom: 32px;
        }

        .verify-icon {
            width: 64px;
            height: 64px;
            background: linear-gradient(135deg, #dbeafe 0%, #93c5fd 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            font-size: 32px;
        }

        .card-title {
            font-size: 24px;
            font-weight: 800;
            color: #1e1b4b;
            margin-bottom: 8px;
        }

        .card-subtitle {
            font-size: 15px;
            color: #6b7280;
            line-height: 1.5;
        }

        .email-display {
            background: #f3f4f6;
            padding: 12px 16px;
            border-radius: 10px;
            font-size: 14px;
            color: #374151;
            margin-top: 12px;
            word-break: break-all;
        }

        /* Alert Messages */
        .alert {
            padding: 14px 16px;
            border-radius: 10px;
            margin-bottom: 20px;
            font-size: 14px;
            font-weight: 500;
        }

        .alert-error {
            background: #fef2f2;
            color: #dc2626;
            border: 1px solid #fecaca;
        }

        .alert-success {
            background: #f0fdf4;
            color: #16a34a;
            border: 1px solid #bbf7d0;
        }

        /* Form Styles */
        .form-group {
            margin-bottom: 20px;
        }

        .otp-input {
            width: 100%;
            padding: 16px;
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            font-size: 24px;
            font-weight: 700;
            color: #1e1b4b;
            background: white;
            transition: all 0.2s;
            font-family: inherit;
            text-align: center;
            letter-spacing: 8px;
        }

        .otp-input:focus {
            outline: none;
            border-color: #4f46e5;
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }

        .otp-input::placeholder {
            color: #9ca3af;
            font-weight: 400;
        }

        /* Submit Button */
        .btn-submit {
            width: 100%;
            padding: 16px 24px;
            background: #22c55e;
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn-submit:hover {
            background: #16a34a;
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(34, 197, 94, 0.3);
        }

        .btn-submit:active {
            transform: translateY(0);
        }

        /* Resend Link */
        .resend-section {
            text-align: center;
            margin-top: 24px;
            padding-top: 24px;
            border-top: 1px solid #e5e7eb;
        }

        .resend-text {
            font-size: 14px;
            color: #6b7280;
            margin-bottom: 8px;
        }

        .resend-link {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            color: #4f46e5;
            text-decoration: none;
            font-weight: 600;
            font-size: 14px;
            transition: all 0.2s;
        }

        .resend-link:hover {
            color: #3730a3;
        }

        .resend-link svg {
            width: 16px;
            height: 16px;
        }

        /* Back Link */
        .back-link {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            color: rgba(255, 255, 255, 0.8);
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
            margin-top: 24px;
            transition: color 0.2s;
        }

        .back-link:hover {
            color: white;
        }

        .back-link svg {
            width: 16px;
            height: 16px;
        }

        /* Responsive */
        @media (max-width: 480px) {
            .card {
                padding: 28px;
            }

            .card-title {
                font-size: 22px;
            }

            .verify-icon {
                width: 56px;
                height: 56px;
                font-size: 28px;
            }

            .otp-input {
                font-size: 20px;
                letter-spacing: 6px;
            }
        }
		/* ================= SECURITY PAGE RESPONSIVE ================= */

/* LOGO IMAGE */
.logo-img{
    width:180px;
    height:auto;
    max-width:100%;
}

/* CONTAINER IMPROVEMENT */
.container{
    width:100%;
    max-width:420px;
    padding:0 10px;
}

/* INPUT FIX (prevents mobile zoom) */
.form-input{
    font-size:16px;
}

/* CARD */
.card{
    width:100%;
}

/* 📱 TABLET */
@media (max-width:768px){

    body{
        padding:15px;
    }

    .logo-img{
        width:140px;
    }

    .card{
        padding:28px;
        border-radius:16px;
    }

    .card-title{
        font-size:20px;
    }

    .card-subtitle{
        font-size:14px;
    }
}

/* 📱 SMALL PHONES */
@media (max-width:480px){

    .logo-img{
        width:120px;
    }

    .card{
        padding:20px;
    }

    .form-input{
        padding:12px;
    }

    .btn-submit{
        padding:14px;
        font-size:15px;
    }

    .security-icon{
        width:52px;
        height:52px;
        font-size:24px;
    }
}
    </style>
</head>
<body>
    <!-- Crypto Background -->
    <div class="crypto-bg">
        <div class="crypto-icon">₿</div>
        <div class="crypto-icon">₿</div>
        <div class="crypto-icon">₿</div>
        <div class="crypto-icon">₿</div>
        <div class="crypto-icon">◊</div>
        <div class="crypto-icon">◊</div>
        <div class="crypto-icon">◎</div>
        <div class="crypto-icon">◎</div>
    </div>

    <!-- Container -->
    <div class="container">
        <!-- Logo Section -->
        <div class="logo-section">
            <a href="index.php" class="logo">
                <img src="img/logo_white.png" class="logo-img">
            </a>
        </div>

        <!-- Card -->
        <div class="card">
            <div class="card-header">
                <div class="verify-icon">📧</div>
                <h1 class="card-title">Verify Your Email</h1>
                <p class="card-subtitle">Enter the 6-digit code sent to your email</p>
                <?php if(isset($emailData['email'])): ?>
<div class="email-display"><?php echo htmlspecialchars($emailData['email']); ?></div>
<?php endif; ?>
            </div>

            <?php if(isset($error)) echo "<div class='alert alert-error'>$error</div>"; ?>

            <form method="POST">
                <div class="form-group">
                    <input type="text" name="otp" class="otp-input" placeholder="000000" maxlength="6" required>
                </div>

                <button type="submit" class="btn-submit">Verify</button>
            </form>

            <div class="resend-section">
                <p class="resend-text">Didn't receive the code?</p>
                <a class="resend-link" href="?resend=1">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <polyline points="23 4 23 10 17 10"></polyline>
                        <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path>
                    </svg>
                    Resend OTP
                </a>
            </div>
        </div>

        <!-- Back Link -->
        <div style="text-align: center;">
            <a href="login.php" class="back-link">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <line x1="19" y1="12" x2="5" y2="12"></line>
                    <polyline points="12 19 5 12 12 5"></polyline>
                </svg>
                Back to Login
            </a>
        </div>
    </div>
</body>
</html>