<?php
require_once 'config/database.php';
require_once 'config/auth_enhanced.php';

requireAdmin();

// Check if event ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('Location: events.php');
    exit;
}

$eventId = (int)$_GET['id'];

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 Registrations</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">Registrations</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title" id="eventTitle">Loading Event...</h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-info" id="viewEventBtn">
                                    <i class="fas fa-eye"></i> View Event
                                </button>
                                <button type="button" class="btn btn-primary" id="addRegistrationBtn">
                                    <i class="fas fa-user-plus"></i> Add Registration
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <!-- Event registration stats -->
                            <div class="row" id="registrationStats">
                                <div class="col-md-3">
                                    <div class="info-box bg-info">
                                        <span class="info-box-icon"><i class="fas fa-users"></i></span>
                                        <div class="info-box-content">
                                            <span class="info-box-text">Total Registrations</span>
                                            <span class="info-box-number" id="totalRegistrations">0</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="info-box bg-success">
                                        <span class="info-box-icon"><i class="fas fa-check"></i></span>
                                        <div class="info-box-content">
                                            <span class="info-box-text">Confirmed</span>
                                            <span class="info-box-number" id="confirmedRegistrations">0</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="info-box bg-warning">
                                        <span class="info-box-icon"><i class="fas fa-clock"></i></span>
                                        <div class="info-box-content">
                                            <span class="info-box-text">Pending</span>
                                            <span class="info-box-number" id="pendingRegistrations">0</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="info-box bg-danger">
                                        <span class="info-box-icon"><i class="fas fa-times"></i></span>
                                        <div class="info-box-content">
                                            <span class="info-box-text">Cancelled</span>
                                            <span class="info-box-number" id="cancelledRegistrations">0</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Registrations table -->
                            <div class="table-responsive mt-4">
                                <table id="registrationsTable" class="table table-bordered table-striped">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Member</th>
                                            <th>KSO ID</th>
                                            <th>Contact</th>
                                            <th>Registration Date</th>
                                            <th>Payment Status</th>
                                            <th>Amount Paid</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- Data will be populated via AJAX -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- Add Registration Modal -->
