<?php
require_once 'config/database.php';
requireAdmin();

require_once 'templates/header.php';
require_once 'templates/navbar.php';
require_once 'templates/sidebar.php';
?>

<!-- Content Wrapper -->
<div class="content-wrapper">
    <!-- Content Header -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Event Calendar</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                        <li class="breadcrumb-item"><a href="events.php">Events</a></li>
                        <li class="breadcrumb-item active">Calendar</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-3">
                    <!-- Event Creation -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Quick Event</h3>
                        </div>
                        <div class="card-body">
                            <form id="quickEventForm">
                                <div class="form-group">
                                    <label>Event Name</label>
                                    <input type="text" class="form-control" name="event_name" required>
                                </div>
                                <div class="form-group">
                                    <label>Date</label>
                                    <input type="date" class="form-control" name="event_date" required>
                                </div>
                                <div class="form-group">
                                    <label>Time</label>
                                    <input type="time" class="form-control" name="event_time">
                                </div>
                                <div class="form-group">
                                    <label>Category</label>
                                    <select class="form-control" name="category">
                                        <option value="meeting">Meeting</option>
                                        <option value="cultural">Cultural</option>
                                        <option value="social">Social</option>
                                        <option value="fundraising">Fundraising</option>
                                        <option value="educational">Educational</option>
                                    </select>
                                </div>
                                <button type="submit" class="btn btn-primary btn-block">
                                    <i class="fas fa-plus"></i> Add Event
                                </button>
                            </form>
                        </div>
                    </div>

                    <!-- Event Filters -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Filter Events</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label>Event Category</label>
                                <select class="form-control" id="categoryFilter">
                                    <option value="">All Categories</option>
                                    <option value="meeting">Meeting</option>
                                    <option value="cultural">Cultural</option>
                                    <option value="social">Social</option>
                                    <option value="fundraising">Fundraising</option>
                                    <option value="educational">Educational</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>Event Status</label>
                                <select class="form-control" id="statusFilter">
                                    <option value="">All Status</option>
                                    <option value="upcoming">Upcoming</option>
                                    <option value="ongoing">Ongoing</option>
                                    <option value="completed">Completed</option>
                                    <option value="cancelled">Cancelled</option>
                                </select>
                            </div>
                            <button type="button" class="btn btn-info btn-block" onclick="filterEvents()">
                                <i class="fas fa-filter"></i> Apply Filters
                            </button>
                        </div>
                    </div>

                    <!-- Upcoming Events -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Upcoming Events</h3>
                        </div>
                        <div class="card-body p-0">
                            <div id="upcomingEvents" class="list-group list-group-flush">
                                <!-- Upcoming events will be populated here -->
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-md-9">
                    <!-- Calendar -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Event Calendar</h3>
                            <div class="card-tools">
                                <div class="btn-group">
                                    <button type="button" class="btn btn-primary" onclick="calendar.changeView('dayGridMonth')">Month</button>
                                    <button type="button" class="btn btn-primary" onclick="calendar.changeView('timeGridWeek')">Week</button>
                                    <button type="button" class="btn btn-primary" onclick="calendar.changeView('timeGridDay')">Day</button>
                                </div>
                            </div>
                        </div>
                        <div class="card-body">
                            <div id="calendar"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- Event Details Modal -->
<div class="modal fade" id="eventModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="eventModalTitle">Event Details</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body" id="eventModalBody">
                <!-- Event details will be populated here -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="editEventBtn">Edit Event</button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Event Modal -->
<div class="modal fade" id="editEventModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Edit Event</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form id="editEventForm">
                <div class="modal-body">
                    <input type="hidden" id="edit_event_id" name="event_id">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Event Name</label>
                                <input type="text" class="form-control" name="event_name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Category</label>
                                <select class="form-control" name="category">
                                    <option value="meeting">Meeting</option>
                                    <option value="cultural">Cultural</option>
                                    <option value="social">Social</option>
                                    <option value="fundraising">Fundraising</option>
                                    <option value="educational">Educational</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Start Date</label>
                                <input type="date" class="form-control" name="start_date" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>End Date</label>
                                <input type="date" class="form-control" name="end_date">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Start Time</label>
                                <input type="time" class="form-control" name="start_time">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>End Time</label>
                                <input type="time" class="form-control" name="end_time">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Location</label>
                        <input type="text" class="form-control" name="location">
                    </div>
                    <div class="form-group">
                        <label>Description</label>
                        <textarea class="form-control" name="description" rows="3"></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Max Registrations</label>
                                <input type="number" class="form-control" name="max_registrations">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Registration Fee</label>
                                <input type="number" class="form-control" name="registration_fee" step="0.01">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Update Event</button>
                </div>
            </form>
        </div>
    </div>
</div>

<link href="https://cdn.jsdelivr.net/npm/fullcalendar@5.10.1/main.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@5.10.1/main.min.js"></script>

<script>
let calendar;

document.addEventListener('DOMContentLoaded', function() {
    initializeCalendar();
    loadUpcomingEvents();
});

