<?php
session_start();

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

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

$companyId   = (int)$_SESSION["company_id"];
$companyName = $_SESSION["company_name"] ?? "My Company";

/* ── Live counts ── */
function safeCount($pdo, $sql, $params = []) {
    try {
        $st = $pdo->prepare($sql);
        $st->execute($params);
        return (int)$st->fetchColumn();
    } catch (Throwable $e) { return 0; }
}

function safeVal($pdo, $sql, $params = [], $default = 0) {
    try {
        $st = $pdo->prepare($sql);
        $st->execute($params);
        return $st->fetchColumn() ?? $default;
    } catch (Throwable $e) { return $default; }
}

$totalStaff    = safeCount($pdo, "SELECT COUNT(*) FROM company_staff WHERE company_id = ?", [$companyId]);
$pendingLeave  = safeCount($pdo, "SELECT COUNT(*) FROM hr_leave WHERE company_id = ? AND status = 'pending'", [$companyId]);
$todayPresent  = safeCount($pdo, "SELECT COUNT(*) FROM hr_attendance WHERE company_id = ? AND work_date = CURDATE() AND status = 'present'", [$companyId]);
$creditBalance = safeVal($pdo,   "SELECT credit_balance FROM companies WHERE id = ?", [$companyId], 0);

/* Current month payroll total */
$currentMonth  = date('n');
$currentYear   = date('Y');
$monthPayroll  = safeVal($pdo,
    "SELECT COALESCE(SUM(net_pay),0) FROM hr_salary WHERE company_id = ? AND month = ? AND year = ?",
    [$companyId, $currentMonth, $currentYear], 0
);
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <?php $pwaTheme = '#0f766e'; include __DIR__ . '/../config/pwa_head.php'; ?>
    <title><?= htmlspecialchars($companyName) ?> — Company 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>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

        :root {
            --primary:    #0f766e;
            --primary-dk: #084740;
            --green:      #16a34a;
            --green-lt:   #dcfce7;
            --amber:      #d97706;
            --amber-lt:   #fef3c7;
            --red:        #dc2626;
            --red-lt:     #fee2e2;
            --blue:       #2563eb;
            --blue-lt:    #dbeafe;
            --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;
        }

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

        .top-bar-brand {
            display: flex; align-items: center; gap: 10px;
        }

        .brand-logo {
            width: 34px; height: 34px;
            background: linear-gradient(135deg, #084740, #0f766e);
            border-radius: 9px;
            display: flex; align-items: center; justify-content: center;
            color: #fff; font-weight: 800; font-size: 14px;
        }

        .brand-name {
            font-size: 14px; font-weight: 700; color: var(--text);
            line-height: 1.2;
        }

        .brand-sub {
            font-size: 11px; color: var(--muted);
        }

        .top-bar-right {
            display: flex; align-items: center; gap: 12px;
        }

        .lang-bar {
            display: flex; align-items: center; gap: 6px;
        }

        .lang-label { font-size: 12px; color: var(--muted); font-weight: 500; }

        .lang-btn {
            display: inline-flex; align-items: center; gap: 4px;
            padding: 4px 11px; border-radius: 999px;
            border: 1.5px solid var(--border);
            background: var(--surface);
            font-size: 11px; 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; }

        .avatar {
            width: 34px; height: 34px;
            background: linear-gradient(135deg, #084740, #0f766e);
            border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            color: #fff; font-weight: 800; font-size: 14px;
        }

        .user-info { font-size: 13px; color: var(--muted); line-height: 1.3; }
        .user-info strong { display: block; color: var(--text); font-size: 13px; }

        .logout-link {
            display: inline-flex; align-items: center; gap: 5px;
            background: var(--red-lt); color: var(--red);
            border: 1.5px solid #fca5a5;
            padding: 6px 13px; 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, #042f2e 0%, #084740 50%, #0f766e 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(4,47,46,.22);
            position: relative;
            overflow: hidden;
        }

        .hero::before, .hero::after {
            content: "";
            position: absolute;
            border-radius: 50%;
            opacity: .07;
            background: #fff;
        }

        .hero::before { width: 300px; height: 300px; right: -70px; top: -90px; }
        .hero::after  { width: 180px; height: 180px; right: 130px; bottom: -70px; }

        .hero-left h1 {
            font-size: 28px; font-weight: 800; line-height: 1.2; margin-bottom: 6px;
        }

        .hero-left .subtitle {
            font-size: 13px; color: rgba(255,255,255,.7);
        }

        .hero-left .welcome {
            font-size: 14px; color: rgba(255,255,255,.88);
            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,.2);
            border-radius: 12px;
            padding: 14px 20px;
            text-align: center;
            min-width: 130px;
        }

        .hero-badge .val {
            font-size: 26px; font-weight: 800; color: #fff;
            display: block; margin-bottom: 3px;
        }

        .hero-badge .lbl {
            font-size: 12px; color: rgba(255,255,255,.75);
        }

        /* ── Stat row ── */
        .stat-row {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(210px, 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.teal   { background: var(--teal-lt); }
        .stat-icon.green  { background: var(--green-lt); }
        .stat-icon.amber  { background: var(--amber-lt); }
        .stat-icon.blue   { background: var(--blue-lt); }
        .stat-icon.purple { background: var(--purple-lt); }

        .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: 12px; font-weight: 700; color: var(--muted);
            text-transform: uppercase; letter-spacing: .6px;
            margin-bottom: 14px; margin-top: 4px;
        }

        /* ── 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(--teal));
            opacity: 0;
            transition: opacity .18s;
        }

        .menu-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 10px 30px rgba(15,23,42,.13);
            border-color: #99f6e4;
        }

        .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, var(--teal-lt));
        }

        .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-teal   { --accent: #0f766e; --icon-bg: #ccfbf1; }
        .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-pink   { --accent: #db2777; --icon-bg: #fce7f3; }
        .card-gray   { --accent: #475569; --icon-bg: #f1f5f9; }

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

        /* ── Credit balance card ── */
        .credit-card {
            background: linear-gradient(135deg, #042f2e, #0f766e);
            border-radius: var(--radius);
            padding: 22px 26px;
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 20px;
            margin-bottom: 28px;
            box-shadow: 0 4px 20px rgba(4,47,46,.2);
        }

        .credit-left .credit-lbl {
            font-size: 12px; color: rgba(255,255,255,.7);
            text-transform: uppercase; letter-spacing: .5px; font-weight: 700;
        }

        .credit-left .credit-val {
            font-size: 32px; font-weight: 800; color: #fff;
            margin-top: 4px; letter-spacing: -.5px;
        }

        .credit-left .credit-sub {
            font-size: 12px; color: rgba(255,255,255,.6); margin-top: 4px;
        }

        .credit-icon { font-size: 42px; opacity: .6; }

        /* ── 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: 20px; }
            .credit-left .credit-val { font-size: 24px; }
        }
    </style>
</head>
<body>

<!-- ── Top bar ── -->
<div class="top-bar">
    <div class="top-bar-brand">
        <div class="brand-logo">CO</div>
        <div>
            <div class="brand-name"><?= htmlspecialchars($companyName) ?></div>
            <div class="brand-sub">Company Portal</div>
        </div>
    </div>

    <div class="top-bar-right">
        <div class="lang-bar">
            <span class="lang-label">ພາສາ:</span>
            <button class="lang-btn" id="btn-lo" onclick="setLang('lo')">🇱🇦 ລາວ</button>
            <button class="lang-btn" id="btn-en" onclick="setLang('en')">🇬🇧 EN</button>
        </div>

        <div style="display:flex;align-items:center;gap:8px;">
            <div class="avatar"><?= strtoupper(mb_substr($_SESSION["name"] ?? "C", 0, 1)) ?></div>
            <div class="user-info">
                <strong><?= htmlspecialchars($_SESSION["name"]) ?></strong>
                <span data-lo="ຜູ້ດູແລບໍລິສັດ" data-en="Company Admin">ຜູ້ດູແລບໍລິສັດ</span>
            </div>
        </div>

        <a class="logout-link" href="../auth/logout.php">
            🚪 <span data-lo="ອອກ" data-en="Logout">ອອກ</span>
        </a>
    </div>
</div>

<div class="page-body">

    <!-- ── Hero ── -->
    <div class="hero">
        <div class="hero-left">
            <h1><?= htmlspecialchars($companyName) ?></h1>
            <div class="subtitle" data-lo="ລະບົບ HR ແລະ ເຄຣດິດ" data-en="HR & Credit Management Portal">
                HR &amp; Credit Management Portal
            </div>
            <div class="welcome">
                👋 <span data-lo="ຍິນດີຕ້ອນຮັບ," data-en="Welcome,">ຍິນດີຕ້ອນຮັບ,</span>
                <?= htmlspecialchars($_SESSION["name"]) ?>
            </div>
        </div>

        <div class="hero-badges">
            <div class="hero-badge">
                <span class="val"><?= number_format($totalStaff) ?></span>
                <span class="lbl" data-lo="ພະນັກງານ" data-en="Staff">ພະນັກງານ</span>
            </div>
            <div class="hero-badge">
                <span class="val"><?= number_format($todayPresent) ?></span>
                <span class="lbl" data-lo="ມາວັນນີ້" data-en="Present today">ມາວັນນີ້</span>
            </div>
            <?php if ($pendingLeave > 0): ?>
            <div class="hero-badge" style="background:rgba(220,38,38,.25);border-color:rgba(220,38,38,.4);">
                <span class="val"><?= $pendingLeave ?></span>
                <span class="lbl" data-lo="ຂໍລາພັກລໍຖ້າ" data-en="Leave pending">ຂໍລາພັກລໍຖ້າ</span>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- ── Credit balance card ── -->
    <div class="credit-card">
        <div class="credit-left">
            <div class="credit-lbl" data-lo="ຍອດເຄຣດິດຄົງເຫຼືອ" data-en="Available Credit Balance">
                ຍອດເຄຣດິດຄົງເຫຼືອ
            </div>
            <div class="credit-val">
                ₭ <?= number_format((float)$creditBalance, 0) ?>
            </div>
            <div class="credit-sub" data-lo="ໂອນໂດຍ Seven Digital Admin" data-en="Funded by Seven Digital Admin">
                ໂອນໂດຍ Seven Digital Admin
            </div>
        </div>
        <div class="credit-icon">💰</div>
    </div>

    <!-- ── Stats ── -->
    <div class="stat-row">
        <div class="stat-card">
            <div class="stat-icon teal">👥</div>
            <div class="stat-info">
                <div class="val"><?= number_format($totalStaff) ?></div>
                <div class="lbl" data-lo="ພະນັກງານທັງໝົດ" data-en="Total Staff">ພະນັກງານທັງໝົດ</div>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-icon green">✅</div>
            <div class="stat-info">
                <div class="val"><?= number_format($todayPresent) ?></div>
                <div class="lbl" data-lo="ເຂົ້າວຽກມື້ນີ້" data-en="Present Today">ເຂົ້າວຽກມື້ນີ້</div>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-icon amber">📋</div>
            <div class="stat-info">
                <div class="val"><?= number_format($pendingLeave) ?></div>
                <div class="lbl" data-lo="ຂໍລາພັກລໍຖ້າ" data-en="Leave Requests">ຂໍລາພັກລໍຖ້າ</div>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-icon blue">💵</div>
            <div class="stat-info">
                <div class="val">₭ <?= number_format((float)$monthPayroll, 0) ?></div>
                <div class="lbl" data-lo="ເງິນເດືອນເດືອນນີ້" data-en="This Month Payroll">ເງິນເດືອນເດືອນນີ້</div>
            </div>
        </div>
    </div>

    <!-- ── Staff management ── -->
    <div class="section-title" data-lo="ຈັດການພະນັກງານ" data-en="Staff Management">
        ຈັດການພະນັກງານ / Staff Management
    </div>

    <div class="menu-grid">

        <a class="menu-card card-teal" href="staff.php">
            <div class="card-icon">👥</div>
            <h3 data-lo="ພະນັກງານ" data-en="Staff List">ພະນັກງານ</h3>
            <p  data-lo="ເບິ່ງ, ເພີ່ມ, ແກ້ໄຂ ແລະ ລຶບພະນັກງານ"
                data-en="View, add, edit and remove staff members.">
                ເບິ່ງ, ເພີ່ມ, ແກ້ໄຂ ແລະ ລຶບພະນັກງານ
            </p>
        </a>

        <a class="menu-card card-amber" href="hr_attendance.php">
            <div class="card-icon">🕐</div>
            <h3 data-lo="ການເຂົ້າວຽກ" data-en="Attendance">ການເຂົ້າວຽກ</h3>
            <p  data-lo="ບັນທຶກ ແລະ ຈັດການເວລາເຂົ້າ-ອອກວຽກ"
                data-en="Record and manage staff check-in and check-out.">
                ບັນທຶກ ແລະ ຈັດການເວລາເຂົ້າ-ອອກວຽກ
            </p>
        </a>

        <a class="menu-card card-green" href="hr_leave.php" style="position:relative;">
            <?php if ($pendingLeave > 0): ?>
                <span class="pending-dot"><?= $pendingLeave ?></span>
            <?php endif; ?>
            <div class="card-icon">🏖️</div>
            <h3 data-lo="ການລາພັກ" data-en="Leave Requests">ການລາພັກ</h3>
            <p  data-lo="ອະນຸມັດ ຫຼື ປະຕິເສດການຂໍລາພັກ"
                data-en="Approve or reject staff leave requests.">
                ອະນຸມັດ ຫຼື ປະຕິເສດການຂໍລາພັກ
            </p>
        </a>

    </div>

    <!-- ── HR & Payroll ── -->
    <div class="section-title" data-lo="HR ແລະ ເງິນເດືອນ" data-en="HR & Payroll">
        HR &amp; Payroll
    </div>

    <div class="menu-grid">

        <a class="menu-card card-blue" href="hr_salary.php">
            <div class="card-icon">💵</div>
            <h3 data-lo="ເງິນເດືອນ" data-en="Salary">ເງິນເດືອນ</h3>
            <p  data-lo="ຕັ້ງ ແລະ ແກ້ໄຂຂໍ້ມູນເງິນເດືອນ, OT ພະນັກງານ"
                data-en="Set and edit staff base salary and OT records.">
                ຕັ້ງ ແລະ ແກ້ໄຂຂໍ້ມູນເງິນເດືອນ, OT ພະນັກງານ
            </p>
        </a>

        <a class="menu-card card-purple" href="hr_allowances.php">
            <div class="card-icon">🎁</div>
            <h3 data-lo="ເບ້ຍຕ່າງໆ" data-en="Allowances">ເບ້ຍຕ່າງໆ</h3>
            <p  data-lo="ຈັດການເບ້ຍຂົນສົ່ງ, ທີ່ພັກ, ອາຫານ ແລະ ອື່ນໆ"
                data-en="Manage transport, housing, meal and other allowances.">
                ຈັດການເບ້ຍຂົນສົ່ງ, ທີ່ພັກ, ອາຫານ ແລະ ອື່ນໆ
            </p>
        </a>

        <a class="menu-card card-pink" href="hr_payslips.php">
            <div class="card-icon">🧾</div>
            <h3 data-lo="ໃບແຈ້ງເງິນເດືອນ" data-en="Payslips">ໃບແຈ້ງເງິນເດືອນ</h3>
            <p  data-lo="ສ້າງ ແລະ ສ່ງໃບແຈ້ງເງິນເດືອນລາຍເດືອນ"
                data-en="Generate and distribute monthly payslips.">
                ສ້າງ ແລະ ສ່ງໃບແຈ້ງເງິນເດືອນລາຍເດືອນ
            </p>
        </a>

    </div>

    <!-- ── Credit & Reporting ── -->
    <div class="section-title" data-lo="ເຄຣດິດ ແລະ ລາຍງານ" data-en="Credit & Reports">
        ເຄຣດິດ &amp; ລາຍງານ
    </div>

    <div class="menu-grid">

        <a class="menu-card card-gray" href="credit_balance.php">
            <div class="card-icon">💰</div>
            <h3 data-lo="ຍອດເຄຣດິດ" data-en="Credit Balance">ຍອດເຄຣດິດ</h3>
            <p  data-lo="ເບິ່ງຍອດຄົງເຫຼືອ ແລະ ປະຫວັດການໂອນເຄຣດິດ"
                data-en="View balance and credit transfer history from Seven Digital.">
                ເບິ່ງຍອດຄົງເຫຼືອ ແລະ ປະຫວັດການໂອນເຄຣດິດ
            </p>
        </a>

    </div>

    <!-- ── Footer ── -->
    <div class="footer-row">
        <span><?= htmlspecialchars($companyName) ?> &copy; <?= date("Y") ?></span>
        <span style="color:var(--muted);font-size:11px;">
            Powered by <strong style="color:var(--primary);">Seven Digital</strong>
        </span>
    </div>

</div>

<script>
/* Live polling — pending leave badge every 10s */
const elPendingDot  = document.querySelector("a[href='hr_leave.php'] .pending-dot");
const elHeroPending = document.querySelector(".hero-badge:last-child .val");
const elStatPending = document.querySelectorAll(".stat-card")[2]?.querySelector(".val");

async function pollLeave() {
    try {
        const res  = await fetch("get_leave_count.php", { cache: "no-store" });
        const data = await res.json();
        if (!data.success) return;

        const n = data.pendingLeave;

        if (elStatPending) elStatPending.textContent = n.toLocaleString();

        /* Dot on leave card */
        const card = document.querySelector("a[href='hr_leave.php']");
        if (card) {
            let dot = card.querySelector(".pending-dot");
            if (n > 0) {
                if (!dot) { dot = document.createElement("span"); dot.className = "pending-dot"; card.appendChild(dot); }
                dot.textContent = n;
            } else if (dot) { dot.remove(); }
        }

        document.title = n > 0
            ? `(${n}) <?= htmlspecialchars($companyName) ?> Dashboard`
            : "<?= htmlspecialchars($companyName) ?> Dashboard";

    } catch (e) {}
}

pollLeave();
setInterval(pollLeave, 10000);
</script>

<?php include __DIR__ . '/../config/pwa_foot.php'; ?>
</body>
</html>