<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once '../../config.php'; // আপনার config.php ফাইলের সঠিক পাথ দিন

$auto_verified = false;

// ----------------------------------------------------------------------
// ১. ইমেইলের লিংক থেকে অটো ভেরিফাই + ৫ বছরের লাইফটাইম লগইন (High Security)
// ----------------------------------------------------------------------
if (isset($_GET['e']) && isset($_GET['c'])) {
    $e = base64_decode($_GET['e']);
    $c = base64_decode($_GET['c']);
    
    // SQL Injection Security
    $stmt = $conn->prepare("SELECT id, fullname, is_verified, otp FROM users WHERE email=?");
    $stmt->bind_param("s", $e);
    $stmt->execute();
    $res = $stmt->get_result();
    
    if ($res->num_rows > 0) {
        $row = $res->fetch_assoc();
        
        // যদি আগেই ভেরিফাই হয়ে থাকে বা OTP ভুল হয়
        if ($row['is_verified'] == 1 || $row['otp'] !== $c) {
            header("Location: /login/"); // ভুল লিংক হলে লগইনে পাঠিয়ে দেবে
            exit();
        } else {
            // ৫ বছরের জন্য সিকিউর টোকেন জেনারেট (লগইন সিস্টেমের মতই)
            $cookie_token = bin2hex(random_bytes(32)); 
            $hashed_token = hash('sha256', $cookie_token); // ডাটাবেসের জন্য হ্যাশ করা
            
            // ডাটাবেস আপডেট করা
            $update = $conn->prepare("UPDATE users SET is_verified=1, otp=NULL, remember_token=? WHERE id=?");
            $update->bind_param("si", $hashed_token, $row['id']);
            $update->execute();
            
            // ব্রাউজারে ৫ বছরের কুকি সেট (XSS & CSRF Protection সহ)
            $cookie_expire = time() + 157680000; // ৫ বছর
            $is_secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on';
            setcookie('auth_remember', $cookie_token,[
                'expires' => $cookie_expire,
                'path' => '/',
                'domain' => '', 
                'secure' => $is_secure,
                'httponly' => true,
                'samesite' => 'Lax'
            ]);
            
            // Session Fixation Attack প্রতিরোধ
            session_regenerate_id(true);

            // সেশনে ইউজারের ডাটা সেট করে লগইন করানো
            $_SESSION['user_logged_in'] = true;
            $_SESSION['user_id'] = $row['id'];
            $_SESSION['user_name'] = $row['fullname'];
            
            $auto_verified = true;
        }
    } else {
        header("Location: /signup/"); 
        exit();
    }
}

// যদি ইউজার ভেরিফাই পেজে সরাসরি আসার চেষ্টা করে (সেশন বা অটো ভেরিফাই লিংক ছাড়া)
if (!$auto_verified && !isset($_SESSION['verify_email'])) {
    header("Location: /signup/"); 
    exit();
}

$user_email = $_SESSION['verify_email'] ?? ($e ?? '');

// Absolute Path for Header
$doc_root = $_SERVER['DOCUMENT_ROOT'];
if (file_exists($doc_root . '/includes/header.php')) { require_once $doc_root . '/includes/header.php'; } 
elseif (file_exists($doc_root . '/header.php')) { require_once $doc_root . '/header.php'; } 
else { include '../../header.php'; }
?>

