<?php
include '../includes/auth.php';
include '../includes/functions.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_event'])) {
        $nama_event = sanitize($_POST['nama_event']);
        $tanggal_event = sanitize($_POST['tanggal_event']);
        $pengesan = sanitize($_POST['pengesan']);
        $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, status) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("ssss", $nama_event, $tanggal_event, $pengesan, $status);
        
        if ($stmt->execute()) {
            $_SESSION['success'] = "Event berhasil ditambahkan";
        } else {
            $_SESSION['error'] = "Gagal menambahkan event: " . $conn->error;
        }
        
        $stmt->close();
        header("Location: events.php");
        exit();
    } elseif (isset($_POST['update_event'])) {
        $id_event = (int)$_POST['id_event'];
        $nama_event = sanitize($_POST['nama_event']);
        $tanggal_event = sanitize($_POST['tanggal_event']);
        $pengesan = sanitize($_POST['pengesan']);
        $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 = ?, status = ? WHERE id_event = ?");
        $stmt->bind_param("ssssi", $nama_event, $tanggal_event, $pengesan, $status, $id_event);
        
        if ($stmt->execute()) {
            $_SESSION['success'] = "Event berhasil diperbarui";
        } else {
            $_SESSION['error'] = "Gagal memperbarui event: " . $conn->error;
        }
        
        $stmt->close();
        header("Location: events.php");
        exit();
    } elseif (isset($_POST['delete_event'])) {
        $id_event = (int)$_POST['id_event'];
        
        // Hapus dulu absensi terkait
        $conn->query("DELETE FROM dafdir_absensi WHERE id_event = $id_event");
        
        // Kemudian hapus event
        if ($conn->query("DELETE FROM dafdir_event WHERE id_event = $id_event")) {
            $_SESSION['success'] = "Event berhasil dihapus";
        } else {
            $_SESSION['error'] = "Gagal menghapus event: " . $conn->error;
        }
        
        header("Location: events.php");
        exit();
    }
}

$allEvents = getAllEvents();
?>
<!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="../assets/css/style.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">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="#">
                <i class="fas fa-user-check text-primary"></i> <!-- Ikon absensi -->
                <span class="ms-2">Absensi Digital </span>
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="dashboard.php">Dashboard</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="events.php">Kelola Event</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="attendance.php">Daftar Hadir</a>
                    </li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <?= $_SESSION['admin_username'] ?>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="logout.php">Logout</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-5">
        <h2 class="mb-4">Kelola Event</h2>
        
        <?php if (isset($_SESSION['success'])): ?>
            <div class="alert alert-success"><?= $_SESSION['success'] ?></div>
            <?php unset($_SESSION['success']); ?>
        <?php endif; ?>
        
        <?php if (isset($_SESSION['error'])): ?>
            <div class="alert alert-danger"><?= $_SESSION['error'] ?></div>
            <?php unset($_SESSION['error']); ?>
        <?php endif; ?>
        
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                Tambah Event Baru
            </div>
            <div class="card-body">
                <form method="POST">
                    <div class="mb-3">
                        <label for="nama_event" class="form-label">Nama Event</label>
                        <input type="text" class="form-control" id="nama_event" name="nama_event" required>
                    </div>
                    <div class="mb-3">
                        <label for="tanggal_event" class="form-label">Tanggal Event</label>
                        <input type="date" class="form-control" id="tanggal_event" name="tanggal_event" required>
                    </div>
                    <div class="mb-3">
                        <label for="pengesan" class="form-label">Pengesah</label>
                        <input type="text" class="form-control" id="pengesan" name="pengesan" required>
                    </div>
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="status" name="status">
                        <label class="form-check-label" for="status">Aktifkan Event Ini</label>
                    </div>
                    <button type="submit" name="add_event" class="btn btn-primary">Tambah Event</button>
                </form>
            </div>
        </div>
        
        <div class="card">
            <div class="card-header bg-primary text-white">
                Daftar Event
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>Nama Event</th>
                                <th>Tanggal</th>
                                <th>Pengesah</th>
                                <th>Status</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($allEvents as $event): ?>
                            <tr>
                                <td><?= $event['nama_event'] ?></td>
                                <td><?= date('d/m/Y', strtotime($event['tanggal_event'])) ?></td>
                                <td><?= $event['pengesah'] ?></td>
                                <td>
                                    <span class="badge bg-<?= $event['status'] === 'aktif' ? 'success' : 'secondary' ?>">
                                        <?= ucfirst($event['status']) ?>
                                    </span>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-warning edit-event" data-id="<?= $event['id_event'] ?>" 
                                        data-nama="<?= $event['nama_event'] ?>" 
                                        data-tanggal="<?= $event['tanggal_event'] ?>" 
                                        data-pengesan="<?= $event['pengesah'] ?>" 
                                        data-status="<?= $event['status'] ?>">
                                        Edit
                                    </button>
                                    <form method="POST" style="display: inline;">
                                        <input type="hidden" name="id_event" value="<?= $event['id_event'] ?>">
                                        <button type="submit" name="delete_event" class="btn btn-sm btn-danger" 
                                            onclick="return confirm('Apakah Anda yakin ingin menghapus event ini?')">
                                            Hapus
                                        </button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Event Modal -->
    <div class="modal fade" id="editEventModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Event</h5>
                    <button type="button" class="btn-close" 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</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</label>
                            <input type="date" class="form-control" id="edit_tanggal_event" name="tanggal_event" required>
                        </div>
                        <div class="mb-3">
                            <label for="edit_pengesan" class="form-label">Pengesah</label>
                            <input type="text" class="form-control" id="edit_pengesan" name="pengesan" required>
                        </div>
                        <div class="mb-3 form-check">
                            <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>

    <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>
        // 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_pengesan').value = this.dataset.pengesan;
                document.getElementById('edit_status').checked = this.dataset.status === 'aktif';
                
                modal.show();
            });
        });
    </script>
</body>
</html>