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

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

$user_id = $_SESSION['user_id'];
$error = "";
$success = "";

// ===============================
// 💱 GET CURRENCY (SAFE ADDITION)
// ===============================
$currency = $_COOKIE['currency_selected'] ?? 'USD';

// ✅ VALIDATE ALLOWED CURRENCY
$allowed = ["USD","ZAR","NGN","EUR","GBP","CHF","CAD","AUD","INR"];
if (!in_array($currency, $allowed)) {
    $currency = "USD";
}

$currency = mysqli_real_escape_string($conn, $currency);
// ===============================


if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $phone = mysqli_real_escape_string($conn, $_POST['phone']);

    // ✅ VALIDATE EMAIL
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "❌ Invalid email format.";
    } else {

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

        // 🔥 STEP 1: CHECK IF EMAIL EXISTS ANYWHERE
        $globalCheck = mysqli_query($conn, "
            SELECT * FROM user_emails 
            WHERE email='$email'
            LIMIT 1
        ");

        if (mysqli_num_rows($globalCheck) > 0) {

            // ✅ EMAIL EXISTS → SEND OTP
            $existing = mysqli_fetch_assoc($globalCheck);
            $email_id = $existing['id'];

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

            // 🔥 OWNER SWITCH (UNCHANGED)
            $_SESSION['verify_email_owner'] = $existing['user_id'];

            // ===============================
            // 💱 SAVE CURRENCY TO OWNER USER
            // ===============================
            mysqli_query($conn, "
                UPDATE users 
                SET currency='$currency' 
                WHERE id='{$existing['user_id']}'
            ");
            // ===============================

            $success = "✅ OTP sent to existing email.";

        } else {

            // 🔍 LIMIT EMAILS (MAX 5)
            $countRes = mysqli_query($conn, "
                SELECT COUNT(*) as total FROM user_emails WHERE user_id='$user_id'
            ");
            $countRow = mysqli_fetch_assoc($countRes);

            if ($countRow['total'] >= 5) {
                mysqli_query($conn, "
                    DELETE FROM user_emails 
                    WHERE user_id='$user_id'
                    ORDER BY created_at ASC 
                    LIMIT 1
                ");
            }

            // ✅ INSERT NEW EMAIL
            mysqli_query($conn, "
                INSERT INTO user_emails 
                (user_id, email, phone, otp, otp_expires_at, verified)
                VALUES ('$user_id', '$email', '$phone', '$otp', '$expiry', 0)
            ");

            $email_id = mysqli_insert_id($conn);

            // 🔥 KEEP ORIGINAL BEHAVIOR
            unset($_SESSION['verify_email_owner']);

            // ===============================
            // 💱 SAVE CURRENCY TO CURRENT USER
            // ===============================
            mysqli_query($conn, "
                UPDATE users 
                SET currency='$currency' 
                WHERE id='$user_id'
            ");
            // ===============================

            $success = "✅ OTP sent to new email.";
        }

        // ✅ SAVE SESSION (UNCHANGED)
        $_SESSION['verify_email'] = $email;
        $_SESSION['verify_email_id'] = $email_id;

        // 📧 SEND EMAIL (UNCHANGED)
        $subject = "Your Verification Code";

        $message = "
        <div style='font-family:Arial;background:#f4f6f8;padding:30px;text-align:center;'>
            <div style='max-width:420px;margin:auto;background:#fff;padding:30px;border-radius:12px;'>
                <h2 style='color:#1e1b4b;'>Verify Your Account</h2>
                <p>Your OTP code is:</p>
                <div style='font-size:28px;font-weight:bold;color:#4f46e5;margin:20px 0;'>
                    $otp
                </div>
                <p>This code expires in 5 minutes.</p>
            </div>
        </div>
        ";

        $headers  = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=UTF-8\r\n";
        $headers .= "From: no-reply@yourdomain.com\r\n";

        mail($email, $subject, $message, $headers);

        header("Location: verify.php");
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verify Account - 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;
        }

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

        .form-label {
            display: block;
            font-size: 14px;
            font-weight: 600;
            color: #374151;
            margin-bottom: 6px;
        }

        .form-input {
            width: 100%;
            padding: 14px 16px;
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            font-size: 15px;
            color: #374151;
            background: white;
            transition: all 0.2s;
            font-family: inherit;
        }

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

        .form-input::placeholder {
            color: #9ca3af;
        }

        /* 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;
            margin-top: 8px;
        }

        .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);
        }

        /* Card Footer */
        .card-footer {
            text-align: center;
            margin-top: 24px;
            padding-top: 24px;
            border-top: 1px solid #e5e7eb;
        }

        .footer-text {
            font-size: 14px;
            color: #6b7280;
        }

        .footer-link {
            color: #4f46e5;
            text-decoration: none;
            font-weight: 600;
            transition: color 0.2s;
        }

        .footer-link:hover {
            color: #3730a3;
            text-decoration: underline;
        }

        /* 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;
            }
        }
		/* ================= 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>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/intl-tel-input@18.1.1/build/css/intlTelInput.css"/>
</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 Account</h1>
                <p class="card-subtitle">Please enter your email and phone number to receive a verification code.</p>
                
                <?php if(!empty($error)): ?>
    <div style="
        background:#ef4444;
        color:#fff;
        padding:12px;
        border-radius:8px;
        margin-bottom:15px;
        text-align:center;
    ">
        <?php echo $error; ?>
    </div>
<?php endif; ?>
            </div>

            <form method="POST">
                <div class="form-group">
                    <label class="form-label" for="email">Email Address</label>
                    <input type="email" name="email" id="email" class="form-input" placeholder="you@example.com" required>
                </div>

                <div class="form-group">
                    <label class="form-label" for="phone">Phone Number</label>
                  <input type="tel" name="phone" id="phone" class="form-input" required>
                </div>

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

            <div class="card-footer">
                <p class="footer-text">
                    Already verified? <a href="login.php" class="footer-link">Sign In</a>
                </p>
            </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>

<script src="https://cdn.jsdelivr.net/npm/intl-tel-input@18.1.1/build/js/intlTelInput.min.js"></script>

<script>
const input = document.querySelector("#phone");

const iti = window.intlTelInput(input, {
    initialCountry: "auto", // 🔥 auto detect
    geoIpLookup: function(callback) {
        fetch("https://ipapi.co/json/")
        .then(res => res.json())
        .then(data => {
            callback(data.country_code);
        })
        .catch(() => {
            callback("US"); // fallback
        });
    },
    utilsScript: "https://cdn.jsdelivr.net/npm/intl-tel-input@18.1.1/build/js/utils.js"
});

// 🔥 Save full number with country code
document.querySelector("form").addEventListener("submit", function() {
    input.value = iti.getNumber();
});
</script>
</body>
</html>