<style>
    /* Modern SaaS Professional Design */
    body { background-color: #f8fafc; margin: 0; font-family: 'Inter', sans-serif; }
    .verify-content { display: flex; justify-content: center; align-items: center; padding: 60px 20px; min-height: 75vh; }
    .verify-card { background-color: #ffffff; width: 100%; max-width: 420px; padding: 40px; border-radius: 16px; box-shadow: 0 10px 40px rgba(0,0,0,0.06); text-align: center; border: 1px solid #e2e8f0; position: relative; overflow: hidden;}
    
    /* Top Accent Line */
    .verify-card::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 5px; background: linear-gradient(135deg, #10b981, #059669); }

    .verify-icon { width: 75px; height: 75px; background: #ecfdf5; color: #10b981; border-radius: 50%; display: flex; justify-content: center; align-items: center; font-size: 32px; margin: 0 auto 20px; box-shadow: 0 4px 15px rgba(16, 185, 129, 0.15);}
    .verify-card h2 { color: #0f172a; margin-bottom: 12px; font-size: 26px; font-weight: 700; letter-spacing: -0.5px;}
    .verify-card p { color: #64748b; font-size: 15px; margin-bottom: 25px; line-height: 1.6; }
    
    .verify-input { width: 100%; padding: 18px; border: 2px solid #e2e8f0; border-radius: 10px; font-size: 28px; text-align: center; letter-spacing: 15px; margin-bottom: 20px; outline: none; transition: 0.3s; font-weight: 700; color:#0f172a; box-sizing: border-box; background: #f8fafc;}
    .verify-input:focus { border-color: #10b981; background: #ffffff; box-shadow: 0 0 0 4px rgba(16, 185, 129, 0.1); }
    
    .btn-verify { width: 100%; background: linear-gradient(135deg, #10b981, #059669); color: #fff; border: none; padding: 16px; border-radius: 10px; font-size: 16px; font-weight: 600; cursor: pointer; transition: all 0.3s; margin-bottom: 20px; box-shadow: 0 4px 15px rgba(16, 185, 129, 0.25);}
    .btn-verify:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(16, 185, 129, 0.35); }
    .btn-verify:disabled { background: #94a3b8; cursor: not-allowed; box-shadow: none; transform: none;}

    .timers { display: flex; justify-content: space-between; font-size: 14px; font-weight: 600; margin-bottom: 25px;}
    .expire-timer { color: #ef4444; background: #fee2e2; padding: 5px 10px; border-radius: 6px;} 
    .resend-timer { color: #64748b; padding: 5px 10px;} 
    .resend-btn { color: #10b981; cursor: pointer; border: none; background: none; font-weight: 700; display: none; font-size: 14px;}
    .resend-btn:hover { text-decoration: underline; }

    #success-ui { display: none; animation: fadeIn 0.6s ease-in-out; }
    .success-check { font-size: 65px; color: #10b981; margin-bottom: 20px; animation: popIn 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275); }
    
    @keyframes fadeIn { from { opacity: 0; transform: translateY(10px);} to { opacity: 1; transform: translateY(0);} }
    @keyframes popIn { 0% { transform: scale(0); opacity: 0;} 80% { transform: scale(1.1); opacity: 1;} 100% { transform: scale(1); } }
</style>

<main class="verify-content">
    <div class="verify-card">
        
        <!-- Verification Form UI -->
        <div id="form-ui" style="<?php echo $auto_verified ? 'display:none;' : 'display:block;'; ?>">
            <div class="verify-icon"><i class="fas fa-shield-alt"></i></div>
            <h2>Secure Verification</h2>
            
            <?php 
                // Email Masking (e.g. jo***@gmail.com)
                $parts = explode("@", $user_email); 
                $hidden_email = (strlen($parts[0]) > 2) ? substr($parts[0], 0, 2) . str_repeat("*", strlen($parts[0]) - 2) . "@" . $parts[1] : $user_email; 
            ?>
            <p>We've sent a 6-digit secure code to <br><span style="font-weight: 700; color: #0f172a; font-size: 16px;"><?php echo htmlspecialchars($hidden_email, ENT_QUOTES, 'UTF-8'); ?></span></p>
            
            <div id="error-msg" style="display:none; background:#fee2e2; color:#dc2626; padding:12px; border-radius:8px; margin-bottom:15px; font-size:14px; font-weight: 500;"></div>

            <form id="verifyForm">
                <input type="text" id="otp_input" name="otp" class="verify-input" placeholder="------" maxlength="6" required autocomplete="off" oninput="this.value = this.value.replace(/[^0-9]/g, '');">
                
                <div class="timers">
                    <span class="expire-timer">Expires in: <span id="expire-time">05:00</span></span>
                    <span class="resend-timer" id="resend-text">Resend in <span id="resend-time">60</span>s</span>
                    <button type="button" class="resend-btn" id="resend-btn" onclick="resendCode()">Resend Code</button>
                </div>
                <button type="submit" id="verify-btn" class="btn-verify">Verify & Secure Account</button>
            </form>
            <p style="font-size:13px; color:#94a3b8; margin-top:20px; margin-bottom: 0;"><i class="fas fa-lock"></i> Secured by 256-bit encryption</p>
        </div>

        <!-- Success UI (Shows upon auto-verify or successful manual verify) -->
        <div id="success-ui" style="<?php echo $auto_verified ? 'display:block;' : 'display:none;'; ?>">
            <div class="success-check"><i class="fas fa-check-circle"></i></div>
            <h2 style="color: #10b981;">Verification Successful!</h2>
            <p style="color: #64748b; font-size:16px;">Your account is fully secured and logged in.</p>
            <div style="margin-top: 30px; padding: 15px; background: #f8fafc; border-radius: 8px; border: 1px solid #e2e8f0;">
                <p style="font-size:14px; font-weight:600; color:#0f172a; margin: 0;"><i class="fas fa-circle-notch fa-spin" style="color: #10b981; margin-right: 8px;"></i> Redirecting to Dashboard...</p>
            </div>
        </div>

    </div>
</main>

<script>
    // অটো ভেরিফাই লিংকে ক্লিক করে আসলে সরাসরি ড্যাশবোর্ডে পাঠাবে
    <?php if($auto_verified): ?>
        setTimeout(() => { window.location.href = "/dashboard/"; }, 2000); 
    <?php endif; ?>

    // ব্যাকগ্রাউন্ডে চেক করবে ইউজার অন্য ট্যাব থেকে ভেরিফাই করেছে কিনা
    <?php if(!$auto_verified): ?>
    setInterval(() => {
        fetch('/api/auth/check_status.php')
        .then(response => response.json())
        .then(data => {
            if (data.status === 'verified') {
                document.getElementById('form-ui').style.display = 'none';
                document.getElementById('success-ui').style.display = 'block';
                setTimeout(() => { window.location.href = "/dashboard/"; }, 2000);
            }
        });
    }, 4000); 
    <?php endif; ?>

    // টাইমার ফাংশন
    let expireTime = 300; let resendTime = 60; let expireInterval, resendInterval;
    function startTimers() {
        clearInterval(expireInterval); clearInterval(resendInterval);
        document.getElementById("resend-text").style.display = "inline"; document.getElementById("resend-btn").style.display = "none";
        expireTime = 300; resendTime = 60;
        
        expireInterval = setInterval(() => {
            let m = Math.floor(expireTime / 60); let s = expireTime % 60;
            document.getElementById("expire-time").innerText = (m < 10 ? "0" : "") + m + ":" + (s < 10 ? "0" : "") + s;
            if (expireTime <= 0) { clearInterval(expireInterval); document.getElementById("expire-time").innerText = "Expired!"; }
            expireTime--;
        }, 1000);
        
        resendInterval = setInterval(() => {
            document.getElementById("resend-time").innerText = resendTime;
            if (resendTime <= 0) { clearInterval(resendInterval); document.getElementById("resend-text").style.display = "none"; document.getElementById("resend-btn").style.display = "inline-block"; }
            resendTime--;
        }, 1000);
    }
    <?php if(!$auto_verified): ?> startTimers(); <?php endif; ?>

    // রিসেন্ড কোড ফাংশন
    function resendCode() {
        let btn = document.getElementById('resend-btn'); btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...'; btn.disabled = true;
        fetch('/api/auth/resend_api.php').then(response => response.json()).then(data => {
            let errorMsg = document.getElementById('error-msg'); errorMsg.style.display = 'block';
            if (data.status === 'success') {
                errorMsg.style.background = '#ecfdf5'; errorMsg.style.color = '#059669'; errorMsg.innerText = data.message;
                btn.innerHTML = 'Resend Code'; btn.disabled = false; startTimers();
            } else {
                errorMsg.style.background = '#fee2e2'; errorMsg.style.color = '#dc2626'; errorMsg.innerText = data.message;
                btn.innerHTML = 'Resend Code'; if(!data.message.includes('blocked')){ btn.disabled = false; }
            }
        });
    }

    // OTP সাবমিট লজিক
    document.getElementById('verifyForm').addEventListener('submit', function(e) {
        e.preventDefault();
        let btn = document.getElementById('verify-btn'); btn.disabled = true; btn.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i> Verifying...';
        let otp = document.getElementById('otp_input').value;
        
        fetch('/api/auth/verify_api.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'otp=' + encodeURIComponent(otp) })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                document.getElementById('form-ui').style.display = 'none'; document.getElementById('success-ui').style.display = 'block';
                setTimeout(() => { window.location.href = "/dashboard/"; }, 2000);
            } else {
                let errorMsg = document.getElementById('error-msg'); errorMsg.innerText = data.message; errorMsg.style.display = 'block';
                btn.disabled = false; btn.innerHTML = 'Verify & Secure Account';
            }
        });
    });
</script>

<?php 
// Absolute Path for Footer
if (file_exists($doc_root . '/includes/footer.php')) { require_once $doc_root . '/includes/footer.php'; } 
elseif (file_exists($doc_root . '/footer.php')) { require_once $doc_root . '/footer.php'; } 
else { include '../../footer.php'; }
?>