<?php
require_once __DIR__ . '/../includes/header_admin.php';
require_once __DIR__ . '/../config/db.php';

//////////////////////////////////////////////////////
// INPUT FILTER
//////////////////////////////////////////////////////

$search_uid     = trim($_GET['search_uid'] ?? '');
$search_siswa   = trim($_GET['search_siswa'] ?? '');
$filter_kelas   = trim($_GET['filter_kelas'] ?? '');
$filter_jurusan = trim($_GET['filter_jurusan'] ?? '');

// Pagination params
$limit_pool = 20; // per page for UID pool (A)
$page_pool = isset($_GET['p_uid']) ? max(1, intval($_GET['p_uid'])) : 1;
$offset_pool = ($page_pool - 1) * $limit_pool;

$limit_assigned = 20;
$page_assigned  = isset($_GET["p"]) ? max(1, intval($_GET["p"])) : 1;
$offset_assigned = ($page_assigned - 1) * $limit_assigned;

//////////////////////////////////////////////////////
// UID POOL (search applied + pagination)
//////////////////////////////////////////////////////

$sql_pool = "SELECT * FROM uid_pool";
$cond_pool = [];

if ($search_uid !== '') {
    $cond_pool[] = "uid LIKE :search_uid";
}

if ($cond_pool) $sql_pool .= " WHERE " . implode(" AND ", $cond_pool);
$sql_pool .= " ORDER BY first_seen DESC LIMIT :limit_pool OFFSET :offset_pool";

$stmt_pool = $pdo->prepare($sql_pool);

if ($search_uid !== '') {
    $stmt_pool->bindValue(":search_uid", "%$search_uid%");
}
$stmt_pool->bindValue(":limit_pool", (int)$limit_pool, PDO::PARAM_INT);
$stmt_pool->bindValue(":offset_pool", (int)$offset_pool, PDO::PARAM_INT);

$stmt_pool->execute();
$pool = $stmt_pool->fetchAll();

// count total pool for pagination
$sql_pool_count = "SELECT COUNT(*) FROM uid_pool";
if ($cond_pool) $sql_pool_count .= " WHERE " . implode(" AND ", $cond_pool);
$stmt_pool_count = $pdo->prepare($sql_pool_count);
if ($search_uid !== '') {
    $stmt_pool_count->bindValue(":search_uid", "%$search_uid%");
}
$stmt_pool_count->execute();
$total_pool = (int)$stmt_pool_count->fetchColumn();
$total_pool_pages = max(1, (int)ceil($total_pool / $limit_pool));

//////////////////////////////////////////////////////
// UID ASSIGNED (search + filter + pagination)
//////////////////////////////////////////////////////

$where  = ["uid IS NOT NULL"];
$params = [];

// Search siswa
if ($search_siswa !== "") {
    $where[] = "(nama LIKE :s OR nis LIKE :s OR uid LIKE :s)";
    $params[":s"] = "%$search_siswa%";
}

// Filter kelas
if ($filter_kelas !== "") {
    $where[] = "kelas = :kelas";
    $params[":kelas"] = $filter_kelas;
}

// Filter jurusan
if ($filter_jurusan !== "") {
    $where[] = "jurusan = :jurusan";
    $params[":jurusan"] = $filter_jurusan;
}

$where_sql = implode(" AND ", $where);

// Count for pagination
$stmt_count = $pdo->prepare("SELECT COUNT(*) FROM siswa WHERE $where_sql");
$stmt_count->execute($params);
$total = $stmt_count->fetchColumn();
$total_pages = max(1, (int)ceil($total / $limit_assigned));

// Fetch data
$sql_assigned = "
    SELECT id, nama, nis, kelas, jurusan, rombel, uid
    FROM siswa
    WHERE $where_sql
    ORDER BY nama ASC
    LIMIT :limit_assigned OFFSET :offset_assigned
";

$stmt_assigned = $pdo->prepare($sql_assigned);

foreach ($params as $k => $v) {
    $stmt_assigned->bindValue($k, $v);
}

$stmt_assigned->bindValue(":limit_assigned", (int)$limit_assigned, PDO::PARAM_INT);
$stmt_assigned->bindValue(":offset_assigned", (int)$offset_assigned, PDO::PARAM_INT);
$stmt_assigned->execute();

