<?php
require_once($_SERVER["DOCUMENT_ROOT"] . '/includes/config.php');

// Cookie params — COOKIE_DOMAIN dan keladi (.inpay.uz prod / empty test)
session_set_cookie_params([
    'lifetime' => 0,
    'path'     => '/',
    'domain'   => COOKIE_DOMAIN,
    'secure'   => ($_inpay_is_https ?? (($_SERVER['HTTPS'] ?? '') === 'on')),
    'httponly' => true,
    'samesite' => COOKIE_DOMAIN === '' ? 'Lax' : 'None',
]);
if (session_status() === PHP_SESSION_NONE) { session_start(); }
include_once($_SERVER["DOCUMENT_ROOT"] . '/includes/db.php');

// ── Already logged in check ───────────────────────────────────
if (isset($_SESSION['user_id']) && isset($_SESSION['session_token'])) {
    $stmt = $conn->prepare("SELECT COUNT(*) FROM user_sessions WHERE user_id=? AND session_token=?");
    $stmt->bind_param("is", $_SESSION['user_id'], $_SESSION['session_token']);
    $stmt->execute(); $stmt->bind_result($active_session); $stmt->fetch(); $stmt->close();
    if ($active_session > 0) { header('Location: ' . BUSINESS_URL . '/'); exit; }
    else { session_unset(); session_destroy(); }
}

if (DEBUG_MODE) { ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); }

// ── OAuth providerlar (DB-backed: oauth_providers jadvali, /admin/oauth_providers.php) ────
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/oauth_providers.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/passkey_helpers.php';
$_SESSION['oauth_state'] = bin2hex(random_bytes(16));
$oauth_enabled_providers = [];
foreach (oauth_providers_all(true) as $_op_key => $_op) {
    // Passkey is not an OAuth flow — surface it as its own button below.
        if ($_op_key === 'neoid') continue;   // ← QO'SHING
    if ($_op_key === 'passkey') continue;
    $_op_url = oauth_build_authorize_url($_op_key, $_SESSION['oauth_state']);
    if ($_op_url === null) continue; // sozlanmagan yoki client_id bo'sh — yashiramiz
    $oauth_enabled_providers[$_op_key] = $_op + ['authorize_url' => $_op_url];
}
unset($_op_key, $_op, $_op_url);
$passkey_enabled = inpay_passkey_enabled($conn);

/* ───────── Login chap panel reklamalari (admin/login_ads.php boshqaradi) ─────────
 * Faqat enabled=1 va vaqt oynasi ichidagilarni olamiz. Weighted shuffle:
 * har bir reklama o'z og'irligi qadar takrorlanadi → random_shuffle. Bu MySQL
 * ORDER BY RAND()'dan ko'ra deterministik va o'qiladi. */
