<?php

$judul = "Checklist Management";
$menu  = "checklist";

include 'layout/header.php';

/* ==========================
   HANDLE HAPUS
========================== */
if(isset($_GET['hapus'])){
    $id = (int)$_GET['hapus'];

    /* Hapus pic dulu baru master */
    mysqli_query($conn, "DELETE FROM checklist_pic WHERE id_checklist = '$id'");
    mysqli_query($conn, "DELETE FROM checklist_master WHERE id_checklist = '$id'");

    header("Location: checklist.php");
    exit;
}

/* ==========================
   QUERY — JOIN ke checklist_pic
   GROUP_CONCAT agar jabatan dari pic
   terkumpul jadi satu string per checklist
========================== */
$data = mysqli_query($conn,"
    SELECT
        cm.*,
        GROUP_CONCAT(cp.jabatan ORDER BY cp.id_pic SEPARATOR ',') AS pic_list,
        COUNT(cp.id_pic) AS pic_count
    FROM checklist_master cm
    LEFT JOIN checklist_pic cp ON cm.id_checklist = cp.id_checklist
    GROUP BY cm.id_checklist
    ORDER BY cm.id_checklist DESC
");

if($data === false){
    die("Query error: " . mysqli_error($conn));
}

include 'layout/sidebar.php';
?>

<style>

*, *::before, *::after { box-sizing: border-box; }

.cl-wrapper {
    padding: 28px 24px 48px;
    max-width: 1300px;
    margin: 0 auto;
    font-family: 'DM Sans', 'Inter', sans-serif;
}

.page-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 28px;
    padding-bottom: 20px;
    border-bottom: 2px solid #e8faf2;
    flex-wrap: wrap;
    gap: 12px;
}

.page-head-left h1 {
    font-size: 1.4rem;
    font-weight: 800;
    color: #0a2e1c;
    letter-spacing: -0.02em;
    margin: 0 0 4px;
}

.page-head-left p {
    font-size: 0.8rem;
    color: #6b9e82;
    margin: 0;
}