$assigned = $stmt_assigned->fetchAll();

//////////////////////////////////////////////////////
// List kelas & jurusan for filter dropdown
//////////////////////////////////////////////////////

$list_kelas = $pdo->query("SELECT DISTINCT kelas FROM siswa ORDER BY kelas")->fetchAll(PDO::FETCH_COLUMN);
$list_jurusan = $pdo->query("SELECT DISTINCT jurusan FROM siswa ORDER BY jurusan")->fetchAll(PDO::FETCH_COLUMN);

?>
<style>
/* small tweak to make the unassign icon bolder/closer to provided art */
.unassign-icon {
    font-size: 1.05rem;
    font-weight: 700;
    transform: scale(1.05);
}
.btn-assign {
    min-width: 72px;
}
</style>
<!-- UID POOL -->
<div class="card shadow-sm mb-4">
    <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
        <strong>UID Baru</strong>

        <form method="GET" class="d-flex">
            <input type="text" name="search_uid" class="form-control form-control-sm me-2"
                placeholder="Cari UID..."
                value="<?= htmlspecialchars($search_uid) ?>"
                style="width:140px">
            <button class="btn btn-sm btn-light">Cari</button>
        </form>
    </div>

    <div class="card-body p-0">

        <div class="p-2 d-flex gap-2">
            <button id="btnDeleteSelected" class="btn btn-danger btn-sm">Hapus Terpilih</button>
            <button id="btnRefreshPool" class="btn btn-secondary btn-sm">Refresh</button>
        </div>

        <table class="table table-hover align-middle mb-0" 
       style="border-radius:10px; overflow:hidden; background:#fff;">
    <thead class="table-light">
        <tr>
            <th width="50"><input type="checkbox" id="checkAll"></th>
            <th>UID</th>
            <th>First Seen</th>
            <th width="160">Assign</th>
        </tr>
    </thead>

    <tbody id="uidPoolBody">
        <?php foreach ($pool as $p): ?>
        <tr>
            <td class="text-center">
                <input type="checkbox" class="uid-check" value="<?= htmlspecialchars($p['uid']) ?>">
            </td>

            <td><?= htmlspecialchars($p['uid']) ?></td>
            <td><?= htmlspecialchars($p['first_seen']) ?></td>

            <td>
                <button class="btn btn-success btn-sm btnOpenAssignModal btn-assign"
                        data-uid="<?= htmlspecialchars($p['uid']) ?>">
                    Assign
                </button>
            </td>
        </tr>
        <?php endforeach; ?>

        <?php if (empty($pool)): ?>
        <tr>
            <td colspan="4" class="text-center text-muted py-3">Tidak ada UID baru</td>
        </tr>
        <?php endif; ?>
    </tbody>
</table>

        <!-- Pagination UID Pool -->
        <div class="p-2">
        <nav class="mt-2">
            <ul class="pagination mb-0">
                <?php for($i=1; $i <= $total_pool_pages; $i++): ?>
                <li class="page-item <?= ($i == $page_pool ? 'active' : '') ?>">
                    <a class="page-link"
                       href="?p_uid=<?= $i ?>&search_uid=<?= urlencode($search_uid) ?>&search_siswa=<?= urlencode($search_siswa) ?>&filter_kelas=<?= urlencode($filter_kelas) ?>&filter_jurusan=<?= urlencode($filter_jurusan) ?>">
                       <?= $i ?>
                    </a>
                </li>
                <?php endfor; ?>
            </ul>
        </nav>
        </div>

    </div>
</div>

