<?php
session_start();
if (!isset($_SESSION['admin_id'])) {
    header('Location: login_admin.php');
    exit;
}

include '../db.php';

// Inisialisasi variabel pencarian
$kode_booking_search = isset($_GET['kode_booking']) ? $_GET['kode_booking'] : '';
$nama_search = isset($_GET['nama']) ? $_GET['nama'] : '';
$hari_search = isset($_GET['hari']) ? $_GET['hari'] : '';
$tempat_search = isset($_GET['tempat']) ? $_GET['tempat'] : '';

// Pagination setup
$items_per_page = 8;
$current_page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($current_page - 1) * $items_per_page;

// Query untuk mengambil data berdasarkan pencarian, dengan limit dan offset
$query = "SELECT * FROM reservations 
          WHERE (kode_booking LIKE ? OR ? = '') 
          AND (nama LIKE ? OR ? = '') 
          AND (hari LIKE ? OR ? = '') 
          AND (tempat LIKE ? OR ? = '') 
          ORDER BY id DESC 
          LIMIT ? OFFSET ?";

$stmt = $conn->prepare($query);
$search_kode_booking = "%$kode_booking_search%";
$search_nama = "%$nama_search%";
$search_hari = "%$hari_search%";
$search_tempat = "%$tempat_search%";
$stmt->bind_param(
    "ssssssssii",
    $search_kode_booking,
    $kode_booking_search,
    $search_nama,
    $nama_search,
    $search_hari,
    $hari_search,
    $search_tempat,
    $tempat_search,
    $items_per_page,
    $offset
);
$stmt->execute();
$result = $stmt->get_result();

// Query untuk menghitung total data
$count_query = "SELECT COUNT(*) AS total FROM reservations 
                WHERE (kode_booking LIKE ? OR ? = '') 
                AND (nama LIKE ? OR ? = '') 
                AND (hari LIKE ? OR ? = '') 
                AND (tempat LIKE ? OR ? = '')";

$count_stmt = $conn->prepare($count_query);
$count_stmt->bind_param(
    "ssssssss",
    $search_kode_booking,
    $kode_booking_search,
    $search_nama,
    $nama_search,
    $search_hari,
    $hari_search,
    $search_tempat,
    $tempat_search
);
$count_stmt->execute();
$count_result = $count_stmt->get_result();
$total_data = $count_result->fetch_assoc()['total'];

