<?php
include 'koneksi.php';
include 'auth.php';
include 'akses_ditolak.php';

// 🔁 Reset filter jika tombol reset diklik
if (isset($_GET['reset']) && $_GET['reset'] == 1) {
    header("Location: report_stay.php");
    exit;
}

// 🟡 Ambil parameter filter
$tanggalFilter = $_GET['tanggal'] ?? date('Y-m-d');
$siftFilter = $_GET['sift'] ?? '';
$searchNama = $_GET['search'] ?? '';

// 🔍 Filter berdasarkan parameter tambahan
$query = "SELECT * FROM absen WHERE tanggal = ?";
$types = "s";
$params = [$tanggalFilter];

if ($siftFilter !== '') {
    $query .= " AND sift = ?";
    $types .= "s";
    $params[] = $siftFilter;
}
if ($searchNama !== '') {
    $query .= " AND nama LIKE ?";
    $types .= "s";
    $params[] = "%$searchNama%";
}

// 🧾 Jalankan query filter
$totalSetelahFilter = 0;
$stmt = $koneksi->prepare($query);
if ($stmt) {
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $data = $stmt->get_result();
    $totalSetelahFilter = $data->num_rows;
} else {
    die("Query gagal: " . $koneksi->error);
}
?>

<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/navbar.css">
    <link rel="stylesheet" href="css/admin.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>

<style>
    thead th {
        position: sticky;
        top: 0;
         background: #233a6a;
        color: #f5d216;
        z-index: 1;
    }
</style>

<body>
    <h4>DAILY STANBY</h4>
    <input type="text" id="tanggal-saat-ini" readonly style="pointer-events: none;">
    <form method="GET" class="flex-1 flex gap-2 items-center">
        <input type="text" name="search" placeholder="Cari nama..." value="<?= htmlspecialchars($searchNama) ?>"
            autocomplete="off">
        <div style="display: flex; gap: 10px; margin-top: 5px;">
            <input type="text" readonly
                style="flex:1; height:40px; font-weight:bold; text-align:center;"
                value="<?= $totalSetelahFilter ?> Aktif">
            <button type="submit" class="btn-yellow" style="flex:1; height:40px;">Cari</button>
            <button type="button" class="btn-green" style="flex:1; height:40px;" onclick="bukaFilter()">Filter</button>
        </div>
        <?php if (
            isset($_GET['sift']) && $_GET['sift'] !== '' ||
            isset($_GET['search']) && $_GET['search'] !== '' ||
            (isset($_GET['tanggal']) && $_GET['tanggal'] !== date('Y-m-d'))
        ): ?>

            <button style="height:40px;" type="submit" name="reset" value="1"
                class="bg-red-600 hover:bg-red-700 px-4 py-2 rounded text-sm">Reset</button>

        <?php endif; ?>

    </form>

    <div class="table-container" style="  max-height: 55vh; min-height: 55vh;">
        <table>
            <thead>
                <tr>
                    <th style="display:none;">TGL</th>
                    <th>Nama</th>
                    <th>Sift</th>
                    <th>Stay</th>
                    <th>Off</th>
                    <th>Del</th> <!-- Kolom baru untuk tombol hapus -->
                </tr>
            </thead>
            <tbody>
                <?php if ($data->num_rows > 0): ?>
                    <?php while ($row = $data->fetch_assoc()): ?>
                        <tr id="row-<?= $row['id'] ?>">
                            <td style="display:none;"><?= htmlspecialchars($row['tanggal']) ?></td>
                            <td class="nama"><?= htmlspecialchars($row['nama']) ?></td>
                            <td><?= htmlspecialchars($row['sift']) ?></td>
                            <td><?= htmlspecialchars($row['stay']) ?></td>
                            <td><?= htmlspecialchars($row['off']) ?></td>
                            <td style="text-align: center;">
                                <button class="btn-delete" data-id="<?= $row['id'] ?>" title="Hapus Data"
                                    style="background: red; border: none; cursor: pointer; color:white; height:20px; width:20px">
                                </button>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="6" class="text-center p-4">Tidak ada data untuk hari ini.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <p style="text-align:center ; color: gray;">Klik Nama Member untuk detail Rincian</p>

    <script>
        function bukaFilter() {
            const today = new Date();
            const yyyy = today.getFullYear();
            const mm = String(today.getMonth() + 1).padStart(2, '0'); // Bulan dimulai dari 0
            const dd = String(today.getDate()).padStart(2, '0');
            const formattedToday = `${yyyy}-${mm}-${dd}`; // format yyyy-mm-dd

            Swal.fire({
                title: 'Filter Data',
                html:
                    `<input type="date" id="tanggal" class="swal2-input" value="${formattedToday}">
            <select id="sift" class="swal2-input">
                <option value="">Semua Sift</option>
                <option value="Pagi">Pagi</option>
                <option value="Siang">Siang</option>
                <option value="Non">Non</option>
            </select>`,
                focusConfirm: false,
                confirmButtonText: 'OK',
                preConfirm: () => {
                    const tanggal = document.getElementById('tanggal').value;
                    const sift = document.getElementById('sift').value;
                    window.location.href = `report_stay.php?tanggal=${tanggal}&sift=${sift}`;
                }
            });
        }

        const tanggalInput = document.getElementById('tanggal-saat-ini');
        const tanggal = new Date();
        const hari = tanggal.toLocaleString('id-ID', { weekday: 'long' });
        const tanggalFormat = tanggal.getDate();
        const bulan = tanggal.toLocaleString('id-ID', { month: 'long' });
        const tahun = tanggal.getFullYear();
        const labelTanggal = `${hari}, ${tanggalFormat} ${bulan} ${tahun}`;
        tanggalInput.value = labelTanggal;
    </script>

    <?php include 'navbar4.php'; ?>
    <script>
        document.querySelectorAll('.btn-delete').forEach(button => {
            button.addEventListener('click', function () {
                const id = this.getAttribute('data-id');
                Swal.fire({
                    title: 'Yakin ingin menghapus data ini?',
                    text: "Data yang dihapus tidak bisa dikembalikan!",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6',
                    confirmButtonText: 'Ya, hapus!',
                    cancelButtonText: 'Batal'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Kirim request AJAX ke server untuk hapus data
                        fetch('delete_absen.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            },
                            body: 'id=' + encodeURIComponent(id)
                        })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    Swal.fire('Terhapus!', 'Data berhasil dihapus.', 'success');
                                    // Hapus baris dari tabel tanpa reload
                                    const row = document.getElementById('row-' + id);
                                    if (row) row.remove();
                                } else {
                                    Swal.fire('Gagal!', data.message || 'Gagal menghapus data.', 'error');
                                }
                            })
                            .catch(() => {
                                Swal.fire('Error!', 'Terjadi kesalahan saat menghapus data.', 'error');
                            });
                    }
                });
            });
        });

        document.addEventListener('DOMContentLoaded', function () {
            document.querySelectorAll('.nama').forEach(function (cell) {
                cell.addEventListener('click', function () {
                    const fullName = this.textContent.trim();

                    Swal.fire({
                        title: 'Nama Lengkap',
                        text: fullName,
                        imageWidth: 150,
                        imageHeight: 150,
                        imageUrl: 'img/head.png',
                        confirmButtonText: 'Tutup'
                    });
                });
            });
        });

    </script>

</body>

</html>