<?php

$judul = "Laporan Checklist";
$menu  = "laporan";

include 'layout/header.php';

$dari   = isset($_GET['dari'])   ? $_GET['dari']   : date('Y-m-01');
$sampai = isset($_GET['sampai']) ? $_GET['sampai'] : date('Y-m-d');

$jumlah_hari = (int)((strtotime($sampai) - strtotime($dari)) / 86400) + 1;

$role_to_jabatan = [
    'Store_Manager'  => 'Store_Manager',
    'kadiv_gudang'   => 'Kadiv_gudang',
    'kadiv_ops'      => 'kadiv_ops',
    'kadiv_cs'       => 'kadiv_cs',
    'kadiv_kasir'    => 'kadiv_kasir',
];

/* ==========================
   REKAP PER TANGGAL
   total per hari = jumlah checklist_master daily aktif (LOWER agar konsisten)
========================== */
$total_per_hari = (int)(mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT COUNT(DISTINCT cm.id_checklist) AS n
    FROM checklist_master cm
    WHERE LOWER(cm.jenis) = 'daily'
    AND   cm.status = 'aktif'
"))['n'] ?? 0);

// Semua tanggal dalam rentang
$dates = [];
$d   = new DateTime($dari);
$end = new DateTime($sampai);
while ($d <= $end) {
    $dates[] = $d->format('Y-m-d');
    $d->modify('+1 day');
}

// Selesai per tanggal — DISTINCT per checklist per hari agar tidak double-count
$q_selesai_tgl = mysqli_query($conn,"
    SELECT ch.tanggal,
           COUNT(DISTINCT ch.id_checklist) AS selesai
    FROM checklist_harian ch
    JOIN checklist_master cm ON ch.id_checklist = cm.id_checklist
    WHERE ch.tanggal BETWEEN '$dari' AND '$sampai'
    AND   ch.status       = 'Selesai'
    AND   cm.status       = 'aktif'
    AND   LOWER(cm.jenis) = 'daily'
    GROUP BY ch.tanggal
");

$selesai_map = [];
while ($row = mysqli_fetch_assoc($q_selesai_tgl)) {
    $selesai_map[$row['tanggal']] = (int)$row['selesai'];
}

// Bangun rekap_hasil: total = total_per_hari, belum = total - selesai
$rekap_hasil = [];
foreach (array_reverse($dates) as $tgl) {
    $selesai = $selesai_map[$tgl] ?? 0;
    $belum   = max(0, $total_per_hari - $selesai);
    $rekap_hasil[] = [
        'tanggal' => $tgl,
        'total'   => $total_per_hari,
        'selesai' => $selesai,
        'belum'   => $belum,
    ];
}

/* ==========================
   REKAP PER JABATAN
========================== */
$q_jabatan = mysqli_query($conn, "
    SELECT
        cp.jabatan,
        COUNT(DISTINCT cp.id_checklist) AS total_master,
        SUM(CASE WHEN ch.status='Selesai' THEN 1 ELSE 0 END) AS selesai
    FROM checklist_pic cp
    JOIN checklist_master cm
        ON cp.id_checklist = cm.id_checklist
        AND cm.status = 'aktif'
        AND LOWER(cm.jenis) = 'daily'
    LEFT JOIN checklist_harian ch
        ON cp.id_checklist = ch.id_checklist
        AND ch.tanggal BETWEEN '$dari' AND '$sampai'
    GROUP BY cp.jabatan
    ORDER BY cp.jabatan
");

/* ==========================
   REKAP PER USER
========================== */
$q_user = mysqli_query($conn, "
    SELECT
        u.id_user,
        u.nama,
        u.role,
        (
            SELECT COUNT(DISTINCT cp.id_checklist)
            FROM checklist_pic cp
            JOIN checklist_master cm ON cp.id_checklist = cm.id_checklist
            WHERE cm.status       = 'aktif'
            AND   LOWER(cm.jenis) = 'daily'
            AND   cp.jabatan = CASE u.role
                WHEN 'Store_Manager' THEN 'Store_Manager'
                WHEN 'kadiv_gudang'  THEN 'Kadiv_gudang'
                WHEN 'kadiv_ops'     THEN 'kadiv_ops'
                WHEN 'kadiv_cs'      THEN 'kadiv_cs'
                WHEN 'kadiv_kasir'   THEN 'kadiv_kasir'
                ELSE u.role
            END
        ) AS total_master,
        SUM(CASE WHEN ch.status='Selesai' THEN 1 ELSE 0 END) AS selesai
    FROM users u
    LEFT JOIN checklist_harian ch
        ON u.id_user   = ch.id_user
        AND ch.tanggal BETWEEN '$dari' AND '$sampai'
    WHERE u.status = 'aktif'
    AND   u.role NOT IN ('admin','direktur')
    GROUP BY u.id_user, u.nama, u.role
    ORDER BY selesai DESC
");

/* ==========================
   SUMMARY KESELURUHAN
========================== */
$q_total_pic = mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT COUNT(cp.id_pic) AS total_pic
    FROM checklist_pic cp
    JOIN checklist_master cm ON cp.id_checklist = cm.id_checklist
    WHERE cm.status       = 'aktif'
    AND   LOWER(cm.jenis) = 'daily'
"));

$total_pic_aktif = (int)($q_total_pic['total_pic'] ?? 0);

$q_user_per_jabatan = mysqli_query($conn,"
    SELECT
        CASE role
            WHEN 'Store_Manager' THEN 'Store_Manager'
            WHEN 'kadiv_gudang'  THEN 'Kadiv_gudang'
            WHEN 'kadiv_ops'     THEN 'kadiv_ops'
            WHEN 'kadiv_cs'      THEN 'kadiv_cs'
            WHEN 'kadiv_kasir'   THEN 'kadiv_kasir'
            ELSE role
        END AS jabatan_mapped,
        COUNT(*) AS jumlah_user
    FROM users
    WHERE status = 'aktif'
    AND role NOT IN ('admin','direktur')
    GROUP BY role
");

$total_wajib = 0;
while ($ujab = mysqli_fetch_assoc($q_user_per_jabatan)) {
    $jab    = $ujab['jabatan_mapped'];
    $n_user = (int)$ujab['jumlah_user'];

    $q_cl_jab = mysqli_fetch_assoc(mysqli_query($conn,"
        SELECT COUNT(DISTINCT cp.id_checklist) AS n
        FROM checklist_pic cp
        JOIN checklist_master cm ON cp.id_checklist = cm.id_checklist
        WHERE cm.status       = 'aktif'
        AND   LOWER(cm.jenis) = 'daily'
        AND   cp.jabatan      = '$jab'
    "));

    $n_cl = (int)($q_cl_jab['n'] ?? 0);
    $total_wajib += $n_cl * $n_user * $jumlah_hari;
}

// Selesai keseluruhan — DISTINCT per (id_checklist, id_user, tanggal) agar tidak double-count
$q_sum_selesai = mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT COUNT(DISTINCT CONCAT(ch.id_checklist,'-',ch.id_user,'-',ch.tanggal)) AS selesai
    FROM checklist_harian ch
    JOIN checklist_master cm ON ch.id_checklist = cm.id_checklist
    WHERE ch.tanggal      BETWEEN '$dari' AND '$sampai'
    AND   ch.status       = 'Selesai'
    AND   cm.status       = 'aktif'
    AND   LOWER(cm.jenis) = 'daily'
"));

$selesai_all = (int)($q_sum_selesai['selesai'] ?? 0);
$belum_all   = max(0, $total_wajib - $selesai_all);
$pct_all     = $total_wajib > 0 ? round(($selesai_all / $total_wajib) * 100) : 0;
$total_all   = $total_wajib;

include 'layout/sidebar.php';
?>

<style>

.lap-wrapper {
    padding: 28px 28px 56px;
    max-width: 1400px;
    margin: 0 auto;
    font-family: 'DM Sans', 'Inter', sans-serif;
}

.lap-page-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 28px;
    padding-bottom: 18px;
    border-bottom: 2px solid var(--green-100);
    flex-wrap: wrap;
    gap: 10px;
}

.lap-page-head h1 { font-size: 1.35rem; font-weight: 800; color: var(--text-dark); letter-spacing: -0.02em; margin: 0 0 3px; }
.lap-page-head p  { font-size: 0.76rem; color: var(--text-muted); margin: 0; font-family: 'Space Mono', monospace; }

.mon-card {
    background: #ffffff;
    border: 1.5px solid var(--green-100);
    border-radius: 16px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    margin-bottom: 24px;
    animation: fadeUp 0.38s ease both;
}

.mon-card:nth-child(2) { animation-delay: 0.05s; }
.mon-card:nth-child(3) { animation-delay: 0.10s; }
.mon-card:nth-child(4) { animation-delay: 0.15s; }

.mon-card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 14px 22px;
    background: linear-gradient(135deg, #f0fdf4, #e8faf1);
    border-bottom: 1.5px solid var(--green-100);
    border-radius: 16px 16px 0 0;
    font-size: 0.85rem;
    font-weight: 700;
    color: var(--text-dark);
    gap: 12px;
    flex-wrap: wrap;
}

.mon-card-header.success-h {
    background: linear-gradient(135deg, #dcfce7, #f0fdf4);
    border-bottom-color: #bbf7d0;
    color: var(--green-700);
}

.mon-card-body-pad { padding: 20px 22px; }

.filter-form {
    display: flex;
    align-items: flex-end;
    gap: 12px;
    flex-wrap: wrap;
    padding: 18px 22px;
}

.filter-form label {
    font-size: 0.72rem;
    font-weight: 700;
    color: var(--text-muted);
    letter-spacing: 0.08em;
    text-transform: uppercase;
    display: block;
    margin-bottom: 7px;
}

.filter-form input[type="date"] {
    background: var(--green-50);
    border: 1.5px solid var(--green-100);
    border-radius: 9px;
    color: var(--text-dark);
    padding: 8px 13px;
    font-size: 0.85rem;
    outline: none;
    transition: border-color 0.2s, box-shadow 0.2s;
}

.filter-form input[type="date"]:focus {
    border-color: var(--green-400);
    box-shadow: 0 0 0 3px rgba(34,197,94,0.12);
}

.btn-filter {
    background: linear-gradient(135deg, #22c55e, #16a34a);
    color: #fff;
    border: none;
    padding: 10px 20px;
    border-radius: 10px;
    font-weight: 600;
    cursor: pointer;
    transition: .2s;
    white-space: nowrap;
}

.btn-filter:hover {
    background: linear-gradient(135deg, #16a34a, #15803d);
    box-shadow: 0 6px 15px rgba(34,197,94,.25);
}

.btn-cetak {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: #ffffff;
    color: var(--green-700);
    border: 1.5px solid var(--green-200);
    border-radius: 9px;
    padding: 9px 18px;
    font-size: 0.85rem;
    font-weight: 600;
    cursor: pointer;
    text-decoration: none;
    transition: background 0.2s, border-color 0.2s, transform 0.18s;
    white-space: nowrap;
}

.btn-cetak:hover { background: var(--green-50); border-color: var(--green-400); color: var(--green-700); transform: translateY(-1px); }

.summary-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin-bottom: 24px;
}

@media (max-width: 900px) { .summary-grid { grid-template-columns: repeat(2, 1fr); } }
@media (max-width: 500px) { .summary-grid { grid-template-columns: 1fr; } }

.sum-card {
    background: #ffffff;
    border: 1.5px solid var(--green-100);
    border-radius: 16px;
    padding: 20px 18px 16px;
    text-align: center;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    transition: transform 0.22s, box-shadow 0.22s, border-color 0.22s;
    position: relative;
    overflow: hidden;
}

.sum-card::before {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 3px;
    border-radius: 16px 16px 0 0;
    opacity: 0;
    transition: opacity 0.2s;
}

.sum-card:hover { transform: translateY(-3px); box-shadow: 0 8px 24px rgba(34,197,94,0.13); border-color: var(--green-200); }
.sum-card:hover::before { opacity: 1; }

.sum-card-icon { width: 42px; height: 42px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 18px; margin: 0 auto 12px; }
.sum-card .sum-val { font-size: 2rem; font-weight: 800; font-family: 'Space Mono', monospace; line-height: 1; margin-bottom: 6px; }
.sum-card .sum-label { font-size: 0.76rem; color: var(--text-soft); font-weight: 500; }
.sum-card .sum-sub { font-size: 0.67rem; color: var(--text-muted); margin-top: 3px; font-family: 'Space Mono', monospace; }

.sum-card.c-total   { border-color: #bbf7d0; }
.sum-card.c-total   .sum-card-icon { background: #dcfce7; border: 1px solid #bbf7d0; }
.sum-card.c-total   .sum-val { color: var(--green-600); }
.sum-card.c-total::before { background: linear-gradient(90deg, #16a34a, #4ade80); }

.sum-card.c-selesai { border-color: #bbf7d0; }
.sum-card.c-selesai .sum-card-icon { background: #dcfce7; border: 1px solid #bbf7d0; }
.sum-card.c-selesai .sum-val { color: var(--green-600); }
.sum-card.c-selesai::before { background: linear-gradient(90deg, #16a34a, #4ade80); }

.sum-card.c-belum   { border-color: #fecaca; }
.sum-card.c-belum   .sum-card-icon { background: #fef2f2; border: 1px solid #fecaca; }
.sum-card.c-belum   .sum-val { color: #dc2626; }
.sum-card.c-belum::before { background: linear-gradient(90deg, #dc2626, #f87171); }

.prog-track { width: 100%; height: 14px; background: var(--green-50); border: 1px solid var(--green-100); border-radius: 999px; overflow: hidden; }
.prog-fill  { height: 100%; border-radius: 999px; transition: width 0.8s ease; }
.prog-fill.success { background: linear-gradient(90deg, var(--green-600), var(--green-400)); box-shadow: 0 0 10px rgba(34,197,94,0.3); }
.prog-fill.warning { background: linear-gradient(90deg, #d97706, #fbbf24); }
.prog-fill.danger  { background: linear-gradient(90deg, #dc2626, #f87171); }

.prog-label { display: flex; justify-content: space-between; margin-top: 10px; flex-wrap: wrap; gap: 6px; }

.prog-meta-item { font-size: 0.73rem; color: var(--text-muted); font-family: 'Space Mono', monospace; background: var(--green-50); border: 1px solid var(--green-100); padding: 4px 12px; border-radius: 8px; }
.prog-meta-item strong { color: var(--text-dark); font-weight: 700; }
.prog-meta-item.pct { color: var(--green-700); font-weight: 700; background: #dcfce7; border-color: #bbf7d0; }

.periode-info { display: inline-flex; align-items: center; gap: 6px; background: var(--green-50); border: 1.5px solid var(--green-100); border-radius: 8px; padding: 6px 14px; font-size: 0.74rem; color: var(--text-muted); font-family: 'Space Mono', monospace; margin-bottom: 18px; }
.periode-info strong { color: var(--green-700); }

.rekap-tabs { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 20px; }

.tab-btn {
    background: #ffffff;
    border: 1.5px solid var(--green-100);
    color: var(--text-soft);
    border-radius: 9px;
    padding: 8px 18px;
    font-size: 0.8rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.18s;
    font-family: 'DM Sans', sans-serif;
}

.tab-btn:hover { background: var(--green-50); color: var(--green-700); border-color: var(--green-200); }
.tab-btn.active { background: linear-gradient(135deg, var(--green-600), var(--green-400)); border-color: var(--green-500); color: #fff; box-shadow: 0 3px 10px rgba(34,197,94,0.25); }

.tab-panel { display: none; }
.tab-panel.active { display: block; }

.table-responsive { width: 100%; overflow-x: auto; }

.mon-table { width: 100%; min-width: 600px; border-collapse: collapse; font-size: 0.82rem; color: var(--text-dark); }
.mon-table thead tr { background: linear-gradient(135deg, #f0fdf4, #e8faf1); border-bottom: 2px solid var(--green-100); }
.mon-table thead th { padding: 11px 16px; font-size: 0.7rem; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: var(--green-700); white-space: nowrap; text-align: left; }
.mon-table thead th:first-child,
.mon-table tbody td:first-child { width: 44px; text-align: center; }
.mon-table tbody tr { border-bottom: 1px solid #f0fdf4; transition: background 0.15s; }
.mon-table tbody tr:last-child { border-bottom: none; }
.mon-table tbody tr:hover { background: #f8fffe; }
.mon-table tbody td { padding: 11px 16px; vertical-align: middle; color: var(--text-dark); }
.mon-table tbody tr.pg-hidden { display: none; }

.row-num { display: inline-flex; width: 26px; height: 26px; border-radius: 50%; background: var(--green-50); border: 1px solid var(--green-100); align-items: center; justify-content: center; font-size: 0.72rem; font-weight: 700; color: var(--green-700); }

.badge { display: inline-block; padding: 3px 10px; border-radius: 999px; font-size: 0.69rem; font-weight: 700; letter-spacing: 0.04em; white-space: nowrap; }
.badge-role    { background: #dcfce7; color: var(--green-700); border: 1px solid #bbf7d0; }
.badge-jabatan { background: #e0f2fe; color: #0369a1; border: 1px solid #bae6fd; }

.tbl-prog-track { width: 100%; min-width: 120px; height: 9px; background: var(--green-50); border: 1px solid var(--green-100); border-radius: 999px; overflow: hidden; }
.tbl-prog-fill { height: 100%; border-radius: 999px; transition: width 0.5s ease; }
.tbl-prog-fill.success { background: linear-gradient(90deg, var(--green-600), var(--green-400)); box-shadow: 0 0 6px rgba(34,197,94,0.3); }
.tbl-prog-fill.warning { background: linear-gradient(90deg, #d97706, #fbbf24); }
.tbl-prog-fill.danger  { background: linear-gradient(90deg, #dc2626, #f87171); }
.tbl-prog-label { font-size: 0.69rem; color: var(--text-muted); margin-top: 3px; font-family: 'Space Mono', monospace; }

.text-success-em { color: var(--green-600); font-weight: 700; }
.text-danger-em  { color: #dc2626; font-weight: 700; }

.empty-state { font-size: 0.85rem; color: var(--text-muted); padding: 28px 22px; text-align: center; }

.pg-bar { display: flex; align-items: center; justify-content: space-between; padding: 12px 22px; border-top: 1.5px solid var(--green-100); background: #f8fffe; border-radius: 0 0 16px 16px; flex-wrap: wrap; gap: 10px; }
.pg-info { font-size: 0.73rem; color: var(--text-muted); font-family: 'Space Mono', monospace; }
.pg-info strong { color: var(--text-dark); }
.pg-btns { display: flex; gap: 5px; flex-wrap: wrap; align-items: center; }

.pg-btn { background: #ffffff; border: 1.5px solid var(--green-100); color: var(--green-700); border-radius: 8px; padding: 5px 11px; font-size: 0.73rem; font-weight: 600; cursor: pointer; transition: all 0.16s; font-family: 'Space Mono', monospace; }
.pg-btn:hover  { background: var(--green-50); border-color: var(--green-300); }
.pg-btn.active { background: linear-gradient(135deg, var(--green-600), var(--green-400)); border-color: var(--green-500); color: #fff; box-shadow: 0 2px 8px rgba(34,197,94,0.28); }
.pg-btn:disabled { opacity: 0.3; cursor: not-allowed; pointer-events: none; }

@keyframes fadeUp {
    from { opacity: 0; transform: translateY(12px); }
    to   { opacity: 1; transform: translateY(0); }
}
</style>

<div class="lap-wrapper">

<!-- Page head -->
<div class="lap-page-head">
    <div>
        <h1>📈 Laporan Checklist</h1>
        <p><?= date('d/m/Y', strtotime($dari)) ?> — <?= date('d/m/Y', strtotime($sampai)) ?></p>
    </div>
</div>

<!-- Filter -->
<div class="mon-card">
    <div class="mon-card-header">🗓️ Filter Periode</div>
    <form method="GET" class="filter-form">
        <div>
            <label>Dari Tanggal</label>
            <input type="date" name="dari" value="<?= $dari ?>">
        </div>
        <div>
            <label>Sampai Tanggal</label>
            <input type="date" name="sampai" value="<?= $sampai ?>">
        </div>
        <button type="submit" class="btn-filter">Tampilkan</button>
        <a href="laporan.php?dari=<?= $dari ?>&sampai=<?= $sampai ?>&cetak=1"
           target="_blank" class="btn-cetak">🖨️ Cetak / PDF</a>
    </form>
</div>

<!-- Summary Cards -->
<div class="summary-grid">
    <div class="sum-card c-total">
        <div class="sum-card-icon">📋</div>
        <div class="sum-val"><?= $total_all ?></div>
        <div class="sum-label">Total Wajib</div>
        <div class="sum-sub"><?= $total_pic_aktif ?> checklist × <?= $jumlah_hari ?> hari</div>
    </div>
    <div class="sum-card c-selesai">
        <div class="sum-card-icon">✅</div>
        <div class="sum-val"><?= $selesai_all ?></div>
        <div class="sum-label">Selesai</div>
    </div>
    <div class="sum-card c-belum">
        <div class="sum-card-icon">⏳</div>
        <div class="sum-val"><?= $belum_all ?></div>
        <div class="sum-label">Belum</div>
    </div>
</div>

<!-- Overall Progress -->
<div class="mon-card">
    <div class="mon-card-header success-h">
        📊 Overall Progress
        <span style="font-weight:400;font-size:0.8rem;color:var(--text-muted);">
            <?= date('d/m/Y', strtotime($dari)) ?> — <?= date('d/m/Y', strtotime($sampai)) ?>
        </span>
    </div>
    <div class="mon-card-body-pad">
        <?php $oc = $pct_all==100 ? 'success' : ($pct_all>=50 ? 'warning' : 'danger'); ?>
        <div class="prog-track">
            <div class="prog-fill <?= $oc ?>" style="width:<?= $pct_all ?>%;"></div>
        </div>
        <div class="prog-label">
            <div class="prog-meta-item">Selesai: <strong><?= $selesai_all ?></strong></div>
            <div class="prog-meta-item pct"><?= $pct_all ?>%</div>
            <div class="prog-meta-item">Total Wajib: <strong><?= $total_all ?></strong></div>
        </div>
    </div>
</div>

<!-- Rekap Tab -->
<div class="mon-card">
    <div class="mon-card-header">📂 Rekap Data</div>
    <div class="mon-card-body-pad">

        <div class="periode-info">
            📅 Periode: <strong><?= $jumlah_hari ?> hari</strong>
            &nbsp;·&nbsp;
            <?= date('d/m/Y', strtotime($dari)) ?> — <?= date('d/m/Y', strtotime($sampai)) ?>
        </div>

        <div class="rekap-tabs">
            <button class="tab-btn active" onclick="switchTab('user',this)">👤 Per User</button>
            <button class="tab-btn"        onclick="switchTab('jabatan',this)">🏷️ Per Jabatan</button>
            <button class="tab-btn"        onclick="switchTab('tanggal',this)">📅 Per Tanggal</button>
        </div>

        <!-- Per User -->
        <div class="tab-panel active" id="panel-user">
            <div class="table-responsive">
                <table class="mon-table" id="tbl-user">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Nama</th>
                            <th>Role</th>
                            <th>Total Wajib</th>
                            <th>Selesai</th>
                            <th>Belum</th>
                            <th style="min-width:150px;">Progress</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                    $no = 1;
                    while($row = mysqli_fetch_assoc($q_user)):
                        $total_wajib_u = (int)$row['total_master'] * $jumlah_hari;
                        $selesai_u     = (int)($row['selesai'] ?? 0);
                        $belum_u       = max(0, $total_wajib_u - $selesai_u);
                        $pct_u         = $total_wajib_u > 0 ? round(($selesai_u/$total_wajib_u)*100) : 0;
                        $fc_u          = $pct_u==100 ? 'success' : ($pct_u>=50 ? 'warning' : 'danger');
                    ?>
                    <tr>
                        <td><span class="row-num"><?= $no++ ?></span></td>
                        <td style="font-weight:600;"><?= htmlspecialchars($row['nama']) ?></td>
                        <td><span class="badge badge-role"><?= strtoupper($row['role']) ?></span></td>
                        <td>
                            <?= $total_wajib_u ?>
                            <span style="font-size:0.68rem;color:var(--text-muted);display:block;">
                                <?= $row['total_master'] ?> × <?= $jumlah_hari ?> hari
                            </span>
                        </td>
                        <td><span class="text-success-em"><?= $selesai_u ?></span></td>
                        <td><span class="text-danger-em"><?= $belum_u ?></span></td>
                        <td>
                            <div class="tbl-prog-track">
                                <div class="tbl-prog-fill <?= $fc_u ?>" style="width:<?= $pct_u ?>%;"></div>
                            </div>
                            <div class="tbl-prog-label"><?= $pct_u ?>%</div>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
            <div class="pg-bar" id="pg-user"></div>
        </div>

        <!-- Per Jabatan -->
        <div class="tab-panel" id="panel-jabatan">
            <div class="table-responsive">
                <table class="mon-table" id="tbl-kategori">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Jabatan</th>
                            <th>Total Master</th>
                            <th>Total Wajib</th>
                            <th>Selesai</th>
                            <th>Belum</th>
                            <th style="min-width:150px;">Progress</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                    $no = 1;
                    while($row = mysqli_fetch_assoc($q_jabatan)):
                        $total_wajib_j = (int)$row['total_master'] * $jumlah_hari;
                        $selesai_j     = (int)($row['selesai'] ?? 0);
                        $belum_j       = max(0, $total_wajib_j - $selesai_j);
                        $pct_j         = $total_wajib_j > 0 ? round(($selesai_j/$total_wajib_j)*100) : 0;
                        $fc_j          = $pct_j==100 ? 'success' : ($pct_j>=50 ? 'warning' : 'danger');
                    ?>
                    <tr>
                        <td><span class="row-num"><?= $no++ ?></span></td>
                        <td><span class="badge badge-jabatan"><?= htmlspecialchars($row['jabatan']) ?></span></td>
                        <td style="font-family:'Space Mono',monospace;font-size:0.8rem;">
                            <?= $row['total_master'] ?> checklist
                        </td>
                        <td>
                            <?= $total_wajib_j ?>
                            <span style="font-size:0.68rem;color:var(--text-muted);display:block;">
                                <?= $row['total_master'] ?> × <?= $jumlah_hari ?> hari
                            </span>
                        </td>
                        <td><span class="text-success-em"><?= $selesai_j ?></span></td>
                        <td><span class="text-danger-em"><?= $belum_j ?></span></td>
                        <td>
                            <div class="tbl-prog-track">
                                <div class="tbl-prog-fill <?= $fc_j ?>" style="width:<?= $pct_j ?>%;"></div>
                            </div>
                            <div class="tbl-prog-label"><?= $pct_j ?>%</div>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
            <div class="pg-bar" id="pg-kategori"></div>
        </div>

        <!-- Per Tanggal -->
        <div class="tab-panel" id="panel-tanggal">
            <?php if(empty($rekap_hasil)): ?>
                <div class="empty-state">
                    <div style="font-size:32px;margin-bottom:8px;opacity:.4;">📭</div>
                    Tidak ada data pada periode ini.
                </div>
            <?php else: ?>
            <div class="table-responsive">
                <table class="mon-table" id="tbl-tanggal">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Tanggal</th>
                            <th>Total</th>
                            <th>Selesai</th>
                            <th>Belum</th>
                            <th style="min-width:150px;">Progress</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                    $no = 1;
                    foreach($rekap_hasil as $row):
                        $pct_t = $row['total'] > 0 ? round(($row['selesai'] / $row['total']) * 100) : 0;
                        $fc_t  = $pct_t==100 ? 'success' : ($pct_t>=50 ? 'warning' : 'danger');
                    ?>
                    <tr>
                        <td><span class="row-num"><?= $no++ ?></span></td>
                        <td style="font-family:'Space Mono',monospace;font-size:0.8rem;">
                            <?= date('d/m/Y', strtotime($row['tanggal'])) ?>
                        </td>
                        <td><?= $row['total'] ?></td>
                        <td><span class="text-success-em"><?= $row['selesai'] ?></span></td>
                        <td><span class="text-danger-em"><?= $row['belum'] ?></span></td>
                        <td>
                            <div class="tbl-prog-track">
                                <div class="tbl-prog-fill <?= $fc_t ?>" style="width:<?= $pct_t ?>%;"></div>
                            </div>
                            <div class="tbl-prog-label"><?= $pct_t ?>%</div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <div class="pg-bar" id="pg-tanggal"></div>
            <?php endif; ?>
        </div>

    </div>
</div>

</div>

<script>
function switchTab(name, btn) {
    document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    document.getElementById('panel-' + name).classList.add('active');
    btn.classList.add('active');
}

function makePagination(tableId, barId, perPage = 10) {
    const tbody = document.querySelector('#' + tableId + ' tbody');
    const bar   = document.getElementById(barId);
    if (!tbody || !bar) return;

    const rows  = Array.from(tbody.querySelectorAll('tr'));
    const total = rows.length;
    if (total <= perPage) return;

    const totalPages = Math.ceil(total / perPage);

    function render(page) {
        rows.forEach((tr, i) => {
            tr.classList.toggle('pg-hidden', i < (page-1)*perPage || i >= page*perPage);
        });

        const from = (page-1)*perPage + 1;
        const to   = Math.min(page*perPage, total);

        bar.innerHTML = `
            <span class="pg-info">
                Menampilkan <strong>${from}–${to}</strong> dari <strong>${total}</strong> data
            </span>
            <div class="pg-btns" id="${barId}-btns"></div>
        `;

        const btns = document.getElementById(barId + '-btns');

        const prev = document.createElement('button');
        prev.className = 'pg-btn'; prev.textContent = '← Prev';
        prev.disabled = page === 1;
        prev.onclick = () => render(page - 1);
        btns.appendChild(prev);

        for (let p = 1; p <= totalPages; p++) {
            if (p === 1 || p === totalPages || (p >= page-1 && p <= page+1)) {
                const btn = document.createElement('button');
                btn.className = 'pg-btn' + (p === page ? ' active' : '');
                btn.textContent = p;
                btn.onclick = () => render(p);
                btns.appendChild(btn);
            } else if (p === page-2 || p === page+2) {
                const ell = document.createElement('span');
                ell.className = 'pg-btn';
                ell.style.cssText = 'cursor:default;opacity:0.35;pointer-events:none;';
                ell.textContent = '…';
                btns.appendChild(ell);
            }
        }

        const next = document.createElement('button');
        next.className = 'pg-btn'; next.textContent = 'Next →';
        next.disabled = page === totalPages;
        next.onclick = () => render(page + 1);
        btns.appendChild(next);
    }

    render(1);
}

makePagination('tbl-user',     'pg-user',     10);
makePagination('tbl-kategori', 'pg-kategori', 10);
makePagination('tbl-tanggal',  'pg-tanggal',  10);
</script>

<?php include 'layout/footer.php'; ?>