function initializeCalendar() {
    const calendarEl = document.getElementById('calendar');
    
    calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: 'dayGridMonth',
        height: 'auto',
        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay'
        },
        events: function(fetchInfo, successCallback, failureCallback) {
            $.ajax({
                url: 'api/fetch_calendar_events.php',
                type: 'GET',
                data: {
                    start: fetchInfo.startStr,
                    end: fetchInfo.endStr,
                    category: $('#categoryFilter').val(),
                    status: $('#statusFilter').val()
                },
                success: function(response) {
                    if (response.success) {
                        successCallback(response.events);
                    } else {
                        failureCallback();
                    }
                },
                error: function() {
                    failureCallback();
                }
            });
        },
        eventClick: function(info) {
            showEventDetails(info.event);
        },
        dateClick: function(info) {
            // Pre-fill quick event form with clicked date
            $('#quickEventForm input[name="event_date"]').val(info.dateStr);
        },
        eventColor: '#007bff',
        eventClassNames: function(arg) {
            return ['event-' + arg.event.extendedProps.category];
        }
    });
    
    calendar.render();
}

function showEventDetails(event) {
    const eventId = event.id;
    
    $.ajax({
        url: 'api/fetch_event_details.php',
        type: 'GET',
        data: { id: eventId },
        success: function(response) {
            if (response.success) {
                const event = response.event;
                
                $('#eventModalTitle').text(event.event_name);
                
                let html = `
                    <div class="row">
                        <div class="col-md-6">
                            <strong>Category:</strong> ${event.category}<br>
                            <strong>Start Date:</strong> ${event.start_date}<br>
                            <strong>End Date:</strong> ${event.end_date || 'N/A'}<br>
                            <strong>Location:</strong> ${event.location || 'N/A'}
                        </div>
                        <div class="col-md-6">
                            <strong>Status:</strong> <span class="badge badge-info">${event.status}</span><br>
                            <strong>Registrations:</strong> ${event.current_registrations}/${event.max_registrations || 'Unlimited'}<br>
                            <strong>Registration Fee:</strong> ₹${event.registration_fee || 0}<br>
                            <strong>Created By:</strong> ${event.created_by_name}
                        </div>
                    </div>
                    <hr>
                    <div class="row">
                        <div class="col-12">
                            <strong>Description:</strong><br>
                            ${event.description || 'No description available'}
                        </div>
                    </div>
                `;
                
                $('#eventModalBody').html(html);
                $('#editEventBtn').attr('data-event-id', eventId);
                $('#eventModal').modal('show');
            }
        }
    });
}

function loadUpcomingEvents() {
    $.ajax({
        url: 'api/fetch_upcoming_events.php',
        type: 'GET',
        success: function(response) {
            if (response.success) {
                let html = '';
                response.events.forEach(function(event) {
                    html += `
                        <div class="list-group-item">
                            <div class="d-flex w-100 justify-content-between">
                                <h6 class="mb-1">${event.event_name}</h6>
                                <small class="text-muted">${event.days_until} days</small>
                            </div>
                            <p class="mb-1">${event.start_date} ${event.start_time || ''}</p>
                            <small class="text-muted">${event.location || 'Location TBD'}</small>
                        </div>
                    `;
                });
                
                if (html === '') {
                    html = '<div class="list-group-item text-center text-muted">No upcoming events</div>';
                }
                
                $('#upcomingEvents').html(html);
            }
        }
    });
}

function filterEvents() {
    calendar.refetchEvents();
}

// Form submissions
$('#quickEventForm').on('submit', function(e) {
    e.preventDefault();
    
    $.ajax({
        url: 'api/create_quick_event.php',
        type: 'POST',
        data: $(this).serialize(),
        success: function(response) {
            if (response.success) {
                toastr.success('Event created successfully');
                $('#quickEventForm')[0].reset();
                calendar.refetchEvents();
                loadUpcomingEvents();
            } else {
                toastr.error(response.message);
            }
        },
        error: function() {
            toastr.error('Error creating event');
        }
    });
});

$('#editEventBtn').on('click', function() {
    const eventId = $(this).attr('data-event-id');
    
    $.ajax({
        url: 'api/fetch_event_details.php',
        type: 'GET',
        data: { id: eventId },
        success: function(response) {
            if (response.success) {
                const event = response.event;
                
                $('#edit_event_id').val(event.id);
                $('#editEventForm input[name="event_name"]').val(event.event_name);
                $('#editEventForm select[name="category"]').val(event.category);
                $('#editEventForm input[name="start_date"]').val(event.start_date);
                $('#editEventForm input[name="end_date"]').val(event.end_date);
                $('#editEventForm input[name="start_time"]').val(event.start_time);
                $('#editEventForm input[name="end_time"]').val(event.end_time);
                $('#editEventForm input[name="location"]').val(event.location);
                $('#editEventForm textarea[name="description"]').val(event.description);
                $('#editEventForm input[name="max_registrations"]').val(event.max_registrations);
                $('#editEventForm input[name="registration_fee"]').val(event.registration_fee);
                
                $('#eventModal').modal('hide');
                $('#editEventModal').modal('show');
            }
        }
    });
});

$('#editEventForm').on('submit', function(e) {
    e.preventDefault();
    
    $.ajax({
        url: 'api/update_event.php',
        type: 'POST',
        data: $(this).serialize(),
        success: function(response) {
            if (response.success) {
                toastr.success('Event updated successfully');
                $('#editEventModal').modal('hide');
                calendar.refetchEvents();
                loadUpcomingEvents();
            } else {
                toastr.error(response.message);
            }
        },
        error: function() {
            toastr.error('Error updating event');
        }
    });
});
</script>

<style>
.event-meeting { background-color: #007bff !important; }
.event-cultural { background-color: #28a745 !important; }
.event-social { background-color: #ffc107 !important; }
.event-fundraising { background-color: #dc3545 !important; }
.event-educational { background-color: #17a2b8 !important; }
</style>

<?php require_once 'templates/footer.php'; ?>
