<?php

$judul = "Monitoring Checklist";
$menu  = "monitoring";

include 'layout/header.php';

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

/* ── MOD: ambil dari id_petugas, bisa lebih dari 1 per hari ── */
$q_mod = mysqli_query($conn, "
    SELECT
        u.nama,
        mh.shift
    FROM mod_harian mh
    JOIN users u ON mh.id_petugas = u.id_user
    WHERE mh.tanggal = '$tanggal'
    ORDER BY mh.shift ASC
");
$mod_rows  = mysqli_fetch_all($q_mod, MYSQLI_ASSOC);
$mod_count = count($mod_rows);

/* ── Detail checklist ── */
$q_detail = mysqli_query($conn, "
    SELECT
        cm.job_list,
        cm.job_desc,
        cm.waktu,
        cm.jenis,
        cm.jabatan,
        u.nama  AS nama_user,
        ch.status,
        ch.keterangan,
        ch.waktu_selesai
    FROM checklist_master cm
    LEFT JOIN checklist_harian ch
        ON cm.id_checklist = ch.id_checklist
        AND ch.tanggal = '$tanggal'
    LEFT JOIN users u
        ON ch.id_user = u.id_user
    WHERE cm.status = 'aktif'
    ORDER BY cm.jenis, cm.jabatan, cm.job_list
");

if($q_detail === false){
    die("<div style='padding:20px;color:red;font-family:monospace;'>
        Query Error Detail: " . mysqli_error($conn) . "
    </div>");
}

include 'layout/sidebar.php';
?>

<style>

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

.mon-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;
}

.mon-page-head h1 {
    font-size: 1.35rem;
    font-weight: 800;
    color: var(--text-dark);
    letter-spacing: -0.02em;
    margin: 0 0 3px;
}

.mon-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;
    overflow: visible;
    animation: fadeUp 0.38s ease both;
}

.mon-card:nth-child(2) { animation-delay: 0.06s; }
.mon-card:nth-child(3) { animation-delay: 0.12s; }
.mon-card:nth-child(4) { animation-delay: 0.18s; }
.mon-card:nth-child(5) { animation-delay: 0.24s; }

.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);
    flex-wrap: wrap;
    gap: 8px;
}

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

.mon-card-header.warning {
    background: linear-gradient(135deg, #fffbeb, #fef9c3);
    border-bottom-color: #fde68a;
    color: #92400e;
}

.mon-card-body-pad { padding: 18px 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;
    font-family: 'DM Sans', sans-serif;
}

.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;
}

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

