<?php
// Aktifkan error reporting untuk debugging
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error.log');
error_reporting(E_ALL);

include '../includes/auth.php';
include '../includes/functions.php';
include '../includes/headeradm.php';

// Fungsi untuk mendapatkan total event dengan filter pencarian
function getTotalEvents($conn, $search = '') {
    $sql = "SELECT COUNT(*) as total FROM dafdir_event";
    if (!empty($search)) {
        $sql .= " WHERE nama_event LIKE '%$search%' OR pengesah LIKE '%$search%' OR jabatan LIKE '%$search%' OR nip LIKE '%$search%'";
    }
    $result = $conn->query($sql);
    $row = $result->fetch_assoc();
    return $row['total'];
}

// Proses parameter pencarian dan pagination
$search = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';
$per_page = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;

// Hitung total data dan halaman
// $total_events = getTotalEvents($conn, $search);
// $total_pages = $per_page > 0 ? ceil($total_events / $per_page) : 1;

// Hitung total data dan halaman
$total_events = getTotalEvents($conn, $search);
$total_pages = $per_page > 0 ? max(1, ceil($total_events / $per_page)) : 1;

// Validasi nomor halaman
$page = max(1, min($page, $total_pages));
$offset = max(0, ($page - 1) * $per_page);

// Validasi nomor halaman
if ($page < 1) $page = 1;
if ($page > $total_pages) $page = $total_pages;
$offset = ($page - 1) * $per_page;

// Query data dengan filter dan pagination
// $sql = "SELECT * FROM dafdir_event";
// if (!empty($search)) {
//     $sql .= " WHERE nama_event LIKE '%$search%' OR pengesah LIKE '%$search%' OR jabatan LIKE '%$search%' OR nip LIKE '%$search%'";
// }
// $sql .= " ORDER BY tanggal_event DESC";
// if ($per_page > 0) {
//     $sql .= " LIMIT $offset, $per_page";
// }

// Query data dengan filter dan pagination
$sql = "SELECT * FROM dafdir_event";
if (!empty($search)) {
    $sql .= " WHERE nama_event LIKE '%$search%' OR pengesah LIKE '%$search%' OR jabatan LIKE '%$search%' OR nip LIKE '%$search%'";
}
$sql .= " ORDER BY tanggal_event DESC";
if ($per_page > 0) {
    $sql .= " LIMIT " . (int)$offset . ", " . (int)$per_page;
}

$allEvents = $conn->query($sql);