$total_pages = ceil($total_data / $items_per_page);
?>

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

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Kelola Reservasi</title>
    <!-- Fonts & Icons -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet" />
    <!-- Bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="icon" href="../assets/img/logotng.png" type="image/x-icon" />
    <style>
        :root {
            --navy: #002147;
            --navy-dark: #001531;
            --accent: #f0ad4e;
            --sidebar-width: 260px;
            --sidebar-collapsed: 80px;
            --navbar-height: 56px;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: #f4f6fb;
            overflow-x: hidden;
            transition: margin-left .3s;
        }

        /* Sidebar */
        .sidebar {
            position: fixed;
            top: 0;
            left: 0;
            height: 100vh;
            width: var(--sidebar-width);
            background: linear-gradient(180deg, var(--navy) 0%, var(--navy-dark) 100%);
            color: #fff;
            padding: 20px 0;
            transition: width .3s;
            z-index: 1040;
        }

        .sidebar.collapsed {
            width: var(--sidebar-collapsed);
        }

        .sidebar h5 {
            font-weight: 600;
            text-align: center;
            margin-bottom: 1.3rem;
            transition: opacity .3s;
        }

        .sidebar.collapsed h5 {
            opacity: 0;
        }

        .sidebar a {
            color: #fff;
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 22px;
            border-radius: 6px;
            margin: 4px 10px;
            text-decoration: none !important;
            font-weight: 500;
            white-space: nowrap;
            transition: background .2s;
        }

        .sidebar a i {
            min-width: 22px;
            text-decoration: none !important;
            text-align: center;
        }

        .sidebar.collapsed a span {
            display: none;
        }

        .sidebar a.active,
        .sidebar a:focus,
        .sidebar a:hover {
            background-color: rgba(240, 173, 78, 0.18);
            text-decoration: none !important;
        }

        /* Navbar */
        .navbar {
            background: var(--navy);
            height: var(--navbar-height);
            transition: margin-left .3s;
        }

        .navbar .nav-link {
            color: #fff;
            font-weight: 500;
        }

        .navbar .nav-link:hover {
            color: var(--accent);
        }

        /* Content */
        .content {
            margin-left: var(--sidebar-width);
            padding: calc(var(--navbar-height) + 1.5rem) 2rem 4rem;
            transition: margin-left .3s;
        }

        body.sidebar-collapsed .navbar {
            margin-left: var(--sidebar-collapsed);
        }

        body.sidebar-collapsed .content {
            margin-left: var(--sidebar-collapsed);
        }

        /* Table & Buttons */
        .table-wrapper {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
        }

        thead {
            background: var(--navy);
            color: #fff;
        }

        .status-badge {
            padding: .35rem .65rem;
            border-radius: 50px;
            font-size: .8rem;
            font-weight: 500;
            text-transform: capitalize;
        }

        .status-pending {
            background: #ffc1071a;
            color: #ffc107;
        }

        .status-approved {
            background: #28a7451a;
            color: #28a745;
        }

        .status-rejected {
            background: #dc35451a;
            color: #dc3545;
        }

        .btn-custom {
            background: var(--accent);
            color: #fff;
        }

        .btn-custom:hover {
            background: #e39d41;
            color: #fff;
        }

        /* Search */
        .search-group {
            display: flex;
            flex-wrap: wrap;
            gap: .6rem;
        }

        .search-group .form-control {
            min-width: 160px;
        }

        @media(max-width: 768px) {
            .sidebar {
                left: -260px;
            }

            .sidebar.collapsed {
                left: 0;
            }

            .navbar,
            .content {
                margin-left: 0;
            }

            body.sidebar-collapsed .navbar {
                margin-left: 0;
            }
        }
    </style>
</head>

