<?php
session_start();
require_once '../config/database.php';

$error        = "";
$loginUser    = null;
$profilePhoto = null;
$customerCode = null;
$prefillLogin = htmlspecialchars($_POST["login"] ?? "");

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $login    = trim($_POST["login"] ?? "");
    $password = $_POST["password"] ?? "";
    try {
        $colCheck = $pdo->query("SHOW COLUMNS FROM users LIKE 'username'")->fetch();
        if ($colCheck) {
            $stmt = $pdo->prepare("SELECT u.*, c.customer_code FROM users u LEFT JOIN customers c ON c.user_id=u.id WHERE (u.email=? OR u.username=?) AND u.status='active' LIMIT 1");
            $stmt->execute([$login, $login]);
        } else {
            $stmt = $pdo->prepare("SELECT u.*, c.customer_code FROM users u LEFT JOIN customers c ON c.user_id=u.id WHERE u.email=? AND u.status='active' LIMIT 1");
            $stmt->execute([$login]);
        }
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Throwable $e) { $user = null; $error = "Database error."; }

    if ($user && password_verify($password, $user["password"])) {
        $_SESSION["user_id"]       = $user["id"];
        $_SESSION["name"]          = $user["name"];
        $_SESSION["role"]          = $user["role"];
        $_SESSION["company_id"]    = null;
        $_SESSION["company_name"]  = null;
        $_SESSION["staff_role"]    = null;
        $_SESSION["profile_photo"] = $user["profile_photo"] ?? null;
        if (in_array($user["role"], ["company_admin","staff","customer"])) {
            try {
                $cs = $pdo->prepare("SELECT cs.company_id,cs.staff_role,c.name AS company_name FROM company_staff cs JOIN companies c ON c.id=cs.company_id WHERE cs.user_id=? LIMIT 1");
                $cs->execute([$user["id"]]);
                $csRow = $cs->fetch(PDO::FETCH_ASSOC);
                if ($csRow) { $_SESSION["company_id"]=$csRow["company_id"]; $_SESSION["company_name"]=$csRow["company_name"]; $_SESSION["staff_role"]=$csRow["staff_role"]; }
            } catch (Throwable $e) {}
        }
        $ua = $_SERVER["HTTP_USER_AGENT"] ?? "";
        $isMobile = (bool)preg_match('/android|iphone|ipad|ipod|blackberry|windows phone|mobile/i', $ua);

        /* Decide where to send the user, then redirect on the CLIENT side. */
        $redirectTo = null;
        switch ($user["role"]) {
            case "admin":         $redirectTo = "../admin/dashboard.php"; break;
            case "company_admin": $redirectTo = $isMobile ? "../customer/dashboard.php" : "../company/dashboard.php"; break;
            case "partner":       $redirectTo = "../partner/dashboard.php"; break;
            case "customer":      $redirectTo = $isMobile ? "../customer/dashboard.php" : "../customer/desktop.php"; break;
            default:              $error = "Your account has no assigned role.";
        }

        if ($redirectTo) {
            /* Client-side redirect (NOT an HTTP 302) so iOS 26 keeps us inside the
               installed home-screen web app instead of popping the in-app browser. */
            echo "<!doctype html><meta charset='utf-8'>";
            echo "<meta name='apple-mobile-web-app-capable' content='yes'>";
            echo "<meta name='viewport' content='width=device-width,initial-scale=1,viewport-fit=cover'>";
            echo "<script>location.replace(" . json_encode($redirectTo) . ");</script>";
            echo "<noscript><a href='" . htmlspecialchars($redirectTo, ENT_QUOTES) . "'>Continue</a></noscript>";
            exit;
        }
    } elseif (empty($error)) {
        $error = "Invalid username/email or password.";
        try {
            $st = $pdo->prepare("SELECT u.name,u.profile_photo,c.customer_code FROM users u LEFT JOIN customers c ON c.user_id=u.id WHERE (u.username=? OR u.email=?) AND u.status='active' LIMIT 1");
            $st->execute([$login,$login]);
            $loginUser = $st->fetch(PDO::FETCH_ASSOC);
            $profilePhoto = $loginUser["profile_photo"] ?? null;
            $customerCode = $loginUser["customer_code"] ?? null;
        } catch (Throwable $e) {}
    }
}