// Proses form tambah/edit/hapus event
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_event'])) {
        $nama_event = $_POST['nama_event'];
        $tanggal_event = $_POST['tanggal_event'];
        $pengesah = $_POST['pengesah'];
        $jabatan = $_POST['jabatan'];
        $nip = $_POST['nip'];
        $status = isset($_POST['status']) ? 'aktif' : 'nonaktif';
        
        // Nonaktifkan semua event lain jika yang baru aktif
        if ($status === 'aktif') {
            $conn->query("UPDATE dafdir_event SET status = 'nonaktif'");
        }
        
        $stmt = $conn->prepare("INSERT INTO dafdir_event (nama_event, tanggal_event, pengesah, jabatan, nip, status) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssss", $nama_event, $tanggal_event, $pengesah, $jabatan, $nip, $status);
        
        if ($stmt->execute()) {
            $_SESSION['swal'] = [
                'title' => 'Sukses',
                'text' => 'Event berhasil ditambahkan',
                'icon' => 'success'
            ];
        } else {
            $_SESSION['swal'] = [
                'title' => 'Gagal',
                'text' => 'Gagal menambahkan event: ' . $conn->error,
                'icon' => 'error'
            ];
        }
        
        $stmt->close();
        header("Location: events.php?page=$page&per_page=$per_page&search=" . urlencode($search));
        exit();
    } elseif (isset($_POST['update_event'])) {
        $id_event = (int)$_POST['id_event'];
        $nama_event = $_POST['nama_event'];
        $tanggal_event = $_POST['tanggal_event'];
        $pengesah = $_POST['pengesah'];
        $jabatan = $_POST['jabatan'];
        $nip = $_POST['nip'];
        $status = isset($_POST['status']) ? 'aktif' : 'nonaktif';
        
        // Nonaktifkan semua event lain jika yang ini diaktifkan
        if ($status === 'aktif') {
            $conn->query("UPDATE dafdir_event SET status = 'nonaktif' WHERE id_event != $id_event");
        }
        
         $stmt = $conn->prepare("UPDATE dafdir_event SET nama_event = ?, tanggal_event = ?, pengesah = ?, jabatan = ?, nip = ?, status = ? WHERE id_event = ?");
        $stmt->bind_param("ssssssi", $nama_event, $tanggal_event, $pengesah, $jabatan, $nip, $status, $id_event);
        
        if ($stmt->execute()) {
            $_SESSION['swal'] = [
                'title' => 'Sukses',
                'text' => 'Event berhasil diperbarui',
                'icon' => 'success'
            ];
        } else {
            $_SESSION['swal'] = [
                'title' => 'Gagal',
                'text' => 'Gagal memperbarui event: ' . $conn->error,
                'icon' => 'error'
            ];
        }
        
        $stmt->close();
        header("Location: events.php?page=$page&per_page=$per_page&search=" . urlencode($search));
        exit();
    } elseif (isset($_POST['delete_event'])) {
        $id_event = (int)$_POST['id_event'];
        
        // Cek apakah event sudah memiliki data absensi
        $check = $conn->query("SELECT COUNT(*) as total FROM dafdir_absensi WHERE id_event = $id_event");
        $result = $check->fetch_assoc();
        
        if ($result['total'] > 0) {
            $_SESSION['swal'] = [
                'title' => 'Gagal',
                'text' => 'Tidak dapat menghapus event karena sudah memiliki data absensi',
                'icon' => 'error'
            ];
        } else {
            // Hapus event jika tidak ada absensi
            if ($conn->query("DELETE FROM dafdir_event WHERE id_event = $id_event")) {
                $_SESSION['swal'] = [
                    'title' => 'Sukses',
                    'text' => 'Event berhasil dihapus',
                    'icon' => 'success'
                ];
            } else {
                $_SESSION['swal'] = [
                    'title' => 'Gagal',
                    'text' => 'Gagal menghapus event: ' . $conn->error,
                    'icon' => 'error'
                ];
            }
        }
        
        header("Location: events.php?page=$page&per_page=$per_page&search=" . urlencode($search));
        exit();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Event - DIGITAL PANDAI</title>
    <link href="../assets/css/sweetalert2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link href="../assets/css/style.css" rel="stylesheet">
    <style>
    /* Styling placeholder secara umum */
    input::placeholder {
        color: #6c757d;         /* Abu-abu (bootstrap muted) */
        font-style: italic;     /* Italik */
        font-size: 0.875em;     /* Ukuran lebih kecil (misalnya 14px jika default 16px) */
    }
    /* Samakan ukuran semua tombol di kolom action */
.table td .btn {
    min-width: 90px;          /* lebar minimum tombol */
    height: 36px;             /* tinggi seragam */
    font-size: 0.875rem;      /* ukuran teks */
    display: inline-flex;     /* ikon dan teks sejajar */
    align-items: center;      /* vertikal tengah */
    justify-content: center;  /* horizontal tengah */
    padding: 0 10px;          /* jarak kiri-kanan */
}
</style>
</head>
<body>
    <div class="container mt-5">
        <h2 class="mb-4">Kelola Event</h2>
        
        <!-- Baris Pencarian dan Tombol Tambah -->
        <div class="row mb-4">
            <div class="col-md-6">
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addEventModal">
                    <i class="fas fa-plus me-2"></i>Tambah Event Baru
                </button>
            </div>
            <div class="col-md-6">
                <form method="GET" class="d-flex">
                    <div class="input-group">
                        <input type="text" class="form-control" name="search" placeholder="Cari event..." value="<?= htmlspecialchars($search) ?>">
                        <button class="btn btn-primary" type="submit">
                            <i class="fas fa-search"></i>
                        </button>
                        <?php if (!empty($search)): ?>
                            <a href="events.php" class="btn btn-outline-secondary">
                                <i class="fas fa-times"></i>
                            </a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>

        <!-- Baris Opsi Tampilan dan Informasi Data -->
        <div class="row mb-3">
            <div class="col-md-6">
                <form method="GET" class="form-inline">
                    <input type="hidden" name="search" value="<?= htmlspecialchars($search) ?>">
                    <label for="per_page" class="me-2">Tampilkan:</label>
                    <select name="per_page" id="per_page" class="form-select form-select-sm" onchange="this.form.submit()" style="width: auto; display: inline-block;">
                        <option value="10" <?= $per_page == 10 ? 'selected' : '' ?>>10</option>
                        <option value="30" <?= $per_page == 30 ? 'selected' : '' ?>>30</option>
                        <option value="50" <?= $per_page == 50 ? 'selected' : '' ?>>50</option>
                        <option value="0" <?= $per_page == 0 ? 'selected' : '' ?>>Semua</option>
                    </select>
                </form>
            </div>
            <!-- disini -->
        </div>
        
        <!-- Tabel Daftar Event -->
        <div class="card">
            <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                <span>Daftar Event</span>
                <span class="badge bg-light text-dark">Total: <?= $total_events ?></span>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>Nama Event</th>
                                <th>Tanggal</th>
                                <th>Pengesah</th>
                                <th>Jabatan</th>
                                <th>NIP</th>
                                <th>Status</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($allEvents->num_rows > 0): ?>
                                <?php while ($event = $allEvents->fetch_assoc()): ?>
                                <tr>
                                    <td><?= htmlspecialchars($event['nama_event']) ?></td>
                                    <td><?= date('d/m/Y', strtotime($event['tanggal_event'])) ?></td>
                                    <td><?= htmlspecialchars($event['pengesah']) ?></td>
                                    <td><?= htmlspecialchars($event['jabatan'] ?? '') ?></td>
                                    <td><?= htmlspecialchars($event['nip'] ?? '') ?></td>
                                    <td>
                                        <span class="badge bg-<?= $event['status'] === 'aktif' ? 'success' : 'secondary' ?>">
                                            <?= ucfirst($event['status']) ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="d-flex flex-wrap gap-1">
                                            <button class="btn btn-sm btn-secondary btn-undangan" data-id="<?= $event['id_event'] ?>">
                                                <i class="fas fa-file-image me-1"></i>Undangan
                                            </button>
                                            <!-- Tombol Notulen -->
                                            <button class="btn btn-sm btn-info btn-notulen" data-id="<?= $event['id_event'] ?>">
                                                <i class="fas fa-file-text me-1"></i>Notulen
                                            </button>
                                            
                                            <!-- Tombol Foto -->
                                            <button class="btn btn-sm btn-primary btn-foto" data-id="<?= $event['id_event'] ?>">
                                                <i class="fas fa-camera me-1"></i>Foto
                                            </button>

                                              <!-- Tombol Cetak PDF -->
                                                <a href="print_notulen.php?event_id=<?= $event['id_event'] ?>" 
                                                class="btn btn-sm btn-success" 
                                                target="_blank"
                                                title="Cetak Notulen dan Foto">
                                                    <i class="fas fa-file-pdf me-1"></i>PDF
                                                </a>
                                            
                                            <!-- Tombol Edit -->
                                            <button class="btn btn-sm btn-warning edit-event" data-id="<?= $event['id_event'] ?>" 
                                                data-nama="<?= htmlspecialchars($event['nama_event']) ?>" 
                                                data-tanggal="<?= $event['tanggal_event'] ?>" 
                                                data-pengesah="<?= htmlspecialchars($event['pengesah']) ?>" 
                                                data-jabatan="<?= htmlspecialchars($event['jabatan']) ?>"
                                                data-nip="<?= htmlspecialchars($event['nip'] ?? '') ?>"
                                                data-status="<?= $event['status'] ?>">
                                                <i class="fas fa-edit me-1"></i>Edit
                                            </button>
                                            
                                            <!-- Tombol Hapus -->
                                            <form method="POST" class="delete-form">
                                                <input type="hidden" name="id_event" value="<?= $event['id_event'] ?>">
                                                <button type="submit" name="delete_event" class="btn btn-sm btn-danger <?= $event['status'] === 'aktif' ? 'disabled' : '' ?>" 
                                                    <?= $event['status'] === 'aktif' ? 'title="Event aktif tidak dapat dihapus"' : '' ?>>
                                                    <i class="fas fa-trash me-1"></i>Hapus
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6" class="text-center py-4">Tidak ada data event ditemukan</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            <div class="col-md-6 text-start">
                <p class="mb-0 text-primary">
                    Menampilkan <?= ($offset + 1) ?> - <?= min($offset + ($per_page > 0 ? $per_page : $total_events), $total_events) ?> dari <?= $total_events ?> event
                </p>
            </div>

                <!-- Pagination -->
                <?php if ($total_pages > 1 && $per_page > 0): ?>
                <nav aria-label="Page navigation" class="mt-4">
                    <ul class="pagination justify-content-center">
                        <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                            <a class="page-link" href="?page=1&per_page=<?= $per_page ?>&search=<?= urlencode($search) ?>" aria-label="First">
                                <span aria-hidden="true">&laquo;&laquo;</span>
                            </a>
                        </li>
                        <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                            <a class="page-link" href="?page=<?= $page - 1 ?>&per_page=<?= $per_page ?>&search=<?= urlencode($search) ?>" aria-label="Previous">
                                <span aria-hidden="true">&laquo;</span>
                            </a>
                        </li>
                        
                        <?php 
                        // Tampilkan maksimal 5 halaman di sekitar halaman aktif
                        $start_page = max(1, $page - 2);
                        $end_page = min($total_pages, $page + 2);
                        
                        if ($start_page > 1) {
                            echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                        }
                        
                        for ($i = $start_page; $i <= $end_page; $i++): ?>
                            <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                                <a class="page-link" href="?page=<?= $i ?>&per_page=<?= $per_page ?>&search=<?= urlencode($search) ?>"><?= $i ?></a>
                            </li>
                        <?php endfor;
                        
                        if ($end_page < $total_pages) {
                            echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                        }
                        ?>
                        
                        <li class="page-item <?= $page >= $total_pages ? 'disabled' : '' ?>">
                            <a class="page-link" href="?page=<?= $page + 1 ?>&per_page=<?= $per_page ?>&search=<?= urlencode($search) ?>" aria-label="Next">
                                <span aria-hidden="true">&raquo;</span>
                            </a>
                        </li>
                        <li class="page-item <?= $page >= $total_pages ? 'disabled' : '' ?>">
                            <a class="page-link" href="?page=<?= $total_pages ?>&per_page=<?= $per_page ?>&search=<?= urlencode($search) ?>" aria-label="Last">
                                <span aria-hidden="true">&raquo;&raquo;</span>
                            </a>
                        </li>
                    </ul>
                </nav>
                <?php endif; ?>
            </div>
        </div>
    </div>

   <!-- Modal Tambah Event -->
<div class="modal fade" id="addEventModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Tambah Event Baru</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="nama_event" class="form-label">Nama Event <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="nama_event" name="nama_event" required placeholder="Isikan Nama lengkap dengan Gelar">
                    </div>
                    <div class="mb-3">
                        <label for="tanggal_event" class="form-label">Tanggal Event <span class="text-danger">*</span></label>
                        <input type="date" class="form-control" id="tanggal_event" name="tanggal_event" required>
                    </div>
                    <div class="mb-3">
                        <label for="pengesah" class="form-label">Pengesah <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="pengesah" name="pengesah" required placeholder="Masukkan Nama Pimpinan Yang Akan Mendandatangani Daftar Hadir">
                    </div>
                    <div class="mb-3">
                        <label for="jabatan" class="form-label">Jabatan <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="jabatan" name="jabatan" required placeholder="Masukkan Jabatan Pengesah">
                    </div>
                    <div class="mb-3">
                        <label for="nip" class="form-label">NIP <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="nip" name="nip" required placeholder="Masukkan NIP disini">
                    </div>
                    <div class="mb-3 form-check form-switch">
                        <input type="checkbox" class="form-check-input" id="status" name="status">
                        <label class="form-check-label" for="status">Aktifkan Event Ini</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                    <button type="submit" name="add_event" class="btn btn-primary">Simpan Event</button>
                </div>
            </form>
        </div>
    </div>
</div>

    <!-- Modal Edit Event -->
<div class="modal fade" id="editEventModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Edit Event</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="id_event" id="edit_id_event">
                    <div class="mb-3">
                        <label for="edit_nama_event" class="form-label">Nama Event <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="edit_nama_event" name="nama_event" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit_tanggal_event" class="form-label">Tanggal Event <span class="text-danger">*</span></label>
                        <input type="date" class="form-control" id="edit_tanggal_event" name="tanggal_event" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit_pengesah" class="form-label">Pengesah <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="edit_pengesah" name="pengesah" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit_jabatan" class="form-label">Jabatan <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="edit_jabatan" name="jabatan" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit_nip" class="form-label">NIP <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="edit_nip" name="nip" required>
                    </div>
                    <div class="mb-3 form-check form-switch">
                        <input type="checkbox" class="form-check-input" id="edit_status" name="status">
                        <label class="form-check-label" for="edit_status">Aktifkan Event Ini</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                    <button type="submit" name="update_event" class="btn btn-primary">Simpan Perubahan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal Notulen -->
<div class="modal fade" id="notulenModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Kelola Notulen</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="notulenForm" method="POST">
                <input type="hidden" name="id_event" id="notulen_event_id">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="isi_notulen" class="form-label">Isi Notulen <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="isi_notulen" name="isi_notulen" rows="10" required></textarea>
                    </div>
                
                        <div class="col-md-4">
                            <label for="pembuat" class="form-label">Pembuat Notulen <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="pembuat" name="pembuat" required>
                        </div>
                        <div class="col-md-4">
                            <label for="jabatan" class="form-label">Jabatan <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="jabatan" name="jabatan" required>
                        </div>
                        <div class="col-md-4">
                            <label for="nip_notulen" class="form-label">NIP <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="nip_notulen" name="nip" required>
                        </div>
                    </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                    <button type="submit" class="btn btn-primary">Simpan Notulen</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal Foto Kegiatan -->
<div class="modal fade" id="fotoModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Kelola Foto Kegiatan</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="uploadFotoForm" enctype="multipart/form-data">
                    <input type="hidden" name="id_event" id="foto_event_id">
                    <div class="mb-3">
                        <label for="eventPhotos" class="form-label">Upload Foto (Maksimal 6 foto)</label>
                        <input class="form-control" type="file" id="eventPhotos" name="photos[]" multiple accept="image/*" required>
                        <small class="text-muted">Format: JPG, PNG. Maksimal 200kb per foto.</small>
                    </div>
                    <div class="mb-3">
                        <label for="photoDescription" class="form-label">Deskripsi (Opsional)</label>
                        <input type="text" class="form-control" id="photoDescription" name="description" placeholder="Deskripsi foto...">
                    </div>
                    <button type="submit" class="btn btn-primary">Upload</button>
                </form>
                
                <hr>
                
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i>Maksimal 6 foto per event.
                </div>
                
                <div id="fotoContainer" class="row mt-3">
                    <!-- Foto akan ditampilkan di sini -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
            </div>
        </div>
    </div>
</div>

<!-- Modal Undangan -->
<div class="modal fade" id="undanganModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Kelola Undangan</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="uploadUndanganForm" enctype="multipart/form-data">
                    <input type="hidden" name="id_event" id="undangan_event_id">
                    <div class="mb-3">
                        <label for="undanganFile" class="form-label">Upload File Undangan</label>
                        <input class="form-control" type="file" id="undanganFile" name="undangan" accept="image/*,.pdf" required>
                        <small class="text-muted">Format: JPG, PNG, PDF. Maksimal 2kb.</small>
                    </div>
                    <div class="mb-3">
                        <label for="undanganDesc" class="form-label">Deskripsi (Opsional)</label>
                        <input type="text" class="form-control" id="undanganDesc" name="description" placeholder="Deskripsi undangan...">
                    </div>
                    <button type="submit" class="btn btn-primary">Upload</button>
                </form>
                
                <hr>
                
                <div id="undanganContainer" class="mt-3">
                    <!-- Undangan akan ditampilkan di sini -->
                    <div class="alert alert-info" id="noUndanganAlert">
                        <i class="fas fa-info-circle me-2"></i>Belum ada file undangan untuk event ini.
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
            </div>
        </div>
    </div>
</div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../assets/js/sweetalert2.min.js"></script>
    <script>
        // SweetAlert notifications
        <?php if (isset($_SESSION['swal'])): ?>
            Swal.fire({
                title: '<?= $_SESSION['swal']['title'] ?>',
                text: '<?= $_SESSION['swal']['text'] ?>',
                icon: '<?= $_SESSION['swal']['icon'] ?>',
                confirmButtonText: 'OK'
            });
            <?php unset($_SESSION['swal']); ?>
        <?php endif; ?>

        // Edit Event Modal
        document.querySelectorAll('.edit-event').forEach(button => {
            button.addEventListener('click', function() {
                const modal = new bootstrap.Modal(document.getElementById('editEventModal'));
                
                document.getElementById('edit_id_event').value = this.dataset.id;
                document.getElementById('edit_nama_event').value = this.dataset.nama;
                document.getElementById('edit_tanggal_event').value = this.dataset.tanggal;
                document.getElementById('edit_pengesah').value = this.dataset.pengesah;
                document.getElementById('edit_jabatan').value = this.dataset.jabatan;
                document.getElementById('edit_nip').value = this.dataset.nip;
                document.getElementById('edit_status').checked = this.dataset.status === 'aktif';
                
                modal.show();
            });
        });

        // Delete confirmation with SweetAlert
        document.querySelectorAll('.delete-form').forEach(form => {
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                
                Swal.fire({
                    title: 'Apakah Anda yakin?',
                    text: "Anda tidak akan dapat mengembalikan data ini!",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Ya, hapus!',
                    cancelButtonText: 'Batal'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Create a hidden input for delete_event
                        const deleteInput = document.createElement('input');
                        deleteInput.type = 'hidden';
                        deleteInput.name = 'delete_event';
                        deleteInput.value = '1';
                        form.appendChild(deleteInput);
                        
                        // Submit the form
                        form.submit();
                    }
                });
            });
        });

        // Set tanggal hari ini sebagai default untuk form tambah event
        document.addEventListener('DOMContentLoaded', function() {
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('tanggal_event').value = today;
        });

