<?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">Events Management</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 active">Events</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <!-- Info boxes -->
            <div class="row">
                <div class="col-12 col-sm-6 col-md-3">
                    <div class="info-box">
                        <span class="info-box-icon bg-info elevation-1"><i class="fas fa-calendar-alt"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Total Events</span>
                            <span class="info-box-number" id="totalEvents">0</span>
                        </div>
                    </div>
                </div>
                <div class="col-12 col-sm-6 col-md-3">
                    <div class="info-box mb-3">
                        <span class="info-box-icon bg-success elevation-1"><i class="fas fa-calendar-check"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Upcoming Events</span>
                            <span class="info-box-number" id="upcomingEvents">0</span>
                        </div>
                    </div>
                </div>
                <div class="col-12 col-sm-6 col-md-3">
                    <div class="info-box mb-3">
                        <span class="info-box-icon bg-warning elevation-1"><i class="fas fa-calendar-day"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Ongoing Events</span>
                            <span class="info-box-number" id="ongoingEvents">0</span>
                        </div>
                    </div>
                </div>
                <div class="col-12 col-sm-6 col-md-3">
                    <div class="info-box mb-3">
                        <span class="info-box-icon bg-danger elevation-1"><i class="fas fa-calendar-times"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Completed Events</span>
                            <span class="info-box-number" id="completedEvents">0</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Events Table -->
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">All Events</h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addEventModal">
                                    <i class="fas fa-plus"></i> Add Event
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <table id="eventsTable" class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th>Title</th>
                                        <th>Date</th>
                                        <th>Time</th>
                                        <th>Location</th>
                                        <th>Type</th>
                                        <th>Max Participants</th>
                                        <th>Registration Fee</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Data will be populated via AJAX -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- Add Event Modal -->
<div class="modal fade" id="addEventModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Add New Event</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form id="addEventForm">
                <div class="modal-body">
                    <div class="form-group">
                        <label>Event Title *</label>
                        <input type="text" class="form-control" name="event_title" required>
                    </div>
                    <div class="form-group">
                        <label>Event Description</label>
                        <textarea class="form-control" name="event_description" rows="3"></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Event Date *</label>
                                <input type="date" class="form-control" name="event_date" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Event Time</label>
                                <input type="time" class="form-control" name="event_time">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Location</label>
                                <input type="text" class="form-control" name="event_location">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Event Type *</label>
                                <select class="form-control" name="event_type" required>
                                    <option value="">Select Type</option>
                                    <option value="meeting">Meeting</option>
                                    <option value="cultural">Cultural</option>
                                    <option value="sports">Sports</option>
                                    <option value="educational">Educational</option>
                                    <option value="social">Social</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Max Participants</label>
                                <input type="number" class="form-control" name="max_participants">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Registration Fee (₹)</label>
                                <input type="number" step="0.01" class="form-control" name="registration_fee" value="0">
                            </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">Add Event</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Load event statistics
    loadEventStats();
    
    // Initialize DataTable
    const table = $('#eventsTable').DataTable({
        "processing": true,
        "serverSide": false,
        "ajax": {
            "url": "api/fetch_events.php",
            "dataSrc": function(json) {
                return json.success ? json.data : [];
            }
        },
        "columns": [
            { "data": "event_title" },
            { "data": "event_date" },
            { "data": "event_time" },
            { "data": "event_location" },
            { "data": "event_type" },
            { "data": "max_participants" },
            { "data": "registration_fee", "render": function(data) {
                return data ? `₹${parseFloat(data).toFixed(2)}` : '₹0.00';
            }},
            { "data": "status", "render": function(data) {
                const badges = {
                    'upcoming': 'info',
                    'ongoing': 'warning',
                    'completed': 'success',
                    'cancelled': 'danger'
                };
                return `<span class="badge badge-${badges[data] || 'secondary'}">${data}</span>`;
            }},
            { "data": null, "render": function(data) {
                return `
                    <button class="btn btn-sm btn-info" onclick="viewEvent(${data.id})">View</button>
                    <button class="btn btn-sm btn-warning" onclick="editEvent(${data.id})">Edit</button>
                    <button class="btn btn-sm btn-success" onclick="viewRegistrations(${data.id})">Registrations</button>
                `;
            }}
        ]
    });

    // Add event form submission
    $('#addEventForm').on('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        
        $.ajax({
            url: 'api/add_event.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    $('#addEventModal').modal('hide');
                    table.ajax.reload();
                    loadEventStats();
                    toastr.success('Event added successfully');
                } else {
                    toastr.error(response.message);
                }
            },
            error: function() {
                toastr.error('Error adding event');
            }
        });
    });
});

function loadEventStats() {
    $.get('api/fetch_event_stats.php', function(data) {
        if (data.success) {
            $('#totalEvents').text(data.data.total);
            $('#upcomingEvents').text(data.data.upcoming);
            $('#ongoingEvents').text(data.data.ongoing);
            $('#completedEvents').text(data.data.completed);
        }
    });
}

function viewEvent(id) {
    window.location.href = `event-details.php?id=${id}`;
}

function editEvent(id) {
    window.location.href = `edit-event.php?id=${id}`;
}

function viewRegistrations(id) {
    window.location.href = `event-registrations.php?id=${id}`;
}
</script>

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