$login_ads = [];
$_now = date('Y-m-d H:i:s');
$_ads_stmt = @$conn->prepare("SELECT id, title, subtitle, cta_text, cta_url,
                                     media_type, media_path, bg_accent, weight
                              FROM login_ads
                              WHERE enabled=1
                                AND (start_at IS NULL OR start_at <= ?)
                                AND (end_at   IS NULL OR end_at   >= ?)
                              ORDER BY sort_order ASC, id DESC");
if ($_ads_stmt) {
    $_ads_stmt->bind_param('ss', $_now, $_now);
    $_ads_stmt->execute();
    $_ads_res = $_ads_stmt->get_result();
    $_pool = [];
    while ($_a = $_ads_res->fetch_assoc()) {
        $_w = max(1, (int)$_a['weight']);
        for ($i = 0; $i < $_w; $i++) $_pool[] = $_a;
    }
    $_ads_stmt->close();
    if ($_pool) {
        shuffle($_pool);
        $_seen = [];
        foreach ($_pool as $_a) {
            if (isset($_seen[$_a['id']])) continue;
            $_seen[$_a['id']] = true;
            $login_ads[] = $_a;
        }
        if ($login_ads) {
            $_ids = array_map(fn($a)=>(int)$a['id'], $login_ads);
            $_in  = implode(',', $_ids);
            @$conn->query("UPDATE login_ads SET views=views+1 WHERE id IN ($_in)");
        }
    }
    unset($_pool, $_seen);
}
unset($_now, $_ads_stmt, $_ads_res, $_a, $_w, $_i);

// ── QR token ──────────────────────────────────────────────────
$qr_token = bin2hex(random_bytes(16));
$stmt = $conn->prepare("INSERT INTO login_tokens (token, created_at) VALUES (?, NOW())");
$stmt->bind_param("s", $qr_token); $stmt->execute(); $stmt->close();
$qr_url = "https://api.qrserver.com/v1/create-qr-code/?size=500x500&&data=" . urlencode($qr_token);

function detect_device($ua) {
    if (preg_match('/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile|Opera Mini)/i', $ua)) return "Mobile Device";
    elseif (preg_match('/(Macintosh|Windows|Linux)/i', $ua)) return "Desktop/Laptop";
    return "Unknown Device";
}
function save_user_session($conn, $user_id) {
    $ip = $_SERVER['REMOTE_ADDR'] ?? '';
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
    $device = detect_device($ua);
    $session_token = bin2hex(random_bytes(32));
    $stmt = $conn->prepare("INSERT INTO user_sessions (user_id,device,user_agent,last_login,ip_address,session_token) VALUES (?,?,?,NOW(),?,?)");
    $stmt->bind_param("issss", $user_id, $device, $ua, $ip, $session_token); $stmt->execute(); $stmt->close();
    $_SESSION['session_token'] = $session_token;
    $stmt = $conn->prepare("DELETE FROM user_sessions WHERE user_id=? AND id NOT IN (SELECT id FROM (SELECT id FROM user_sessions WHERE user_id=? ORDER BY id DESC LIMIT 3) t)");
    $stmt->bind_param("ii", $user_id, $user_id); $stmt->execute(); $stmt->close();
    // Persistent auth cookie — keeps user signed in across browser restarts.
    if (function_exists('inpay_set_auth_cookie')) inpay_set_auth_cookie($session_token);
}

// ── POST handler ──────────────────────────────────────────────
$error = null;
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !isset($_POST['neo_id_login'])) {

    // reCAPTCHA — faqat production'da tekshiriladi
    $recaptcha_ok = true;
    if (RECAPTCHA_ENABLED) {
        $recaptcha_response = $_POST['g-recaptcha-response'] ?? '';
        $ctx = stream_context_create(['http'=>['method'=>'POST','header'=>"Content-Type: application/x-www-form-urlencoded\r\n",
            'content'=>http_build_query(['secret'=>RECAPTCHA_SECRET_KEY,'response'=>$recaptcha_response,'remoteip'=>$_SERVER['REMOTE_ADDR']])]]);
        $rr = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $ctx);
        $rj = json_decode($rr);
        $recaptcha_ok = !empty($rj->success);
        if (!$recaptcha_ok) $error = "reCAPTCHA tasdiqlanmadi!";
    }

    if ($recaptcha_ok) {
        $username = $_POST['username'] ?? '';
        $password = $_POST['password'] ?? '';
        $stmt = $conn->prepare("SELECT * FROM users WHERE username=?");
        $stmt->bind_param("s", $username); $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc(); $stmt->close();
        if ($user && password_verify($password, $user['password'])) {
            if (!empty($user['two_factor_enabled']) && $user['two_factor_enabled'] == 1) {
                $_SESSION['2fa_user_id'] = $user['id'];
                $_SESSION['2fa_remember'] = ['role' => $user['role']];
                header('Location: ' . BUSINESS_URL . '/login/2fa/'); exit;
            }
            $_SESSION['user_id'] = $user['id']; $_SESSION['role'] = $user['role'];
            save_user_session($conn, $_SESSION['user_id']);
            header('Location: ' . BUSINESS_URL . '/'); exit;
        } else {
            $error = "Login yoki parol noto'g'ri!";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="uz">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0">
<meta name="turbo-skip" content="true">
<title><?php echo BRAND_NAME; ?> Business — Kirish</title>
<meta name="description" content="<?php echo BRAND_NAME; ?> Business — Professional to'lov platformasi">
<meta name="theme-color" content="#f7f8fc">
<link rel="icon" type="image/png" href="<?php echo BRAND_LOGO_SM; ?>">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Space+Grotesk:wght@500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<?php if (RECAPTCHA_ENABLED): ?>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<?php endif; ?>
<style>
/* ════════════════════════════════════════════════════════
   inPAY Business — Login (Soft Cloud theme)
   Pastel · Glass · 4D buttons · Mobile-first
════════════════════════════════════════════════════════ */
*{box-sizing:border-box;margin:0;padding:0;-webkit-tap-highlight-color:transparent;}
:root{
  --bg:        #f7f8fc;
  --paper:     #ffffff;
  --soft:      #f4f6fc;
  --line:      #eaeef7;
  --line2:     #d6dcec;

  --txt:       #1b2240;
  --txt2:      #5f6987;
  --txt3:      #98a2bf;

  --sky:       #a5c8ff;
  --sky-d:     #6fa1f7;
  --sky-deep:  #4577d4;
  --lav:       #cdb8ff;
  --lav-d:     #9d83ee;
  --lav-deep:  #6f53d4;
  --mint:      #a6ecd2;
  --mint-d:    #5fcca0;
  --peach:     #ffd0b8;
  --peach-d:   #ffa886;
  --rose-d:    #f78aab;
  --danger:    #ef4444;
  --danger-l:  rgba(239,68,68,.07);
  --danger-brd:rgba(239,68,68,.25);

  --grad-cta:  linear-gradient(135deg, var(--sky-d) 0%, var(--lav-d) 100%);

  --r1: 12px; --r2: 16px; --r3: 22px; --r4: 30px;

  --fs: 'Inter', system-ui, sans-serif;
  --fh: 'Space Grotesk', system-ui, sans-serif;

  --e-out:    cubic-bezier(.22,.61,.36,1);
  --e-soft:   cubic-bezier(.16,1,.3,1);
  --e-spring: cubic-bezier(.34,1.4,.64,1);
}

html,body{overflow-x:hidden;-webkit-text-size-adjust:100%;}
html{height:100%;}
body{
  font-family: var(--fs);
  color: var(--txt);
  min-height: 100vh;
  /* Column flex + auto-margin wrap = vertical centering when content fits,
     natural scroll when it overflows. align-items:center cuts the top off
     when the form is taller than the viewport. */
  display: flex; flex-direction: column;
  padding: clamp(16px, 4vh, 56px) 16px;
  -webkit-font-smoothing: antialiased;
  background:
    radial-gradient(900px 500px at 8% -10%,  rgba(165,200,255,.55), transparent 60%),
    radial-gradient(900px 500px at 100% 8%,  rgba(205,184,255,.45), transparent 60%),
    radial-gradient(800px 600px at 50% 100%, rgba(255,193,210,.30), transparent 60%),
    var(--bg);
}
body::before{
  content:''; position:fixed; inset:0; z-index:0; pointer-events:none;
  background-image: radial-gradient(rgba(110,130,170,.08) 1px, transparent 1px);
  background-size: 22px 22px;
  mask-image: radial-gradient(ellipse 80% 60% at 50% 30%, #000 30%, transparent 95%);
  opacity: .5;
}

a{ color: inherit; text-decoration: none; }
button{ font: inherit; color: inherit; cursor: pointer; }
img{ max-width: 100%; display: block; }
::selection{ background: rgba(111,161,247,.25); color: var(--txt); }

/* ── Layout ── */
.wrap{
  width: 100%; max-width: 1080px; position: relative; z-index: 1;
  /* margin:auto inside a column-flex parent = center vertically when it fits,
     stick to top + scroll when content is taller than viewport. */
  margin: auto;
  display: flex; align-items: center; gap: 56px;
}
.left{ flex: 1; min-width: 0; }
.right{ width: 440px; flex-shrink: 0; }

/* ── Left branding ── */
.brand-logo{ height: 36px; margin-bottom: 32px; display: block; }
.brand-headline{
  font-family: var(--fh); font-weight: 800; line-height: 1.08;
  font-size: clamp(2rem, 3.4vw, 2.8rem);
  letter-spacing: -.025em;
  color: var(--txt);
  margin-bottom: 18px;
}
.brand-headline .grad{
  background: linear-gradient(135deg, var(--sky-deep), var(--lav-deep));
  -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent;
}
.brand-sub{ font-size: 1rem; color: var(--txt2); line-height: 1.65; max-width: 380px; margin-bottom: 36px; }

.features{ display: flex; flex-direction: column; gap: 12px; margin-bottom: 32px; }
.feat{
  display: flex; align-items: center; gap: 14px;
  padding: 16px 18px;
  background: var(--paper);
  border: 1px solid var(--line);
  border-radius: var(--r2);
  box-shadow: 0 2px 6px -2px rgba(110,130,170,.10);
  transition: transform .35s var(--e-spring), border-color .25s var(--e-out), box-shadow .35s var(--e-soft);
}
.feat:hover{ transform: translate3d(4px,0,0); border-color: rgba(165,200,255,.5); box-shadow: 0 6px 16px -6px rgba(110,130,170,.22); }
.feat-ico{
  width: 42px; height: 42px; flex-shrink: 0;
  border-radius: 12px;
  display: flex; align-items: center; justify-content: center;
  font-size: 18px; color: #fff;
  background: linear-gradient(135deg, var(--sky), var(--sky-d));
  box-shadow: 0 6px 14px -5px rgba(111,161,247,.45), inset 0 1px 0 rgba(255,255,255,.4);
}
.feat:nth-child(2) .feat-ico{ background: linear-gradient(135deg, var(--mint), var(--mint-d)); box-shadow: 0 6px 14px -5px rgba(95,204,160,.45), inset 0 1px 0 rgba(255,255,255,.4); }
.feat:nth-child(3) .feat-ico{ background: linear-gradient(135deg, var(--peach), var(--peach-d)); box-shadow: 0 6px 14px -5px rgba(255,168,134,.45), inset 0 1px 0 rgba(255,255,255,.4); }
.feat-title{ font-family: var(--fh); font-size: .92rem; font-weight: 700; color: var(--txt); margin-bottom: 2px; }
.feat-sub{ font-size: .8rem; color: var(--txt2); }

.contact-box{
  background: var(--paper);
  border: 1px solid var(--line);
  border-radius: var(--r2);
  padding: 16px 20px;
  display: flex; align-items: center; gap: 14px;
  box-shadow: 0 2px 6px -2px rgba(110,130,170,.10);
}
.contact-box i{ color: var(--sky-deep); font-size: 20px; }
.contact-lbl{ font-size: .68rem; color: var(--txt3); font-weight: 700; text-transform: uppercase; letter-spacing: .1em; margin-bottom: 2px; }
.contact-val{ font-family: var(--fh); font-size: 1rem; font-weight: 700; color: var(--txt); transition: color .2s var(--e-out); }
.contact-val:hover{ color: var(--sky-deep); }

/* ── Right form card ── */
.form-card{
  background: var(--paper);
  border: 1px solid var(--line);
  border-radius: var(--r4);
  overflow: hidden;
  box-shadow:
    0 2px 4px rgba(110,130,170,.04),
    0 30px 80px -24px rgba(110,130,170,.30);
}
.form-card-head{
  padding: 22px 26px 18px;
  border-bottom: 1px solid var(--line);
  background:
    radial-gradient(400px 200px at 100% 0%, rgba(165,200,255,.30), transparent 70%),
    radial-gradient(300px 150px at 0% 100%, rgba(205,184,255,.25), transparent 70%),
    var(--paper);
  position: relative; overflow: hidden;
}
.btn-home{
  display: inline-flex; align-items: center; gap: 6px;
  padding: 6px 11px 6px 9px;
  margin-bottom: 10px;
  background: var(--soft);
  border: 1px solid var(--line);
  border-radius: 10px;
  color: var(--txt2);
  font-family: var(--fh); font-size: .76rem; font-weight: 600;
  text-decoration: none;
  position: relative; z-index: 2;
  transition: transform .25s var(--e-spring), background .2s var(--e-out), border-color .2s var(--e-out), color .2s var(--e-out), box-shadow .3s var(--e-soft);
}
.btn-home i{ font-size: .95rem; transition: transform .25s var(--e-spring); }
.btn-home:hover{
  background: var(--paper);
  border-color: var(--sky);
  color: var(--sky-deep);
  transform: translate3d(-2px,0,0);
  box-shadow: 0 6px 14px -8px rgba(111,161,247,.35);
}
.btn-home:hover i{ transform: translate3d(-2px,0,0); }
.btn-home:active{ transform: translate3d(0,1px,0); }
.form-title{ font-family: var(--fh); font-size: 1.32rem; font-weight: 800; color: var(--txt); position: relative; z-index: 1; letter-spacing: -.015em; }
.form-sub{ font-size: .82rem; color: var(--txt2); margin-top: 3px; position: relative; z-index: 1; }
.mobile-logo{ display: none; margin-bottom: 14px; }
.form-body{ padding: 20px 26px 24px; }

/* ── Alerts ── */
.alert{
  display: flex; align-items: flex-start; gap: 10px;
  padding: 12px 14px;
  border-radius: var(--r1);
  font-size: .85rem; line-height: 1.5;
  margin-bottom: 18px;
}
.alert i{ font-size: 16px; flex-shrink: 0; margin-top: 1px; }
.alert-err{ background: var(--danger-l); border: 1px solid var(--danger-brd); color: #b91c1c; }
.alert-ok { background: rgba(95,204,160,.10); border: 1px solid rgba(95,204,160,.30); color: #047857; }

/* ── Form fields ── */
.fl{ margin-bottom: 14px; }
.fl-lbl{
  font-family: var(--fh);
  font-size: .7rem; font-weight: 700; text-transform: uppercase; letter-spacing: .1em;
  color: var(--txt2); margin-bottom: 6px; display: block;
}
.inp-wrap{ position: relative; }
.inp-ico{
  position: absolute; left: 14px; top: 50%; transform: translateY(-50%);
  color: var(--txt3); font-size: 16px; pointer-events: none;
  transition: color .2s var(--e-out);
}
.inp{
  width: 100%;
  background: var(--soft);
  border: 1px solid var(--line);
  border-radius: var(--r1);
  padding: 12px 14px 12px 42px;
  font-size: .94rem; color: var(--txt);
  outline: none;
  font-family: var(--fs);
  transition: background .25s var(--e-out), border-color .25s var(--e-out), box-shadow .25s var(--e-out);
}
.inp:focus{
  background: var(--paper);
  border-color: var(--sky-d);
  box-shadow: 0 0 0 4px rgba(111,161,247,.12);
}
.inp::placeholder{ color: var(--txt3); opacity: .6; }
.inp.pr{ padding-right: 42px; }
.inp-right{
  position: absolute; right: 8px; top: 50%; transform: translateY(-50%);
  background: none; border: none; color: var(--txt3);
  padding: 8px; font-size: 16px; border-radius: 8px;
  transition: color .2s var(--e-out), background .2s var(--e-out);
}
.inp-right:hover{ color: var(--txt); background: rgba(110,130,170,.08); }

/* ── Options row ── */
.opts{ display: flex; align-items: center; justify-content: space-between; margin-bottom: 14px; }
.link-btn{
  background: none; border: none;
  color: var(--sky-deep); font-size: .82rem; font-weight: 600;
  font-family: var(--fs); padding: 0;
  transition: color .2s var(--e-out);
}
.link-btn:hover{ color: var(--lav-deep); }
.qr-trigger{
  background: var(--soft); border: 1px solid var(--line);
  width: 36px; height: 36px; border-radius: 10px;
  color: var(--txt2);
  display: inline-flex; align-items: center; justify-content: center;
  font-size: 17px;
  transition: all .25s var(--e-spring);
}
.qr-trigger:hover{ color: var(--sky-deep); border-color: var(--sky); transform: translate3d(0,-2px,0); box-shadow: 0 6px 14px -6px rgba(111,161,247,.30); }

/* ── reCAPTCHA wrapper ── */
.recaptcha-wrap{ margin: 14px 0; display: flex; justify-content: center; transform: scale(.92); transform-origin: center; }
@media(max-width:380px){ .recaptcha-wrap{ transform: scale(.82); } }

/* ── 4D Submit button ── */
.btn-submit{
  --b-h: 5px;
  width: 100%;
  padding: 12px 18px;
  border: none; border-radius: 13px;
  background: var(--grad-cta);
  background-size: 180% 180%; background-position: 0% 50%;
  color: #fff;
  font-family: var(--fh); font-weight: 700; font-size: .96rem;
  display: flex; align-items: center; justify-content: center; gap: 8px;
  cursor: pointer;
  transform: translate3d(0,0,0);
  transition: transform .3s var(--e-spring), box-shadow .35s var(--e-soft), background-position .6s var(--e-soft), opacity .25s var(--e-out);
  box-shadow:
    inset 0 1px 0 rgba(255,255,255,.55),
    0 var(--b-h) 0 -2px rgba(60,90,160,.18),
    0 10px 20px -8px rgba(111,161,247,.45),
    0 20px 40px -16px rgba(157,131,238,.30);
}
.btn-submit:hover:not(:disabled){
  transform: translate3d(0,-3px,0);
  background-position: 100% 50%;
  box-shadow:
    inset 0 1px 0 rgba(255,255,255,.65),
    0 calc(var(--b-h) + 3px) 0 -2px rgba(60,90,160,.22),
    0 18px 32px -10px rgba(111,161,247,.7),
    0 32px 60px -14px rgba(157,131,238,.55);
}
.btn-submit:active:not(:disabled){ transform: translate3d(0,1px,0); transition-duration: .12s; }
.btn-submit:disabled{ opacity: .55; cursor: not-allowed; }
.btn-submit i{ transition: transform .3s var(--e-spring); }
.btn-submit:hover:not(:disabled) i{ transform: translate3d(3px,0,0); }

/* ── Divider ── */
.divider{ display: flex; align-items: center; gap: 12px; margin: 18px 0 14px; }
.divider::before, .divider::after{ content: ''; flex: 1; height: 1px; background: var(--line); }
.divider span{ font-family: var(--fh); font-size: .72rem; font-weight: 700; text-transform: uppercase; letter-spacing: .1em; color: var(--txt3); }

/* ── OAuth ── */
.oauth-row{ display: grid; grid-template-columns: repeat(2,1fr); gap: 10px; }
.oauth-btn{
  display: flex; align-items: center; justify-content: center;
  padding: 10px;
  background: var(--paper);
  border: 1px solid var(--line);
  border-radius: 11px;
  min-height: 44px;
  transition: transform .3s var(--e-spring), background .25s var(--e-out), border-color .25s var(--e-out), box-shadow .35s var(--e-soft);
}
.oauth-btn:hover{
  transform: translate3d(0,-3px,0);
  background: var(--soft);
  border-color: var(--sky);
  box-shadow: 0 10px 22px -8px rgba(111,161,247,.30);
}
.oauth-btn img{ height: 22px; border-radius: 4px; }
.oauth-btn i{ font-size: 20px; color: var(--txt2); transition: color .2s var(--e-out); }
.oauth-btn:hover i{ color: var(--sky-deep); }

/* ── Register ── */
.register-row{
  margin-top: 18px; padding-top: 16px;
  border-top: 1px solid var(--line);
  text-align: center;
}
.register-row p{ font-size: .82rem; color: var(--txt2); margin-bottom: 10px; }
.btn-reg{
  display: inline-flex; align-items: center; gap: 8px;
  padding: 10px 20px;
  background: var(--paper);
  border: 1px solid var(--line2);
  border-radius: 11px;
  color: var(--txt);
  font-family: var(--fh); font-size: .9rem; font-weight: 600;
  transition: transform .3s var(--e-spring), background .25s var(--e-out), border-color .25s var(--e-out), box-shadow .35s var(--e-soft);
  box-shadow: 0 3px 0 -2px rgba(110,130,170,.10), 0 6px 14px -8px rgba(110,130,170,.15);
}
.btn-reg:hover{
  transform: translate3d(0,-2px,0);
  background: #fbfcff;
  border-color: var(--sky);
  box-shadow: 0 6px 0 -2px rgba(110,130,170,.14), 0 14px 24px -8px rgba(111,161,247,.22);
}
.btn-reg:active{ transform: translate3d(0,1px,0); }

/* ── Modals ── */
.modal-bd{
  position: fixed; inset: 0;
  background: rgba(27,34,64,.45); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
  z-index: 9000;
  display: none; align-items: center; justify-content: center; padding: 20px;
  opacity: 0;
  transition: opacity .3s var(--e-soft);
}
.modal-bd.open{ display: flex; opacity: 1; }
.modal{
  background: var(--paper);
  border: 1px solid var(--line);
  border-radius: var(--r3);
  width: 100%; max-width: 420px;
  overflow: hidden;
  box-shadow: 0 30px 80px -20px rgba(27,34,64,.35);
  transform: scale(.96);
  transition: transform .4s var(--e-spring);
}
.modal-bd.open .modal{ transform: scale(1); }
.modal-head{
  padding: 20px 24px 16px;
  border-bottom: 1px solid var(--line);
  display: flex; align-items: center; justify-content: space-between;
}
.modal-title{ font-family: var(--fh); font-size: 1.05rem; font-weight: 700; color: var(--txt); display: flex; align-items: center; gap: 10px; }
.modal-title i{ color: var(--sky-deep); }
.modal-close{
  background: var(--soft); border: 1px solid var(--line);
  color: var(--txt2);
  width: 36px; height: 36px; border-radius: 50%;
  display: flex; align-items: center; justify-content: center;
  font-size: 14px;
  transition: transform .35s var(--e-spring), color .2s var(--e-out), background .2s var(--e-out);
}
.modal-close:hover{ transform: rotate(90deg); color: var(--txt); background: var(--paper); }
.modal-body{ padding: 22px 24px; }

/* Forgot password form */
.fl-modal{ margin-bottom: 14px; }
.fl-modal label{ font-family: var(--fh); font-size: .72rem; font-weight: 700; text-transform: uppercase; letter-spacing: .1em; color: var(--txt2); margin-bottom: 8px; display: block; }
.inp-modal{
  width: 100%; background: var(--soft);
  border: 1px solid var(--line); border-radius: var(--r1);
  padding: 12px 14px; font-size: .95rem; color: var(--txt);
  outline: none; font-family: var(--fs);
  transition: background .2s var(--e-out), border-color .2s var(--e-out), box-shadow .2s var(--e-out);
}
.inp-modal:focus{ background: var(--paper); border-color: var(--sky-d); box-shadow: 0 0 0 4px rgba(111,161,247,.12); }
.btn-modal{
  width: 100%; padding: 13px 16px;
  border: none; border-radius: 12px;
  background: var(--grad-cta); color: #fff;
  font-family: var(--fh); font-size: .94rem; font-weight: 700;
  cursor: pointer;
  transition: transform .25s var(--e-spring), box-shadow .3s var(--e-soft);
  box-shadow: inset 0 1px 0 rgba(255,255,255,.45), 0 6px 0 -2px rgba(60,90,160,.2), 0 12px 22px -8px rgba(111,161,247,.5);
}
.btn-modal:hover{ transform: translate3d(0,-2px,0); box-shadow: inset 0 1px 0 rgba(255,255,255,.55), 0 8px 0 -2px rgba(60,90,160,.2), 0 16px 30px -8px rgba(111,161,247,.65); }
.btn-modal:active{ transform: translate3d(0,1px,0); }

/* QR modal */
.qr-wrap{
  background: var(--soft); border: 1px solid var(--line);
  border-radius: var(--r2); padding: 18px;
  display: flex; align-items: center; justify-content: center;
  margin-bottom: 16px; position: relative; overflow: hidden;
}
.qr-img{ width: 280px; height: 280px; max-width: 100%; border-radius: 10px; }
.qr-loading{
  position: absolute; inset: 0;
  background: rgba(255,255,255,.92); backdrop-filter: blur(6px);
  display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px;
  opacity: 0; pointer-events: none; transition: opacity .3s;
}
.qr-loading.on{ opacity: 1; pointer-events: auto; }
.qr-spin{ width: 44px; height: 44px; border-radius: 50%; border: 3px solid var(--line); border-top-color: var(--sky-deep); animation: spin .8s linear infinite; }
@keyframes spin{ to{ transform: rotate(360deg); } }
.qr-spin-lbl{ font-size: .85rem; color: var(--txt); font-weight: 600; }

.qr-steps{ display: flex; flex-direction: column; gap: 8px; }
.qr-step{
  display: flex; align-items: flex-start; gap: 12px;
  padding: 10px 12px;
  background: var(--soft);
  border: 1px solid var(--line);
  border-radius: 10px;
}
.qr-step-n{
  width: 22px; height: 22px; border-radius: 7px; flex-shrink: 0;
  background: var(--grad-cta); color: #fff;
  display: flex; align-items: center; justify-content: center;
  font-family: var(--fh); font-size: .72rem; font-weight: 700;
  box-shadow: 0 4px 8px -2px rgba(111,161,247,.35);
}
.qr-step-t{ font-size: .85rem; color: var(--txt2); line-height: 1.45; }

/* ── Responsive ── */
@media(max-width:980px){
  .wrap{ gap: 36px; }
  .right{ width: 420px; }
}
@media(max-width:860px){
  .wrap{ flex-direction: column; gap: 24px; max-width: 460px; align-items: stretch; }
  .left{ display: none; }
  .right{ width: 100%; }
  .mobile-logo{ display: block; margin: 0 auto 12px; }
  .form-card-head{ text-align: center; }
  .btn-home{ margin: 0 auto 10px; }
}
@media(max-width:520px){
  .form-card{ border-radius: 22px; }
  .form-card-head{ padding: 18px 18px 14px; }
  .form-body{ padding: 18px 18px 22px; }
  .form-title{ font-size: 1.2rem; }
  .form-sub{ font-size: .78rem; }
  .inp{ padding: 11px 14px 11px 40px; font-size: .92rem; }
  .inp-ico{ left: 13px; font-size: 15px; }
  .fl-lbl{ font-size: .68rem; }
  .btn-submit{ padding: 11px 16px; font-size: .92rem; }
  .btn-passkey{ padding: 10px 14px; font-size: .88rem; }
  .oauth-btn{ padding: 9px; min-height: 42px; }
  .divider{ margin: 14px 0 12px; }
  .register-row{ margin-top: 14px; padding-top: 14px; }
}
@media(max-width:380px){
  .form-card-head{ padding: 16px 14px 12px; }
  .form-body{ padding: 16px 14px 20px; }
  .form-title{ font-size: 1.12rem; }
}

/* ── Face ID camera UI ── */
.face-cam-wrap{ position: relative; width: 100%; border-radius: var(--r2); overflow: hidden; background: #1b2240; aspect-ratio: 4/3; }
.face-cam-video{ width: 100%; height: 100%; object-fit: cover; display: block; transform: scaleX(-1); }
.face-cam-canvas{ display: none; }
.face-scan-ring{
  position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);
  width: 160px; height: 160px; border-radius: 50%;
  border: 3px solid rgba(165,200,255,.5);
  box-shadow: 0 0 0 6px rgba(165,200,255,.12);
  pointer-events: none; transition: border-color .3s, box-shadow .3s;
}
.face-scan-ring.scanning{ border-color: var(--sky-d); box-shadow: 0 0 0 6px rgba(111,161,247,.18); animation: faceRingPulse 1.2s ease-in-out infinite; }
.face-scan-ring.ok{ border-color: var(--mint-d); box-shadow: 0 0 0 8px rgba(95,204,160,.22); }
.face-scan-ring.err{ border-color: var(--danger); box-shadow: 0 0 0 8px rgba(239,68,68,.18); }
@keyframes faceRingPulse{ 0%,100%{ transform: translate(-50%,-50%) scale(1); opacity: 1;} 50%{ transform: translate(-50%,-50%) scale(1.06); opacity: .7;} }
.face-corner{ position: absolute; width: 22px; height: 22px; border-color: var(--sky-d); border-style: solid; }
.face-corner.tl{ top: 14px; left: 14px; border-width: 2px 0 0 2px; border-radius: 4px 0 0 0; }
.face-corner.tr{ top: 14px; right: 14px; border-width: 2px 2px 0 0; border-radius: 0 4px 0 0; }
.face-corner.bl{ bottom: 14px; left: 14px; border-width: 0 0 2px 2px; border-radius: 0 0 0 4px; }
.face-corner.br{ bottom: 14px; right: 14px; border-width: 0 2px 2px 0; border-radius: 0 0 4px 0; }
.face-status{
  position: absolute; bottom: 14px; left: 50%; transform: translateX(-50%);
  background: rgba(255,255,255,.92); backdrop-filter: blur(8px);
  border: 1px solid var(--line); border-radius: 100px;
  padding: 6px 14px; font-size: .76rem; font-weight: 600;
  color: var(--txt); white-space: nowrap; transition: all .3s;
}
.face-status.scanning{ color: var(--sky-deep); border-color: var(--sky); }
.face-status.ok { color: var(--mint-d); border-color: rgba(95,204,160,.4); }
.face-status.err{ color: var(--danger); border-color: var(--danger-brd); }
.face-result-card{
  display: none; margin-top: 14px;
  padding: 12px 14px;
  border-radius: var(--r1);
  font-size: .85rem; line-height: 1.5;
}
.face-result-card.ok{ background: rgba(95,204,160,.10); border: 1px solid rgba(95,204,160,.3); color: #047857; }
.face-result-card.err{ background: var(--danger-l); border: 1px solid var(--danger-brd); color: #b91c1c; }
.btn-face{
  width: 100%; padding: 12px 16px;
  border: none; border-radius: 12px;
  font-family: var(--fh); font-size: .92rem; font-weight: 700;
  cursor: pointer;
  display: flex; align-items: center; justify-content: center; gap: 8px;
  margin-top: 12px;
  transition: transform .25s var(--e-spring), box-shadow .3s var(--e-soft), background .25s var(--e-out);
}
.btn-face-start{
  background: var(--soft); border: 1px solid var(--line); color: var(--txt);
  box-shadow: 0 4px 0 -2px rgba(110,130,170,.12);
}
.btn-face-start:hover{ background: var(--paper); border-color: var(--sky); transform: translate3d(0,-2px,0); }
.btn-face-scan{
  background: var(--grad-cta); color: #fff;
  box-shadow: inset 0 1px 0 rgba(255,255,255,.45), 0 6px 0 -2px rgba(60,90,160,.2), 0 12px 22px -8px rgba(111,161,247,.5);
}
.btn-face-scan:hover:not(:disabled){ transform: translate3d(0,-2px,0); box-shadow: inset 0 1px 0 rgba(255,255,255,.55), 0 8px 0 -2px rgba(60,90,160,.2), 0 16px 30px -8px rgba(111,161,247,.65); }
.btn-face-scan:disabled{ opacity: .5; cursor: not-allowed; transform: none; }

/* ── Login chap reklama slayder ── */
.ads-stage{
  position: relative;
  background: var(--paper);
  border: 1px solid var(--line);
  border-radius: var(--r3);
  overflow: hidden;
  margin-bottom: 24px;
  box-shadow: 0 18px 48px -20px rgba(110,130,170,.30);
  --ad-accent: var(--sky-d);
  /* Aspect ratio — left panel ga harmonik to'g'ri keladi */
  aspect-ratio: 4/3;
  max-height: 420px;
}
.ads-slide{
  position: absolute; inset: 0;
  display: flex; flex-direction: column;
  opacity: 0; transform: translate3d(0,8px,0);
  transition: opacity .55s var(--e-soft), transform .55s var(--e-soft);
  pointer-events: none;
}
.ads-slide.active{
  opacity: 1; transform: translate3d(0,0,0);
  pointer-events: auto;
}
.ads-media{
  flex: 1; min-height: 0; position: relative; overflow: hidden;
  background: linear-gradient(135deg, color-mix(in srgb, var(--ad-accent) 30%, transparent), color-mix(in srgb, var(--lav) 35%, transparent));
}
.ads-media::after{
  content:''; position: absolute; inset: 0;
  background: linear-gradient(to top, rgba(15,18,40,.65) 0%, rgba(15,18,40,.15) 50%, transparent 100%);
  pointer-events: none;
}
.ads-media img, .ads-media video{
  width: 100%; height: 100%; object-fit: cover; display: block;
}
.ads-text{
  position: absolute; left: 0; right: 0; bottom: 0;
  padding: 22px 24px 24px;
  color: #fff;
  z-index: 2;
}
/* If no media, give text a soft accent background */
.ads-slide:not(:has(.ads-media)) .ads-text{
  position: relative;
  background: linear-gradient(135deg, color-mix(in srgb, var(--ad-accent) 22%, var(--paper)), color-mix(in srgb, var(--lav) 18%, var(--paper)));
  color: var(--txt);
  height: 100%;
  display: flex; flex-direction: column; justify-content: center;
}
.ads-title{
  font-family: var(--fh);
  font-size: clamp(1.2rem, 2vw, 1.6rem);
  font-weight: 800;
  line-height: 1.15;
  letter-spacing: -.02em;
  margin: 0 0 8px;
  text-shadow: 0 2px 8px rgba(15,18,40,.35);
}
.ads-slide:not(:has(.ads-media)) .ads-title{ text-shadow: none; }
.ads-sub{
  font-size: .92rem;
  line-height: 1.5;
  margin: 0 0 14px;
  opacity: .92;
  max-width: 520px;
  text-shadow: 0 1px 6px rgba(15,18,40,.28);
}
.ads-slide:not(:has(.ads-media)) .ads-sub{ text-shadow: none; opacity: 1; color: var(--txt2); }
.ads-cta{
  display: inline-flex; align-items: center; gap: 8px;
  padding: 9px 16px;
  background: rgba(255,255,255,.95);
  color: #1b2240;
  font-family: var(--fh); font-weight: 700; font-size: .85rem;
  border-radius: 100px;
  text-decoration: none;
  transition: transform .25s var(--e-spring), background .2s var(--e-out), box-shadow .3s var(--e-soft);
  box-shadow: 0 6px 16px -6px rgba(15,18,40,.35);
}
.ads-cta:hover{
  background: #fff;
  transform: translate3d(0,-2px,0);
  box-shadow: 0 10px 22px -8px rgba(15,18,40,.45);
}
.ads-cta i{ font-size: .9rem; transition: transform .25s var(--e-spring); }
.ads-cta:hover i{ transform: translate3d(2px,-2px,0); }
.ads-slide:not(:has(.ads-media)) .ads-cta{
  background: var(--ad-accent);
  color: #fff;
  box-shadow: 0 6px 16px -6px color-mix(in srgb, var(--ad-accent) 60%, transparent);
}

.ads-dots{
  position: absolute; bottom: 12px; left: 50%; transform: translateX(-50%);
  display: flex; gap: 6px; z-index: 3;
  padding: 6px 10px;
  background: rgba(15,18,40,.35);
  backdrop-filter: blur(8px);
  border-radius: 100px;
}
.ads-dot{
  width: 18px; height: 6px; border-radius: 100px;
  background: rgba(255,255,255,.45);
  border: none; cursor: pointer; padding: 0;
  transition: background .25s var(--e-out), width .35s var(--e-spring);
}
.ads-dot:hover{ background: rgba(255,255,255,.7); }
.ads-dot.active{ background: #fff; width: 28px; }

.ads-arrow{
  position: absolute; top: 50%; transform: translateY(-50%);
  width: 36px; height: 36px; border-radius: 50%;
  background: rgba(255,255,255,.92);
  color: #1b2240; border: none; cursor: pointer;
  display: flex; align-items: center; justify-content: center;
  font-size: 16px; z-index: 3;
  opacity: 0;
  transition: opacity .3s var(--e-out), transform .25s var(--e-spring), background .2s var(--e-out);
  box-shadow: 0 6px 16px -6px rgba(15,18,40,.4);
}
.ads-stage:hover .ads-arrow{ opacity: 1; }
.ads-prev{ left: 12px; }
.ads-next{ right: 12px; }
.ads-arrow:hover{ background: #fff; transform: translateY(-50%) scale(1.05); }

/* ── Passkey button (sage accent — distinct from gradient submit) ── */
.btn-passkey{
  width:100%;margin-top:10px;
  display:flex;align-items:center;justify-content:center;gap:9px;
  padding:11px 16px;
  background:#fbfdfa;
  border:1px solid #cfe1d4;
  border-radius:12px;
  color:#3f6b53;
  font-family:var(--fh);font-size:.9rem;font-weight:700;
  cursor:pointer;
  transition:transform .25s var(--e-spring), background .2s var(--e-out), border-color .2s var(--e-out), box-shadow .3s var(--e-soft);
  box-shadow:0 3px 0 -2px rgba(63,107,83,.08), 0 6px 14px -8px rgba(63,107,83,.15);
}
.btn-passkey:hover{
  transform:translate3d(0,-2px,0);
  background:#f4faef;
  border-color:#a9c8b3;
  box-shadow:0 6px 0 -2px rgba(63,107,83,.12), 0 14px 22px -8px rgba(63,107,83,.28);
}
.btn-passkey:active{ transform:translate3d(0,1px,0); }
.btn-passkey:disabled{ opacity:.55; cursor:not-allowed; transform:none; }
.btn-passkey i{ font-size:17px; }
.passkey-msg{
  margin-top:10px;text-align:center;
  font-size:.82rem;font-weight:600;
  min-height:18px;
  transition:color .2s var(--e-out);
}
.passkey-msg.err{ color:#b91c1c; }
.passkey-msg.ok{ color:#047857; }

/* ── Reduced motion ── */
@media (prefers-reduced-motion: reduce){
  *{ animation: none !important; transition: none !important; }
}
</style>
</head>
<body>

<!-- ══════════════════ MODALS ══════════════════ -->
<!-- Forgot password -->
<div class="modal-bd" id="modalForgot">
  <div class="modal" role="dialog" aria-modal="true" aria-labelledby="dlgForgotTitle">
    <div class="modal-head">
      <div class="modal-title" id="dlgForgotTitle"><i class="bi bi-key-fill"></i> Parolni tiklash</div>
      <button class="modal-close" onclick="closeModal('Forgot')" aria-label="Yopish"><i class="bi bi-x-lg"></i></button>
    </div>
    <div class="modal-body">
      <form method="POST" action="<?php echo BUSINESS_URL; ?>/login/password_reset/">
        <div class="fl-modal">
          <label>Telefon raqamingiz</label>
          <input class="inp-modal" type="tel" name="phone" required placeholder="+998 90 123 45 67" pattern="^\+998[0-9]{9}$">
        </div>
        <button class="btn-modal" type="submit" name="forgot_password">SMS yuborish</button>
      </form>
    </div>
  </div>
</div>

<!-- QR Login -->
<div class="modal-bd" id="modalQR">
  <div class="modal" role="dialog" aria-modal="true" aria-labelledby="dlgQRTitle">
    <div class="modal-head">
      <div class="modal-title" id="dlgQRTitle"><i class="bi bi-qr-code"></i> QR orqali kirish</div>
      <button class="modal-close" onclick="closeModal('QR')" aria-label="Yopish"><i class="bi bi-x-lg"></i></button>
    </div>
    <div class="modal-body">
      <div class="qr-wrap">
        <img src="<?=$qr_url?>" id="qrImg" class="qr-img" alt="QR Code">
        <div class="qr-loading" id="qrLoading">
          <div class="qr-spin"></div>
          <div class="qr-spin-lbl">Kirilmoqda...</div>
        </div>
      </div>
      <div class="qr-steps">
        <div class="qr-step"><span class="qr-step-n">1</span><span class="qr-step-t">Mobile ilovada Sozlamalarni oching</span></div>
        <div class="qr-step"><span class="qr-step-n">2</span><span class="qr-step-t">QR login bo'limiga o'ting</span></div>
        <div class="qr-step"><span class="qr-step-n">3</span><span class="qr-step-t">Yuqoridagi QR kodni skanerlang</span></div>
      </div>
    </div>
  </div>
</div>

<!-- ══════════════════ MAIN LAYOUT ══════════════════ -->
<div class="wrap">
  <!-- Left branding (desktop only) -->
  <div class="left">
    <img src="<?php echo BRAND_LOGO; ?>" class="brand-logo" alt="<?php echo BRAND_NAME; ?>" onerror="this.outerHTML='<div style=\'font-family:var(--fh);font-weight:800;font-size:1.6rem;background:linear-gradient(135deg,var(--sky-deep),var(--lav-deep));-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent;margin-bottom:32px\'>inPAY</div>'">

    <?php if (!empty($login_ads)): ?>
      <!-- AD SLIDESHOW (admin/login_ads.php) -->
      <div class="ads-stage" id="adsStage" data-count="<?= count($login_ads) ?>">
        <?php foreach ($login_ads as $i => $ad):
          $accent = !empty($ad['bg_accent']) ? $ad['bg_accent'] : '';
        ?>
        <div class="ads-slide<?= $i===0 ? ' active' : '' ?>"
             data-idx="<?= $i ?>" data-ad="<?= (int)$ad['id'] ?>"
             <?= $accent ? 'style="--ad-accent:'.htmlspecialchars($accent, ENT_QUOTES).'"' : '' ?>>
          <?php if ($ad['media_type']==='image' && !empty($ad['media_path'])): ?>
            <div class="ads-media">
              <img src="<?= htmlspecialchars($ad['media_path'], ENT_QUOTES) ?>"
                   alt="<?= htmlspecialchars($ad['title'] ?? '', ENT_QUOTES) ?>" loading="lazy">
            </div>
          <?php elseif ($ad['media_type']==='video' && !empty($ad['media_path'])): ?>
            <div class="ads-media">
              <video src="<?= htmlspecialchars($ad['media_path'], ENT_QUOTES) ?>"
                     muted loop playsinline preload="metadata"
                     <?= $i===0 ? 'autoplay' : '' ?>></video>
            </div>
          <?php endif; ?>
          <?php if (!empty($ad['title']) || !empty($ad['subtitle']) || !empty($ad['cta_text'])): ?>
          <div class="ads-text">
            <?php if (!empty($ad['title'])): ?>
              <h2 class="ads-title"><?= nl2br(htmlspecialchars($ad['title'])) ?></h2>
            <?php endif; ?>
            <?php if (!empty($ad['subtitle'])): ?>
              <p class="ads-sub"><?= nl2br(htmlspecialchars($ad['subtitle'])) ?></p>
            <?php endif; ?>
            <?php if (!empty($ad['cta_text']) && !empty($ad['cta_url'])): ?>
              <a class="ads-cta" href="<?= htmlspecialchars($ad['cta_url'], ENT_QUOTES) ?>"
                 target="_blank" rel="noopener nofollow">
                <?= htmlspecialchars($ad['cta_text']) ?> <i class="bi bi-arrow-up-right"></i>
              </a>
            <?php endif; ?>
          </div>
          <?php endif; ?>
        </div>
        <?php endforeach; ?>

        <?php if (count($login_ads) > 1): ?>
          <div class="ads-dots" id="adsDots">
            <?php foreach ($login_ads as $i => $_): ?>
              <button type="button" class="ads-dot<?= $i===0 ? ' active' : '' ?>" data-go="<?= $i ?>" aria-label="Slayd <?= $i+1 ?>"></button>
            <?php endforeach; ?>
          </div>
          <button type="button" class="ads-arrow ads-prev" id="adsPrev" aria-label="Oldingi"><i class="bi bi-chevron-left"></i></button>
          <button type="button" class="ads-arrow ads-next" id="adsNext" aria-label="Keyingi"><i class="bi bi-chevron-right"></i></button>
        <?php endif; ?>
      </div>
    <?php else: ?>
      <!-- Static fallback — reklama yo'q paytda -->
      <h1 class="brand-headline">E-commerce<br><span class="grad">platformasi</span></h1>
      <p class="brand-sub">Biznesingizni raqamli darajaga ko'taring va to'lovlarni oson, tez va xavfsiz boshqaring.</p>

      <div class="features">
        <div class="feat">
          <div class="feat-ico"><i class="bi bi-shield-check"></i></div>
          <div><div class="feat-title">Xavfsiz tranzaksiyalar</div><div class="feat-sub">Bank darajasidagi shifrlash va himoya</div></div>
        </div>
        <div class="feat">
          <div class="feat-ico"><i class="bi bi-lightning-charge-fill"></i></div>
          <div><div class="feat-title">Tezkor integratsiya</div><div class="feat-sub">5 daqiqada to'lovlarni qabul qiling</div></div>
        </div>
        <div class="feat">
          <div class="feat-ico"><i class="bi bi-headset"></i></div>
          <div><div class="feat-title">24/7 Qo'llab-quvvatlash</div><div class="feat-sub">Har doim sizning yoningizda</div></div>
        </div>
      </div>
    <?php endif; ?>

    <div class="contact-box">
      <i class="bi bi-telephone-fill"></i>
      <div>
        <div class="contact-lbl">Texnik yordam</div>
        <a href="tel:<?php echo SUPPORT_PHONE_E; ?>" class="contact-val"><?php echo SUPPORT_PHONE; ?></a>
      </div>
    </div>
  </div>

  <!-- Right: form card -->
  <div class="right">
    <div class="form-card">
      <div class="form-card-head">
        <a href="<?php echo BASE_URL; ?>/" class="btn-home" title="Bosh sahifaga qaytish">
          <i class="bi bi-arrow-left"></i> Bosh sahifa
        </a>
        <img src="<?php echo BRAND_LOGO; ?>" class="mobile-logo" style="height:30px" alt="<?php echo BRAND_NAME; ?>" onerror="this.outerHTML=''">
        <div class="form-title">Tizimga kirish</div>
        <div class="form-sub"><?php echo BRAND_NAME; ?> Business platformasi</div>
      </div>
      <div class="form-body">

        <!-- Alerts -->
        <?php if(!empty($error)):?>
        <div class="alert alert-err"><i class="bi bi-exclamation-circle-fill"></i><?=htmlspecialchars($error)?></div>
        <?php endif;?>
        <?php if(!empty($_SESSION['success'])):?>
        <div class="alert alert-ok"><i class="bi bi-check-circle-fill"></i><?=htmlspecialchars($_SESSION['success'])?></div>
        <?php unset($_SESSION['success']);?>
        <?php endif;?>
        <?php if(!empty($_SESSION['error'])):?>
        <div class="alert alert-err"><i class="bi bi-x-circle-fill"></i><?=htmlspecialchars($_SESSION['error'])?></div>
        <?php unset($_SESSION['error']);?>
        <?php endif;?>

        <!-- Login form -->
        <form method="POST" id="loginForm" novalidate>
          <input type="hidden" name="csrf_token" value="<?=htmlspecialchars($_SESSION['csrf_token']??'')?>">

          <div class="fl">
            <label class="fl-lbl">Foydalanuvchi nomi</label>
            <div class="inp-wrap">
              <i class="bi bi-person inp-ico"></i>
              <input class="inp" type="text" name="username" required autocomplete="username" placeholder="username" id="usernameInp">
            </div>
          </div>

          <div class="fl">
            <label class="fl-lbl">Parol</label>
            <div class="inp-wrap">
              <i class="bi bi-lock inp-ico"></i>
              <input class="inp pr" type="password" name="password" id="passInp" required autocomplete="current-password" placeholder="••••••••">
              <button type="button" class="inp-right" id="togglePass" aria-label="Ko'rsatish"><i class="bi bi-eye"></i></button>
            </div>
          </div>

          <div class="opts">
            <button type="button" class="link-btn" onclick="openModal('Forgot')">Parolni unutdingizmi?</button>
            <button type="button" class="qr-trigger" onclick="openModal('QR');startQRPoll()" aria-label="QR Login"><i class="bi bi-qr-code-scan"></i></button>
          </div>

          <?php if (RECAPTCHA_ENABLED): ?>
          <div class="recaptcha-wrap">
            <div class="g-recaptcha" data-sitekey="<?php echo RECAPTCHA_SITE_KEY; ?>" data-callback="enableSubmit" data-theme="light"></div>
          </div>
          <?php endif; ?>

          <button type="submit" class="btn-submit" id="submitBtn" <?php echo RECAPTCHA_ENABLED ? 'disabled' : ''; ?>>
            Kirish <i class="bi bi-arrow-right"></i>
          </button>
        </form>

        <?php if ($passkey_enabled): ?>
        <button type="button" class="btn-passkey" id="passkeyLoginBtn" onclick="loginWithPasskey()">
          <i class="bi bi-fingerprint"></i> <span>Passkey bilan kirish</span>
        </button>
        <div id="passkeyMsg" class="passkey-msg"></div>
        <?php endif; ?>

        <?php if (!empty($oauth_enabled_providers)): ?>
        <div class="divider"><span>yoki</span></div>

        <!-- OAuth — DB-driven (admin/oauth_providers.php) -->
        <div class="oauth-row">
          <?php foreach ($oauth_enabled_providers as $_p): ?>
            <a href="<?= htmlspecialchars($_p['authorize_url'], ENT_QUOTES) ?>"
               class="oauth-btn"
               title="<?= htmlspecialchars($_p['display_name']) ?> bilan kirish">
              <?php if (!empty($_p['logo_url'])): ?>
                <img src="<?= htmlspecialchars($_p['logo_url'], ENT_QUOTES) ?>"
                     alt="<?= htmlspecialchars($_p['display_name']) ?>"
                     onerror="this.outerHTML='<i class=\'bi <?= htmlspecialchars($_p['icon'] ?: 'bi-box-arrow-in-right', ENT_QUOTES) ?>\' style=\'font-size:18px;color:var(--txt2)\'></i>'">
              <?php else: ?>
                <i class="bi <?= htmlspecialchars($_p['icon'] ?: 'bi-box-arrow-in-right') ?>"></i>
              <?php endif; ?>
            </a>
          <?php endforeach; unset($_p); ?>
        </div>
        <?php endif; ?>

        <!-- Register -->
        <div class="register-row">
          <p>Akkountingiz yo'qmi?</p>
          <a href="<?php echo BUSINESS_URL; ?>/register" class="btn-reg">
            Ro'yxatdan o'tish <i class="bi bi-arrow-right" style="font-size:.85rem"></i>
          </a>
        </div>

        <!-- Mobile contact -->
        <div style="margin-top:18px;padding-top:18px;border-top:1px solid var(--line);text-align:center;display:none" id="mobileContact">
          <div style="font-size:.7rem;color:var(--txt3);margin-bottom:6px;text-transform:uppercase;letter-spacing:.1em;font-weight:700">Texnik yordam</div>
          <a href="tel:<?php echo SUPPORT_PHONE_E; ?>" style="font-family:var(--fh);font-size:1rem;font-weight:700;color:var(--txt);display:inline-flex;align-items:center;gap:8px">
            <i class="bi bi-telephone-fill" style="color:var(--sky-deep)"></i> <?php echo SUPPORT_PHONE; ?>
          </a>
        </div>

      </div>
    </div>
  </div>
</div>

<!-- ══════════════════ FACE ID MODAL ══════════════════ -->
<div class="modal-bd" id="modalFace">
  <div class="modal" role="dialog" aria-modal="true" aria-labelledby="dlgFaceTitle" style="max-width:440px;">
    <div class="modal-head">
      <div class="modal-title" id="dlgFaceTitle">
        <i class="bi bi-person-bounding-box"></i> Face ID orqali kirish
      </div>
      <button class="modal-close" onclick="closeFaceModal()" aria-label="Yopish">
        <i class="bi bi-x-lg"></i>
      </button>
    </div>
    <div class="modal-body">
      <div class="face-cam-wrap" id="faceCamWrap">
        <video id="faceLoginVideo" class="face-cam-video" autoplay playsinline muted></video>
        <canvas id="faceLoginCanvas" class="face-cam-canvas" width="640" height="480"></canvas>
        <div class="face-scan-ring" id="faceScanRing"></div>
        <div class="face-corner tl"></div>
        <div class="face-corner tr"></div>
        <div class="face-corner bl"></div>
        <div class="face-corner br"></div>
        <div class="face-status" id="faceStatusLabel">Kamerani yoqing</div>
      </div>

      <div class="face-result-card" id="faceLoginResult"></div>

      <button class="btn-face btn-face-start" id="btnFaceStartCam" onclick="startFaceCam()">
        <i class="bi bi-camera-video"></i> Kamerani yoqish
      </button>
      <button class="btn-face btn-face-scan" id="btnFaceScan" disabled onclick="scanFaceLogin()">
        <i class="bi bi-person-check"></i> Yuzni aniqlash
      </button>

      <div style="margin-top:14px;padding-top:14px;border-top:1px solid var(--line);text-align:center;">
        <span style="font-size:.78rem;color:var(--txt2);">
          <i class="bi bi-info-circle" style="margin-right:4px;color:var(--sky-deep)"></i>
          Ro'yxatdan o'tgan yuzlar tizimga kirishi mumkin
        </span>
      </div>
    </div>
  </div>
</div>

<script>
window.INPAY = {
  baseUrl:     <?php echo json_encode(BASE_URL); ?>,
  businessUrl: <?php echo json_encode(BUSINESS_URL); ?>,
  qrToken:     <?php echo json_encode($qr_token); ?>
};

/* ═══════════════════════════════════════════
   FACE ID LOGIN
═══════════════════════════════════════════ */
let faceStream = null;

function openFaceModal(){
  document.getElementById('modalFace').classList.add('open');
  document.body.style.overflow = 'hidden';
  resetFaceModal();
}
function closeFaceModal(){
  document.getElementById('modalFace').classList.remove('open');
  document.body.style.overflow = '';
  stopFaceCam(); resetFaceModal();
}
function resetFaceModal(){
  setFaceStatus('', 'Kamerani yoqing');
  const res = document.getElementById('faceLoginResult');
  res.style.display = 'none'; res.className = 'face-result-card';
  document.getElementById('btnFaceScan').disabled = true;
  document.getElementById('btnFaceStartCam').style.display = 'flex';
}
function stopFaceCam(){
  if (faceStream){ faceStream.getTracks().forEach(t => t.stop()); faceStream = null; }
}
function setFaceStatus(type, text){
  const ring  = document.getElementById('faceScanRing');
  const label = document.getElementById('faceStatusLabel');
  ring.className  = 'face-scan-ring'  + (type ? ' ' + type : '');
  label.className = 'face-status' + (type ? ' ' + type : '');
  label.textContent = text;
}
function showFaceLoginResult(type, html){
  const el = document.getElementById('faceLoginResult');
  el.className = 'face-result-card ' + type;
  el.innerHTML = html;
  el.style.display = 'block';
}
async function startFaceCam(){
  const btn = document.getElementById('btnFaceStartCam');
  btn.disabled = true;
  btn.innerHTML = '<i class="bi bi-hourglass-split"></i> Kamera ochilmoqda...';
  try {
    faceStream = await navigator.mediaDevices.getUserMedia({
      video: { facingMode: 'user', width: { ideal: 640 }, height: { ideal: 480 } }
    });
    document.getElementById('faceLoginVideo').srcObject = faceStream;
    btn.style.display = 'none';
    document.getElementById('btnFaceScan').disabled = false;
    setFaceStatus('scanning', 'Yuzingizni to\'g\'rilang...');
  } catch(e){
    btn.disabled = false;
    btn.innerHTML = '<i class="bi bi-camera-video"></i> Kamerani yoqish';
    showFaceLoginResult('err', '❌ Kameraga ruxsat berilmadi. Brauzer sozlamalarini tekshiring.');
    setFaceStatus('err', 'Kamera xatosi');
  }
}
function captureFaceFrame(){
  const video  = document.getElementById('faceLoginVideo');
  const canvas = document.getElementById('faceLoginCanvas');
  const ctx    = canvas.getContext('2d');
  ctx.save();
  ctx.translate(canvas.width, 0);
  ctx.scale(-1, 1);
  ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
  ctx.restore();
  return canvas.toDataURL('image/jpeg', 0.88).split(',')[1];
}
async function scanFaceLogin(){
  const btn = document.getElementById('btnFaceScan');
  btn.disabled = true;
  btn.innerHTML = '<i class="bi bi-arrow-repeat" style="animation:spin .8s linear infinite;display:inline-block"></i> Aniqlanmoqda...';
  document.getElementById('faceLoginResult').style.display = 'none';
  setFaceStatus('scanning', 'Yuz aniqlanmoqda...');

  try {
    const image = captureFaceFrame();
    const faceResp = await fetch(INPAY.businessUrl + '/login/face/proxy/', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action: 'identify', image })
    });
    const faceData = await faceResp.json();

    if (!faceData.ok || !faceData.user_id){
      setFaceStatus('err', 'Yuz tanilmadi');
      showFaceLoginResult('err', '❌ Yuz aniqlanmadi. Yaxshi yoritilgan joyda qaytadan urinib ko\'ring.');
      btn.disabled = false; btn.innerHTML = '<i class="bi bi-person-check"></i> Qaytadan urinish';
      return;
    }

    const similarity = Math.round((faceData.similarity || 0) * 100);
    const loginResp = await fetch(INPAY.businessUrl + '/login/face/', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ face_user_id: faceData.user_id, similarity: faceData.similarity })
    });
    const loginData = await loginResp.json();

    if (loginData.success){
      setFaceStatus('ok', `✅ Xush kelibsiz! (${similarity}%)`);
      showFaceLoginResult('ok',
        `✅ <strong>${loginData.username || 'Foydalanuvchi'}</strong> sifatida kirildi!
         &nbsp;<span style="opacity:.7;font-size:.78rem;">O'xshashlik: ${similarity}%</span>
         <br><span style="font-size:.78rem;">Yo'naltirilmoqda...</span>`);
      stopFaceCam();
      setTimeout(() => { window.location.href = INPAY.businessUrl + '/'; }, 1500);
    } else {
      setFaceStatus('err', 'Kirish rad etildi');
      showFaceLoginResult('err', '❌ ' + (loginData.message || 'Tizimga kirish rad etildi.'));
      btn.disabled = false; btn.innerHTML = '<i class="bi bi-person-check"></i> Qaytadan urinish';
    }
  } catch(e){
    setFaceStatus('err', 'Xatolik');
    showFaceLoginResult('err', '❌ Server bilan aloqa xatosi. Qaytadan urinib ko\'ring.');
    btn.disabled = false; btn.innerHTML = '<i class="bi bi-person-check"></i> Qaytadan urinish';
  }
}
document.getElementById('modalFace')?.addEventListener('click', function(e){
  if (e.target === this) closeFaceModal();
});

/* ── reCAPTCHA callback ── */
function enableSubmit(){ const b = document.getElementById('submitBtn'); if (b) b.disabled = false; }

/* ── Password show/hide toggle ── */
document.getElementById('togglePass')?.addEventListener('click', function(){
  const p = document.getElementById('passInp');
  const i = this.querySelector('i');
  if (p.type === 'password'){ p.type = 'text'; i.className = 'bi bi-eye-slash'; }
  else { p.type = 'password'; i.className = 'bi bi-eye'; }
});

/* ── Input focus icon color ── */
document.querySelectorAll('.inp').forEach(inp => {
  inp.addEventListener('focus', () => { const ico = inp.parentNode.querySelector('.inp-ico'); if (ico) ico.style.color = 'var(--sky-deep)'; });
  inp.addEventListener('blur',  () => { const ico = inp.parentNode.querySelector('.inp-ico'); if (ico) ico.style.color = ''; });
});

/* ── Modals ── */
function openModal(name){ const m = document.getElementById('modal'+name); if (m){ m.classList.add('open'); document.body.style.overflow = 'hidden'; } }
function closeModal(name){ const m = document.getElementById('modal'+name); if (m){ m.classList.remove('open'); document.body.style.overflow = ''; } }
document.querySelectorAll('.modal-bd').forEach(m => {
  m.addEventListener('click', function(e){ if (e.target === this){ const n = this.id.replace('modal',''); closeModal(n); } });
});
document.addEventListener('keydown', e => {
  if (e.key === 'Escape') document.querySelectorAll('.modal-bd.open').forEach(m => { const n = m.id.replace('modal',''); closeModal(n); });
});

/* ── QR poll ── */
let qrInterval = null;
function startQRPoll(){
  if (qrInterval) return;
  qrInterval = setInterval(() => {
    fetch(INPAY.businessUrl + '/login/qr_login/?token=' + encodeURIComponent(INPAY.qrToken))
      .then(r => r.json()).then(d => {
        if (d?.success){
          document.getElementById('qrLoading')?.classList.add('on');
          clearInterval(qrInterval); qrInterval = null;
          setTimeout(() => window.location.href = INPAY.businessUrl + '/', 700);
        }
      }).catch(() => {});
  }, 2000);
}
document.getElementById('modalQR')?.querySelector('.modal-close')?.addEventListener('click', () => {
  if (qrInterval){ clearInterval(qrInterval); qrInterval = null; }
});

/* ── Mobile contact show ── */
function checkMobile(){
  const mc = document.getElementById('mobileContact');
  if (mc) mc.style.display = window.innerWidth <= 860 ? 'block' : 'none';
}
checkMobile(); window.addEventListener('resize', checkMobile);

document.addEventListener('touchstart', function(){}, { passive: true });

/* ═══════════════════════════════════════════
   AD SLIDESHOW (chap panel — desktop)
   - Auto-advance 6s; pause on hover/focus; pause when tab is hidden
   - Manual dots + arrow nav
   - Video slides: rewind+play on become active, pause when leaving
═══════════════════════════════════════════ */
(function(){
  var stage = document.getElementById('adsStage');
  if (!stage) return;
  var slides = stage.querySelectorAll('.ads-slide');
  var dots   = stage.querySelectorAll('.ads-dot');
  var prev   = document.getElementById('adsPrev');
  var next   = document.getElementById('adsNext');
  if (slides.length <= 1){
    // Bitta slayd — videoni boshlatamiz xolos.
    var v0 = stage.querySelector('.ads-slide.active video'); if (v0) try{ v0.play(); }catch(_){}
    return;
  }
  var i = 0;
  var TICK = 6000;
  var t = null, paused = false;

  function activate(idx){
    if (idx === i) return;
    slides[i].classList.remove('active');
    dots[i].classList.remove('active');
    var oldVid = slides[i].querySelector('video'); if (oldVid){ try{ oldVid.pause(); }catch(_){} }
    i = (idx + slides.length) % slides.length;
    slides[i].classList.add('active');
    dots[i].classList.add('active');
    var newVid = slides[i].querySelector('video');
    if (newVid){
      try{ newVid.currentTime = 0; newVid.play(); }catch(_){}
    }
  }
  function tick(){ if (!paused) activate(i + 1); }
  function startTimer(){ stopTimer(); t = setInterval(tick, TICK); }
  function stopTimer(){ if (t){ clearInterval(t); t = null; } }
  function pause(){ paused = true; }
  function resume(){ paused = false; }

  dots.forEach(function(d, k){
    d.addEventListener('click', function(){
      activate(k);
      startTimer();
    });
  });
  if (prev) prev.addEventListener('click', function(){ activate(i - 1); startTimer(); });
  if (next) next.addEventListener('click', function(){ activate(i + 1); startTimer(); });

  stage.addEventListener('mouseenter', pause);
  stage.addEventListener('mouseleave', resume);
  stage.addEventListener('focusin',  pause);
  stage.addEventListener('focusout', resume);
  document.addEventListener('visibilitychange', function(){
    if (document.hidden) pause(); else resume();
  });

  // Birinchi videoni boshlatish (autoplay attr bo'lsa ham, ba'zi brauzerlarda muted talabi bo'ladi)
  var firstVid = slides[0].querySelector('video');
  if (firstVid) try{ firstVid.play(); }catch(_){}

  startTimer();
})();

/* ═══════════════════════════════════════════
   PASSKEY LOGIN (WebAuthn)
   - If username field has a value, server narrows allowCredentials to that
     user. Otherwise the browser shows ALL discoverable credentials bound
     to this RP — true passwordless UX.
═══════════════════════════════════════════ */
function pkB64UrlToBytes(s){
  s = String(s).replace(/-/g,'+').replace(/_/g,'/');
  while (s.length % 4) s += '=';
  const bin = atob(s);
  const out = new Uint8Array(bin.length);
  for (let i=0;i<bin.length;i++) out[i] = bin.charCodeAt(i);
  return out;
}
function pkBytesToB64Url(buf){
  const b = new Uint8Array(buf);
  let s = ''; for (let i=0;i<b.length;i++) s += String.fromCharCode(b[i]);
  return btoa(s).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,'');
}
function pkSetMsg(type, text){
  const el = document.getElementById('passkeyMsg');
  if (!el) return;
  el.className = 'passkey-msg' + (type ? ' '+type : '');
  el.textContent = text || '';
}
async function loginWithPasskey(){
  const btn = document.getElementById('passkeyLoginBtn');
  if (!btn) return;
  if (!window.PublicKeyCredential || !navigator.credentials){
    pkSetMsg('err', "Brauzer Passkey'ni qo'llab-quvvatlamaydi");
    return;
  }
  btn.disabled = true;
  const orig = btn.innerHTML;
  btn.innerHTML = '<i class="bi bi-arrow-repeat" style="animation:spin .8s linear infinite;display:inline-block"></i> <span>Tayyorlanmoqda…</span>';
  pkSetMsg('', '');

  try {
    const username = (document.getElementById('usernameInp')?.value || '').trim();
    const optsResp = await fetch(INPAY.businessUrl + '/login/passkey/auth_options.php', {
      method:'POST',
      credentials:'same-origin',
      headers:{'Content-Type':'application/json'},
      body: JSON.stringify({ username })
    });
    if (!optsResp.ok) throw new Error('options HTTP '+optsResp.status);
    const opts = await optsResp.json();

    const publicKey = {
      challenge: pkB64UrlToBytes(opts.challenge),
      rpId: opts.rpId,
      timeout: opts.timeout || 60000,
      userVerification: opts.userVerification || 'required',
      allowCredentials: (opts.allowCredentials||[]).map(c => ({
        type: c.type, id: pkB64UrlToBytes(c.id),
      })),
    };

    btn.innerHTML = '<i class="bi bi-fingerprint"></i> <span>Qurilmangiz tasdiqlashini kutmoqda…</span>';
    const cred = await navigator.credentials.get({ publicKey });
    if (!cred) throw new Error('no credential');

    const r = cred.response;
    const payload = {
      id: cred.id,
      rawId: pkBytesToB64Url(cred.rawId),
      type: cred.type,
      response: {
        clientDataJSON:    pkBytesToB64Url(r.clientDataJSON),
        authenticatorData: pkBytesToB64Url(r.authenticatorData),
        signature:         pkBytesToB64Url(r.signature),
        userHandle:        r.userHandle ? pkBytesToB64Url(r.userHandle) : null,
      },
    };

    btn.innerHTML = '<i class="bi bi-shield-check"></i> <span>Tekshirilmoqda…</span>';
    const verifyResp = await fetch(INPAY.businessUrl + '/login/passkey/auth_verify.php', {
      method:'POST',
      credentials:'same-origin',
      headers:{'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest'},
      body: JSON.stringify(payload)
    });
    const text = await verifyResp.text();
    let data = null;
    try { data = JSON.parse(text); } catch(_) {}
    if (data && data.success){
      pkSetMsg('ok', "Xush kelibsiz! Yo'naltirilmoqda…");
      setTimeout(() => { window.location.assign(data.redirect || (INPAY.businessUrl + '/')); }, 500);
      return;
    }
    const why = (data && (data.detail || data.error)) || ('HTTP '+verifyResp.status);
    throw new Error(why);
  } catch(e){
    const msg = (e && e.message) ? e.message : 'unknown';
    pkSetMsg('err', "Passkey kirishi: " + msg);
    btn.disabled = false;
    btn.innerHTML = orig;
    console.warn('[passkey login]', e);
  }
}
</script>
</body>
</html>