<!-- FILTER SISWA -->
<div class="card shadow-sm mb-3">
    <div class="card-header bg-success text-white">
        <strong>Filter & Pencarian Siswa</strong>
    </div>

    <div class="card-body">
        <form method="GET" class="row g-2">
            <div class="col-md-3">
                <input type="text" name="search_siswa"
                       class="form-control"
                       placeholder="Cari nama / NIS / UID"
                       value="<?= htmlspecialchars($search_siswa) ?>">
            </div>

            <div class="col-md-2">
                <select name="filter_kelas" class="form-select">
                    <option value="">-- Kelas --</option>
                    <?php foreach ($list_kelas as $k): ?>
                    <option value="<?= $k ?>" <?= ($k == $filter_kelas ? "selected" : "") ?>>
                        <?= $k ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-3">
                <select name="filter_jurusan" class="form-select">
                    <option value="">-- Jurusan --</option>
                    <?php foreach ($list_jurusan as $j): ?>
                    <option value="<?= $j ?>" <?= ($j == $filter_jurusan ? "selected" : "") ?>>
                        <?= $j ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <button class="btn btn-primary w-100">Terapkan</button>
            </div>

            <div class="col-md-2">
                <a href="manage_uid.php" class="btn btn-secondary w-100">Reset</a>
            </div>
        </form>
    </div>
</div>

<!-- UID ASSIGNED -->
<div class="card shadow-sm">

    <div class="card-header bg-success text-white d-flex justify-content-between">
        <strong>UID Assigned ke Siswa</strong>

        <button id="btnClearAllAssigned" class="btn btn-danger btn-sm">
            Hapus Semua UID Assigned
        </button>
    </div>

    <div class="p-2 d-flex justify-content-end">
    <button id="btnDeleteAssignedSelected" class="btn btn-danger btn-sm d-none">
        Hapus UID Terpilih
    </button>
</div>

        <table class="table table-hover align-middle mb-0" style="background:#fff;">
    <thead class="table-light">
        <tr>
            <th width="50"><input type="checkbox" id="checkAllAssigned"></th>
            <th width="60">No</th>
            <th>Nama</th>
            <th>NIS</th>
            <th>Kelas</th>
            <th>UID</th>
            <th width="100">Aksi</th>
        </tr>
    </thead>

    <tbody>
        <?php $no = $offset_assigned + 1; ?>
        <?php foreach ($assigned as $a): ?>
        <?php $kelas_full = trim($a['kelas'].' '.$a['jurusan'].' '.$a['rombel']); ?>

        <tr>
            <td class="text-center">
                <input type="checkbox" class="assigned-check" value="<?= (int)$a['id'] ?>">
            </td>

            <td><?= $no++ ?></td>
            <td><?= htmlspecialchars($a["nama"]) ?></td>
            <td><?= htmlspecialchars($a["nis"]) ?></td>
            <td><?= htmlspecialchars($kelas_full) ?></td>
            <td><?= htmlspecialchars($a["uid"]) ?></td>

            <td class="text-center">
                <button class="btn btn-warning btn-sm btnUnassign"
                        data-id="<?= (int)$a['id'] ?>" title="Unassign UID">
                    <i class="bi bi-link-45deg unassign-icon"></i>
                </button>
            </td>
        </tr>

        <?php endforeach; ?>

        <?php if (empty($assigned)): ?>
        <tr>
            <td colspan="7" class="text-center text-muted">Tidak ada data</td>
        </tr>
        <?php endif; ?>
    </tbody>
</table>

        <!-- Pagination UID Assigned -->
        <div class="p-2">
        <nav class="mt-2">
            <ul class="pagination mb-0">
                <?php for ($i=1; $i <= $total_pages; $i++): ?>
                <li class="page-item <?= ($i==$page_assigned ? 'active' : '') ?>">
                    <a class="page-link" href="?p=<?= $i ?>&search_siswa=<?= urlencode($search_siswa) ?>&filter_kelas=<?= urlencode($filter_kelas) ?>&filter_jurusan=<?= urlencode($filter_jurusan) ?>">
                        <?= $i ?>
                    </a>
                </li>
                <?php endfor; ?>
            </ul>
        </nav>
        </div>

    </div>
</div>

