<?php
include '../db.php';
session_start();

// Pastikan admin sudah login
if (!isset($_SESSION['admin_id'])) {
    header('Location: login_admin.php');
    exit;
}

// Proses Hapus Data Tempat
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    $id = intval($_POST['id']);

    // Ambil data gambar tempat sebelum dihapus
    $sql = "SELECT image FROM places WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $place = $result->fetch_assoc();

    // Hapus gambar terkait jika ada
    if ($place && $place['image']) {
        $imagePath = "../" . $place['image'];
        if (file_exists($imagePath)) {
            unlink($imagePath);
        }
    }

    // Hapus data tempat dari database
    $sql = "DELETE FROM places WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $id);
    if ($stmt->execute()) {
        header('Location: kelola_tempat.php');
        exit;
    } else {
        echo "Error: " . $stmt->error;
    }
}

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

// Ambil data tempat dengan limit dan offset
$sql = "SELECT * FROM places LIMIT ? OFFSET ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $items_per_page, $offset);
$stmt->execute();
$places = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Hitung total data untuk pagination
$sql_count = "SELECT COUNT(*) AS total FROM places";
$total_data = $conn->query($sql_count)->fetch_assoc()['total'];
$total_pages = ceil($total_data / $items_per_page);

function h($string)
{
    return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
}
?>

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

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Kelola Tempat</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-h: 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, left .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;
            text-decoration: none !important;
            border-radius: 6px;
            margin: 4px 10px;
            font-weight: 500;
            white-space: nowrap;
            transition: background .2s
        }

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

        .sidebar.collapsed a span {
            display: none
        }

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

        /* Navbar */
        .navbar {
            background: var(--navy);
            height: var(--navbar-h);
            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);
            /* semula +1.5rem → jadi +2.5rem */
            padding: calc(var(--navbar-h) + 2.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 */
        .table-wrapper {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, .05)
        }

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

        .img-thumb {
            width: 90px;
            height: 60px;
            object-fit: cover;
            border-radius: 6px;
            box-shadow: 0 0 5px rgba(0, 0, 0, .1)
        }

        .btn-custom {
            background: var(--accent);
            /* oranye */
            border: none;
            color: #fff;
            font-weight: 600;
            padding: .45rem 1rem;
            border-radius: .45rem;
        }

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

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

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

            .sidebar.show {
                left: 0
            }

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

            .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"><i class="fas fa-table"></i> <span>Data Reservasi</span></a>
        <a href="kelola_tempat.php" class="active"><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">Kelola Tempat</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">
                    <!-- Header card: judul + tombol -->
                    <div class="card-header bg-white d-flex justify-content-between align-items-center border-0">
                        <h5 class="mb-0 fw-semibold">Daftar Tempat</h5>

                        <a href="tambah_tempat.php"
                            class="btn btn-custom d-inline-flex align-items-center">
                            <i class="fas fa-plus me-2"></i><span>Tambah&nbsp;Tempat</span>
                        </a>
                    </div>

                    <div class="table-responsive">
                        <table class="table align-middle mb-0">
                            <thead>
                                <tr>
                                    <th>Nama Tempat</th>
                                    <th>Deskripsi</th>
                                    <th>Lokasi</th>
                                    <th>Gambar</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (count($places)): foreach ($places as $p): ?>
                                        <tr id="row-<?= $p['id'] ?>">
                                            <td><?= h($p['name']) ?></td>
                                            <td style="max-width:260px;white-space:pre-wrap;"><?= h($p['description']) ?></td>
                                            <td><?= h($p['lokasi']) ?></td>
                                            <td><img src="../<?= h($p['image']) ?>" alt="<?= h($p['name']) ?>" class="img-thumb"></td>
                                            <td style="min-width:150px;">
                                                <div class="d-flex flex-wrap gap-1">
                                                    <a href="edit_tempat.php?id=<?= $p['id'] ?>" class="btn btn-warning btn-sm"><i class="fas fa-edit"></i></a>
                                                    <button class="btn btn-danger btn-sm delete-place" data-id="<?= $p['id'] ?>"><i class="fas fa-trash"></i></button>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach;
                                else: ?>
                                    <tr>
                                        <td colspan="5" class="text-center py-4">Belum ada tempat</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>

    <!-- SweetAlert2 Confirmation Script -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        function confirmDelete(id) {
            Swal.fire({
                title: 'Anda yakin ingin menghapus?',
                text: "Data ini akan dihapus secara permanen!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Hapus',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    document.getElementById('deleteForm_' + id).submit();
                }
            });
        }

        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>';
            }
        });
        // close mobile sidebar on outside click
        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');
            }
        });
    </script>
</body>

</html>