<?php
session_start();
include('include/db_conn.php');

if (!empty($_GET['from'])) {
    $_SESSION['dynamic_url'] = $_GET['from'];
}

// Define the timezone
$timezone = new DateTimeZone('Asia/Kolkata');
$date = new DateTime('now', $timezone);
$formatted_date = $date->format('Y-m-d h:i A');

if (!empty($_SESSION['user_rand_id'])) {
    $dynamic_url = $_SESSION['dynamic_url'] ?? '';
    header('Location: ' . ($dynamic_url ?: 'https://staging.visafir.com/'));
    exit;
}

error_reporting(0);
ini_set('display_errors', 0);
$dynamic_url = $_SESSION['dynamic_url'] ?? '';
$protocol    = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$domain      = $protocol . $_SERVER['HTTP_HOST'];

// Get domain name

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5" />
    <meta name="theme-color" content="#4f46e5" />
    <meta http-equiv="Cache-Control" content="no-store, no-cache, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <title>Sign in — Visafir</title>
    <meta name="description" content="Sign in to Visafir with WhatsApp or email OTP — no passwords, just one tap." />
    <meta name="robots" content="noindex, nofollow" />
    <link rel="icon" type="../../image/png" href="css/auth/assets/img/logo/favicon.png" sizes="32x32">
    <!-- Google Fonts & Bootstrap Icons -->
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet" />
<link rel="stylesheet" href="https://staging.visafir.com/css/visafirlogin.css"  />
    <style>
       
    </style>
</head>