<div class="modal fade" id="addRegistrationModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Add New Registration</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form id="addRegistrationForm">
                <input type="hidden" name="event_id" value="<?php echo $eventId; ?>">
                <div class="modal-body">
                    <div class="form-group">
                        <label>Member *</label>
                        <select class="form-control select2" name="member_id" id="memberSelect" style="width: 100%;" required>
                            <option value="">Select Member</option>
                            <!-- Options will be loaded via AJAX -->
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Payment Status</label>
                        <select class="form-control" name="payment_status">
                            <option value="pending">Pending</option>
                            <option value="completed">Completed</option>
                            <option value="waived">Fee Waived</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Amount Paid (₹)</label>
                        <input type="number" step="0.01" class="form-control" name="amount_paid" value="0">
                    </div>
                    <div class="form-group">
                        <label>Registration Status</label>
                        <select class="form-control" name="status">
                            <option value="confirmed">Confirmed</option>
                            <option value="pending">Pending</option>
                            <option value="cancelled">Cancelled</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Notes</label>
                        <textarea class="form-control" name="notes" rows="3"></textarea>
                    </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 Registration</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    const eventId = <?php echo $eventId; ?>;
    
    // Initialize select2
    $('.select2').select2({
        theme: 'bootstrap4'
    });
    
    // Load event details
    $.ajax({
        url: 'api/get_event.php',
        type: 'GET',
        data: { id: eventId },
        success: function(response) {
            if (response.success) {
                $('#eventTitle').text(`Registrations for: ${response.data.event_title}`);
            } else {
                toastr.error('Event not found');
            }
        }
    });
    
    // Load registration stats
    function loadRegistrationStats() {
        $.ajax({
            url: 'api/fetch_registration_stats.php',
            type: 'GET',
            data: { event_id: eventId },
            success: function(response) {
                if (response.success) {
                    $('#totalRegistrations').text(response.data.total || 0);
                    $('#confirmedRegistrations').text(response.data.confirmed || 0);
                    $('#pendingRegistrations').text(response.data.pending || 0);
                    $('#cancelledRegistrations').text(response.data.cancelled || 0);
                }
            }
        });
    }
    
    // Load registration stats initially
    loadRegistrationStats();
    
    // Initialize DataTable
    const table = $('#registrationsTable').DataTable({
        "processing": true,
        "serverSide": false,
        "ajax": {
            "url": "api/fetch_event_registrations.php",
            "data": function(d) {
                d.event_id = eventId;
                return d;
            },
            "dataSrc": function(json) {
                return json.success ? json.data : [];
            }
        },
        "columns": [
            { "data": "id" },
            { "data": null, "render": function(data) {
                return `${data.first_name} ${data.last_name}`;
            }},
            { "data": "kso_id" },
            { "data": null, "render": function(data) {
                return `${data.email}<br>${data.phone}`;
            }},
            { "data": "registration_date" },
            { "data": "payment_status", "render": function(data) {
                const badges = {
                    'pending': 'warning',
                    'completed': 'success',
                    'waived': 'info',
                    'failed': 'danger'
                };
                return `<span class="badge badge-${badges[data] || 'secondary'}">${data}</span>`;
            }},
            { "data": "amount_paid", "render": function(data) {
                return `₹${parseFloat(data).toFixed(2)}`;
            }},
            { "data": "status", "render": function(data) {
                const badges = {
                    'confirmed': 'success',
                    'pending': 'warning',
                    '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="viewRegistration(${data.id})">View</button>
                    <button class="btn btn-sm btn-warning" onclick="editRegistration(${data.id})">Edit</button>
                    <button class="btn btn-sm btn-danger" onclick="deleteRegistration(${data.id})">Delete</button>
                `;
            }}
        ]
    });
    
    // Setup buttons
    $('#viewEventBtn').click(function() {
        window.location.href = 'event-details.php?id=' + eventId;
    });
    
    $('#addRegistrationBtn').click(function() {
        // Load members for select dropdown
        $.ajax({
            url: 'api/fetch_members.php',
            type: 'GET',
            success: function(response) {
                if (response.success) {
                    const members = response.data;
                    let options = '<option value="">Select Member</option>';
                    
                    members.forEach(function(member) {
                        options += `<option value="${member.id}">${member.first_name} ${member.last_name} (${member.kso_id})</option>`;
                    });
                    
                    $('#memberSelect').html(options);
                    $('#memberSelect').trigger('change');
                    
                    // Show modal
                    $('#addRegistrationModal').modal('show');
                } else {
                    toastr.error('Failed to load members');
                }
            },
            error: function() {
                toastr.error('Error loading members');
            }
        });
    });
    
    // Handle registration form submission
    $('#addRegistrationForm').on('submit', function(e) {
        e.preventDefault();
        
        const formData = $(this).serialize();
        
        $.ajax({
            url: 'api/add_event_registration.php',
            type: 'POST',
            data: formData,
            success: function(response) {
                if (response.success) {
                    $('#addRegistrationModal').modal('hide');
                    table.ajax.reload();
                    loadRegistrationStats();
                    toastr.success('Registration added successfully');
                } else {
                    toastr.error(response.message || 'Failed to add registration');
                }
            },
            error: function() {
                toastr.error('Error adding registration');
            }
        });
    });
});

// View registration details
function viewRegistration(id) {
    // Implementation will depend on your needs
    toastr.info('Viewing registration ID: ' + id);
}

// Edit registration
function editRegistration(id) {
    // Implementation will depend on your needs
    toastr.info('Editing registration ID: ' + id);
}

// Delete registration
function deleteRegistration(id) {
    if (confirm('Are you sure you want to delete this registration?')) {
        $.ajax({
            url: 'api/delete_event_registration.php',
            type: 'POST',
            data: { id: id },
            success: function(response) {
                if (response.success) {
                    $('#registrationsTable').DataTable().ajax.reload();
                    loadRegistrationStats();
                    toastr.success('Registration deleted successfully');
                } else {
                    toastr.error(response.message || 'Failed to delete registration');
                }
            },
            error: function() {
                toastr.error('Error deleting registration');
            }
        });
    }
}

// Refresh registration stats (called after CRUD operations)
function loadRegistrationStats() {
    const eventId = <?php echo $eventId; ?>;
    
    $.ajax({
        url: 'api/fetch_registration_stats.php',
        type: 'GET',
        data: { event_id: eventId },
        success: function(response) {
            if (response.success) {
                $('#totalRegistrations').text(response.data.total || 0);
                $('#confirmedRegistrations').text(response.data.confirmed || 0);
                $('#pendingRegistrations').text(response.data.pending || 0);
                $('#cancelledRegistrations').text(response.data.cancelled || 0);
            }
        }
    });
}
</script>

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