// Handle tombol notulen
document.querySelectorAll('.btn-notulen').forEach(btn => {
    btn.addEventListener('click', function() {
        const eventId = this.dataset.id;
        document.getElementById('notulen_event_id').value = eventId;
        
        // Load notulen yang sudah ada
        fetch(`get_notulen.php?id_event=${eventId}`)
            .then(response => response.json())
            .then(data => {
                document.getElementById('pembuat').value = data.pembuat || '';
                document.getElementById('jabatan').value = data.jabatan || '';
                document.getElementById('nip_notulen').value = data.nip || '';
                document.getElementById('isi_notulen').value = data.isi_notulen || '';
                const modal = new bootstrap.Modal(document.getElementById('notulenModal'));
                modal.show();
            });
    });
});

// Handle form notulen
document.getElementById('notulenForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    fetch('save_notulen.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            Swal.fire({
                title: 'Berhasil!',
                text: 'Notulen berhasil disimpan',
                icon: 'success'
            }).then(() => {
                const modal = bootstrap.Modal.getInstance(document.getElementById('notulenModal'));
                modal.hide();
            });
        } else {
            Swal.fire({
                title: 'Gagal!',
                text: data.message || 'Gagal menyimpan notulen',
                icon: 'error'
            });
        }
    });
});