/* ── MOD List ── */
.mod-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.mod-item {
    display: flex;
    align-items: center;
    gap: 10px;
    background: linear-gradient(135deg, #f0fdf4, #e8faf1);
    border: 1.5px solid #bbf7d0;
    border-radius: 12px;
    padding: 10px 16px;
    min-width: 200px;
    flex: 1;
}

.mod-item-icon {
    font-size: 1.3rem;
    flex-shrink: 0;
}

.mod-item-info { flex: 1; }

.mod-item-name {
    font-size: 0.9rem;
    font-weight: 700;
    color: var(--green-700);
    display: block;
    margin-bottom: 2px;
}

.mod-item-shift {
    display: inline-block;
    font-size: 0.7rem;
    font-weight: 700;
    padding: 2px 8px;
    border-radius: 999px;
    font-family: 'Space Mono', monospace;
}

.shift-pagi   { background: #fef9c3; color: #92400e; border: 1px solid #fde68a; }
.shift-siang  { background: #fff7ed; color: #c2410c; border: 1px solid #fed7aa; }
.shift-sore   { background: #ede9fe; color: #6d28d9; border: 1px solid #ddd6fe; }
.shift-malam  { background: #1e1b4b; color: #c7d2fe; border: 1px solid #3730a3; }
.shift-default{ background: #f1f5f9; color: #475569; border: 1px solid #cbd5e1; }

.mod-empty { font-size: 0.85rem; color: var(--text-muted); }

.mod-count-badge {
    background: var(--green-600);
    color: #fff;
    font-family: 'Space Mono', monospace;
    font-size: 0.72rem;
    font-weight: 700;
    padding: 2px 10px;
    border-radius: 999px;
}

/* ── Table ── */
.table-responsive {
    width: 100%;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

.mon-table {
    width: 100%;
    min-width: 700px;
    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;
    word-break: break-word;
    max-width: 260px;
    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-jenis-daily   { background: #dcfce7; color: #166534;          border: 1px solid #bbf7d0; }
.badge-jenis-weekly  { background: #fef9c3; color: #854d0e;          border: 1px solid #fde68a; }
.badge-jenis-monthly { background: #dbeafe; color: #1e40af;          border: 1px solid #bfdbfe; }
.badge-jabatan       { background: #f1f5f9; color: #475569;          border: 1px solid #e2e8f0; }
.badge-selesai       { background: #dcfce7; color: var(--green-700); border: 1px solid #bbf7d0; }
.badge-belum         { background: #fef2f2; color: #dc2626;          border: 1px solid #fecaca; }
.badge-none          { background: #f8fafc; color: #94a3b8;          border: 1px solid #e2e8f0; }

.waktu-pill {
    display: inline-block;
    background: var(--green-50);
    border: 1px solid var(--green-100);
    border-radius: 6px;
    padding: 2px 8px;
    font-size: 0.72rem;
    font-family: 'Space Mono', monospace;
    color: var(--green-700);
    white-space: nowrap;
}

.job-desc-cell {
    font-size: 0.78rem;
    color: var(--text-soft);
    max-width: 220px;
    line-height: 1.5;
}

.empty-state {
    font-size: 0.85rem;
    color: var(--text-muted);
    padding: 36px 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-400); }
.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="mon-wrapper">

<div class="mon-page-head">
    <div>
        <h1>👁️ Monitoring Checklist</h1>
        <p><?= strtoupper(date('D, d M Y', strtotime($tanggal))) ?></p>
    </div>
</div>

<!-- FILTER -->
<div class="mon-card">
    <div class="mon-card-header">🗓️ Filter Tanggal</div>
    <form method="GET" class="filter-form">
        <div>
            <label>Pilih Tanggal</label>
            <input type="date" name="tanggal" value="<?= htmlspecialchars($tanggal) ?>">
        </div>
        <button type="submit" class="btn-filter">Tampilkan</button>
    </form>
</div>

<!-- MOD -->
<div class="mon-card">
    <div class="mon-card-header primary">
        <span>🛡️ MOD Tanggal <?= date('d/m/Y', strtotime($tanggal)) ?></span>
        <?php if($mod_count > 0): ?>
            <span class="mod-count-badge"><?= $mod_count ?> Petugas</span>
        <?php endif; ?>
    </div>
    <div class="mon-card-body-pad">
        <?php if($mod_count > 0): ?>
            <div class="mod-list">
                <?php foreach($mod_rows as $mod):
                    $waktu_lower = strtolower($mod['waktu'] ?? '');
                    if(str_contains($waktu_lower, 'pagi')){
                        $shift_class = 'shift-pagi';
                        $shift_icon  = '🌅';
                    } elseif(str_contains($waktu_lower, 'siang')){
                        $shift_class = 'shift-siang';
                        $shift_icon  = '☀️';
                    } elseif(str_contains($waktu_lower, 'sore')){
                        $shift_class = 'shift-sore';
                        $shift_icon  = '🌇';
                    } elseif(str_contains($waktu_lower, 'malam')){
                        $shift_class = 'shift-malam';
                        $shift_icon  = '🌙';
                    } else {
                        $shift_class = 'shift-default';
                        $shift_icon  = '⏰';
                    }
                ?>
                <div class="mod-item">
                    <span class="mod-item-icon">🛡️</span>
                    <div class="mod-item-info">
                        <span class="mod-item-name">
                            <?= htmlspecialchars($mod['nama']) ?>
                        </span>
                        <?php if(!empty($mod['waktu'])): ?>
                        <span class="mod-item-shift <?= $shift_class ?>">
                            <?= $shift_icon ?> <?= htmlspecialchars($mod['waktu']) ?>
                        </span>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <span class="mod-empty">
                📭 Belum ada MOD terdaftar untuk tanggal ini.
            </span>
        <?php endif; ?>
    </div>
</div>

<!-- Detail Checklist -->
<div class="mon-card">
    <div class="mon-card-header">📋 Detail Status Checklist</div>
    <div class="table-responsive">
        <table class="mon-table" id="tbl-detail" style="min-width:960px;">
            <thead>
                <tr>
                    <th>No</th>
                    <th style="min-width:200px;">Job List</th>
                    <th style="min-width:200px;">Job Desc</th>
                    <th>Waktu</th>
                    <th>Jenis</th>
                    <th>Jabatan</th>
                    <th style="min-width:130px;">Dikerjakan Oleh</th>
                    <th>Status</th>
                    <th>Selesai</th>
                    <th style="min-width:160px;">Keterangan</th>
                </tr>
            </thead>
            <tbody>
            <?php if(mysqli_num_rows($q_detail) > 0):
                $no = 1;
                while($row = mysqli_fetch_assoc($q_detail)):
                    $jenis_lower = strtolower($row['jenis'] ?? 'daily');
            ?>
                <tr>
                    <td><span class="row-num"><?= $no++ ?></span></td>
                    <td style="font-weight:600;"><?= htmlspecialchars($row['job_list']) ?></td>
                    <td>
                        <div class="job-desc-cell">
                            <?= htmlspecialchars($row['job_desc'] ?? '—') ?>
                        </div>
                    </td>
                    <td>
                        <span class="waktu-pill">
                            <?= htmlspecialchars($row['waktu'] ?? '—') ?>
                        </span>
                    </td>
                    <td>
                        <span class="badge badge-jenis-<?= $jenis_lower ?>">
                            <?= htmlspecialchars($row['jenis']) ?>
                        </span>
                    </td>
                    <td>
                        <span class="badge badge-jabatan">
                            <?= htmlspecialchars($row['jabatan']) ?>
                        </span>
                    </td>
                    <td><?= htmlspecialchars($row['nama_user'] ?? '—') ?></td>
                    <td>
                        <?php if($row['status'] == 'Selesai'): ?>
                            <span class="badge badge-selesai">✓ Selesai</span>
                        <?php elseif($row['status'] == 'Belum'): ?>
                            <span class="badge badge-belum">⏳ Belum</span>
                        <?php else: ?>
                            <span class="badge badge-none">—</span>
                        <?php endif; ?>
                    </td>
                    <td style="font-family:'Space Mono',monospace;font-size:0.78rem;color:var(--text-soft);">
                        <?= $row['waktu_selesai'] ? date('H:i', strtotime($row['waktu_selesai'])) : '—' ?>
                    </td>
                    <td style="color:var(--text-soft);font-size:0.8rem;">
                        <?= htmlspecialchars($row['keterangan'] ?? '—') ?>
                    </td>
                </tr>
            <?php endwhile; else: ?>
                <tr>
                    <td colspan="10">
                        <div class="empty-state">
                            <div style="font-size:28px;margin-bottom:8px;opacity:.4;">📋</div>
                            Tidak ada checklist aktif.
                        </div>
                    </td>
                </tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
    <div class="pg-bar" id="pg-detail"></div>
</div>

</div>

<script>
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')).filter(tr =>
        !tr.querySelector('td[colspan]')
    );
    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-detail', 'pg-detail', 10);
</script>

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