<body>
    <!-- Sidebar -->
    <aside id="sidebar" class="sidebar">
        <h5><i class="fas fa-building me-1"></i><span class="sidebar-title">Disbudpar</span></h5>
        <a href="dashboard_admin.php"><i class="fas fa-home"></i> <span>Dashboard</span></a>
        <a href="kelola_reserv.php" class="active"><i class="fas fa-table"></i> <span>Data Reservasi</span></a>
        <a href="kelola_tempat.php"><i class="fas fa-map-marker-alt"></i> <span>Kelola Tempat</span></a>
        <a href="calendar.php"><i class="fas fa-calendar"></i> <span>Kalender</span></a>
        <a href="logout_admin.php"><i class="fas fa-sign-out-alt"></i> <span>Logout</span></a>
    </aside>

    <!-- Navbar -->
    <nav class="navbar fixed-top navbar-dark shadow-sm">
        <div class="container-fluid px-3">
            <span class="navbar-brand d-none d-lg-block fw-semibold">Daftar Reservasi</span>
            <!-- Icon buttons on the right -->
            <div class="d-flex align-items-center gap-2 ms-auto">
                <button id="sidebarToggle" class="btn btn-outline-light btn-sm" title="Menu"><i class="fas fa-bars"></i></button>
                <button id="fullscreenToggle" class="btn btn-outline-light btn-sm" title="Fullscreen"><i class="fas fa-expand"></i></button>
                <!-- <a href="dashboard_admin.php" class="btn btn-outline-light btn-sm" title="Back"><i class="fas fa-arrow-left"></i></a> -->
            </div>
        </div>
    </nav>


    <!-- Main Content -->
    <main class="content">
        <div class="container-fluid">
            <div class="card table-wrapper">
                <div class="card-body">
                    <!-- Search -->
                    <form class="mb-4" method="GET">
                        <div class="search-group">
                            <input type="text" name="kode_booking" class="form-control" placeholder="Kode Booking" value="<?= htmlspecialchars($kode_booking_search) ?>">
                            <input type="text" name="nama" class="form-control" placeholder="Nama" value="<?= htmlspecialchars($nama_search) ?>">
                            <input type="text" name="tempat" class="form-control" placeholder="Tempat" value="<?= htmlspecialchars($tempat_search) ?>">
                            <input type="date" name="hari" class="form-control" value="<?= htmlspecialchars($hari_search) ?>">
                            <button class="btn btn-custom" type="submit"><i class="fas fa-search me-1"></i>Cari</button>
                            <a href="kelola_reserv.php" class="btn btn-outline-secondary"><i class="fas fa-undo me-1"></i>Reset</a>
                        </div>
                    </form>

                    <!-- Table -->
                    <div class="table-responsive">
                        <table class="table align-middle mb-0">
                            <thead>
                                <tr>
                                    <th>Kode Booking</th>
                                    <th>Nama</th>
                                    <th>Email</th>
                                    <th>Tempat</th>
                                    <th>Hari</th>
                                    <th>Jam Mulai</th>
                                    <th>Status</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($result->num_rows > 0): ?>
                                    <?php while ($row = $result->fetch_assoc()): ?>
                                        <?php $badgeClass = $row['status'] === 'pending' ? 'status-pending' : ($row['status'] === 'disetujui' ? 'status-approved' : 'status-rejected'); ?>
                                        <tr id="row-<?= $row['id'] ?>">
                                            <td><?= htmlspecialchars($row['kode_booking']) ?></td>
                                            <td><?= htmlspecialchars($row['nama']) ?></td>
                                            <td><?= htmlspecialchars($row['surat']) ?></td>
                                            <td><?= htmlspecialchars($row['tempat']) ?></td>
                                            <td><?= htmlspecialchars($row['hari']) ?></td>
                                            <td><?= htmlspecialchars($row['jam_mulai']) ?></td>
                                            <td id="status-<?= $row['id'] ?>"><span class="status-badge <?= $badgeClass ?>"><?= ucfirst($row['status']) ?></span></td>
                                            <td style="min-width:180px;">
                                                <div class="d-flex flex-wrap gap-1">
                                                    <select id="status-select-<?= $row['id'] ?>" class="form-select form-select-sm w-auto">
                                                        <option value="pending" <?= $row['status'] === 'pending' ? 'selected' : '' ?>>Pending</option>
                                                        <option value="ditolak" <?= $row['status'] === 'ditolak' ? 'selected' : '' ?>>Ditolak</option>
                                                        <option value="disetujui" <?= $row['status'] === 'disetujui' ? 'selected' : '' ?>>Disetujui</option>
                                                    </select>
                                                    <button class="btn btn-custom btn-sm update-status" data-id="<?= $row['id'] ?>"><i class="fas fa-sync"></i></button>
                                                    <a class="btn btn-primary btn-sm" href="view_reserv.php?id=<?= $row['id'] ?>"><i class="fas fa-eye"></i></a>
                                                    <a class="btn btn-warning btn-sm" href="edit_reserv.php?id=<?= $row['id'] ?>"><i class="fas fa-edit"></i></a>
                                                    <button class="btn btn-danger btn-sm delete-reservation" data-id="<?= $row['id'] ?>"><i class="fas fa-trash"></i></button>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="8" class="text-center py-4">Tidak ada data ditemukan</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <nav>
                        <ul class="pagination justify-content-center mt-4">
                            <?php if ($current_page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?= $current_page - 1; ?>">Previous</a>
                                </li>
                            <?php endif; ?>

                            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                <li class="page-item <?= $i == $current_page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?= $i; ?>"> <?= $i; ?> </a>
                                </li>
                            <?php endfor; ?>

                            <?php if ($current_page < $total_pages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?= $current_page + 1; ?>">Next</a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </nav>

                    <p class="text-muted text-center">Menampilkan halaman <?= $current_page ?> dari <?= $total_pages ?></p>
                </div>
            </div>
        </div>
        </div>
    </main>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <!-- Script -->
    <script>
$(document).on('click', '.update-status', function () {
  const id        = $(this).data('id');
  const newStatus = $('#status-select-' + id).val();

  // fungsi yang benar‑benar mengirim ke PHP
  const sendUpdate = (note='') => {
    $.post('update_status.php',   // ←  path sesuai file yang ada
      { id, status: newStatus, note }, res => {

        if (res.trim() === 'OK') {
          const badge = $('#status-' + id + ' span');
          badge.text(newStatus.charAt(0).toUpperCase() + newStatus.slice(1))
               .removeClass('status-pending status-approved status-rejected')
               .addClass(newStatus==='pending'  ? 'status-pending'  :
                         newStatus==='disetujui'? 'status-approved' :
                                                   'status-rejected');

          const msg = newStatus === 'ditolak'
                    ? 'Status DI TOLAK & email catatan sudah dikirim'
                    : newStatus === 'disetujui'
                    ? 'Reservasi Berhasil Disetujui dan Dikirim ke Gmail'
                    : 'Status menjadi Pending';
          Swal.fire('Berhasil', msg, 'success');
        } else {
          Swal.fire('Error', res, 'error');
        }
    });
  };

  // Jika Ditolak → minta catatan
  if (newStatus === 'ditolak') {
    Swal.fire({
      title: 'Catatan Penolakan',
      input: 'textarea',
      inputPlaceholder: 'Tulis alasan singkat...',
      showCancelButton: true,
      confirmButtonText: 'Kirim',
    }).then(r => { if (r.isConfirmed) sendUpdate(r.value); });
  } else {
    sendUpdate();    // tanpa catatan
  }
});

        // Sidebar & Fullscreen logic
        const sidebar = document.getElementById('sidebar');
        document.getElementById('sidebarToggle').addEventListener('click', () => {
            if (window.matchMedia('(max-width:768px)').matches) {
                sidebar.classList.toggle('show');
            } else {
                sidebar.classList.toggle('collapsed');
                document.body.classList.toggle('sidebar-collapsed');
            }
        });
        const fsBtn = document.getElementById('fullscreenToggle');
        fsBtn.addEventListener('click', () => {
            if (!document.fullscreenElement) {
                document.documentElement.requestFullscreen();
                fsBtn.innerHTML = '<i class="fas fa-compress"></i>';
            } else {
                document.exitFullscreen();
                fsBtn.innerHTML = '<i class="fas fa-expand"></i>';
            }
        });
        document.addEventListener('click', e => {
            if (window.matchMedia('(max-width:768px)').matches && sidebar.classList.contains('show') && !sidebar.contains(e.target) && !e.target.closest('#sidebarToggle')) {
                sidebar.classList.remove('show');
            }
        });

        // Ketika tombol delete reservation diklik
        $(".delete-reservation").click(function() {
            var id = $(this).data("id");

            Swal.fire({
                title: 'Yakin ingin menghapus?',
                text: "Data tidak bisa dikembalikan setelah dihapus!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Ya, hapus!'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: "delete_reservation.php",
                        method: "POST",
                        data: {
                            id: id
                        },
                        success: function(response) {
                            if (response === 'success') {
                                $("#row-" + id).remove();
                                Swal.fire('Deleted!', 'Reservasi telah dihapus.', 'success');
                            } else {
                                Swal.fire('Error!', 'Gagal menghapus data.', 'error');
                            }
                        }
                    });
                }
            });
        });
    </script>
</body>

</html>