// Handle tombol foto
document.querySelectorAll('.btn-foto').forEach(btn => {
    btn.addEventListener('click', function() {
        const eventId = this.dataset.id;
        document.getElementById('foto_event_id').value = eventId;
        loadFotoKegiatan(eventId);
        const modal = new bootstrap.Modal(document.getElementById('fotoModal'));
        modal.show();
    });
});

// Update the loadFotoKegiatan function
function loadFotoKegiatan(eventId) {
    fetch(`get_foto.php?id_event=${eventId}`)
        .then(response => response.json())
        .then(data => {
            const container = document.getElementById('fotoContainer');
            container.innerHTML = '';
            
            if (data.length === 0) {
                container.innerHTML = '<div class="col-12 text-center py-4"><em>Belum ada foto untuk event ini</em></div>';
                return;
            }
            
            data.forEach(foto => {
                const col = document.createElement('div');
                col.className = 'col-md-4 mb-3 foto-item';
                col.setAttribute('data-id', foto.id_foto);
                col.innerHTML = `
                    <div class="card h-100">
                        <img src="../uploads/event_foto/${foto.nama_file}" class="card-img-top foto-thumbnail" style="height: 200px; object-fit: cover;">
                        <div class="card-body">
                            <p class="card-text">${foto.deskripsi || 'Tidak ada deskripsi'}</p>
                        </div>
                        <div class="card-footer bg-transparent">
                            <button class="btn btn-sm btn-danger btn-hapus-foto" data-id="${foto.id_foto}">
                                <i class="fas fa-trash"></i> Hapus
                            </button>
                        </div>
                    </div>
                `;
                container.appendChild(col);
            });

            // Add event listeners to all delete buttons
            container.querySelectorAll('.btn-hapus-foto').forEach(button => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    const fotoId = this.getAttribute('data-id');
                    const eventId = document.getElementById('foto_event_id').value;
                    hapusFoto(fotoId, eventId);
                });
            });
        })
        .catch(error => {
            console.error('Error loading photos:', error);
            Swal.fire('Error', 'Gagal memuat foto', 'error');
        });
}