<!-- ASSIGN MODAL -->
<div class="modal fade" id="assignModal">
  <div class="modal-dialog">
    <div class="modal-content">

      <div class="modal-header bg-success text-white">
        <h5 class="modal-title">Assign UID ke Siswa</h5>
        <button class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">
        <input type="hidden" id="modal_uid">
        <p>UID: <strong id="display_uid"></strong></p>

        <label>Pilih Siswa:</label>
        <!-- SEARCH INPUT -->
        <input type="text" id="searchSiswa" class="form-control mb-2" placeholder="Cari nama / NIS...">
        <!-- DROPDOWN SISWA -->
        <select id="modal_siswa" size="8" class="form-select">
            <option value="">-- Pilih Siswa --</option>

            <?php
            // Hanya tampilkan siswa yang BELUM memiliki UID
            $students = $pdo->query("SELECT id, nama, nis FROM siswa WHERE uid IS NULL OR uid = ''ORDER BY nama")->fetchAll();
            foreach ($students as $s) {
                $label = $s['nama'] . " (" . $s['nis'] . ")";
                echo "<option value='{$s['id']}' data-name='".strtolower($s['nama'])."' data-nis='{$s['nis']}'>$label</option>";
        }
        ?>
        </select>

    </div>

      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
        <button id="btnAssignSave" class="btn btn-success">Simpan</button>
      </div>

    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
// ====================== SEARCH/FILTER SISWA ======================
document.getElementById("searchSiswa").addEventListener("input", function () {
    let q = this.value.toLowerCase();
    let opts = document.querySelectorAll("#modal_siswa option");

    opts.forEach(op => {
        if (op.value === "") return; // skip placeholder

        let nama = op.dataset.name;
        let nis  = op.dataset.nis;

        // cocok nama ATAU nis
        if (nama.includes(q) || nis.includes(q)) {
            op.hidden = false;
        } else {
            op.hidden = true;
        }
    });
});

/* ASSIGN MODAL OPEN */
document.querySelectorAll(".btnOpenAssignModal").forEach(btn=>{
    btn.addEventListener("click", function(){
        const uid = this.dataset.uid;
        document.getElementById("modal_uid").value = uid;
        document.getElementById("display_uid").innerText = uid;
        new bootstrap.Modal(document.getElementById("assignModal")).show();
    });
});

/* SIMPAN ASSIGN UID (AJAX) */
document.getElementById("btnAssignSave").addEventListener("click", function(){
    let uid = document.getElementById("modal_uid").value;
    let siswa_id = document.getElementById("modal_siswa").value;

    if (!siswa_id) {
        Swal.fire("Pilih siswa dahulu!", "", "warning");
        return;
    }

    let fd = new FormData();
    fd.append("uid", uid);
    fd.append("siswa_id", siswa_id);

    fetch("/presensi_v1/process/uid_assign.php", {
        method: "POST",
        body: fd
    })
    .then(() => {
        Swal.fire("Berhasil", "UID berhasil diassign!", "success")
        .then(() => location.reload());
    });
});

/* CHECK ALL (Bulk Delete) */
document.getElementById("checkAll").addEventListener("change", function(){
    document.querySelectorAll(".uid-check").forEach(cb => cb.checked = this.checked);
});

/* HAPUS MASSAL UID POOL */
document.getElementById("btnDeleteSelected").addEventListener("click", function(){

    let selected = [...document.querySelectorAll(".uid-check:checked")].map(cb => cb.value);

    if (selected.length === 0) {
        Swal.fire("Belum ada UID dipilih!", "", "warning");
        return;
    }

    Swal.fire({
        title: "Hapus UID terpilih?",
        icon: "warning",
        showCancelButton: true
    }).then(res => {
        if (!res.isConfirmed) return;

        let fd = new FormData();
        selected.forEach(uid => fd.append("uids[]", uid));

        fetch("/presensi_v1/process/uid_delete_bulk.php", {
            method:"POST",
            body: fd
        })
        .then(r=>r.json())
        .then(j=>{
            Swal.fire("Berhasil!", "UID berhasil dihapus.", "success")
            .then(()=> location.reload());
        });
    });
});

/* REFRESH UID POOL MANUAL */
document.getElementById("btnRefreshPool").addEventListener("click", function(){
    refreshUidPool();
});

