<%- include('partials/header-sidebar') %>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">


    <div class="page-wrapper" id="toTop">
        <div class="content">
            <div class="page-header">
                <div class="page-title">
                    <h4>All Events</h4>
                    <h6>View and manage events</h6>
                </div>
            </div>

            <div class="row" id="eventsContainer">
                <!-- Event cards go here -->
            </div>

            <div class="mt-4 d-flex justify-content-center align-items-center gap-3">
                <button id="prevPage" class="btn btn-outline-primary">Previous</button>
                <span id="pageInfo" class="fw-bold"></span>
                <button id="nextPage" class="btn btn-outline-primary">Next</button>
            </div>
        </div>
    </div>

    <%- include('partials/footer') %>

        <script>
            let currentPage = 1;
            const limit = 6;

            document.addEventListener('DOMContentLoaded', () => {
                loadEvents(currentPage);
            });

            document.getElementById('prevPage').addEventListener('click', () => {
                if (currentPage > 1) {
                    currentPage--;
                    loadEvents(currentPage);
                }
            });

            document.getElementById('nextPage').addEventListener('click', () => {
                currentPage++;
                loadEvents(currentPage);
            });

            async function loadEvents(page) {
                try {
                    const res = await fetch(`/api/events?page=${page}&limit=${limit}`);
                    const data = await res.json();

                    const container = document.getElementById('eventsContainer');
                    container.innerHTML = '';

                    if (!data.events.length) {
                        container.innerHTML = `<div class="col-12 text-center text-muted">No events found.</div>`;
                        document.getElementById('pageInfo').textContent = `Page ${page}`;
                        return;
                    }

                    data.events.forEach(event => {
                        const card = `
          <div class="col-lg-4 col-md-6 mb-4">
            <div class="card shadow-sm border-0 h-100">
              <div class="card-body d-flex flex-column justify-content-between">
                <div>
                  <h5 class="card-title text-primary">${event.title}</h5>
                  <p class="text-muted mb-1"><i class="fas fa-calendar-alt me-1"></i> ${new Date(event.date).toLocaleDateString()}</p>
                  <p class="text-muted mb-1"><i class="fas fa-clock me-1"></i> ${event.startTime} - ${event.endTime}</p>
                  <p class="text-muted mb-2"><i class="fas fa-map-marker-alt me-1"></i> ${event.location}</p>
                  <p class="card-text small">${event.description}</p>
                </div>
                <div class="d-flex justify-content-end gap-2 mt-3">
                  <button class="btn btn-sm btn-outline-secondary" onclick="editEvent('${event._id}')">Edit
  <i class="bi bi-pencil-square"></i>
</button>
<button class="btn btn-sm btn-outline-danger" onclick="deleteEvent('${event._id}')">
  Delete<i class="bi bi-trash-fill"></i>
</button>

                </div>
              </div>
            </div>
          </div>
        `;
                        container.insertAdjacentHTML('beforeend', card);
                    });

                    document.getElementById('pageInfo').textContent = `Page ${page}`;
                } catch (error) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to load events. Please try again later.'
                    });
                }
            }

            function editEvent(id) {
                window.location.href = `/api/events?id=${id}`; // Adjust as needed
            }

            async function deleteEvent(id) {
                const confirm = await Swal.fire({
                    icon: 'warning',
                    title: 'Are you sure?',
                    text: 'This will permanently delete the event.',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, delete it!'
                });

                if (confirm.isConfirmed) {
                    try {
                        const res = await fetch(`/api/events/${id}`,
                            {
                                method: 'DELETE',

                                headers: {
                                    'Content-Type': 'application/json',
                                    "Authorization": `Bearer ${token}`,
                                }
                            });
                        const result = await res.json();

                        if (res.ok) {
                            Swal.fire('Deleted!', result.message || 'Event deleted.', 'success');
                            loadEvents(currentPage);
                        } else {
                            throw new Error(result.message || 'Failed to delete');
                        }
                    } catch (err) {
                        Swal.fire('Error', err.message, 'error');
                    }
                }
            }
        </script>