<body>

    <!-- Loading Indicator -->
    <div id="ldr">
        <div class="spin"></div>
    </div>

    <main>
        <div class="card">
            <div class="topbar">
                <div class="inner">
                    <a href="https://staging.visafir.com/" class="brand">
                        <img src="../assets/img/logo/favicon.ico.png" style="height:48px; width:auto; display:block;" alt="Visafir Logo">
                    </a>
                    <a href='https://staging.visafir.com/' class="close-btn" aria-label="Close"><i class="bi bi-x-lg"></i></a>
                </div>
            </div>

            <!-- Visual Progress Tracker -->
            <div class="steps">
                <div class="step active" id="s1"></div>
                <div class="step" id="s2"></div>
            </div>

            <h1 class="card-title" id="cardTitle">Welcome to Visafir</h1>
            <p class="card-sub" id="cardSub">Sign in or create an account — no password needed.</p>

            <label class="field-label" for="inp">Email or WhatsApp number</label>
            <div class="smart-wrap" id="smartWrap">
                <div class="s-icon"><i class="bi bi-person" id="sic"></i></div>
                <span class="s-prefix" id="prefix">+91&nbsp;</span>
                <input type="text" id="inp" autocomplete="off" inputmode="text" placeholder="Enter email or 10-digit number" oninput="detect()">
            </div>
            <p class="field-hint" id="hint">We'll send a 6-digit OTP to verify it's you.</p>

            <div class="terms-row" id="termsRow">
                <input type="checkbox" id="tc" checked>
                <label for="tc">I agree to Visafir's <a href="terms-condition">Terms</a> and <a href="privacy-policy">Privacy Policy</a>.</label>
            </div>

            <button class="btn-main" id="sendBtn" onclick="sendOtp()">
                <i class="bi bi-shield-check"></i> Send OTP to verify
            </button>
            <div class="timer-row" id="timerRow"></div>

            <!-- OTP Input Section -->
            <div class="otp-wrap" id="otpWrap">
                <button class="back-link" id="backBtn" onclick="goBack()">
                    <i class="bi bi-arrow-left"></i> Edit contact
                </button>

                <div class="sent-note" id="sentNote">
                    <i class="bi bi-check-circle-fill"></i>
                    <span id="sentText">OTP sent</span>
                </div>

                <label class="field-label" style="margin-bottom:10px">Enter 6-digit code</label>
                
                <input type="text" id="otpMaster" autocomplete="one-time-code" inputmode="numeric" pattern="[0-9]*" maxlength="6">

                <div class="otp-row" id="otpRow">
                    <input maxlength="1" class="ob" inputmode="numeric" pattern="[0-9]">
                    <input maxlength="1" class="ob" inputmode="numeric" pattern="[0-9]">
                    <input maxlength="1" class="ob" inputmode="numeric" pattern="[0-9]">
                    <input maxlength="1" class="ob" inputmode="numeric" pattern="[0-9]">
                    <input maxlength="1" class="ob" inputmode="numeric" pattern="[0-9]">
                    <input maxlength="1" class="ob" inputmode="numeric" pattern="[0-9]">
                </div>

                <button class="btn-verify" onclick="verifyOtp()">
                    <i class="bi bi-check2-circle"></i> Verify &amp; continue
                </button>
            </div>

            <p class="msg" id="msg"></p>

            <div class="auth-foot">
                Need help? <a href="contact-us">Contact support</a>
            </div>

            <div class="trust">
                <span><i class="bi bi-shield-lock-fill"></i> 256-bit SSL</span>
                <span><i class="bi bi-patch-check-fill"></i> DPDP compliant</span>
                <span><i class="bi bi-clock-fill"></i> Codes expire in 10 min</span>
            </div>
        </div>
    </main>
  
    <script>
      const wrap = document.getElementById('smartWrap');
        const sic = document.getElementById('sic');
        const inp = document.getElementById('inp');
        const hint = document.getElementById('hint');
        const sendBtn = document.getElementById('sendBtn');
        const timerRow = document.getElementById('timerRow');
        const otpWrap = document.getElementById('otpWrap');
        const sentNote = document.getElementById('sentNote');
        const sentTxt = document.getElementById('sentText');
        const msgEl = document.getElementById('msg');
        const boxes = document.querySelectorAll('.ob');
        const ldr = document.getElementById('ldr');
        const masterInput = document.getElementById('otpMaster');

        let channel = 'email',
            tInt,
            webOtpController = null;

        /* ── Auto-detect input: Email vs WhatsApp ── */
        function detect() {
            const v = inp.value;
            if (!v.trim()) {
                neutral();
                return;
            }
            /[a-zA-Z@]/.test(v) ? setEmail() : setWA(v.replace(/\D/g, '').slice(0, 10));
        }

        function neutral() {
            channel = 'email';
            wrap.classList.remove('wa');
            sic.className = 'bi bi-person';
            hint.className = 'field-hint';
            hint.innerHTML = "We'll send a 6-digit OTP to verify it's you.";
        }

        function setEmail() {
            channel = 'email';
            wrap.classList.remove('wa');
            sic.className = 'bi bi-envelope-fill';
            hint.className = 'field-hint';
            hint.innerHTML = "We'll send your OTP to this <b>email address</b>.";
        }

        function setWA(d) {
            channel = 'mobile';
            if (inp.value !== d) inp.value = d;
            wrap.classList.add('wa');
            sic.className = 'bi bi-whatsapp';
            hint.className = 'field-hint wa';
            hint.innerHTML = d.length === 10 ?
                "We'll send your OTP via <b>WhatsApp</b>." :
                `Enter your 10-digit <b>WhatsApp</b> number. (${d.length}/10)`;
        }

        function showLdr() {
            ldr.style.display = 'flex';
        }

        function hideLdr() {
            ldr.style.display = 'none';
        }

        function setMsg(t, ok) {
            msgEl.textContent = t;
            msgEl.className = ok ? 'msg ok' : 'msg';
        }

        /* ── Send OTP API Trigger ── */
        function sendOtp() {
            if (!document.getElementById('tc').checked) {
                setMsg('Please accept the Terms and Privacy Policy.');
                return;
            }
            setMsg('');
            let id = '';
            if (channel === 'email') {
                id = inp.value.trim();
                if (!id || !id.includes('@') || !id.includes('.')) {
                    setMsg('Please enter a valid email address.');
                    return;
                }
            } else {
                id = inp.value.replace(/\D/g, '');
                if (id.length !== 10) {
                    setMsg('Please enter a valid 10-digit WhatsApp number.');
                    return;
                }
            }

            showLdr();

            const fd = new FormData();
            fd.append('identifier', id);
            fd.append('channel', channel);
            fd.append('action', 'send');
            fetch('../otp_handler.php', {
                    method: 'POST',
                    body: fd,
                    credentials: 'same-origin'
                })
                .then(r => r.json()).then(d => {
                    hideLdr();
                    handleSendResponse(d, id);
                })
                .catch(e => {
                    hideLdr();
                    setMsg('Network error: ' + e.message);
                });
        }

        function handleSendResponse(d, id) {
            if (d.status === 'success') {
                setMsg('OTP sent!', true);
                revealOtp(id);
                startTimer();
                clearBoxes();
                setTimeout(() => boxes[0].focus(), 80);
                
                // Trigger WebOTP browser auto-fill listener
                initWebOtpEngine();
            } else {
                setMsg(d.message || 'Failed to send OTP.');
            }
        }

        function revealOtp(id) {
            document.getElementById('s1').classList.add('done');
            document.getElementById('s2').classList.add('active');

            document.getElementById('cardTitle').textContent = "Verify it's you";
            document.getElementById('cardSub').textContent = "Enter the 6-digit code we sent you.";

            if (channel === 'email') {
                sentNote.className = 'sent-note em';
                sentNote.querySelector('i').className = 'bi bi-envelope-fill';
                sentTxt.textContent = 'OTP sent to ' + id;
            } else {
                sentNote.className = 'sent-note wa';
                sentNote.querySelector('i').className = 'bi bi-whatsapp';
                sentTxt.textContent = 'OTP sent via WhatsApp to +91 ' + id;
            }

            inp.disabled = true;
            wrap.style.opacity = '.55';
            otpWrap.classList.add('open');
            document.getElementById('termsRow').style.display = 'none';
        }

        /* ── WebOTP System Handler ── */
        function initWebOtpEngine() {
            if (!('OTPCredential' in window)) return;
            
            if (webOtpController) webOtpController.abort();
            webOtpController = new AbortController();

            navigator.credentials.get({
                otp: { transport: ['sms'] },
                signal: webOtpController.signal
            }).then(otp => {
                if (otp && otp.code) {
                    masterInput.value = otp.code;
                    otp.code.split('').forEach((char, index) => {
                        if (boxes[index]) {
                            boxes[index].value = char;
                            boxes[index].classList.add('filled');
                        }
                    });
                    verifyOtp();
                }
            }).catch(err => {
                console.log('WebOTP session ended:', err);
            });
        }

        /* ── Return to Contact Input ── */
        function goBack() {
            if (webOtpController) {
                webOtpController.abort();
                webOtpController = null;
            }
            otpWrap.classList.remove('open');
            document.getElementById('s1').classList.remove('done');
            document.getElementById('s2').classList.remove('active');
            document.getElementById('cardTitle').textContent = 'Welcome to Visafir';
            document.getElementById('cardSub').textContent = 'Sign in or create an account — no password needed.';
            inp.disabled = false;
            wrap.style.opacity = '1';
            document.getElementById('termsRow').style.display = 'flex';
            sendBtn.disabled = false;
            sendBtn.innerHTML = '<i class="bi bi-shield-check"></i> Send OTP to verify';
            timerRow.textContent = '';
            clearInterval(tInt);
            clearBoxes();
            setMsg('');
        }

        /* ── Resend Countdown Timer ── */
        function startTimer() {
            sendBtn.disabled = true;
            sendBtn.innerHTML = '<i class="bi bi-arrow-clockwise"></i> Resend OTP';
            let s = 30;
            clearInterval(tInt);
            timerRow.textContent = 'Resend in ' + s + 's';
            tInt = setInterval(() => {
                s--;
                if (s > 0) {
                    timerRow.textContent = 'Resend in ' + s + 's';
                } else {
                    clearInterval(tInt);
                    timerRow.textContent = '';
                    sendBtn.disabled = false;
                }
            }, 1000);
        }

        /* ── Verify OTP Function ── */
        function verifyOtp() {
            let otp = '';
            boxes.forEach(b => otp += b.value);
            if (otp.length !== 6) {
                setMsg('Please enter all 6 digits.');
                return;
            }

            showLdr();

            const fd = new FormData();
            fd.append('otp', otp);
            fd.append('action', 'verify');
            fetch('../otp_handler.php', {
                    method: 'POST',
                    body: fd,
                    credentials: 'same-origin'
                })
                .then(r => r.json()).then(r => {
                    hideLdr();
                    handleVerify(r);
                })
                .catch(e => {
                    hideLdr();
                    setMsg('Error: ' + e.message);
                });
        }

        function handleVerify(r) {
            if (r.status === 'success') {
                if (webOtpController) webOtpController.abort();
                setMsg('Verified! Redirecting…', true);
                let dynamicUrl = "<?php $dynamic_url ?>";
                let domain_url = "<?= $domain ?>";
                setTimeout(() => {
                    location.href = r.user_exists ? (dynamicUrl || domain_url) : "auth/register";
                }, 600);
            } else {
                setMsg(r.message || 'Invalid OTP. Try again.');
                const row = document.getElementById('otpRow');
                row.style.animation = 'none';
                void row.offsetWidth;
                row.style.animation = 'shake .4s ease';
            }
        }

        /* ── Individual Field Interaction UX ── */
        boxes.forEach((b, i, a) => {
            b.addEventListener('input', () => {
                b.value = b.value.replace(/\D/g, '').slice(-1);
                b.classList.toggle('filled', b.value !== '');
                if (b.value && i < a.length - 1) a[i + 1].focus();
                if ([...a].every(x => x.value)) verifyOtp();
            });
            b.addEventListener('keydown', e => {
                if (e.key === 'Backspace' && !b.value && i > 0) {
                    a[i - 1].value = '';
                    a[i - 1].classList.remove('filled');
                    a[i - 1].focus();
                }
            });
            b.addEventListener('paste', e => {
                e.preventDefault();
                const d = (e.clipboardData.getData('text') || '').replace(/\D/g, '').slice(0, 6);
                d.split('').forEach((c, k) => {
                    if (a[k]) {
                        a[k].value = c;
                        a[k].classList.add('filled');
                    }
                });
                const nx = a[Math.min(d.length, a.length - 1)];
                if (nx) nx.focus();
                if (d.length === 6) verifyOtp();
            });
        });

        function clearBoxes() {
            masterInput.value = '';
            boxes.forEach(b => {
                b.value = '';
                b.classList.remove('filled');
            });
        }</script>
</body>
</html>