/* ========== FUNGSI REFRESH UID POOL ========== */
function refreshUidPool() {

    let search = document.querySelector("input[name='search_uid']").value;

    fetch(`/presensi_v1/ajax/get_uid_pool.php?search_uid=${encodeURIComponent(search)}&p_uid=<?= $page_pool ?>`)
    .then(r=>r.json())
    .then(data => {

        let tbody = document.querySelector("#uidPoolBody");
        tbody.innerHTML = "";

        data.forEach(p => {
            tbody.innerHTML += `
                <tr>
                    <td><input type="checkbox" class="uid-check" value="${p.uid}"></td>
                    <td>${p.uid}</td>
                    <td>${p.first_seen}</td>
                    <td>
                        <button class="btn btn-sm btn-success btnOpenAssignModal btn-assign"
                                data-uid="${p.uid}">
                            Assign
                        </button>
                    </td>
                </tr>
            `;
        });

        // Re-register modal button event
        document.querySelectorAll(".btnOpenAssignModal").forEach(btn=>{
            btn.addEventListener("click", function(){
                const uid = this.dataset.uid;
                document.getElementById("modal_uid").value = uid;
                document.getElementById("display_uid").innerText = uid;
                new bootstrap.Modal(document.getElementById("assignModal")).show();
            });
        });
    });
}

/* KOSONGKAN SEMUA UID ASSIGNED */
document.getElementById("btnClearAllAssigned").addEventListener("click", function(){

    Swal.fire({
        title: "Kosongkan semua UID Assigned?",
        text: "Semua UID akan dikembalikan ke UID Pool!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Ya, Kosongkan"
    }).then(res => {

        if (!res.isConfirmed) return;

        fetch("/presensi_v1/process/uid_unassign_all.php", {
            method:"POST"
        })
        .then(r=>r.json())
        .then(j=>{
            Swal.fire("Berhasil!", "Semua UID telah dikosongkan.", "success")
            .then(()=> location.reload());
        });
    });

});

/* UNASSIGN SINGLE WITH SWEETALERT (AJAX) */
document.querySelectorAll(".btnUnassign").forEach(btn => {
    btn.addEventListener("click", function () {

        let id = this.dataset.id;

        Swal.fire({
            title: "Unassign UID?",
            text: "UID akan dikembalikan ke UID Pool.",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya, Unassign",
            cancelButtonText: "Batal"
        }).then(res => {

            if (!res.isConfirmed) return;

            fetch(`/presensi_v1/process/uid_unassign.php?id=${id}`)
                .then(() => {

                    Swal.fire({
                        title: "Berhasil!",
                        text: "UID berhasil di-unassign.",
                        icon: "success",
                        timer: 1200,
                        showConfirmButton: false
                    }).then(() => {
                        location.reload();
                    });

                }).catch(()=> {
                    Swal.fire("Error","Gagal unassign","error");
                });
        });

    });
});

// ================================
// HAPUS MASSAL UID ASSIGNED
// ================================
const checkAllAssigned = document.getElementById("checkAllAssigned");
const deleteAssignedBtn = document.getElementById("btnDeleteAssignedSelected");

function updateAssignedBulk() {
    const count = document.querySelectorAll(".assigned-check:checked").length;
    deleteAssignedBtn.classList.toggle("d-none", count === 0);
}

if (checkAllAssigned) {
    checkAllAssigned.addEventListener("change", function () {
        document.querySelectorAll(".assigned-check")
            .forEach(cb => cb.checked = checkAllAssigned.checked);
        updateAssignedBulk();
    });
}

document.querySelectorAll(".assigned-check")
    .forEach(cb => cb.addEventListener("change", updateAssignedBulk));

deleteAssignedBtn.addEventListener("click", function () {
    let ids = [...document.querySelectorAll(".assigned-check:checked")].map(e => e.value);
    if (!ids.length) return;

    Swal.fire({
        title: "Hapus UID terpilih?",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Hapus",
        confirmButtonColor: "#d33"
    }).then(res => {

        if (!res.isConfirmed) return;

        const fd = new URLSearchParams();
        ids.forEach(id => fd.append("ids[]", id));

        fetch("/presensi_v1/process/uid_unassign_bulk.php", {
            method: "POST",
            headers: { "Content-Type":"application/x-www-form-urlencoded" },
            body: fd
        })
        .then(r => r.json())
        .then(j => {
            Swal.fire("Berhasil", "UID terpilih berhasil dihapus & dikembalikan ke pool", "success")
                .then(()=> location.reload());
        });

    });
});

</script>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>