// Ganti bagian hapusFoto dengan ini:
function hapusFoto(idFoto, eventId) {
    Swal.fire({
        title: 'Apakah Anda yakin?',
        text: "Foto akan dihapus permanen!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Ya, hapus!',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Sedang menghapus...',
                html: 'Mohon tunggu',
                allowOutsideClick: false,
                didOpen: () => Swal.showLoading()
            });

            // Ubah format pengiriman data
            const formData = new FormData();
            formData.append('id', idFoto);

            fetch('hapus_foto.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                // Pastikan response adalah JSON valid
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                Swal.close();
                if (data.success) {
                    Swal.fire('Berhasil!', 'Foto telah dihapus.', 'success');
                    loadFotoKegiatan(eventId);
                } else {
                    Swal.fire('Gagal!', data.message || 'Gagal menghapus foto', 'error');
                }
            })
            .catch(error => {
                Swal.close();
                Swal.fire('Error!', 'Terjadi kesalahan: ' + error.message, 'error');
                console.error('Error:', error);
            });
        }
    });
}

// Fungsi untuk mengupdate urutan foto
function updateUrutanFoto(eventId) {
    const fotoItems = Array.from(document.querySelectorAll('.foto-item'));
    const urutan = fotoItems.map((item, index) => ({
        id_foto: item.getAttribute('data-id'),
        urutan: index + 1
    }));
    
    fetch('update_urutan_foto.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            eventId: eventId,
            urutan: urutan
        })
    });
}