$photoUrl    = $profilePhoto ? "/seven-credit-system/assets/profile_photos/".htmlspecialchars($profilePhoto) : null;
$displayName = $loginUser["name"] ?? null;
$qrContent   = $customerCode ?? "SEVEN-DIGITAL";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login — Seven Wallet</title>
<link rel="manifest" href="/seven-credit-system/manifest.json">
<link rel="apple-touch-icon" href="/seven-credit-system/assets/sc_logo1.png?v=2">
<meta name="theme-color" content="#ffffff">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover,user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<meta name="apple-mobile-web-app-title" content="Seven Digital">
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;600;700;800&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Great+Vibes&family=Playfair+Display:wght@600;700&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{--red:#b91c1c;--surface:#fff;--border:#e5e7eb;--text:#111827;--muted:#6b7280;--red-lt:#fee2e2;--gold1:#c79b3b;--gold2:#f4d27a;--gold3:#b8862f;--red-grad:linear-gradient(180deg,#cf2626 0%,#b91c1c 48%,#8f1414 100%)}
html,body{margin:0;padding:0;width:100%;height:100%;font-family:"Noto Sans Lao","Inter",Arial,sans-serif;background:var(--red);overflow:hidden;overscroll-behavior:none;-webkit-text-size-adjust:100%;text-size-adjust:100%}
.page{height:100vh;height:100dvh;display:flex;flex-direction:column;align-items:center;max-width:480px;margin:0 auto;background:#fff;position:relative;overflow:hidden}
.qr-section{flex:1;min-height:0;display:flex;flex-direction:column;align-items:center}

/* TOP BAR */
.top-bar{width:100%;background:#fff;padding:calc(14px + env(safe-area-inset-top)) 20px 14px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--border);position:sticky;top:0;z-index:60}
.logo-wrap{display:flex;align-items:center;gap:10px}
.logo-box{width:42px;height:42px;border-radius:10px;object-fit:contain;flex-shrink:0;display:block}
.logo-name{font-size:15px;font-weight:800;color:var(--text);white-space:nowrap}
.logo-sub{font-size:11px;color:var(--muted);white-space:nowrap}
.lang-icon{width:42px;height:42px;border-radius:12px;border:1.5px solid var(--border);background:#fff;font-size:21px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:all .15s}
.lang-icon:hover{border-color:var(--red)}
.lang-icon:active{transform:scale(.94)}

/* ── LOGIN-SCREEN PAYMENT NOTIFICATION (mirrors the dashboard "New Money Received" box) ── */
.login-notif{display:none;align-items:center;justify-content:space-between;gap:10px;margin:10px 16px 0;background:#dcfce7;border:1px solid #86efac;color:#166534;border-radius:14px;padding:11px 14px;text-decoration:none;box-shadow:0 4px 14px rgba(0,0,0,.10);cursor:pointer;animation:notifPop .25s ease}
@keyframes notifPop{from{transform:translateY(-6px);opacity:0}to{transform:translateY(0);opacity:1}}
.login-notif strong{display:block;font-size:14px;font-weight:800;color:#166534}
.login-notif p{margin:3px 0 0;color:#15803d;font-size:12px}
.login-notif .ln-badge{background:#16a34a;color:#fff;padding:8px 12px;border-radius:10px;font-weight:800;font-size:12px;flex-shrink:0;white-space:nowrap}

/* LANGUAGE POPUP */
.lang-overlay{position:fixed;inset:0;background:rgba(17,24,39,.45);display:none;align-items:center;justify-content:center;z-index:100;padding:24px}
.lang-overlay.open{display:flex}
.lang-card{width:100%;max-width:340px;background:#fff;border-radius:24px;overflow:hidden;box-shadow:0 20px 60px rgba(0,0,0,.32);animation:langPop .2s ease}
@keyframes langPop{from{transform:scale(.9);opacity:0}to{transform:scale(1);opacity:1}}
.lang-row{width:100%;display:flex;align-items:center;gap:16px;padding:18px 22px;background:none;border:none;border-bottom:1px solid var(--border);font-family:inherit;cursor:pointer;text-align:left;transition:background .12s}
.lang-row:last-child{border-bottom:none}
.lang-row:hover{background:#f9fafb}
.lang-row:active{background:#f3f4f6}
.lang-flag{width:48px;height:48px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:42px;line-height:1;overflow:hidden;background:#f3f4f6;flex-shrink:0;border:1px solid var(--border)}
.lang-text{font-size:18px;font-weight:700;color:var(--text)}
.lang-row.active .lang-text{color:var(--red)}

/* QR CODE SECTION — real scannable QR with photo in the center */
.qr-section{width:100%;background:#fff;display:flex;flex-direction:column;align-items:center;padding:24px 20px 14px}
.qr-box{position:relative;width:226px;height:226px;margin-bottom:16px;display:flex;align-items:center;justify-content:center}
#qrCode{width:226px;height:226px;display:flex;align-items:center;justify-content:center}
#qrCode img,#qrCode canvas{width:226px!important;height:226px!important;display:block;image-rendering:pixelated}
.photo-circle{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:58px;height:58px;border-radius:50%;overflow:hidden;background:#fff;box-shadow:0 0 0 7px #fff,0 2px 10px rgba(0,0,0,.18)}
.photo-circle img{width:100%;height:100%;object-fit:cover}
.photo-initial{width:100%;height:100%;background:linear-gradient(135deg,#7f1d1d,var(--red));display:flex;align-items:center;justify-content:center;color:#fff;font-size:26px;font-weight:800}
.scan-hint{font-size:11px;color:var(--muted);text-align:center;background:#f9fafb;border:1px solid var(--border);padding:4px 14px;border-radius:999px;display:none}

/* TAGLINE — "Inspire / Possibility" both in the same script font */
.tagline{text-align:center;margin-top:8px;line-height:1}
.tag-script{
    font-family:"Great Vibes",cursive;font-size:38px;
    color:var(--red);
    transform:rotate(-4deg);display:inline-block;margin-bottom:-6px;
}
.tag-serif{
    font-family:"Great Vibes",cursive;font-size:44px;
    color:var(--red);letter-spacing:0;line-height:1.1;
}
.tag-c{font-size:11px;vertical-align:super;color:var(--muted);margin-left:2px;letter-spacing:0}

/* RED PANEL — flat-top red area (gradient + texture) with a layered wave divider */
.red-panel{width:100%;position:relative;z-index:10}
/* wave divider sits in normal flow at the very top of the red area */
.red-wave{display:block;width:100%;height:44px;line-height:0;margin-bottom:-1px}
.red-wave svg{display:block;width:100%;height:100%}
/* red body: gradient + texture, content lives here */
.red-body{position:relative;width:100%;background:var(--red-grad)}
/* soft top highlight */
.red-body::before{
    content:"";position:absolute;left:0;right:0;top:0;height:150px;
    background:radial-gradient(120% 100% at 50% 0%,rgba(255,255,255,.14),rgba(255,255,255,0) 65%);
    pointer-events:none;z-index:0;
}
/* faint wave / contour texture */
.red-body::after{
    content:"";position:absolute;inset:0;pointer-events:none;opacity:.55;z-index:0;
    background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='420' height='150' viewBox='0 0 420 150'%3E%3Cg fill='none' stroke='%23ffffff' stroke-opacity='0.07' stroke-width='2'%3E%3Cpath d='M-20,30 Q90,-2 210,30 T440,30'/%3E%3Cpath d='M-20,60 Q90,28 210,60 T440,60'/%3E%3Cpath d='M-20,90 Q90,58 210,90 T440,90'/%3E%3Cpath d='M-20,120 Q90,88 210,120 T440,120'/%3E%3C/g%3E%3C/svg%3E");
    background-size:420px 150px;
}

/* CALENDAR — transparent bar over the red panel; body expands UP as overlay */
.cal-wrap{width:100%;background:transparent;position:relative;z-index:30;padding-top:14px}

/* Toggle button */
.cal-toggle{
    display:flex;align-items:center;justify-content:space-between;
    padding:12px 20px;cursor:pointer;
    border:none;background:none;width:100%;font-family:inherit;
}
.cal-toggle-left{display:flex;align-items:flex-start;gap:12px}
.cal-big-num{font-size:58px;font-weight:800;color:#fff;line-height:1;flex-shrink:0}
.cal-info{text-align:left;padding-top:4px}
.cal-day-name{font-size:15px;font-weight:800;color:#fff}
.cal-bud-year{font-size:13px;font-weight:700;color:rgba(255,255,255,.9);margin-top:3px}
.cal-lunar{font-size:13px;font-weight:700;color:rgba(255,255,255,.85);margin-top:4px;line-height:1.55}
.cal-toggle-right{display:flex;flex-direction:column;align-items:center;gap:0;color:rgba(255,255,255,.7);flex-shrink:0;padding-top:4px}
.cal-chevron{font-size:14px;line-height:0.8;transition:transform .3s;display:block;color:rgba(255,255,255,.7)}
.cal-chevron.up{transform:rotate(180deg)}

/* Collapsible body — absolute overlay anchored to the TOP of the bar, grows upward */
.cal-body{
    position:absolute;left:0;right:0;bottom:100%;
    background:var(--red-grad);
    overflow:hidden;max-height:0;
    transition:max-height .35s ease;
    box-shadow:0 -10px 30px rgba(0,0,0,.28);
    border-radius:18px 18px 0 0;
    z-index:45;
}
.cal-body.open{max-height:480px}
.cal-inner{padding:14px 16px 16px}

.cal-month-row{display:flex;align-items:center;justify-content:space-between;margin-bottom:10px}
.cal-month-label{font-size:13px;font-weight:800;color:#fff}
.cal-arrows{display:flex;gap:4px}
.cal-arr{width:28px;height:28px;border-radius:50%;border:1.5px solid rgba(255,255,255,.4);background:rgba(255,255,255,.15);font-size:14px;cursor:pointer;display:flex;align-items:center;justify-content:center;color:#fff;transition:all .15s}
.cal-arr:hover{background:rgba(255,255,255,.3)}

.cal-grid{display:grid;grid-template-columns:repeat(7,1fr);gap:3px;margin-bottom:8px}
.cal-dow{font-size:11px;font-weight:700;color:rgba(255,255,255,.6);text-align:center;padding:3px 0}
.cal-cell{
    aspect-ratio:1;display:flex;flex-direction:column;align-items:center;
    justify-content:center;border-radius:6px;font-size:13px;font-weight:600;
    color:#fff;cursor:pointer;position:relative;gap:1px;transition:background .1s;
}
.cal-cell:hover{background:rgba(255,255,255,.15)}
.cal-cell.today{
    background:#fff;color:var(--red);font-weight:800;border-radius:8px;
}
.cal-cell.other{color:rgba(255,255,255,.3)}
.cal-cell.sun{color:#fca5a5}
.cal-cell.sat{color:#93c5fd}
.cal-cell.today.sun,.cal-cell.today.sat{color:var(--red)}
.cal-dot{width:4px;height:4px;border-radius:50%;background:rgba(255,255,255,.8);flex-shrink:0}
.cal-cell.today .cal-dot{background:var(--red)}

.cal-hlist{border-top:1px solid rgba(255,255,255,.2);padding-top:8px;margin-top:4px}
.cal-hitem{display:flex;align-items:center;gap:8px;font-size:11px;color:rgba(255,255,255,.8);padding:3px 0}
.cal-hdot{width:5px;height:5px;border-radius:50%;background:rgba(255,255,255,.8);flex-shrink:0}

/* BOTTOM RED SECTION */
.bottom-section{width:100%;background:transparent;padding:20px 20px calc(24px + env(safe-area-inset-bottom));position:relative;z-index:20}
.error-box{display:flex;align-items:center;gap:8px;background:rgba(255,255,255,.15);border:1.5px solid rgba(255,255,255,.3);color:#fff;padding:11px 14px;border-radius:10px;margin-bottom:14px;font-size:13px;font-weight:600}
.form-group{margin-bottom:12px}
.field-label{display:block;font-size:11px;font-weight:700;color:rgba(255,255,255,.75);margin-bottom:6px;text-transform:uppercase;letter-spacing:.5px}
.input-wrap{position:relative}
.input-wrap input{width:100%;padding:13px 44px 13px 16px;border:none;border-radius:12px;font-size:15px;font-family:inherit;color:var(--text);background:#fff;outline:none}
.input-wrap input::placeholder{color:#9ca3af}
.input-icon{position:absolute;right:14px;top:50%;transform:translateY(-50%);font-size:18px;cursor:pointer;color:var(--muted);background:none;border:none;padding:2px}

/* Login form (hidden by default) */
.pw-form{display:none;margin-bottom:14px}

/* TWO BUTTONS — smaller / more compact, BCEL bottom-bar size */
.btn-row{display:flex;gap:8px}
.btn-bio{
    flex:1;padding:10px 8px;
    background:rgba(139,0,0,.55);
    border:2px solid rgba(255,255,255,.35);
    border-radius:14px;color:#fff;
    font-size:12px;font-weight:800;font-family:inherit;
    cursor:pointer;display:flex;flex-direction:column;
    align-items:center;gap:4px;transition:all .15s;
    box-shadow:inset 0 1px 0 rgba(255,255,255,.15);
}
.btn-bio:hover{background:rgba(139,0,0,.75)}
.btn-bio:active{transform:scale(.97)}
.btn-bio .bio-icon{font-size:22px;line-height:1}
.btn-login{
    flex:2;padding:11px 12px;
    background:rgba(139,0,0,.55);
    border:2px solid rgba(255,255,255,.35);
    border-radius:14px;color:#fff;
    font-size:14px;font-weight:800;font-family:inherit;
    cursor:pointer;display:flex;align-items:center;
    justify-content:center;gap:8px;transition:all .15s;
    box-shadow:inset 0 1px 0 rgba(255,255,255,.15);
}
.btn-login:hover{background:rgba(139,0,0,.75)}
.btn-login:active{transform:scale(.98)}

/* Submit button inside form */
.btn-submit{width:100%;padding:14px;background:#fff;color:var(--red);border:none;border-radius:12px;font-size:16px;font-weight:800;font-family:inherit;cursor:pointer;margin-top:10px;transition:opacity .15s}
.btn-submit:hover{opacity:.9}
.btn-back{display:block;width:100%;background:none;border:none;color:rgba(255,255,255,.7);font-size:14px;font-weight:700;font-family:inherit;cursor:pointer;padding:10px;text-align:center;margin-top:4px}
.btn-back:hover{color:#fff}

/* ── RESPONSIVE: scale the QR/spacing down on shorter screens so nothing clips ── */
@media (max-height:760px){
    .qr-box,#qrCode{width:190px;height:190px}
    #qrCode img,#qrCode canvas{width:190px!important;height:190px!important}
    .qr-section{padding-top:16px}
    .tag-script{font-size:32px}
    .tag-serif{font-size:38px}
}
@media (max-height:660px){
    .qr-box,#qrCode{width:158px;height:158px}
    #qrCode img,#qrCode canvas{width:158px!important;height:158px!important}
    .qr-section{padding:12px 20px 8px}
    .tagline{margin-top:4px}
    .tag-script{font-size:28px}
    .tag-serif{font-size:32px}
    .photo-circle{width:50px;height:50px}
}
/* very narrow phones: keep the header on one line */
@media (max-width:360px){
    .logo-name{font-size:14px}
}
</style>
</head>
<body>
<div class="page">

<!-- TOP BAR -->
<div class="top-bar">
    <div class="logo-wrap">
        <img class="logo-box" src="/seven-credit-system/assets/7.png?v=1" alt="Seven Digital">
        <div>
            <div class="logo-name">Seven Digital</div>
        </div>
    </div>
    <button class="lang-icon" id="langIcon" onclick="openLangSheet()" aria-label="Language">🌐</button>
</div>

<!-- PAYMENT NOTIFICATION — shows the same "New Money Received" alert the user sees
     after login, as soon as their account is identified on this screen. Count only. -->
<div class="login-notif" id="loginNotif" onclick="showForm()">
    <div>
        <strong data-lo="ໄດ້ຮັບເງິນໃໝ່" data-en="New Money Received">New Money Received</strong>
        <p id="loginNotifText"></p>
    </div>
    <span class="ln-badge" data-lo="ເຂົ້າສູ່ລະບົບເພື່ອເບິ່ງ" data-en="Log in to view">Log in to view</span>
</div>

<!-- LANGUAGE POPUP -->
<div class="lang-overlay" id="langOverlay" onclick="closeLangSheet(event)">
    <div class="lang-card">
        <button class="lang-row" data-lang="lo" onclick="pickLang('lo')">
            <span class="lang-flag">🇱🇦</span>
            <span class="lang-text">ພາສາລາວ</span>
        </button>
        <button class="lang-row" data-lang="en" onclick="pickLang('en')">
            <span class="lang-flag">🇺🇸</span>
            <span class="lang-text">English</span>
        </button>
    </div>
</div>

<!-- QR RING -->
<div class="qr-section">
    <div class="qr-box" id="qrBox">
        <div id="qrCode"></div>
        <div class="photo-circle" id="photoCircle">
            <?php if ($photoUrl): ?>
                <img src="<?= $photoUrl ?>?v=<?= time() ?>" alt="Profile">
            <?php else: ?>
                <img src="/seven-credit-system/assets/7.png" style="object-fit:contain;padding:6px" alt="Seven Digital">
            <?php endif; ?>
        </div>
    </div>
    <div class="scan-hint" id="scanHint">📷 ສະແກນເພື່ອໂອນເງິນ</div>

    <!-- Brand tagline -->
    <div class="tagline">
        <div class="tag-script">Inspire</div>
        <div class="tag-serif">Possibility<span class="tag-c">©</span></div>
    </div>
</div>

<!-- RED PANEL — curved top + gradient + wave texture wraps calendar & buttons -->
<div class="red-panel">
<div class="red-wave">
  <svg viewBox="0 0 480 44" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M0,17 C95,3 180,25 270,15 C350,6 420,21 480,13 L480,44 L0,44 Z" fill="#f4c9c9"/>
    <path d="M0,29 C100,15 190,33 290,25 C380,18 440,31 480,27 L480,44 L0,44 Z" fill="#cf2626"/>
  </svg>
</div>
<div class="red-body">

<!-- CALENDAR — body pops UP as overlay -->
<div class="cal-wrap">

    <!-- Collapsible body (overlay, expands upward) -->
    <div class="cal-body" id="calBody">
        <div class="cal-inner">
            <div class="cal-month-row">
                <div class="cal-month-label" id="calMonthLabel">ມີຖຸນາ 2026 | 2569</div>
                <div class="cal-arrows">
                    <button class="cal-arr" onclick="changeMonth(-1)">‹</button>
                    <button class="cal-arr" onclick="changeMonth(1)">›</button>
                </div>
            </div>
            <div class="cal-grid" id="calGrid"></div>
            <div class="cal-hlist" id="calHList" style="display:none"></div>
        </div>
    </div>

    <!-- Toggle header: always visible -->
    <button class="cal-toggle" onclick="toggleCal()" aria-label="Toggle calendar">
        <div class="cal-toggle-left">
            <div class="cal-big-num" id="calNum">21</div>
            <div class="cal-info">
                <div class="cal-day-name" id="calDayName">ວັນອາທິດ</div>
                <div class="cal-bud-year" id="calBudYear">ມີຖຸນາ 2026 | 2569</div>
                <div class="cal-lunar" id="calLunar">ຂຶ້ນ 7 ຄ່ຳ, ເດືອນ 8.1 ລາວ, ປີມະເມຍ</div>
            </div>
        </div>
        <!-- Double chevron up — tap to expand upward -->
        <div class="cal-toggle-right" id="calChevrons">
            <span class="cal-chevron" id="chev1">∧</span>
            <span class="cal-chevron" id="chev2">∧</span>
        </div>
    </button>
</div>

<!-- BOTTOM RED -->
<div class="bottom-section">

    <?php if (!empty($error)): ?>
    <div class="error-box">⚠️ <?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <form method="POST" id="loginForm">
        <!-- Hidden login form, shown when Login tapped -->
        <div class="pw-form" id="pwForm">
            <div class="form-group">
                <label class="field-label" data-lo="ຊື່ຜູ້ໃຊ້ / ອີເມວ" data-en="Username / Email">Username / Email</label>
                <div class="input-wrap">
                    <input type="text" name="login" id="loginInput" placeholder="username or email"
                        value="<?= $prefillLogin ?>" autocomplete="username" oninput="debounce(this.value)">
                    <button type="button" class="input-icon" onclick="clearUser()">✕</button>
                </div>
            </div>
            <div class="form-group">
                <label class="field-label" data-lo="ລະຫັດຜ່ານ" data-en="Password">Password</label>
                <div class="input-wrap">
                    <input type="password" name="password" id="pwInput" placeholder="••••••••" autocomplete="current-password">
                    <button type="button" class="input-icon" onclick="togglePw()">👁</button>
                </div>
            </div>
            <button class="btn-submit" type="submit">
                <span data-lo="ເຂົ້າລະບົບ" data-en="Sign In">Sign In</span> →
            </button>
            <button type="button" class="btn-back" onclick="hideForm()">
                ← <span data-lo="ກັບຄືນ" data-en="Back">Back</span>
            </button>
        </div>
    </form>

    <!-- Two main buttons -->
    <div class="btn-row" id="mainBtns">
        <button class="btn-bio" id="bioBtn" onclick="loginWithFaceID()">
            <span class="bio-icon" id="bioIcon">👆</span>
            <span id="bioLabel" data-lo="ສະແກນໜ້າ" data-en="Biometrics">Biometrics</span>
        </button>
        <button class="btn-login" onclick="showForm()">
            🔑 <span data-lo="ເຂົ້າດ້ວຍລະຫັດ" data-en="Login">Login</span>
        </button>
    </div>

</div><!-- /bottom-section -->
</div><!-- /red-body -->
</div><!-- /red-panel -->
</div>

<script>
/* ═══ LANGUAGE ═══ */
const LANG_KEY='seven_lang';
function setLang(lang){
    document.querySelectorAll('[data-lo],[data-en]').forEach(el=>{
        const t=el.getAttribute('data-'+lang);if(t!==null)el.textContent=t;
    });
    document.querySelectorAll('.lang-row').forEach(r=>r.classList.toggle('active',r.dataset.lang===lang));
    localStorage.setItem(LANG_KEY,lang);
    renderCalendar();
    updateHero(new Date(calYear,calMonth,selectedDay||new Date().getDate()));
    /* re-localise the dynamic payment-notification text (count message) */
    if(notifLogin) checkLoginNotif(notifLogin);
}
function openLangSheet(){
    document.querySelectorAll('.lang-row').forEach(r=>r.classList.toggle('active',r.dataset.lang===(localStorage.getItem(LANG_KEY)||'en')));
    document.getElementById('langOverlay').classList.add('open');
}
function closeLangSheet(e){
    if(e && e.target.id!=='langOverlay') return;   // only close when tapping the dark backdrop
    document.getElementById('langOverlay').classList.remove('open');
}
function pickLang(lang){
    setLang(lang);
    document.getElementById('langOverlay').classList.remove('open');
}

/* ═══ SHOW/HIDE FORM ═══ */
function showForm(){
    document.getElementById('pwForm').style.display='block';
    document.getElementById('mainBtns').style.display='none';
    const li=document.getElementById('loginInput');
    setTimeout(()=>li.value?document.getElementById('pwInput').focus():li.focus(),50);
}
function hideForm(){
    document.getElementById('pwForm').style.display='none';
    document.getElementById('mainBtns').style.display='flex';
}
function togglePw(){const i=document.getElementById('pwInput');i.type=i.type==='password'?'text':'password';}

/* Auto-show form on error */
<?php if(!empty($error)||$prefillLogin): ?>
document.addEventListener('DOMContentLoaded',()=>{showForm();});
<?php endif; ?>

/* ═══ REAL SCANNABLE QR + REMEMBER LAST USER ═══ */
let currentQR=<?=json_encode($qrContent)?>;
const LAST_USER_KEY='seven_last_user';
const PHOTO_BASE='/seven-credit-system/assets/profile_photos/';
const DEFAULT_AVATAR='/seven-credit-system/assets/7.png';   // ← change this file/path to set the default QR-centre logo
/* When nobody is identified yet, the QR encodes this generic app link instead of a
   meaningless placeholder. Scanning it just opens the app (never a broken transfer). */
const APP_LOGIN_URL='https://7d-lao.com/seven-credit-system/auth/login.php';

/* render a real, scannable QR (photo overlays the centre via CSS) */
function renderQR(txt){
    const box=document.getElementById('qrCode');
    if(!box) return;
    box.innerHTML='';
    if(!txt || txt==='SEVEN-DIGITAL') txt=APP_LOGIN_URL;   // generic, always scannable
    try{
        new QRCode(box,{text:txt,width:226,height:226,colorDark:'#111827',colorLight:'#ffffff',correctLevel:QRCode.CorrectLevel.H});
    }catch(e){}
}

function setPhoto(photo,initial){
    const circ=document.getElementById('photoCircle');
    if(photo){circ.innerHTML='<img src="'+PHOTO_BASE+photo+'?v='+Date.now()+'" style="width:100%;height:100%;object-fit:cover">';}
    else{circ.innerHTML='<img src="'+DEFAULT_AVATAR+'" style="width:100%;height:100%;object-fit:contain;padding:6px" alt="">';}
}

/* paint the screen for a known user */
function applyUser(u){
    if(!u) return;
    setPhoto(u.photo,u.initial);
    currentQR=u.customer_code||'SEVEN-DIGITAL';
    renderQR(currentQR);
    document.getElementById('scanHint').style.display=u.customer_code?'block':'none';
    const li=document.getElementById('loginInput');
    if(li && !li.value && u.login) li.value=u.login;
    watchNotif(u.login);          // start watching this account for new payments
}

function saveLastUser(u){try{localStorage.setItem(LAST_USER_KEY,JSON.stringify(u));}catch(e){}}
function getLastUser(){try{return JSON.parse(localStorage.getItem(LAST_USER_KEY)||'null');}catch(e){return null;}}

/* initial paint */
renderQR(currentQR);

/* ═══ LOGIN-SCREEN PAYMENT NOTIFICATION ═══
   Mirrors the dashboard "New Money Received" box. Shows ONLY a count (no amounts,
   senders or balances) for the identified account, and refreshes every 5s so a
   payment that lands while this screen is open pops up right away. */
let notifLogin = null;       // the account login we're currently watching
let notifTimer = null;

function notifTextLogin(n){
    const lang=localStorage.getItem(LANG_KEY)||'en';
    return lang==='lo'
        ? ('ທ່ານມີ '+n+' ການແຈ້ງເຕືອນທີ່ຍັງບໍ່ໄດ້ອ່ານ')
        : ('You have '+n+' unread payment notification(s).');
}
function renderLoginNotif(unread){
    const box=document.getElementById('loginNotif');
    const txt=document.getElementById('loginNotifText');
    if(!box||!txt) return;
    if(unread>0){
        txt.textContent=notifTextLogin(unread);
        box.style.display='flex';
    }else{
        box.style.display='none';
    }
}
async function checkLoginNotif(login){
    if(!login || login.trim().length<2){ renderLoginNotif(0); return; }
    try{
        const r=await fetch('check_login_notification.php?u='+encodeURIComponent(login.trim()));
        const d=await r.json();
        renderLoginNotif((d && d.success && d.found) ? (d.unread||0) : 0);
    }catch(e){ /* silent — never block the login screen on a notif error */ }
}
function watchNotif(login){
    const next=login||null;
    /* if we're already watching this same account, keep the existing poller */
    if(next===notifLogin && notifTimer) return;
    notifLogin=next;
    clearInterval(notifTimer); notifTimer=null;
    if(notifLogin){
        checkLoginNotif(notifLogin);                                   // immediate
        notifTimer=setInterval(()=>checkLoginNotif(notifLogin),5000);  // then live
    }else{
        renderLoginNotif(0);
    }
}

/* ═══ LIVE USER LOOKUP ═══ */
let ltimer=null;
function debounce(v){clearTimeout(ltimer);if(v.trim().length<2){return;}ltimer=setTimeout(()=>lookupUser(v.trim()),500);}
async function lookupUser(login){
    try{
        const res=await fetch('lookup_user.php?u='+encodeURIComponent(login));
        const d=await res.json();if(!d.found)return;
        const u={login:login,name:d.name,photo:d.photo||null,initial:d.initial||'',customer_code:d.customer_code||null};
        applyUser(u);
        saveLastUser(u);            // remember for next app open
        checkBioForUser(login);
    }catch(e){}
}
function clearUser(){
    document.getElementById('loginInput').value='';
    setPhoto(null,'7');
    document.getElementById('scanHint').style.display='none';
    currentQR='SEVEN-DIGITAL';renderQR(currentQR);
    watchNotif(null);                                        // stop watching + hide banner
    try{localStorage.removeItem(LAST_USER_KEY);}catch(e){}   // forget remembered user
}

/* ═══ CALENDAR ═══ */
const MO_LO=['ມັງກອນ','ກຸມພາ','ມີນາ','ເມສາ','ພຶດສະພາ','ມີຖຸນາ','ກໍລະກົດ','ສິງຫາ','ກັນຍາ','ຕຸລາ','ພະຈິກ','ທັນວາ'];
const MO_EN=['January','February','March','April','May','June','July','August','September','October','November','December'];
const DW_LO=['ອາ','ຈ','ອ','ພ','ພຫ','ສ','ເສ'];
const DW_EN=['Su','Mo','Tu','We','Th','Fr','Sa'];
const DW_FULL_LO=['ອາທິດ','ຈັນ','ອັງຄານ','ພຸດ','ພະຫັດ','ສຸກ','ເສົາ'];
const DW_FULL_EN=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
const ZODIAC_LO=['ຊວດ','ສະຫງົວ','ຂານ','ເຖາະ','ມະໂລງ','ມະເສັງ','ມະເມຍ','ມະແມ','ວອກ','ລະກາ','ຈໍ','ກຸນ'];
const HOLIDAYS={'1-1':{lo:'ວັນປີໃໝ່ສາກົນ',en:"New Year's Day"},'3-8':{lo:'ວັນແມ່ຍິງສາກົນ',en:"Women's Day"},'4-14':{lo:'ວັນປີໃໝ່ລາວ',en:'Lao New Year'},'4-15':{lo:'ວັນປີໃໝ່ລາວ',en:'Lao New Year'},'4-16':{lo:'ວັນປີໃໝ່ລາວ',en:'Lao New Year'},'5-1':{lo:'ວັນກຳມະກອນ',en:'Labour Day'},'12-2':{lo:'ວັນຊາດ',en:'National Day'}};
const BUDDHIST=543;
let calYear,calMonth,selectedDay;

/* ── Accurate Lao lunar calendar (Chula Sakarat / ປະຕິທິນລາວ) ── */
function laoLunar(input){
    const D=new Date(input.getFullYear(),input.getMonth(),input.getDate()); // calendar date, no time
    const aharakoune=y=>(y*292207+373)%800;
    const harakoune=y=>Math.floor((y*292207+373)/800)+1;
    const avomane=y=>(11*harakoune(y)+650)%692;
    const regularLeap=y=>(800-aharakoune(y))<=207;
    const bodethey=y=>{const ha=harakoune(y);return (ha+Math.floor((11*ha+650)/692))%30;};
    function jaisLeap(y){const b0=bodethey(y),b1=bodethey(y+1);return b0>24||b0<6||(b0===24&&b1===6)||(b0===25&&b1===5);}
    function isProtetinLeap(y){const a0=avomane(y),a1=avomane(y+1),normal=regularLeap(y);let v=normal&&a0<127;if(!normal){if(a0===137&&a1===0)v=false;else if(a0<138)v=true;}if(!v)v=isProtetinLeap(y-1)&&jaisLeap(y-1);return v;}
    function greatLeap(y){let v=isProtetinLeap(y);if(jaisLeap(y)&&v)v=false;return v;}
    function daysInYear(y){return jaisLeap(y)?384:greatLeap(y)?355:354;}
    function lunarDiffDays(end){let c=0,x=1970-638+1,yy=end.getFullYear()-638;if(x>yy){const t=x;x=yy;yy=t;}while(x<yy)c+=daysInYear(x++);return c;}
    function diffDays(end){return Math.abs(Math.round((end-286596e5)/86400000));}
    function monthsOfYear(y){const ath=jaisLeap(y),great=greatLeap(y),it=[];for(let i=0;i<12+(ath|0);i++){let j=i;if(ath&&j>=8)j--;it.push(29+((j%2!=0)|0)+((j==6&&great)|0));}return it;}
    const dt=new Date(D-7*3600*1000);
    let y=dt.getFullYear()-638;
    let day=Math.abs(diffDays(dt)-lunarDiffDays(dt))+1;
    const len=daysInYear(y);
    if(day>len){day-=len;y++;}
    let m=0;for(const mm of monthsOfYear(y)){if(day<=mm)break;day-=mm;m++;}
    const leap=jaisLeap(y);
    const phase=day<=15?'ຂຶ້ນ':'ແຮມ';          // waxing / waning
    const kham=day<=15?day:day-15;
    let mo=leap?(m<7?(m+1)+'':m===7?'8.1':m===8?'8.2':''+m):(m+1)+'';
    return {phase,kham,month:mo};
}
function zodiac(y){return ZODIAC_LO[(((y-4)%12)+12)%12]||'';}

function updateHero(date){
    const lang=localStorage.getItem(LANG_KEY)||'en';
    const dw=lang==='lo'?DW_FULL_LO:DW_FULL_EN;
    const mo=lang==='lo'?MO_LO:MO_EN;
    const by=date.getFullYear()+BUDDHIST;
    document.getElementById('calNum').textContent=date.getDate();
    document.getElementById('calDayName').textContent=(lang==='lo'?'ວັນ':'')+dw[date.getDay()];
    document.getElementById('calBudYear').textContent=mo[date.getMonth()]+' '+date.getFullYear()+' | '+by;
    const ll=laoLunar(date);
    const zd=zodiac(date.getFullYear());
    document.getElementById('calLunar').innerHTML=ll.phase+' '+ll.kham+' ຄ່ຳ, ເດືອນ '+ll.month+' ລາວ, ປີ'+zd;
}

function renderCalendar(){
    const lang=localStorage.getItem(LANG_KEY)||'en';
    const mo=lang==='lo'?MO_LO:MO_EN;
    const dw=lang==='lo'?DW_LO:DW_EN;
    const by=calYear+BUDDHIST;
    document.getElementById('calMonthLabel').textContent=mo[calMonth]+' '+calYear+' | '+by;
    const today=new Date();
    const first=new Date(calYear,calMonth,1).getDay();
    const dim=new Date(calYear,calMonth+1,0).getDate();
    const prev=new Date(calYear,calMonth,0).getDate();
    let h=dw.map((d,i)=>`<div class="cal-dow ${i===0?'s':i===6?'sa':''}">${d}</div>`).join('');
    for(let i=first-1;i>=0;i--)h+=`<div class="cal-cell other">${prev-i}</div>`;
    const hdays=[];
    for(let d=1;d<=dim;d++){
        const date=new Date(calYear,calMonth,d);
        const dow=date.getDay();
        const hk=`${calMonth+1}-${d}`;
        const hol=HOLIDAYS[hk];
        const isTod=d===today.getDate()&&calMonth===today.getMonth()&&calYear===today.getFullYear();
        const isSel=d===selectedDay&&calMonth===calMonth&&calYear===calYear;
        let cls='cal-cell';
        if(isTod)cls+=' today';
        if(dow===0&&!isTod)cls+=' sun';
        if(dow===6&&!isTod)cls+=' sat';
        if(hol)hdays.push({d,hol});
        const dot=hol&&!isTod?'<div class="cal-dot"></div>':'';
        h+=`<div class="${cls}" onclick="clickDay(${d})">${d}${dot}</div>`;
    }
    const rem=(first+dim)%7===0?0:7-(first+dim)%7;
    for(let d=1;d<=rem;d++)h+=`<div class="cal-cell other">${d}</div>`;
    document.getElementById('calGrid').innerHTML=h;
    const hl=document.getElementById('calHList');
    if(hdays.length){
        hl.innerHTML=hdays.map(({d,hol})=>`<div class="cal-hitem"><div class="cal-hdot"></div><span><b>${d}</b> — ${lang==='lo'?hol.lo:hol.en}</span></div>`).join('');
        hl.style.display='block';
    } else { hl.style.display='none'; }
}

function changeMonth(dir){
    calMonth+=dir;
    if(calMonth<0){calMonth=11;calYear--;}
    if(calMonth>11){calMonth=0;calYear++;}
    selectedDay=null;
    renderCalendar();
}
function clickDay(d){
    selectedDay=d;
    updateHero(new Date(calYear,calMonth,d));
    renderCalendar();
}

/* ═══ BIOMETRIC ═══ */
const CRED_KEY='seven_webauthn_cred';
function checkBioAvailable(){
    const isIOS=/iphone|ipad|ipod/i.test(navigator.userAgent);
    document.getElementById('bioIcon').textContent=isIOS?'🔒':'👆';
}
function checkBioForUser(login){
    try{const s=JSON.parse(localStorage.getItem(CRED_KEY)||'null');
    if(s&&s.username===login){const isIOS=/iphone|ipad|ipod/i.test(navigator.userAgent);document.getElementById('bioIcon').textContent=isIOS?'🔒':'👆';}}catch(e){}
}
function b64ToBuffer(b64){const bin=atob(b64.replace(/-/g,'+').replace(/_/g,'/'));return Uint8Array.from(bin,c=>c.charCodeAt(0));}
function bufToB64(buf){return btoa(String.fromCharCode(...new Uint8Array(buf))).replace(/\+/g,'-').replace(/\//g,'_').replace(/=/g,'');}
async function loginWithFaceID(){
    if(!window.PublicKeyCredential){alert('Biometrics not supported on this device.');return;}
    const lang=localStorage.getItem(LANG_KEY)||'en';

    /* figure out a username in case there's no local credential pointer */
    const stored=JSON.parse(localStorage.getItem(CRED_KEY)||'null');
    const typed=(document.getElementById('loginInput').value||'').trim();
    const last=getLastUser();
    const username=typed||(stored&&stored.username)||(last&&last.login)||'';

    const btn=document.getElementById('bioBtn');btn.style.opacity='.5';
    try{
        let challenge,credId;
        if(stored&&stored.credentialId){
            /* fast path — credential pointer saved in this browser */
            const ch=await (await fetch('../auth/webauthn_challenge.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({action:'get_challenge',credential_id:stored.credentialId})})).json();
            if(!ch.success)throw new Error(ch.error);
            challenge=ch.challenge;credId=stored.credentialId;
        }else if(username){
            /* server path — look up the credential by username (survives data-clear; works across Safari & the home-screen app) */
            const ch=await (await fetch('../auth/webauthn_challenge.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({action:'get_challenge_by_user',username})})).json();
            if(!ch.success)throw new Error(ch.error);
            challenge=ch.challenge;credId=ch.credential_id;
        }else{
            /* nothing to identify the account — ask for the username */
            btn.style.opacity='1';
            alert(lang==='lo'?'ກະລຸນາໃສ່ຊື່ຜູ້ໃຊ້ ຫຼື ອີເມວ ກ່ອນ ແລ້ວກົດ ສະແກນໜ້າ ອີກຄັ້ງ':'Enter your username or email first, then tap Face Scan again.');
            showForm();
            return;
        }

        const a=await navigator.credentials.get({publicKey:{challenge:b64ToBuffer(challenge),allowCredentials:[{id:b64ToBuffer(credId),type:'public-key',transports:['internal']}],timeout:60000,userVerification:'required'}});
        const v=await (await fetch('../auth/webauthn_challenge.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({action:'verify',credential_id:bufToB64(a.rawId),authenticator_data:bufToB64(a.response.authenticatorData),client_data_json:bufToB64(a.response.clientDataJSON),signature:bufToB64(a.response.signature),challenge:challenge})})).json();
        if(v.success){
            /* save the pointer so next time uses the fast path */
            try{localStorage.setItem(CRED_KEY,JSON.stringify({credentialId:credId,username:username||(stored&&stored.username)||''}));}catch(e){}
            /* client-side navigation keeps us inside the standalone web app */
            location.replace(v.redirect);
        }else throw new Error(v.error);
    }catch(e){btn.style.opacity='1';if(e.name!=='NotAllowedError')alert('Failed: '+(e.message||e));}
}

/* ═══ CALENDAR TOGGLE (expands upward, buttons stay put) ═══ */
let calOpen = false;
function toggleCal(){
    calOpen = !calOpen;
    const body = document.getElementById('calBody');
    const c1   = document.getElementById('chev1');
    const c2   = document.getElementById('chev2');
    body.classList.toggle('open', calOpen);
    c1.classList.toggle('up', calOpen);
    c2.classList.toggle('up', calOpen);
}

/* ═══ INIT ═══ */
window.addEventListener('load',()=>{
    const saved=localStorage.getItem(LANG_KEY)||'en';
    const now=new Date();
    calYear=now.getFullYear();calMonth=now.getMonth();selectedDay=now.getDate();
    setLang(saved);
    checkBioAvailable();
    const v=document.getElementById('loginInput').value;
    if(v.trim().length>=2){
        lookupUser(v.trim());
    }else{
        const last=getLastUser();
        if(last){
            applyUser(last);                       // show last user instantly
            if(last.login)lookupUser(last.login);  // refresh photo/name/QR from server
        }
    }
});

if('serviceWorker' in navigator){navigator.serviceWorker.register('/seven-credit-system/service-worker.js',{scope:'/seven-credit-system/'});}
</script>
</body>
</html>