<?php
/* ============================================================================
 *  company/attendance_today.php — manager live board: who has checked in today
 *  and who hasn't. Counts only staff who are required to check in (non-exempt),
 *  and treats full-day approved leave separately. Bilingual EN/Lao.
 * ==========================================================================*/
session_start();
if (!isset($_SESSION["user_id"]) || $_SESSION["role"] !== "company_admin") {
    header("Location: ../auth/login.php"); exit;
}
require_once '../config/database.php';
date_default_timezone_set('Asia/Vientiane');

$companyId   = (int)$_SESSION["company_id"];
$companyName = $_SESSION["company_name"] ?? "My Company";
$today       = date('Y-m-d');

/* active, non-exempt staff */
$st = $pdo->prepare("
    SELECT cs.user_id, u.name, cs.staff_code, cs.position, cs.department, cs.photo
    FROM company_staff cs
    JOIN users u ON u.id = cs.user_id AND u.status='active'
    LEFT JOIN att_staff a ON a.company_id = cs.company_id AND a.staff_id = cs.user_id
    WHERE cs.company_id = ? AND COALESCE(a.checkin_required,1) = 1
    ORDER BY (cs.staff_code IS NULL OR cs.staff_code=''), cs.staff_code, u.name");
$st->execute([$companyId]);
$staff = $st->fetchAll(PDO::FETCH_ASSOC);

/* today's attendance keyed by staff */
$aq = $pdo->prepare("SELECT staff_id, am_in, am_out, pm_in, pm_out, am_late, pm_late FROM hr_attendance WHERE company_id=? AND work_date=?");
$aq->execute([$companyId, $today]);
$att = [];
foreach ($aq->fetchAll(PDO::FETCH_ASSOC) as $r) $att[(int)$r['staff_id']] = $r;

/* full-day approved leave today */
$lv = $pdo->prepare("SELECT staff_id FROM hr_leave WHERE company_id=? AND status='approved' AND is_hourly=0 AND start_date<=? AND end_date>=?");
$lv->execute([$companyId, $today, $today]);
$onLeave = array_fill_keys(array_map('intval', $lv->fetchAll(PDO::FETCH_COLUMN)), true);

/* classify */
$rows = [];
$nIn = 0; $nOut = 0; $nLeave = 0;
foreach ($staff as $s) {
    $uid = (int)$s['user_id'];
    $a = $att[$uid] ?? null;
    $hasIn  = $a && (!empty($a['am_in']) || !empty($a['pm_in']));
    $firstIn = $a ? ($a['am_in'] ?: $a['pm_in']) : null;
    if (isset($onLeave[$uid]))       { $state='leave';   $nLeave++; }
    elseif ($hasIn)                  { $state='in';      $nIn++; }
    else                             { $state='out';     $nOut++; }
    $s['state']=$state; $s['firstIn']=$firstIn;
    $rows[] = $s;
}
/* not-checked-in first, then leave, then checked-in */
usort($rows, function($a,$b){ $o=['out'=>0,'leave'=>1,'in'=>2]; return $o[$a['state']]<=>$o[$b['state']]; });
$total = count($rows);

/* render one punch cell: time in green, late in amber (+Nm), missing as — */
function punchCell($t, $late = 0){
    if (empty($t)) return '<span style="color:#cbd5e1;font-weight:800;">—</span>';
    $hm = substr($t, 0, 5);
    if ((int)$late > 0) {
        return '<span style="color:#b45309;font-weight:800;">'.$hm.' <small style="color:#dc2626;font-weight:800;">+'.(int)$late.'m</small></span>';
    }
    return '<span style="color:#15803d;font-weight:800;">'.$hm.'</span>';
}
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <?php $pwaTheme='#0f766e'; include __DIR__.'/../config/pwa_head.php'; ?>
    <title><?= htmlspecialchars($companyName) ?> — Today's Check-in</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;--surface:#fff;--bg:#f0f4f8;--border:#e2e8f0;--text:#0f172a;--muted:#64748b;--green:#16a34a;--green-lt:#dcfce7;--red:#dc2626;--red-lt:#fee2e2;--amber:#d97706;--amber-lt:#fef3c7;--blue:#2563eb;--blue-lt:#dbeafe;--radius:14px;--shadow:0 2px 14px rgba(15,23,42,.07);}
        body{font-family:"Noto Sans Lao","Inter",Arial,sans-serif;background:var(--bg);color:var(--text);min-height:100vh;}
        .top-bar{background:var(--surface);border-bottom:1px solid var(--border);padding:calc(12px + env(safe-area-inset-top,0px)) 24px 12px;display:flex;justify-content:space-between;align-items:center;gap:14px;position:sticky;top:0;z-index:100;box-shadow:0 1px 6px rgba(15,23,42,.06);flex-wrap:wrap;}
        .back-link{display:inline-flex;align-items:center;gap:6px;background:#f1f5f9;color:var(--text);border:1.5px solid var(--border);padding:7px 13px;border-radius:8px;text-decoration:none;font-size:13px;font-weight:700;}
        .lang-bar{display:flex;gap:7px;}
        .lang-btn{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;}
        .lang-btn.active{background:var(--primary);border-color:var(--primary);color:#fff;}
        .page{max-width:1000px;margin:auto;padding:22px 18px;}
        h1{font-size:21px;font-weight:800;}
        .date{color:var(--muted);font-size:13px;font-weight:700;margin:4px 0 16px;}
        .stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:12px;margin-bottom:18px;}
        .sb{background:var(--surface);border:1px solid var(--border);border-radius:14px;padding:16px;box-shadow:var(--shadow);text-align:center;}
        .sb .v{font-size:30px;font-weight:800;line-height:1;}
        .sb .l{font-size:12px;color:var(--muted);font-weight:700;margin-top:6px;text-transform:uppercase;letter-spacing:.3px;}
        .card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow);overflow:hidden;}
        .tbl-wrap{overflow-x:auto;}
        table{width:100%;border-collapse:collapse;font-size:14px;min-width:640px;}
        th br{display:block;} th small{font-weight:600;}
        .legend{display:flex;gap:16px;flex-wrap:wrap;font-size:12px;color:var(--muted);margin:0 2px 12px;font-weight:600;}
        .legend b{color:#15803d;} .legend .lt{color:#b45309;}
        th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.3px;color:var(--muted);padding:11px;border-bottom:2px solid var(--border);background:#f8fafc;}
        td{padding:10px 11px;border-bottom:1px solid var(--border);vertical-align:middle;}
        tr:last-child td{border-bottom:none;}
        .who{display:flex;align-items:center;gap:10px;}
        .av{width:34px;height:34px;border-radius:9px;object-fit:cover;background:#e2e8f0;display:flex;align-items:center;justify-content:center;font-weight:800;color:#475569;font-size:13px;flex-shrink:0;}
        .nm{font-weight:700;}.sc{font-size:11px;color:var(--muted);}
        .tag{display:inline-flex;align-items:center;gap:5px;padding:4px 11px;border-radius:999px;font-size:12px;font-weight:800;}
        .tag.in{background:var(--green-lt);color:#15803d;}.tag.out{background:var(--red-lt);color:#b91c1b;}.tag.leave{background:var(--amber-lt);color:#92400e;}
        .refresh{background:var(--primary);color:#fff;border:none;padding:8px 14px;border-radius:9px;font-weight:800;font-size:13px;cursor:pointer;font-family:inherit;text-decoration:none;display:inline-flex;align-items:center;gap:6px;}
        .upd{font-size:12px;color:var(--muted);}
    </style>
</head>
<body>

<div class="top-bar">
    <a class="back-link" href="dashboard.php">← <span data-lo="ກັບຄືນ" data-en="Back">Back</span></a>
    <div class="lang-bar">
        <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>

<div class="page">
    <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;">
        <div>
            <h1 data-lo="ການເຂົ້າວຽກມື້ນີ້" data-en="Today's Check-in">Today's Check-in</h1>
            <div class="date">📅 <?= date('l, d/m/Y') ?> · <span class="upd" data-lo="ອັບເດດ" data-en="updated">updated</span> <?= date('H:i') ?></div>
        </div>
        <a class="refresh" href="attendance_today.php">🔄 <span data-lo="ໂຫຼດໃໝ່" data-en="Refresh">Refresh</span></a>
    </div>

    <div class="stats">
        <div class="sb"><div class="v"><?= $total ?></div><div class="l" data-lo="ຕ້ອງເຂົ້າວຽກ" data-en="Expected">Expected</div></div>
        <div class="sb"><div class="v" style="color:#16a34a"><?= $nIn ?></div><div class="l" data-lo="ເຂົ້າແລ້ວ" data-en="Checked in">Checked in</div></div>
        <div class="sb"><div class="v" style="color:#dc2626"><?= $nOut ?></div><div class="l" data-lo="ຍັງບໍ່ເຂົ້າ" data-en="Not yet">Not yet</div></div>
        <div class="sb"><div class="v" style="color:#d97706"><?= $nLeave ?></div><div class="l" data-lo="ລາພັກ" data-en="On leave">On leave</div></div>
    </div>

    <div class="legend">
        <span><b>08:30</b> = <span data-lo="ເຂົ້າ/ອອກ ຕາມເວລາ" data-en="on-time punch">on-time punch</span></span>
        <span><span class="lt">08:45 +15m</span> = <span data-lo="ຊ້າ" data-en="late (minutes)">late (minutes)</span></span>
        <span>— = <span data-lo="ຍັງບໍ່ໄດ້ຕອກບັດ" data-en="not punched">not punched</span></span>
    </div>

    <div class="card">
        <div class="tbl-wrap">
        <table>
            <thead><tr>
                <th data-lo="ພະນັກງານ" data-en="Staff">Staff</th>
                <th style="text-align:center;" data-lo="ເຂົ້າ ເຊົ້າ (8:30)" data-en="Morning In (8:30)">Morning In<br>≤ 8:30</th>
                <th style="text-align:center;" data-lo="ອອກ ເຊົ້າ (12:00)" data-en="Morning Out (12:00)">Morning Out<br>≥ 12:00</th>
                <th style="text-align:center;" data-lo="ເຂົ້າ ບ່າຍ (13:30)" data-en="Afternoon In (13:30)">Afternoon In<br>≤ 13:30</th>
                <th style="text-align:center;" data-lo="ອອກ ບ່າຍ (17:00)" data-en="Afternoon Out (17:00)">Afternoon Out<br>≥ 17:00</th>
            </tr></thead>
            <tbody>
            <?php if (!$rows): ?>
                <tr><td colspan="5" style="text-align:center;color:var(--muted);padding:26px;" data-lo="ບໍ່ມີພະນັກງານ" data-en="No staff">No staff</td></tr>
            <?php else: foreach ($rows as $r): $a = $att[(int)$r['user_id']] ?? null; ?>
                <tr>
                    <td><div class="who">
                        <?php if (!empty($r['photo'])): ?><img class="av" src="../<?= htmlspecialchars($r['photo']) ?>" alt="">
                        <?php else: ?><div class="av"><?= strtoupper(mb_substr($r['name'],0,1)) ?></div><?php endif; ?>
                        <div><div class="nm"><?= htmlspecialchars($r['name']) ?></div>
                            <div class="sc"><?= htmlspecialchars(($r['staff_code']? $r['staff_code'].' · ':'').($r['department']?:'')) ?></div></div>
                    </div></td>
                    <?php if ($r['state']==='leave'): ?>
                        <td colspan="4" style="text-align:center;"><span class="tag leave" data-lo="🌴 ລາພັກ" data-en="🌴 On leave">🌴 On leave</span></td>
                    <?php else: ?>
                        <td style="text-align:center;"><?= punchCell($a['am_in']  ?? null, $a['am_late'] ?? 0) ?></td>
                        <td style="text-align:center;"><?= punchCell($a['am_out'] ?? null) ?></td>
                        <td style="text-align:center;"><?= punchCell($a['pm_in']  ?? null, $a['pm_late'] ?? 0) ?></td>
                        <td style="text-align:center;"><?= punchCell($a['pm_out'] ?? null) ?></td>
                    <?php endif; ?>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table>
        </div>
    </div>
</div>

<?php require __DIR__ . '/../config/auto_update.php'; ?>
</body>
</html>