// Handle upload foto
document.getElementById('uploadFotoForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const eventId = document.getElementById('foto_event_id').value;
    const formData = new FormData(this);
    
    // Cek jumlah foto yang sudah ada
    fetch(`count_foto.php?id_event=${eventId}`)
        .then(response => response.json())
        .then(data => {
            const totalFoto = data.total;
            const files = document.getElementById('eventPhotos').files;
            
            if (totalFoto + files.length > 6) {
                Swal.fire({
                    title: 'Gagal!',
                    text: 'Maksimal 6 foto per event',
                    icon: 'error'
                });
                return;
            }
            
            fetch('upload_foto.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        title: 'Berhasil!',
                        text: 'Foto berhasil diupload',
                        icon: 'success'
                    });
                    loadFotoKegiatan(eventId);
                    this.reset();
                } else {
                    Swal.fire({
                        title: 'Gagal!',
                        text: data.message || 'Gagal mengupload foto',
                        icon: 'error'
                    });
                }
            });
        });
});

// Handle tombol undangan
document.querySelectorAll('.btn-undangan').forEach(btn => {
    btn.addEventListener('click', function() {
        const eventId = this.dataset.id;
        document.getElementById('undangan_event_id').value = eventId;
        loadUndangan(eventId);
        const modal = new bootstrap.Modal(document.getElementById('undanganModal'));
        modal.show();
    });
});

