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

$event_id = isset($_GET['event_id']) ? (int)$_GET['event_id'] : 0;
$allEvents = getAllEvents();

if ($event_id > 0) {
    // Ambil data dengan urutan berdasarkan kolom sequence
    $attendance = $conn->query("SELECT * FROM dafdir_absensi WHERE id_event = $event_id ORDER BY sequence ASC")->fetch_all(MYSQLI_ASSOC);
    $currentEvent = $conn->query("SELECT * FROM dafdir_event WHERE id_event = $event_id")->fetch_assoc();
} else {
    // Default ke event aktif jika tidak ada event_id yang ditentukan
    $activeEvent = getActiveEvent();
    if ($activeEvent) {
        $event_id = $activeEvent['id_event'];
        $attendance = $conn->query("SELECT * FROM dafdir_absensi WHERE id_event = $event_id ORDER BY sequence ASC")->fetch_all(MYSQLI_ASSOC);
        $currentEvent = $activeEvent;
    } else {
        $attendance = [];
        $currentEvent = null;
    }
}

// Handle delete attendance
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_attendance'])) {
    $id_absensi = (int)$_POST['id_absensi'];
    
    if ($conn->query("DELETE FROM dafdir_absensi WHERE id_absensi = $id_absensi")) {
        $_SESSION['swal'] = [
            'title' => 'Berhasil',
            'text' => 'Data absensi berhasil dihapus',
            'icon' => 'success'
        ];
    } else {
        $_SESSION['swal'] = [
            'title' => 'Gagal',
            'text' => 'Gagal menghapus data absensi: ' . $conn->error,
            'icon' => 'error'
        ];
    }
    
    header("Location: attendance.php?event_id=$event_id");
    exit();
}

// Handle update order
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_order'])) {
    $order = $_POST['order'];
    
    // Mulai transaction
    $conn->begin_transaction();
    
    try {
        foreach ($order as $id_absensi => $seq) {
            $id = (int)$id_absensi;
            $sequence = (int)$seq;
            $stmt = $conn->prepare("UPDATE dafdir_absensi SET sequence = ? WHERE id_absensi = ?");
            $stmt->bind_param("ii", $sequence, $id);
            $stmt->execute();
            $stmt->close();
        }
        
        $conn->commit();
        
        $_SESSION['swal'] = [
            'title' => 'Berhasil',
            'text' => 'Urutan absensi berhasil diperbarui',
            'icon' => 'success'
        ];
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['swal'] = [
            'title' => 'Gagal',
            'text' => 'Gagal memperbarui urutan: ' . $e->getMessage(),
            'icon' => 'error'
        ];
    }
    
    header("Location: attendance.php?event_id=$event_id");
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SMANSAB - Daftar Hadir Digital</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">
</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>
                <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" href="events.php">Kelola Event</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" 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">Daftar Hadir</h2>
        
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                Pilih Event
            </div>
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-8">
                        <select name="event_id" class="form-select" onchange="this.form.submit()">
                            <option value="">-- Pilih Event --</option>
                            <?php foreach ($allEvents as $event): ?>
                            <option value="<?= $event['id_event'] ?>" <?= $event_id == $event['id_event'] ? 'selected' : '' ?>>
                                <?= $event['nama_event'] ?> (<?= date('d/m/Y', strtotime($event['tanggal_event'])) ?>)
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <?php if ($currentEvent): ?>
                            <a href="print_attendance.php?event_id=<?= $currentEvent['id_event'] ?>" class="btn btn-success w-100" target="_blank">
                                <i class="fas fa-print"></i> Cetak Daftar Hadir
                            </a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
        
        <?php if ($currentEvent): ?>
        <div class="card mb-4">
            <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                <span>Daftar Hadir: <?= $currentEvent['nama_event'] ?></span>
                <span class="badge bg-light text-dark">Total: <?= count($attendance) ?></span>
            </div>
            <div class="card-body">
                <form method="POST" id="orderForm">
                    <input type="hidden" name="update_order" value="1">
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th width="5%">No.</th>
                                    <th>Nama Lengkap</th>
                                    <th>Jabatan</th>
                                    <th>Waktu Isi</th>
                                    <th>Tanda Tangan</th>
                                    <th width="15%">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($attendance)): ?>
                                <tr>
                                    <td colspan="6" class="text-center">Tidak ada data absensi</td>
                                </tr>
                                <?php else: ?>
                                <?php foreach ($attendance as $row): ?>
                                <tr>
                                    <td>
                                        <input type="number" name="order[<?= $row['id_absensi'] ?>]" 
                                            value="<?= $row['sequence'] ?>" 
                                            min="1" class="form-control form-control-sm" 
                                            style="width: 50px;">
                                    </td>
                                    <td><?= $row['nama_lengkap'] ?></td>
                                    <td><?= $row['jabatan'] ?></td>
                                    <td><?= date('d/m/Y H:i', strtotime($row['waktu_isi'])) ?></td>
                                    <td>
                                        <?php if (!empty($row['tanda_tangan'])): ?>
                                        <img src="<?= $row['tanda_tangan'] ?>" alt="Tanda Tangan" style="max-height: 50px;">
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <form method="POST" class="delete-form" style="display: inline;">
                                            <input type="hidden" name="id_absensi" value="<?= $row['id_absensi'] ?>">
                                            <button type="button" class="btn btn-sm btn-danger delete-btn">
                                                <i class="fas fa-trash"></i> Hapus
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <?php if (!empty($attendance)): ?>
                    <div class="text-end mt-3">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Simpan Urutan
                        </button>
                    </div>
                    <?php endif; ?>
                </form>
            </div>
        </div>
        <?php endif; ?>
    </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; ?>

        // Konfirmasi penghapusan dengan SweetAlert
        document.querySelectorAll('.delete-btn').forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                const form = this.closest('form');
                
                Swal.fire({
                    title: 'Apakah Anda yakin?',
                    text: "Data absensi akan dihapus permanen!",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Ya, hapus!',
                    cancelButtonText: 'Batal'
                }).then((result) => {
                    if (result.isConfirmed) {
                        const deleteInput = document.createElement('input');
                        deleteInput.type = 'hidden';
                        deleteInput.name = 'delete_attendance';
                        deleteInput.value = '1';
                        form.appendChild(deleteInput);
                        
                        form.submit();
                    }
                });
            });
        });

        // Validasi form urutan
        document.getElementById('orderForm').addEventListener('submit', function(e) {
            const inputs = this.querySelectorAll('input[type="number"]');
            const values = new Set();
            let isValid = true;
            
            inputs.forEach(input => {
                if (values.has(input.value)) {
                    isValid = false;
                    input.classList.add('is-invalid');
                } else {
                    values.add(input.value);
                    input.classList.remove('is-invalid');
                }
            });
            
            if (!isValid) {
                e.preventDefault();
                Swal.fire({
                    title: 'Error',
                    text: 'Nomor urut tidak boleh sama',
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
            }
        });
    </script>
</body>
</html>