<?php
session_start();

if (!isset($_SESSION["user_id"]) || $_SESSION["role"] !== "admin") {
    header("Location: ../auth/login.php");
    exit;
}

require_once '../config/database.php';

function safeCount($pdo, $sql) {
    try { return (int)$pdo->query($sql)->fetchColumn(); }
    catch (Throwable $e) { return 0; }
}

$totalCustomers  = safeCount($pdo, "SELECT COUNT(*) FROM customers");
$totalPartners   = safeCount($pdo, "SELECT COUNT(*) FROM partner_shops");
$pendingReqs     = safeCount($pdo, "SELECT COUNT(*) FROM credit_requests WHERE status='pending'");
$todayTx         = safeCount($pdo, "SELECT COUNT(*) FROM transactions WHERE DATE(created_at)=CURDATE()");
$totalCompanies  = safeCount($pdo, "SELECT COUNT(*) FROM companies WHERE status='active'");
$totalStaffAll   = safeCount($pdo, "SELECT COUNT(*) FROM company_staff");
$pendingLeaveAll = safeCount($pdo, "SELECT COUNT(*) FROM hr_leave WHERE status='pending'");
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;500;600;700;800&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <script src="../assets/lang.js" defer></script>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }

        :root {
            --primary:    #2563eb;
            --primary-dk: #1e3a5f;
            --green:      #16a34a;
            --green-lt:   #dcfce7;
            --amber:      #d97706;
            --amber-lt:   #fef3c7;
            --red:        #dc2626;
            --red-lt:     #fee2e2;
            --purple:     #7c3aed;
            --purple-lt:  #ede9fe;
            --teal:       #0f766e;
            --teal-lt:    #ccfbf1;
            --surface:    #ffffff;
            --bg:         #f0f4f8;
            --border:     #e2e8f0;
            --text:       #0f172a;
            --muted:      #64748b;
            --radius:     16px;
            --shadow:     0 2px 14px rgba(15,23,42,.09);
        }

        body {
            font-family: "Noto Sans Lao", "Inter", Arial, sans-serif;
            background: var(--bg);
            color: var(--text);
            min-height: 100vh;
            padding: 0;
        }

        /* ── Top bar ── */
        .top-bar {
            background: var(--surface);
            border-bottom: 1px solid var(--border);
            padding: 12px 32px;
            display: flex;
            justify-content: flex-end;
            align-items: center;
            gap: 16px;
            position: sticky;
            top: 0;
            z-index: 100;
            box-shadow: 0 1px 6px rgba(15,23,42,.06);
        }

        .lang-bar { display: flex; align-items: center; gap: 6px; margin-bottom: 0; }
        .lang-label { font-size: 12px; color: var(--muted); font-weight: 500; }
        .lang-btn {
            display: inline-flex; align-items: center; gap: 5px;
            padding: 5px 13px; border-radius: 999px;
            border: 1.5px solid var(--border);
            background: var(--surface);
            font-size: 12px; font-weight: 700; color: var(--muted);
            cursor: pointer; font-family: inherit;
            transition: border-color .15s, color .15s, background .15s;
        }
        .lang-btn:hover  { border-color: var(--primary); color: var(--primary); }
        .lang-btn.active { background: var(--primary); border-color: var(--primary); color: #fff; }

        .top-bar-user { display: flex; align-items: center; gap: 10px; font-size: 13px; color: var(--muted); }
        .avatar {
            width: 34px; height: 34px;
            background: linear-gradient(135deg, #1e3a5f, #2563eb);
            border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            color: #fff; font-weight: 800; font-size: 14px; flex-shrink: 0;
        }
        .logout-link {
            display: inline-flex; align-items: center; gap: 5px;
            background: var(--red-lt); color: var(--red);
            border: 1.5px solid #fca5a5;
            padding: 6px 14px; border-radius: 8px;
            text-decoration: none; font-size: 12px; font-weight: 700;
            transition: background .15s, color .15s;
        }
        .logout-link:hover { background: var(--red); color: #fff; }

        /* ── Page body ── */
        .page-body { padding: 28px 32px; max-width: 1280px; margin: auto; }

        /* ── Hero ── */
        .hero {
            background: linear-gradient(135deg, #0f2444 0%, #1e3a5f 55%, #1d4ed8 100%);
            border-radius: 20px;
            padding: 32px 36px;
            margin-bottom: 28px;
            color: #fff;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 20px;
            box-shadow: 0 8px 32px rgba(15,23,42,.18);
            position: relative;
            overflow: hidden;
        }
        .hero::before, .hero::after {
            content: ""; position: absolute; border-radius: 50%; opacity: .08; background: #fff;
        }
        .hero::before { width: 280px; height: 280px; right: -60px; top: -80px; }
        .hero::after  { width: 180px; height: 180px; right: 120px; bottom: -60px; }

        .hero-left h1 { font-size: 30px; font-weight: 800; line-height: 1.2; margin-bottom: 6px; }
        .hero-left .subtitle { font-size: 14px; color: rgba(255,255,255,.72); }
        .hero-left .welcome-name { font-size: 15px; color: rgba(255,255,255,.9); font-weight: 600; margin-top: 8px; }

        .hero-badges { display: flex; gap: 12px; flex-wrap: wrap; position: relative; z-index: 1; }
        .hero-badge {
            background: rgba(255,255,255,.12);
            border: 1px solid rgba(255,255,255,.22);
            border-radius: 12px;
            padding: 14px 20px;
            font-size: 13px;
            color: rgba(255,255,255,.85);
            text-align: center;
            min-width: 130px;
        }
        .hero-badge .badge-val { font-size: 28px; font-weight: 800; color: #fff; display: block; margin-bottom: 4px; }

        /* ── Stat row ── */
        .stat-row {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
            gap: 14px;
            margin-bottom: 28px;
        }
        .stat-card {
            background: var(--surface);
            border-radius: var(--radius);
            padding: 18px 20px;
            box-shadow: var(--shadow);
            border: 1px solid var(--border);
            display: flex;
            align-items: center;
            gap: 14px;
        }
        .stat-icon {
            width: 48px; height: 48px; border-radius: 12px;
            display: flex; align-items: center; justify-content: center;
            font-size: 22px; flex-shrink: 0;
        }
        .stat-icon.blue   { background: #dbeafe; }
        .stat-icon.green  { background: var(--green-lt); }
        .stat-icon.amber  { background: var(--amber-lt); }
        .stat-icon.purple { background: var(--purple-lt); }
        .stat-icon.teal   { background: var(--teal-lt); }
        .stat-icon.pink   { background: #fce7f3; }

        .stat-info .val { font-size: 26px; font-weight: 800; color: var(--text); line-height: 1; }
        .stat-info .lbl { font-size: 12px; color: var(--muted); font-weight: 600; margin-top: 3px; text-transform: uppercase; letter-spacing: .4px; }

        /* ── Section title ── */
        .section-title {
            font-size: 13px; font-weight: 700; color: var(--muted);
            text-transform: uppercase; letter-spacing: .6px;
            margin-bottom: 14px;
        }

        /* ── Menu grid ── */
        .menu-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
            gap: 14px;
            margin-bottom: 28px;
        }
        .menu-card {
            background: var(--surface);
            border-radius: var(--radius);
            padding: 22px;
            box-shadow: var(--shadow);
            text-decoration: none;
            color: var(--text);
            border: 1px solid var(--border);
            display: flex;
            flex-direction: column;
            gap: 10px;
            transition: transform .18s, box-shadow .18s, border-color .18s;
            position: relative;
            overflow: hidden;
        }
        .menu-card::before {
            content: "";
            position: absolute; top: 0; left: 0; right: 0; height: 3px;
            background: var(--accent, var(--primary));
            opacity: 0; transition: opacity .18s;
        }
        .menu-card:hover { transform: translateY(-4px); box-shadow: 0 10px 30px rgba(15,23,42,.13); border-color: #93c5fd; }
        .menu-card:hover::before { opacity: 1; }
        .menu-card .card-icon {
            width: 44px; height: 44px; border-radius: 12px;
            display: flex; align-items: center; justify-content: center;
            font-size: 22px; background: var(--icon-bg, #dbeafe);
        }
        .menu-card h3 { font-size: 15px; font-weight: 700; color: var(--text); line-height: 1.3; }
        .menu-card p  { font-size: 12px; color: var(--muted); line-height: 1.55; }

        .card-blue   { --accent: #2563eb; --icon-bg: #dbeafe; }
        .card-green  { --accent: #16a34a; --icon-bg: #dcfce7; }
        .card-amber  { --accent: #d97706; --icon-bg: #fef3c7; }
        .card-purple { --accent: #7c3aed; --icon-bg: #ede9fe; }
        .card-teal   { --accent: #0f766e; --icon-bg: #ccfbf1; }
        .card-pink   { --accent: #db2777; --icon-bg: #fce7f3; }
        .card-indigo { --accent: #4f46e5; --icon-bg: #e0e7ff; }

        .pending-dot {
            position: absolute; top: 16px; right: 16px;
            background: var(--red); color: #fff;
            font-size: 11px; font-weight: 800;
            padding: 2px 8px; border-radius: 999px;
        }

        /* ── Footer ── */
        .footer-row {
            display: flex; align-items: center;
            justify-content: space-between;
            flex-wrap: wrap; gap: 10px;
            padding-top: 10px;
            border-top: 1px solid var(--border);
            font-size: 12px; color: var(--muted);
        }

        @media (max-width: 700px) {
            .page-body { padding: 16px; }
            .top-bar   { padding: 10px 16px; }
            .hero      { padding: 22px 20px; }
            .hero-left h1 { font-size: 22px; }
        }
    </style>
</head>
<body>

<!-- ── Top bar ── -->
<div class="top-bar">
    <div class="lang-bar">
        <span class="lang-label">ພາສາ / Language:</span>
        <button class="lang-btn" id="btn-lo" onclick="setLang('lo')">🇱🇦 ລາວ</button>
        <button class="lang-btn" id="btn-en" onclick="setLang('en')">🇬🇧 English</button>
    </div>
    <div class="top-bar-user">
        <div class="avatar"><?= strtoupper(mb_substr($_SESSION["name"] ?? "A", 0, 1)) ?></div>
        <span><?= htmlspecialchars($_SESSION["name"]) ?></span>
    </div>
    <a class="logout-link" href="../auth/logout.php">
        🚪 <span data-lo="ອອກຈາກລະບົບ" data-en="Logout">ອອກຈາກລະບົບ</span>
    </a>
</div>

<div class="page-body">

    <!-- ── Hero ── -->
    <div class="hero">
        <div class="hero-left">
            <h1 data-lo="ໜ້າຄວບຄຸມຜູ້ດູແລ" data-en="Admin Dashboard">ໜ້າຄວບຄຸມຜູ້ດູແລ</h1>
            <div class="subtitle" data-lo="Seven Digital Credit System" data-en="Seven Digital Credit System">
                Seven Digital Credit System
            </div>
            <div class="welcome-name">
                👋 <span data-lo="ຍິນດີຕ້ອນຮັບ," data-en="Welcome,">ຍິນດີຕ້ອນຮັບ,</span>
                <?= htmlspecialchars($_SESSION["name"]) ?>
            </div>
        </div>

        <div class="hero-badges">
            <div class="hero-badge">
                <span class="badge-val" id="heroPending"><?= $pendingReqs ?></span>
                <span data-lo="ຄຳຮ້ອງລໍຖ້າ" data-en="Pending Requests">ຄຳຮ້ອງລໍຖ້າ</span>
            </div>
            <div class="hero-badge">
                <span class="badge-val" id="heroCompanies"><?= $totalCompanies ?></span>
                <span data-lo="ບໍລິສັດ" data-en="Companies">ບໍລິສັດ</span>
            </div>
            <div class="hero-badge">
                <span class="badge-val" id="heroLeave"><?= $pendingLeaveAll ?></span>
                <span data-lo="ລາພັກລໍຖ້າ" data-en="Leave Pending">ລາພັກລໍຖ້າ</span>
            </div>
        </div>
    </div>

    <!-- ── Stats ── -->
    <div class="stat-row">
        <div class="stat-card">
            <div class="stat-icon blue">👥</div>
            <div class="stat-info">
                <div class="val" id="statCustomers"><?= number_format($totalCustomers) ?></div>
                <div class="lbl" data-lo="ລູກຄ້າທັງໝົດ" data-en="Total Customers">ລູກຄ້າທັງໝົດ</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon green">🏪</div>
            <div class="stat-info">
                <div class="val" id="statPartners"><?= number_format($totalPartners) ?></div>
                <div class="lbl" data-lo="ຮ້ານຄ້າ Partner" data-en="Partner Shops">ຮ້ານຄ້າ Partner</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon teal">🏢</div>
            <div class="stat-info">
                <div class="val" id="statCompanies"><?= number_format($totalCompanies) ?></div>
                <div class="lbl" data-lo="ບໍລິສັດ" data-en="Companies">ບໍລິສັດ</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon pink">👤</div>
            <div class="stat-info">
                <div class="val" id="statStaff"><?= number_format($totalStaffAll) ?></div>
                <div class="lbl" data-lo="ພະນັກງານທັງໝົດ" data-en="Total Staff">ພະນັກງານທັງໝົດ</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon amber">⏳</div>
            <div class="stat-info">
                <div class="val" id="statPending"><?= number_format($pendingReqs) ?></div>
                <div class="lbl" data-lo="ຄຳຮ້ອງລໍຖ້າ" data-en="Pending Requests">ຄຳຮ້ອງລໍຖ້າ</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon purple">📊</div>
            <div class="stat-info">
                <div class="val" id="statTodayTx"><?= number_format($todayTx) ?></div>
                <div class="lbl" data-lo="ທຸລະກຳມື້ນີ້" data-en="Today's Transactions">ທຸລະກຳມື້ນີ້</div>
            </div>
        </div>
    </div>

    <!-- ── Web system menu ── -->
    <div class="section-title" data-lo="ລະບົບ Web" data-en="Web System">
        ລະບົບ Web / Web System
    </div>
    <div class="menu-grid">
        <a class="menu-card card-blue" href="customers.php">
            <div class="card-icon">👥</div>
            <h3 data-lo="ລູກຄ້າ" data-en="Customers">ລູກຄ້າ</h3>
            <p  data-lo="ເບິ່ງ, ແກ້ໄຂ, ລຶບ ແລະ ຣີເຊັດລະຫັດຜ່ານລູກຄ້າ"
                data-en="View, edit, delete and reset customer passwords.">
                ເບິ່ງ, ແກ້ໄຂ, ລຶບ ແລະ ຣີເຊັດລະຫັດຜ່ານລູກຄ້າ
            </p>
        </a>
        <a class="menu-card card-green" href="partners.php">
            <div class="card-icon">🏪</div>
            <h3 data-lo="ຮ້ານຄ້າ Partner" data-en="Partner Shops">ຮ້ານຄ້າ Partner</h3>
            <p  data-lo="ຈັດການຮ້ານຄ້າ Partner ຂອງ Seven Digital"
                data-en="Manage Seven Digital partner shops.">
                ຈັດການຮ້ານຄ້າ Partner ຂອງ Seven Digital
            </p>
        </a>
        <a class="menu-card card-purple" href="credit_transfer.php">
            <div class="card-icon">💸</div>
            <h3 data-lo="ໂອນເຄຣດິດ" data-en="Transfer Credit">ໂອນເຄຣດິດ</h3>
            <p  data-lo="ສົ່ງເຄຣດິດຈາກ Seven Digital ໄປ Partner"
                data-en="Send credit from Seven Digital to partner shops.">
                ສົ່ງເຄຣດິດຈາກ Seven Digital ໄປ Partner
            </p>
        </a>
        <a class="menu-card card-amber" href="credit_requests.php" style="position:relative;">
            <?php if ($pendingReqs > 0): ?>
                <span class="pending-dot" id="creditReqDot"><?= $pendingReqs ?></span>
            <?php endif; ?>
            <div class="card-icon">📋</div>
            <h3 data-lo="ຄຳຮ້ອງຂໍເຄຣດິດ" data-en="Credit Requests">ຄຳຮ້ອງຂໍເຄຣດິດ</h3>
            <p  data-lo="ອະນຸມັດ ຫຼື ປະຕິເສດຄຳຮ້ອງຂໍເຄຣດິດ Partner"
                data-en="Approve or reject partner credit requests.">
                ອະນຸມັດ ຫຼື ປະຕິເສດຄຳຮ້ອງຂໍເຄຣດິດ Partner
            </p>
        </a>
        <a class="menu-card card-teal" href="transactions.php">
            <div class="card-icon">📊</div>
            <h3 data-lo="ທຸລະກຳ" data-en="Transactions">ທຸລະກຳ</h3>
            <p  data-lo="ເບິ່ງທຸລະກຳເຄຣດິດ Seven Digital ແລະ Partner"
                data-en="View Seven Digital and partner credit transactions.">
                ເບິ່ງທຸລະກຳເຄຣດິດ Seven Digital ແລະ Partner
            </p>
        </a>
        <a class="menu-card card-pink" href="wallet_transactions.php">
            <div class="card-icon">👛</div>
            <h3 data-lo="ທຸລະກຳກະເປົາ" data-en="Wallet Transactions">ທຸລະກຳກະເປົາ</h3>
            <p  data-lo="ເບິ່ງການຕື່ມກະເປົາລູກຄ້າຈາກ Partner"
                data-en="View partner to customer wallet top-ups.">
                ເບິ່ງການຕື່ມກະເປົາລູກຄ້າຈາກ Partner
            </p>
        </a>
    </div>

    <!-- ── Company system menu ── -->
    <div class="section-title" data-lo="ລະບົບບໍລິສັດ" data-en="Company System">
        ລະບົບບໍລິສັດ / Company System
    </div>
    <div class="menu-grid">
        <a class="menu-card card-teal" href="companies.php">
            <div class="card-icon">🏢</div>
            <h3 data-lo="ບໍລິສັດ" data-en="Companies">ບໍລິສັດ</h3>
            <p  data-lo="ເພີ່ມ, ແກ້ໄຂ ແລະ ຈັດການບໍລິສັດທັງໝົດ"
                data-en="Add, edit and manage all companies.">
                ເພີ່ມ, ແກ້ໄຂ ແລະ ຈັດການບໍລິສັດທັງໝົດ
            </p>
        </a>
        <a class="menu-card card-green" href="companies.php">
            <div class="card-icon">💰</div>
            <h3 data-lo="ໂອນເຄຣດິດໃຫ້ບໍລິສັດ" data-en="Fund Companies">ໂອນເຄຣດິດໃຫ້ບໍລິສັດ</h3>
            <p  data-lo="ສົ່ງເຄຣດິດຈາກ Seven Digital ໄປຍັງບໍລິສັດ"
                data-en="Transfer credit from Seven Digital to companies.">
                ສົ່ງເຄຣດິດຈາກ Seven Digital ໄປຍັງບໍລິສັດ
            </p>
        </a>
        <a class="menu-card card-indigo" href="companies.php" style="position:relative;">
            <?php if ($pendingLeaveAll > 0): ?>
                <span class="pending-dot" id="leaveDot"><?= $pendingLeaveAll ?></span>
            <?php endif; ?>
            <div class="card-icon">🏖️</div>
            <h3 data-lo="ການລາພັກທັງໝົດ" data-en="All Leave Requests">ການລາພັກທັງໝົດ</h3>
            <p  data-lo="ເບິ່ງຄຳຮ້ອງລາພັກຈາກທຸກບໍລິສັດ"
                data-en="View pending leave requests across all companies.">
                ເບິ່ງຄຳຮ້ອງລາພັກຈາກທຸກບໍລິສັດ
            </p>
        </a>
    </div>

    <!-- ── Footer ── -->
    <div class="footer-row">
        <span>Seven Digital Credit System &copy; <?= date("Y") ?></span>
        <span data-lo="ຜູ້ດູແລລະບົບ: " data-en="Admin: ">ຜູ້ດູແລລະບົບ: </span>
    </div>

</div>

<script>
/* ── Live polling every 5 seconds ── */
const heroPending   = document.getElementById('heroPending');
const heroCompanies = document.getElementById('heroCompanies');
const heroLeave     = document.getElementById('heroLeave');

const statCustomers = document.getElementById('statCustomers');
const statPartners  = document.getElementById('statPartners');
const statCompanies = document.getElementById('statCompanies');
const statStaff     = document.getElementById('statStaff');
const statPending   = document.getElementById('statPending');
const statTodayTx   = document.getElementById('statTodayTx');

const creditReqCard = document.querySelector("a[href='credit_requests.php']");

let prevPending = <?= $pendingReqs ?>;
let prevLeave   = <?= $pendingLeaveAll ?>;

function highlight(el) {
    if (!el) return;
    el.style.transition = 'color .3s';
    el.style.color = '#2563eb';
    setTimeout(() => el.style.color = '', 800);
}

function updateDot(card, dotId, count) {
    if (!card) return;
    let dot = card.querySelector('.pending-dot');
    if (count > 0) {
        if (!dot) {
            dot = document.createElement('span');
            dot.className = 'pending-dot';
            dot.id = dotId;
            card.appendChild(dot);
        }
        dot.textContent = count;
    } else if (dot) {
        dot.remove();
    }
}

async function pollDashboard() {
    try {
        const resp = await fetch('get_pending_count.php', { cache: 'no-store' });
        const data = await resp.json();
        if (!data.success) return;

        /* Hero badges */
        if (heroPending)   heroPending.textContent   = data.pendingReqs;
        if (heroCompanies) heroCompanies.textContent  = data.totalCompanies;
        if (heroLeave)     heroLeave.textContent      = data.pendingLeaveAll;

        /* Flash hero badge red when pending goes up */
        if (data.pendingReqs > prevPending && heroPending) {
            const badge = heroPending.closest('.hero-badge');
            badge.style.background = 'rgba(220,38,38,.35)';
            setTimeout(() => badge.style.background = '', 1200);
        }

        /* Stat cards */
        const updates = [
            [statCustomers, data.totalCustomers],
            [statPartners,  data.totalPartners],
            [statCompanies, data.totalCompanies],
            [statStaff,     data.totalStaffAll],
            [statPending,   data.pendingReqs],
            [statTodayTx,   data.todayTx],
        ];
        updates.forEach(([el, val]) => {
            if (!el || val === undefined) return;
            const formatted = Number(val).toLocaleString('en-US');
            if (el.textContent.trim() !== formatted) {
                el.textContent = formatted;
                highlight(el);
            }
        });

        /* Pending dots on cards */
        updateDot(creditReqCard, 'creditReqDot', data.pendingReqs);
        updateDot(document.querySelector("a[href='companies.php']:last-of-type"), 'leaveDot', data.pendingLeaveAll);

        /* Tab title */
        const totalAlerts = data.pendingReqs + data.pendingLeaveAll;
        document.title = totalAlerts > 0
            ? `(${totalAlerts}) Admin Dashboard`
            : 'Admin Dashboard';

        prevPending = data.pendingReqs;
        prevLeave   = data.pendingLeaveAll;

    } catch (e) { /* silent fail */ }
}

pollDashboard();
setInterval(pollDashboard, 5000);
</script>

</body>
</html>