// Function to load undangan
// Function to load undangan
function loadUndangan(eventId) {
    const container = document.getElementById('undanganContainer');
    const noUndanganAlert = document.getElementById('noUndanganAlert');
    
    // Reset container first
    container.innerHTML = '';
    noUndanganAlert.style.display = 'block';
    container.appendChild(noUndanganAlert);

    fetch(`get_undangan.php?id_event=${eventId}`)
        .then(response => response.json())
        .then(data => {
            if (data.length === 0) {
                return; // Tetap tampilkan alert "Belum ada undangan"
            }
            
            noUndanganAlert.style.display = 'none';
            
            data.forEach(undangan => {
                const card = document.createElement('div');
                card.className = 'card mb-3';
                card.innerHTML = `
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="card-title">Undangan</h6>
                                <p class="card-text">${undangan.deskripsi || 'Tidak ada deskripsi'}</p>
                                <small class="text-muted">Uploaded: ${new Date(undangan.created_at).toLocaleString()}</small>
                            </div>
                            <div>
                                <a href="../uploads/event_undangan/${undangan.nama_file}" 
                                   class="btn btn-sm btn-primary me-2" 
                                   target="_blank">
                                    <i class="fas fa-eye"></i> Lihat
                                </a>
                                <button class="btn btn-sm btn-danger btn-hapus-undangan" data-id="${undangan.id_undangan}">
                                    <i class="fas fa-trash"></i> Hapus
                                </button>
                            </div>
                        </div>
                    </div>
                `;
                container.appendChild(card);
            });

            // Add event listeners to delete buttons
            container.querySelectorAll('.btn-hapus-undangan').forEach(button => {
                button.addEventListener('click', function() {
                    const undanganId = this.getAttribute('data-id');
                    const eventId = document.getElementById('undangan_event_id').value;
                    hapusUndangan(undanganId, eventId);
                });
            });
        })
        .catch(error => {
            console.error('Error loading undangan:', error);
            Swal.fire('Error', 'Gagal memuat undangan', 'error');
        });
}