.header-action {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

/* Buttons */
.btn-head {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 9px 18px;
    border-radius: 10px;
    font-size: 0.85rem;
    font-weight: 700;
    text-decoration: none;
    border: none;
    cursor: pointer;
    transition: all 0.2s;
    white-space: nowrap;
}

.btn-green {
    background: linear-gradient(135deg, #16a34a, #22c55e);
    color: #fff;
    box-shadow: 0 3px 12px rgba(34,197,94,0.25);
}

.btn-green:hover { opacity: 0.88; transform: translateY(-1px); color: #fff; }

.btn-blue {
    background: linear-gradient(135deg, #2563eb, #3b82f6);
    color: #fff;
    box-shadow: 0 3px 12px rgba(59,130,246,0.25);
}

.btn-blue:hover { opacity: 0.88; transform: translateY(-1px); color: #fff; }

.btn-yellow {
    background: linear-gradient(135deg, #d97706, #f59e0b);
    color: #fff;
    box-shadow: 0 3px 12px rgba(245,158,11,0.25);
}

.btn-yellow:hover { opacity: 0.88; transform: translateY(-1px); color: #fff; }

/* Card */
.main-card {
    background: #ffffff;
    border: 1.5px solid #d4f5e5;
    border-radius: 18px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
    animation: fadeUp 0.4s ease both;
}

.card-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 24px;
    background: linear-gradient(135deg, #f0fdf7, #e6faf1);
    border-bottom: 1.5px solid #c6f0da;
    flex-wrap: wrap;
    gap: 10px;
}

.card-head-title {
    font-size: 0.88rem;
    font-weight: 700;
    color: #0a2e1c;
    display: flex;
    align-items: center;
    gap: 8px;
}

.card-head-count {
    font-size: 0.72rem;
    font-family: 'Space Mono', monospace;
    color: #00a858;
    background: rgba(0,168,88,0.08);
    border: 1px solid rgba(0,168,88,0.18);
    padding: 3px 10px;
    border-radius: 999px;
}

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

.cl-table {
    width: 100%;
    min-width: 800px;
    border-collapse: collapse;
    font-size: 0.83rem;
    color: #1a2e22;
}

.cl-table thead tr {
    background: linear-gradient(135deg, #f0fdf7, #e8faf2);
    border-bottom: 2px solid #c6f0da;
}

.cl-table thead th {
    padding: 12px 16px;
    font-size: 0.7rem;
    font-weight: 700;
    letter-spacing: 0.08em;
    text-transform: uppercase;
    color: #2d7a4f;
    white-space: nowrap;
    text-align: left;
}

.cl-table thead th:first-child { text-align: center; width: 50px; }

.cl-table tbody tr {
    border-bottom: 1px solid #edf9f2;
    transition: background 0.15s;
}

.cl-table tbody tr:last-child { border-bottom: none; }
.cl-table tbody tr:hover      { background: #f5fdf8; }

.cl-table tbody td {
    padding: 12px 16px;
    vertical-align: middle;
    color: #1a2e22;
}

.cl-table tbody td:first-child { text-align: center; }
.cl-table tbody tr.pg-hidden   { display: none; }

/* Row num */
.row-num {
    display: inline-flex;
    width: 26px; height: 26px;
    border-radius: 50%;
    background: #e8faf2;
    border: 1px solid #c6f0da;
    align-items: center; justify-content: center;
    font-size: 0.72rem;
    font-weight: 700;
    color: #2d7a4f;
}

/* Job list / desc */
.job-list-name { font-weight: 700; color: #0a2e1c; font-size: 0.85rem; }

.job-desc-text {
    font-size: 0.77rem;
    color: #5a8a6e;
    max-width: 220px;
    line-height: 1.5;
    word-break: break-word;
}

/* Waktu */
.waktu-pill {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    background: #f0fdf7;
    border: 1px solid #c6f0da;
    border-radius: 7px;
    padding: 3px 9px;
    font-size: 0.72rem;
    font-family: 'Space Mono', monospace;
    color: #2d7a4f;
    white-space: nowrap;
}

/* Badges */
.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-daily   { background: #dcfce7; color: #16a34a; border: 1px solid #bbf7d0; }
.badge-weekly  { background: #fef9c3; color: #ca8a04; border: 1px solid #fde68a; }
.badge-monthly { background: #dbeafe; color: #2563eb; border: 1px solid #bfdbfe; }

/* PIC badges */
.pic-wrap { display: flex; flex-wrap: wrap; gap: 4px; }

.badge-pic {
    display: inline-flex;
    align-items: center;
    gap: 3px;
    background: #f0fdf7;
    color: #0a7a3e;
    border: 1px solid #a7f3d0;
    border-radius: 7px;
    padding: 3px 9px;
    font-size: 0.69rem;
    font-weight: 600;
    white-space: nowrap;
}

/* Sumber badge — dari pic table atau jabatan column */
.badge-pic.from-pic {
    background: #dcfce7;
    border-color: #86efac;
    color: #166534;
}

.badge-pic.from-col {
    background: #eff6ff;
    border-color: #bfdbfe;
    color: #1d4ed8;
}

.no-pic {
    font-size: 0.75rem;
    color: #aaa;
    font-style: italic;
}

/* Action buttons */
.act-wrap { display: flex; gap: 5px; flex-wrap: wrap; }

.btn-act {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 5px 11px;
    border-radius: 8px;
    font-size: 0.74rem;
    font-weight: 600;
    text-decoration: none;
    border: 1.5px solid transparent;
    cursor: pointer;
    transition: all 0.18s;
    white-space: nowrap;
    background: none;
}

.btn-edit   { background: #fefce8; color: #a16207; border-color: #fde68a; }
.btn-edit:hover   { background: #fef08a; color: #92400e; transform: translateY(-1px); }

.btn-delete { background: #fef2f2; color: #dc2626; border-color: #fecaca; }
.btn-delete:hover { background: #fee2e2; color: #991b1b; transform: translateY(-1px); }

/* Empty state */
.empty-state { text-align: center; padding: 56px 20px; color: #6b9e82; }
.empty-state .empty-icon { font-size: 44px; margin-bottom: 12px; opacity: 0.4; display: block; }
.empty-state p { font-size: 0.88rem; margin: 0; }

/* Pagination */
.pg-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 14px 24px;
    border-top: 1.5px solid #e8faf2;
    background: #f8fefb;
    flex-wrap: wrap;
    gap: 10px;
}

.pg-info { font-size: 0.74rem; color: #6b9e82; font-family: 'Space Mono', monospace; }
.pg-info strong { color: #0a7a3e; }
.pg-btns { display: flex; gap: 5px; flex-wrap: wrap; align-items: center; }

.pg-btn {
    background: #ffffff;
    border: 1.5px solid #c6f0da;
    color: #2d7a4f;
    border-radius: 8px;
    padding: 5px 12px;
    font-size: 0.74rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.16s;
    font-family: 'Space Mono', monospace;
}

.pg-btn:hover  { background: #e8faf2; border-color: #4ade80; color: #0a7a3e; }
.pg-btn.active { background: linear-gradient(135deg, #16a34a, #22c55e); border-color: #16a34a; 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(14px); }
    to   { opacity: 1; transform: translateY(0); }
}

</style>

<div class="cl-wrapper">

    <!-- Page Header -->
    <div class="page-head">
        <div class="page-head-left">
            <h1>📋 Checklist Management</h1>
            <p>Kelola daftar checklist harian, mingguan, dan bulanan</p>
        </div>

        <div class="header-action">
            <a href="job_desc.php"           class="btn-head btn-blue">📝 Job Desc</a>
            <a href="tambah_checklist.php"   class="btn-head btn-green">➕ Tambah Checklist</a>
        </div>
    </div>

    <!-- Main Card -->
    <div class="main-card">

        <div class="card-head">
            <div class="card-head-title">📝 Daftar Checklist Master</div>
            <span class="card-head-count"><?= mysqli_num_rows($data) ?> checklist</span>
        </div>

        <div class="table-responsive">
            <table class="cl-table" id="tbl-cl">
                <thead>
                    <tr>
                        <th>#</th>
                        <th style="min-width:180px;">Job List</th>
                        <th style="min-width:200px;">Job Desc</th>
                        <th>Waktu</th>
                        <th>Jenis</th>
                        <th style="min-width:200px;">Jabatan / PIC</th>
                        <th>Aksi</th>
                    </tr>
                </thead>
                <tbody>
                <?php
                $no    = 1;
                $total = mysqli_num_rows($data);

                if($total == 0):
                ?>
                    <tr>
                        <td colspan="7">
                            <div class="empty-state">
                                <span class="empty-icon">📭</span>
                                <p>Belum ada checklist. Klik <strong style="color:#00a858">Tambah Checklist</strong> untuk memulai.</p>
                            </div>
                        </td>
                    </tr>
                <?php else: while($row = mysqli_fetch_assoc($data)):
                    $jenis_lower = strtolower($row['jenis'] ?? 'daily');

                    /*
                       Prioritas tampil jabatan:
                       1. Dari tabel checklist_pic (pic_list) — hasil import / tambah baru
                       2. Fallback ke kolom jabatan di checklist_master
                    */
                    $pic_list    = $row['pic_list'] ?? '';
                    $pic_count   = (int)($row['pic_count'] ?? 0);
                    $jabatan_col = $row['jabatan'] ?? '';
                ?>
                    <tr>
                        <td><span class="row-num"><?= $no++ ?></span></td>

                        <td>
                            <div class="job-list-name">
                                <?= htmlspecialchars($row['job_list']) ?>
                            </div>
                        </td>

                        <td>
                            <div class="job-desc-text">
                                <?= htmlspecialchars($row['job_desc'] ?? '—') ?>
                            </div>
                        </td>

                        <td>
                            <span class="waktu-pill">
                                🕐 <?= htmlspecialchars($row['waktu'] ?? '—') ?>
                            </span>
                        </td>

                        <td>
                            <span class="badge badge-<?= $jenis_lower ?>">
                                <?= htmlspecialchars($row['jenis'] ?? '—') ?>
                            </span>
                        </td>

                        <td>
                            <div class="pic-wrap">
                            <?php
                            if($pic_count > 0 && !empty($pic_list)):
                                /* Dari tabel checklist_pic */
                                $pics = array_filter(array_map('trim', explode(',', $pic_list)));
                                foreach($pics as $p):
                            ?>
                                <span class="badge-pic from-pic">
                                    👤 <?= htmlspecialchars($p) ?>
                                </span>
                            <?php
                                endforeach;
                            elseif(!empty($jabatan_col)):
                                /* Fallback dari kolom jabatan checklist_master */
                                $jabatans = array_filter(array_map('trim', explode(',', $jabatan_col)));
                                foreach($jabatans as $j):
                            ?>
                                <span class="badge-pic from-col">
                                    👤 <?= htmlspecialchars($j) ?>
                                </span>
                            <?php
                                endforeach;
                            else:
                            ?>
                                <span class="no-pic">—</span>
                            <?php endif; ?>
                            </div>
                        </td>

                        <td>
                            <div class="act-wrap">
                                <a href="edit_checklist.php?id=<?= $row['id_checklist'] ?>"
                                   class="btn-act btn-edit">✏️ Edit</a>
                                <a href="checklist.php?hapus=<?= $row['id_checklist'] ?>"
                                   class="btn-act btn-delete"
                                   onclick="return confirm('Yakin hapus checklist ini? Data pic terkait juga akan dihapus.')">
                                   🗑️ Hapus</a>
                            </div>
                        </td>
                    </tr>
                <?php endwhile; endif; ?>
                </tbody>
            </table>
        </div>

        <div class="pg-bar" id="pg-cl"></div>

    </div>

</div>

<script>
function makePagination(tableId, barId, perPage = 15) {
    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> checklist
            </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-cl', 'pg-cl', 15);
</script>

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