<?php
require_once __DIR__ . '/../includes/init.php';

if (isLoggedIn()) redirect(BASE_URL . '/modules/dashboard/index.php');

$step  = 'phone';
$error = '';
$info  = '';
$phone = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid request. Please refresh.';
    }

    elseif (isset($_POST['send_otp']) || (isset($_POST['phone']) && !isset($_POST['verify_otp']))) {
        $raw   = trim($_POST['phone'] ?? '');
        $phone = normalizePhone($raw);

        if (!$phone) {
            $error = 'Invalid number. Enter 10-digit mobile number.';
        } else {
            try {
                $db     = getDBConnection();
                $last10 = substr(preg_replace('/\D/', '', $phone), -10);

                // Get all active users with phone and match last 10 digits in PHP
                $users = dbRows($db, "SELECT * FROM users WHERE is_active=1 AND phone IS NOT NULL AND phone != ''");
                $user  = null;
                foreach ($users as $u) {
                    $uLast10 = substr(preg_replace('/\D/', '', $u['phone']), -10);
                    if ($uLast10 === $last10) { $user = $u; break; }
                }

                if (!$user) {
                    $error = 'No active account found with this number.';
                } else {
                    $otp  = generateOtp($db, $user['id']);
                    $msg  = "🔐 *EMRS Login OTP*\n\nYour OTP: *{$otp}*\n\nValid for 5 minutes only.\nDo not share with anyone.\n\n_EMRS — Electricity Meter Reading System_";
                    $sent = waSend($phone, $msg);

                    $_SESSION['_otp_uid']   = $user['id'];
                    $_SESSION['_otp_phone'] = $phone;
                    $step = 'otp';

                    if ($sent) {
                        $info = 'OTP sent to ' . substr($phone, 0, 5) . 'XXXXX';
                    } else {
                        $error = 'WhatsApp send failed. Check API config.';
                    }
                }
            } catch (Throwable $e) {
                $error = 'Error: ' . $e->getMessage();
            }
        }
    }

    elseif (isset($_POST['verify_otp']) || (isset($_POST['otp']) && !isset($_POST['phone']))) {
        $otp   = trim($_POST['otp'] ?? '');
        $uid   = (int)($_SESSION['_otp_uid']   ?? 0);
        $phone = $_SESSION['_otp_phone'] ?? '';
        $step  = 'otp';

        if (!$uid) {
            // Try to re-find user by phone from POST
            $rawPhone = trim($_POST['phone_hidden'] ?? '');
            if ($rawPhone) {
                $normPhone = normalizePhone($rawPhone);
                $last10    = substr(preg_replace('/\D/', '', $normPhone), -10);
                try {
                    $db2   = getDBConnection();
                    $users = dbRows($db2, "SELECT * FROM users WHERE is_active=1 AND phone IS NOT NULL AND phone != ''");
                    foreach ($users as $u) {
                        if (substr(preg_replace('/\D/', '', $u['phone']), -10) === $last10) {
                            $uid   = $u['id'];
                            $phone = $normPhone;
                            break;
                        }
                    }
                } catch (Throwable $e) {}
            }
        }

        if (!$uid) {
            $error = 'Session expired. Enter number again.';
            $step  = 'phone';
        } elseif (!$otp || strlen($otp) !== 6 || !ctype_digit($otp)) {
            $error = 'Enter valid 6-digit OTP.';
        } else {
            try {
                $db    = getDBConnection();
                $valid = verifyOtp($db, $uid, $otp);
                if ($valid) {
                    $user = dbRow($db, "SELECT * FROM users WHERE id=?", [$uid]);
                    session_regenerate_id(true);
                    $_SESSION['user_id']   = $user['id'];
                    $_SESSION['full_name'] = $user['full_name'];
                    $_SESSION['username']  = $user['username'];
                    $_SESSION['role']      = $user['role'];
                    $_SESSION['division']  = $user['division'];
                    $_SESSION['is_active'] = (bool)$user['is_active'];
                    $_SESSION['_init']     = time();
                    unset($_SESSION['_otp_uid'], $_SESSION['_otp_phone']);
                    redirect(BASE_URL . '/modules/dashboard/index.php');
                } else {
                    $error = 'Wrong or expired OTP. Try again.';
                }
            } catch (Throwable $e) {
                $error = 'Error: ' . $e->getMessage();
            }
        }
    }
} else {
    if (!empty($_SESSION['_otp_uid'])) {
        $step  = 'otp';
        $phone = $_SESSION['_otp_phone'] ?? '';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <meta name="theme-color" content="#1a237e">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <title>Login — <?= APP_NAME ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <link rel="stylesheet" href="../assets/css/style.css">
    <style>
        body { background: #0f1117; }

        .login-page {
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 20px 16px 40px;
            background: linear-gradient(160deg, #0d1757 0%, #1a237e 40%, #0d1117 100%);
        }

        .login-card {
            width: 100%; max-width: 400px;
            background: rgba(255,255,255,.04);
            border: 1px solid rgba(255,255,255,.1);
            border-radius: 24px;
            padding: 32px 28px;
            box-shadow: 0 24px 64px rgba(0,0,0,.5);
        }

        .brand-icon {
            width: 64px; height: 64px;
            background: linear-gradient(135deg, #5c6bc0, #1a237e);
            border-radius: 18px;
            display: flex; align-items: center; justify-content: center;
            margin: 0 auto 12px;
            box-shadow: 0 8px 24px rgba(92,107,192,.4);
        }

        .brand-title { color: #fff; font-size: 1.5rem; font-weight: 800; letter-spacing: -.5px; }
        .brand-sub   { color: rgba(255,255,255,.5); font-size: .78rem; }

        /* Tab switcher */
        .login-tabs {
            display: flex; gap: 4px;
            background: rgba(255,255,255,.06);
            border-radius: 12px; padding: 4px;
            margin-bottom: 24px;
        }
        .login-tab {
            flex: 1; padding: 9px 8px;
            border: none; border-radius: 9px;
            font-size: .84rem; font-weight: 600;
            cursor: pointer; transition: all .2s;
            background: transparent; color: rgba(255,255,255,.5);
        }
        .login-tab.active {
            background: #fff;
            color: #1a237e;
            box-shadow: 0 2px 8px rgba(0,0,0,.2);
        }

        /* Inputs */
        .login-input {
            background: rgba(255,255,255,.08) !important;
            border: 1.5px solid rgba(255,255,255,.12) !important;
            border-radius: 12px !important;
            color: #fff !important;
            font-size: 16px !important;
            min-height: 50px !important;
            padding: 12px 16px !important;
            transition: border-color .2s, background .2s !important;
        }
        .login-input::placeholder { color: rgba(255,255,255,.3) !important; }
        .login-input:focus {
            background: rgba(255,255,255,.12) !important;
            border-color: rgba(92,107,192,.8) !important;
            box-shadow: 0 0 0 3px rgba(92,107,192,.2) !important;
            outline: none !important;
        }
        .login-input-icon {
            background: rgba(255,255,255,.08) !important;
            border: 1.5px solid rgba(255,255,255,.12) !important;
            border-right: none !important;
            border-radius: 12px 0 0 12px !important;
            color: rgba(255,255,255,.4) !important;
            min-height: 50px !important;
        }
        .login-input-icon + .login-input {
            border-left: none !important;
            border-radius: 0 12px 12px 0 !important;
        }
        .login-input-btn {
            background: rgba(255,255,255,.08) !important;
            border: 1.5px solid rgba(255,255,255,.12) !important;
            border-left: none !important;
            border-radius: 0 12px 12px 0 !important;
            color: rgba(255,255,255,.5) !important;
            min-height: 50px !important;
        }
        .form-label { color: rgba(255,255,255,.7) !important; font-size: .82rem !important; font-weight: 600 !important; }

        /* Buttons */
        .btn-wa {
            background: linear-gradient(135deg, #25d366, #128c7e);
            color: #fff !important; border: none;
            border-radius: 12px; min-height: 50px;
            font-size: .95rem; font-weight: 700;
            width: 100%; display: flex; align-items: center; justify-content: center; gap: 8px;
            box-shadow: 0 4px 16px rgba(37,211,102,.3);
            transition: transform .15s, box-shadow .15s;
        }
        .btn-wa:hover { opacity: .9; }
        .btn-wa:active { transform: scale(.98); }

        .btn-primary-login {
            background: linear-gradient(135deg, #5c6bc0, #1a237e);
            color: #fff !important; border: none;
            border-radius: 12px; min-height: 50px;
            font-size: .95rem; font-weight: 700;
            width: 100%; display: flex; align-items: center; justify-content: center; gap: 8px;
            box-shadow: 0 4px 16px rgba(26,35,126,.4);
            transition: transform .15s, box-shadow .15s;
        }
        .btn-primary-login:hover { opacity: .9; }
        .btn-primary-login:active { transform: scale(.98); }

        /* OTP boxes */
        .otp-boxes {
            display: flex; gap: 8px; justify-content: center;
        }
        .otp-box {
            width: 46px; height: 56px;
            background: rgba(255,255,255,.08) !important;
            border: 2px solid rgba(255,255,255,.15) !important;
            border-radius: 12px !important;
            color: #fff !important; font-size: 1.4rem !important;
            font-weight: 700 !important; text-align: center !important;
            padding: 0 !important; min-height: unset !important;
            transition: border-color .2s, background .2s !important;
        }
        .otp-box:focus {
            border-color: #5c6bc0 !important;
            background: rgba(92,107,192,.15) !important;
            box-shadow: 0 0 0 3px rgba(92,107,192,.2) !important;
            outline: none !important;
        }
        .otp-box.filled { border-color: rgba(37,211,102,.6) !important; }

        /* Timer ring */
        .timer-wrap {
            display: flex; align-items: center; justify-content: center;
            gap: 8px; margin: 8px 0;
        }
        .timer-circle {
            width: 36px; height: 36px;
            border-radius: 50%;
            border: 2px solid rgba(255,255,255,.15);
            border-top-color: #5c6bc0;
            display: flex; align-items: center; justify-content: center;
            font-size: .7rem; font-weight: 700; color: #fff;
        }
        .timer-circle.expired { border-top-color: #ef5350; }

        /* Alert */
        .login-alert {
            border-radius: 12px; font-size: .84rem;
            padding: 10px 14px; margin-bottom: 16px;
            display: flex; align-items: center; gap: 8px;
        }
        .login-alert.danger  { background: rgba(198,40,40,.15); border: 1px solid rgba(198,40,40,.3); color: #ef9a9a; }
        .login-alert.success { background: rgba(46,125,50,.15);  border: 1px solid rgba(46,125,50,.3);  color: #81c784; }

        /* Phone display */
        .phone-badge {
            background: rgba(255,255,255,.08);
            border: 1px solid rgba(255,255,255,.12);
            border-radius: 10px; padding: 8px 14px;
            color: rgba(255,255,255,.8); font-size: .84rem;
            display: flex; align-items: center; gap: 8px;
            margin-bottom: 16px;
        }

        .divider {
            display: flex; align-items: center; gap: 10px;
            color: rgba(255,255,255,.25); font-size: .75rem; margin: 4px 0;
        }
        .divider::before, .divider::after {
            content: ''; flex: 1; height: 1px;
            background: rgba(255,255,255,.1);
        }

        .link-muted { color: rgba(255,255,255,.4) !important; font-size: .78rem; text-decoration: none; }
        .link-muted:hover { color: rgba(255,255,255,.7) !important; }

        @media (max-width: 400px) {
            .login-card { padding: 24px 18px; border-radius: 20px; }
            .otp-box { width: 40px; height: 50px; font-size: 1.2rem !important; }
        }
    </style>
</head>
<body>
<div class="login-page">
    <div class="login-card">

        <!-- Brand -->
        <div class="text-center mb-4">
            <div class="brand-icon">
                <i class="bi bi-lightning-charge-fill" style="font-size:1.8rem;color:#fff;"></i>
            </div>
            <div class="brand-title"><?= APP_NAME ?></div>
            <div class="brand-sub"><?= APP_FULL ?></div>
        </div>

        <!-- Alerts -->
        <?php if ($error): ?>
        <div class="login-alert danger">
            <i class="bi bi-exclamation-circle-fill flex-shrink-0"></i><?= h($error) ?>
        </div>
        <?php endif; ?>
        <?php if ($info): ?>
        <div class="login-alert success">
            <i class="bi bi-check-circle-fill flex-shrink-0"></i><?= h($info) ?>
        </div>
        <?php endif; ?>

        <?php if ($step === 'phone'): ?>
        <!-- ══════════ TABS ══════════ -->
        <div class="login-tabs" id="loginTabs">
            <button class="login-tab active" onclick="showTab('otp')" id="tabOtp">
                <i class="bi bi-whatsapp me-1"></i>WhatsApp OTP
            </button>
            <button class="login-tab" onclick="showTab('pass')" id="tabPass">
                <i class="bi bi-lock-fill me-1"></i>Password
            </button>
        </div>

        <!-- ── OTP Tab ── -->
        <div id="panelOtp">
            <form method="POST" novalidate id="phoneForm">
                <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">
                <div class="mb-4">
                    <label class="form-label">Mobile Number</label>
                    <div class="input-group">
                        <span class="input-group-text login-input-icon">
                            <i class="bi bi-phone-fill"></i>
                        </span>
                        <input type="tel" name="phone" id="phoneInput"
                               class="form-control login-input"
                               placeholder="9876543210"
                               value="<?= h($_POST['phone'] ?? '') ?>"
                               maxlength="15" inputmode="numeric"
                               autocomplete="tel" autofocus>
                    </div>
                    <div style="font-size:.74rem;color:rgba(255,255,255,.35);margin-top:5px;">
                        Any format: 9876543210 / 09876543210 / +919876543210
                    </div>
                </div>
                <button type="submit" name="send_otp" class="btn-wa" id="sendOtpBtn">
                    <i class="bi bi-whatsapp"></i>Send OTP on WhatsApp
                </button>
            </form>
        </div>

        <!-- ── Password Tab ── -->
        <div id="panelPass" style="display:none;">
            <form method="POST" action="login.php" novalidate>
                <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">
                <div class="mb-3">
                    <label class="form-label">Username</label>
                    <div class="input-group">
                        <span class="input-group-text login-input-icon">
                            <i class="bi bi-person-fill"></i>
                        </span>
                        <input type="text" name="username" class="form-control login-input"
                               placeholder="Enter username"
                               autocomplete="username">
                    </div>
                </div>
                <div class="mb-4">
                    <label class="form-label">Password</label>
                    <div class="input-group">
                        <span class="input-group-text login-input-icon">
                            <i class="bi bi-lock-fill"></i>
                        </span>
                        <input type="password" name="password" id="passInput"
                               class="form-control login-input"
                               placeholder="Enter password"
                               autocomplete="current-password">
                        <button type="button" class="input-group-text login-input-btn"
                                onclick="togglePass()">
                            <i class="bi bi-eye" id="passIcon"></i>
                        </button>
                    </div>
                </div>
                <button type="submit" class="btn-primary-login">
                    <i class="bi bi-box-arrow-in-right"></i>Login
                </button>
            </form>
        </div>

        <?php else: ?>
        <!-- ══════════ OTP VERIFY ══════════ -->
        <div class="phone-badge">
            <i class="bi bi-whatsapp" style="color:#25d366;font-size:1.1rem;"></i>
            <div>
                <div style="font-size:.72rem;color:rgba(255,255,255,.4);">OTP sent to</div>
                <div class="fw-bold"><?= h(substr($phone,0,5) . 'XXXXX') ?></div>
            </div>
            <a href="login_otp.php" class="ms-auto link-muted" title="Change number">
                <i class="bi bi-pencil-fill"></i>
            </a>
        </div>

        <!-- OTP Boxes -->
        <form method="POST" novalidate id="otpForm">
            <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">
            <input type="hidden" name="otp" id="otpHidden">
            <input type="hidden" name="verify_otp" value="1">
            <input type="hidden" name="phone_hidden" value="<?= h(substr($phone, 3)) ?>">

            <div class="mb-2">
                <label class="form-label text-center d-block" style="font-size:.8rem;">Enter 6-Digit OTP</label>
                <div class="otp-boxes" id="otpBoxes">
                    <?php for ($i = 0; $i < 6; $i++): ?>
                    <input type="text" class="otp-box" maxlength="1"
                           inputmode="numeric" pattern="[0-9]"
                           autocomplete="<?= $i===0?'one-time-code':'off' ?>">
                    <?php endfor; ?>
                </div>
            </div>

            <!-- Timer -->
            <div class="timer-wrap mb-2">
                <div class="timer-circle" id="timerCircle">
                    <span id="timerVal">5:00</span>
                </div>
                <span style="color:rgba(255,255,255,.4);font-size:.76rem;">Expires in <span id="timerText">5:00</span></span>
            </div>

            <button type="submit" class="btn-primary-login mb-2" id="verifyBtn" disabled>
                <i class="bi bi-shield-check"></i>Verify & Login
            </button>
        </form>

        <div class="divider">or</div>

        <form method="POST" class="mt-2">
            <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">
            <input type="hidden" name="phone" value="<?= h(substr($phone, 3)) ?>">
            <input type="hidden" name="send_otp" value="1">
            <button type="submit" class="btn-wa" style="min-height:42px;font-size:.88rem;">
                <i class="bi bi-arrow-clockwise"></i>Resend OTP
            </button>
        </form>

        <div class="text-center mt-2">
            <a href="login_otp.php" class="link-muted" onclick="<?php unset($_SESSION['_otp_uid'],$_SESSION['_otp_phone']); ?>">
                <i class="bi bi-arrow-left me-1"></i>Change Number
            </a>
        </div>
        <?php endif; ?>

    </div><!-- /login-card -->
</div><!-- /login-page -->

<script>
// ── Tab switcher ──────────────────────────────────────────────
function showTab(tab) {
    const isOtp = tab === 'otp';
    document.getElementById('panelOtp').style.display  = isOtp ? '' : 'none';
    document.getElementById('panelPass').style.display = isOtp ? 'none' : '';
    document.getElementById('tabOtp').classList.toggle('active',  isOtp);
    document.getElementById('tabPass').classList.toggle('active', !isOtp);
    if (isOtp) document.getElementById('phoneInput')?.focus();
}

// ── Password toggle ───────────────────────────────────────────
function togglePass() {
    const i = document.getElementById('passInput');
    const c = document.getElementById('passIcon');
    i.type = i.type === 'password' ? 'text' : 'password';
    c.className = i.type === 'password' ? 'bi bi-eye' : 'bi bi-eye-slash';
}

// ── Send OTP button loading ───────────────────────────────────
document.getElementById('phoneForm')?.addEventListener('submit', function() {
    const btn = document.getElementById('sendOtpBtn');
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Sending…';
    // Do NOT disable — disabled buttons don't submit their name
});

// ── OTP Boxes logic ───────────────────────────────────────────
(function() {
    const boxes  = document.querySelectorAll('.otp-box');
    const hidden = document.getElementById('otpHidden');
    const verify = document.getElementById('verifyBtn');
    const form   = document.getElementById('otpForm');
    if (!boxes.length) return;

    boxes[0]?.focus();

    function getOtp() { return [...boxes].map(b => b.value).join(''); }

    function updateState() {
        const otp = getOtp();
        hidden.value = otp;
        boxes.forEach(b => b.classList.toggle('filled', b.value !== ''));
        const complete = otp.length === 6 && /^\d{6}$/.test(otp);
        verify.disabled = !complete;
        if (complete) {
            verify.innerHTML = '<i class="bi bi-shield-check"></i>Verify & Login';
            // Auto submit after short delay
            setTimeout(() => form?.submit(), 300);
        }
    }

    boxes.forEach((box, idx) => {
        box.addEventListener('input', function() {
            this.value = this.value.replace(/\D/g, '').slice(-1);
            if (this.value && idx < 5) boxes[idx + 1].focus();
            updateState();
        });

        box.addEventListener('keydown', function(e) {
            if (e.key === 'Backspace' && !this.value && idx > 0) {
                boxes[idx - 1].value = '';
                boxes[idx - 1].focus();
                updateState();
            }
        });

        box.addEventListener('paste', function(e) {
            e.preventDefault();
            const paste = (e.clipboardData || window.clipboardData).getData('text').replace(/\D/g,'');
            [...paste.slice(0,6)].forEach((ch, i) => { if (boxes[i]) boxes[i].value = ch; });
            boxes[Math.min(paste.length, 5)].focus();
            updateState();
        });
    });

    // ── Countdown timer ───────────────────────────────────────
    let sec = <?= WA_OTP_EXPIRY ?>;
    const timerVal  = document.getElementById('timerVal');
    const timerText = document.getElementById('timerText');
    const timerCircle = document.getElementById('timerCircle');

    const tick = setInterval(() => {
        sec--;
        const m = Math.floor(sec / 60);
        const s = String(sec % 60).padStart(2, '0');
        const str = sec > 0 ? `${m}:${s}` : 'Expired';
        if (timerVal)  timerVal.textContent  = str;
        if (timerText) timerText.textContent = str;
        if (sec <= 0) {
            clearInterval(tick);
            if (timerCircle) timerCircle.classList.add('expired');
            verify.disabled = true;
        }
    }, 1000);
})();
</script>
</body>
</html>