// Function to delete undangan
function hapusUndangan(idUndangan, eventId) {
    Swal.fire({
        title: 'Apakah Anda yakin?',
        text: "Undangan akan dihapus permanen!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Ya, hapus!',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            fetch('hapus_undangan.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ id: idUndangan })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire('Berhasil!', 'Undangan telah dihapus.', 'success');
                    loadUndangan(eventId);
                } else {
                    Swal.fire('Gagal!', data.message || 'Gagal menghapus undangan', 'error');
                }
            });
        }
    });
}

// Handle upload undangan
document.getElementById('uploadUndanganForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const eventId = document.getElementById('undangan_event_id').value;
    const formData = new FormData(this);
    
    Swal.fire({
        title: 'Mengupload...',
        html: 'Mohon tunggu',
        allowOutsideClick: false,
        didOpen: () => Swal.showLoading()
    });

    fetch('upload_undangan.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        Swal.close();
        if (data.success) {
            Swal.fire({
                title: 'Berhasil!',
                text: 'Undangan berhasil diupload',
                icon: 'success'
            });
            loadUndangan(eventId);
            this.reset();
        } else {
            Swal.fire({
                title: 'Gagal!',
                text: data.message || 'Gagal mengupload undangan',
                icon: 'error'
            });
        }
    })
    .catch(error => {
        Swal.close();
        Swal.fire('Error', 'Terjadi kesalahan saat mengupload', 'error');
        console.error('Error:', error);
    });
});

    </script>
</body>
</html>