@extends('front_end.layouts.home')

@php
$showRightSidebar = false;
@endphp
@section('title', 'Blood Drives')

@section('left_sidebar')
@include('front_end.pages.bloodbank.bloodbank_left_sidebar')
@endsection

@section('content')
<div class="bg-white shadow-sm border-0 rounded-3">
    <!-- Header -->
    <div class="card border-0 mb-4">
        <div class="card-body p-0">
            <div class="row g-0">
                <div class="col-12">
                    <div class="bg-primary text-white p-4 rounded-top-3">
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-flex align-items-center">
                                <a href="{{ route('bloodbank.index') }}" class="text-white me-3">
                                    <i class="fas fa-arrow-left fa-lg"></i>
                                </a>
                                <div>
                                    <h4 class="mb-0 text-white">Blood Drives</h4>
                                    <p class="mb-0 text-white">Find and register for upcoming blood donation events</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <!-- Filter Section -->
        <div class="card border-0 shadow-sm rounded-3 mb-4">
            <div class="card-header bg-transparent">
                <h5 class="mb-0">Search & Filter</h5>
            </div>
            <div class="card-body">
                <form id="filterForm">
                    <div class="row g-3">
                        <div class="col-sm-6 col-md-4">
                            <label for="dateFilter" class="form-label">Date Range</label>
                            <select id="dateFilter" class="form-select">
                                <option value="upcoming">Upcoming Drives</option>
                                <option value="this-week">This Week</option>
                                <option value="this-month">This Month</option>
                                <option value="next-month">Next Month</option>
                                <option value="all">All Drives (Including Past)</option>
                            </select>
                        </div>
                        @if(Auth::check() && Auth::user()->latitude && Auth::user()->longitude)
                        <div class="col-sm-6 col-md-4">
                            <label for="distanceFilter" class="form-label">Distance (km)</label>
                            <select id="distanceFilter" class="form-select">
                                <option value="">Any Distance</option>
                                <option value="5">Within 5 km</option>
                                <option value="10">Within 10 km</option>
                                <option value="25">Within 25 km</option>
                                <option value="50">Within 50 km</option>
                            </select>
                        </div>
                        @endif
                        <div class="col-sm-6 col-md-4">
                            <label for="locationSearch" class="form-label">Location</label>
                            <input type="text" class="form-control" id="locationSearch" placeholder="Search by location">
                        </div>
                        <div class="col-12">
                            <button type="submit" class="btn btn-primary mt-1">
                                <i class="fas fa-filter me-2"></i>Apply Filters
                            </button>
                            <button type="button" id="clearFilters" class="btn btn-outline-secondary mt-1 ms-2">
                                <i class="fas fa-times me-2"></i>Clear Filters
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- Calendar View Toggle -->
        <div class="d-flex justify-content-end mb-3">
            <div class="btn-group" role="group">
                <button type="button" class="btn btn-outline-primary active" id="gridViewBtn">
                    <i class="fas fa-th-large me-2"></i>Grid View
                </button>
                <button type="button" class="btn btn-outline-primary" id="calendarViewBtn">
                    <i class="fas fa-calendar-alt me-2"></i>Calendar View
                </button>
            </div>
        </div>

        <!-- Grid View (Default) -->
        <div id="gridView">
            <div class="row g-3" id="drivesGrid">
                <div class="col-12 text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2 text-muted">Loading blood drives...</p>
                </div>
            </div>
        </div>

        <!-- Calendar View (Hidden by default) -->
        <div id="calendarView" class="card border-0 shadow-sm rounded-3 mb-4" style="display: none;">
            <div class="card-body">
                <div id="bloodDrivesCalendar"></div>
            </div>
        </div>

        <!-- Pagination -->
        <nav aria-label="Blood drives navigation" class="mb-4">
            <ul class="pagination justify-content-center" id="paginationContainer">
                <!-- Pagination will be inserted here via JavaScript -->
            </ul>
        </nav>

        <!-- Your Registrations (For authenticated users) -->
        @auth
        <div class="card border-0 shadow-sm rounded-3 mb-4">
            <div class="card-header bg-transparent">
                <h5 class="mb-0">Your Registrations</h5>
            </div>
            <div class="card-body p-0" id="userRegistrations">
                <div class="text-center py-4">
                    <div class="spinner-border spinner-border-sm text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <span class="ms-2">Loading your registrations...</span>
                </div>
            </div>
        </div>
        @endauth
    </div>
</div>

<!-- Registration Modal -->
<div class="modal fade" id="registrationModal" tabindex="-1" aria-labelledby="registrationModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="registrationModalLabel">Register for Blood Drive</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="card bg-light mb-3">
                    <div class="card-body" id="driveDetails">
                        <h6 class="card-title" id="driveTitle">Blood Drive Title</h6>
                        <div class="text-muted small mb-3" id="driveDateTime">
                            <i class="fas fa-calendar-alt me-2"></i><span id="driveDate">February 15, 2025</span>
                            <i class="fas fa-clock ms-3 me-2"></i><span id="driveTime">9:00 AM - 4:00 PM</span>
                        </div>
                        <p class="small mb-1"><i class="fas fa-map-marker-alt me-2"></i><span id="driveLocation">Location</span></p>
                        <p class="small mb-0"><i class="fas fa-user-friends me-2"></i><span id="driveRegistrations">0</span> people registered</p>
                    </div>
                </div>
                
                <input type="hidden" id="driveId" value="">
                
                @auth
                <form id="registrationForm">
                    <div class="mb-3">
                        <label for="regName" class="form-label">Full Name</label>
                        <input type="text" class="form-control" id="regName" value="{{ Auth::user()->name }}" required>
                    </div>
                    <div class="mb-3">
                        <label for="regEmail" class="form-label">Email</label>
                        <input type="email" class="form-control" id="regEmail" value="{{ Auth::user()->email }}" required>
                    </div>
                    <div class="mb-3">
                        <label for="regPhone" class="form-label">Phone Number</label>
                        <input type="tel" class="form-control" id="regPhone" value="{{ Auth::user()->phone }}" required>
                    </div>
                    <div class="mb-3">
                        <label for="regBloodType" class="form-label">Blood Type</label>
                        <select class="form-select" id="regBloodType" required>
                            <option value="">Select Blood Type</option>
                            <option value="A+" {{ Auth::user()->blood_type == 'A+' ? 'selected' : '' }}>A+</option>
                            <option value="A-" {{ Auth::user()->blood_type == 'A-' ? 'selected' : '' }}>A-</option>
                            <option value="B+" {{ Auth::user()->blood_type == 'B+' ? 'selected' : '' }}>B+</option>
                            <option value="B-" {{ Auth::user()->blood_type == 'B-' ? 'selected' : '' }}>B-</option>
                            <option value="AB+" {{ Auth::user()->blood_type == 'AB+' ? 'selected' : '' }}>AB+</option>
                            <option value="AB-" {{ Auth::user()->blood_type == 'AB-' ? 'selected' : '' }}>AB-</option>
                            <option value="O+" {{ Auth::user()->blood_type == 'O+' ? 'selected' : '' }}>O+</option>
                            <option value="O-" {{ Auth::user()->blood_type == 'O-' ? 'selected' : '' }}>O-</option>
                        </select>
                    </div>
                    
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="regTerms" required>
                        <label class="form-check-label" for="regTerms">
                            I confirm that I am at least 17 years old, weigh at least 50kg, and am in good health.
                        </label>
                    </div>
                </form>
                @else
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i>
                    <strong>Login Required</strong>
                    <p class="mb-0 small">Please log in to register for this blood drive.</p>
                </div>
                @endauth
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                @auth
                <button type="button" id="submitRegistration" class="btn btn-primary">Register</button>
                @else
                <a href="{{ route('login') }}?redirect={{ urlencode(route('bloodbank.drives')) }}" class="btn btn-primary">Login to Register</a>
                @endauth
            </div>
        </div>
    </div>
</div>

<!-- Cancellation Modal -->
<div class="modal fade" id="cancellationModal" tabindex="-1" aria-labelledby="cancellationModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="cancellationModalLabel">Cancel Registration</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>Are you sure you want to cancel your registration?</strong>
                </div>
                <p>Your spot will be made available to other potential donors.</p>
                <div class="card bg-light" id="cancelDriveDetails">
                    <div class="card-body">
                        <h6 class="card-title" id="cancelDriveTitle">Blood Drive Title</h6>
                        <p class="small mb-0"><i class="fas fa-calendar-alt me-2"></i><span id="cancelDriveDate">February 15, 2025</span></p>
                    </div>
                </div>
                <input type="hidden" id="cancelDriveId" value="">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Keep Registration</button>
                <button type="button" id="confirmCancellation" class="btn btn-danger">Cancel Registration</button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('extra-js')
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@5.10.0/main.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/fullcalendar@5.10.0/main.min.css" rel="stylesheet">

<script>
    $(document).ready(function() {
        // Define global variables
        const isAuthenticated = {{ Auth::check() ? 'true' : 'false' }};
        let currentPage = 1;
        let currentFilters = {};
        let calendar;
        let allDrives = [];
        
        // Load blood drives on page load
        loadBloodDrives();
        
        // Event listeners
        $('#filterForm').on('submit', function(e) {
            e.preventDefault();
            currentPage = 1;
            loadBloodDrives();
        });
        
        $('#clearFilters').on('click', function() {
            $('#filterForm')[0].reset();
            currentPage = 1;
            loadBloodDrives();
        });
        
        // View toggles
        $('#gridViewBtn').on('click', function() {
            $(this).addClass('active');
            $('#calendarViewBtn').removeClass('active');
            $('#gridView').show();
            $('#calendarView').hide();
        });
        
        $('#calendarViewBtn').on('click', function() {
            $(this).addClass('active');
            $('#gridViewBtn').removeClass('active');
            $('#gridView').hide();
            $('#calendarView').show();
            initCalendar();
        });
        
        // Registration modal handlers
        $('#submitRegistration').on('click', submitRegistration);
        $('#confirmCancellation').on('click', confirmCancellation);
        
        // Function to load blood drives
        function loadBloodDrives() {
            // Get filter values
            currentFilters = {
                include_past: $('#dateFilter').val() === 'all' ? true : false,
                distance: $('#distanceFilter').val(),
                location: $('#locationSearch').val(),
                page: currentPage
            };
            
            // Date range filters
            if ($('#dateFilter').val() === 'this-week') {
                currentFilters.start_date = moment().startOf('week').format('YYYY-MM-DD');
                currentFilters.end_date = moment().endOf('week').format('YYYY-MM-DD');
            } else if ($('#dateFilter').val() === 'this-month') {
                currentFilters.start_date = moment().startOf('month').format('YYYY-MM-DD');
                currentFilters.end_date = moment().endOf('month').format('YYYY-MM-DD');
            } else if ($('#dateFilter').val() === 'next-month') {
                currentFilters.start_date = moment().add(1, 'month').startOf('month').format('YYYY-MM-DD');
                currentFilters.end_date = moment().add(1, 'month').endOf('month').format('YYYY-MM-DD');
            }
            
            // Show loading state
            $('#drivesGrid').html(`
                <div class="col-12 text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2 text-muted">Loading blood drives...</p>
                </div>
            `);
            
            // Fetch drives from API
            const queryParams = new URLSearchParams(currentFilters).toString();
            axios.get(`${base_url}/webapi/bloodbank/drives?${queryParams}`)
                .then(response => {
                    if (response.data.code === 200) {
                        const { data, meta } = response.data;
                        allDrives = data;
                        displayDrives(data);
                        displayPagination(meta);
                        
                        // Load calendar if in calendar view
                        if ($('#calendarView').is(':visible')) {
                            initCalendar();
                        }
                        
                        // Load user registrations if authenticated
                        if (isAuthenticated) {
                            loadUserRegistrations();
                        }
                    }
                })
                .catch(error => {
                    console.error('Error loading blood drives:', error);
                    $('#drivesGrid').html(`
                        <div class="col-12">
                            <div class="alert alert-danger">
                                <i class="fas fa-exclamation-circle me-2"></i>
                                Error loading blood drives. Please try again later.
                            </div>
                        </div>
                    `);
                });
        }
        
        // Display blood drives in grid view
        function displayDrives(drives) {
            const container = $('#drivesGrid');
            container.empty();
            
            if (drives.length === 0) {
                container.html(`
                    <div class="col-12 text-center py-5">
                        <div class="icon-lg">
                            <i class="fas fa-calendar-times text-muted fa-3x mb-3"></i>
                        </div>
                        <h5 class="text-muted">No blood drives found</h5>
                        <p class="text-muted small">Try adjusting your filters or check back later</p>
                    </div>
                `);
                return;
            }
            
            drives.forEach(drive => {
                const startDate = moment(drive.start_datetime).format('dddd, MMMM D, YYYY');
                const startTime = moment(drive.start_datetime).format('h:mm A');
                const endTime = moment(drive.end_datetime).format('h:mm A');
                const isPast = moment(drive.end_datetime).isBefore(moment());
                const isFull = drive.is_full;
                
                const isRegistered = drive.is_registered === true;
                
                let actionButton = '';
                
                if (isPast) {
                    actionButton = `<button class="btn btn-secondary disabled w-100">Ended</button>`;
                } else if (isFull && !isRegistered) {
                    actionButton = `<button class="btn btn-secondary disabled w-100">Full</button>`;
                } else if (isRegistered) {
                    actionButton = `
                        <button class="btn btn-danger cancel-registration w-100" data-id="${drive.id}">
                            <i class="fas fa-times-circle me-2"></i>Cancel Registration
                        </button>
                    `;
                } else {
                    actionButton = `
                        <button class="btn btn-primary register-drive w-100" data-id="${drive.id}">
                            <i class="fas fa-user-plus me-2"></i>Register
                        </button>
                    `;
                }
                
                container.append(`
                    <div class="col-md-6 col-lg-4">
                        <div class="card h-100 border-0 shadow-sm rounded-3">
                            <div class="card-header bg-light text-center py-3">
                                <h5 class="mb-0">${drive.title}</h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <div class="d-flex align-items-center mb-2">
                                        <i class="fas fa-calendar-alt text-primary me-3 fa-lg"></i>
                                        <div>
                                            <p class="mb-0 fw-bold">${startDate}</p>
                                            <p class="mb-0 small text-muted">${startTime} - ${endTime}</p>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-center mb-2">
                                        <i class="fas fa-map-marker-alt text-danger me-3 fa-lg"></i>
                                        <div>
                                            <p class="mb-0">${drive.location}</p>
                                            ${drive.distance ? `<p class="mb-0 small text-muted">${drive.distance.toFixed(1)} km away</p>` : ''}
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-center">
                                        <i class="fas fa-user-friends text-success me-3 fa-lg"></i>
                                        <div>
                                            <p class="mb-0">${drive.registrations_count} / ${drive.capacity} registered</p>
                                            <div class="progress mt-1" style="height: 6px;">
                                                <div class="progress-bar ${isFull ? 'bg-danger' : 'bg-success'}" role="progressbar" 
                                                    style="width: ${(drive.registrations_count / drive.capacity) * 100}%"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                ${drive.description ? `
                                <div class="mb-3">
                                    <p class="small text-muted">${drive.description}</p>
                                </div>
                                ` : ''}
                                
                                <div class="d-flex gap-2">
                                    <a href="${base_url}/bloodbank/drives/${drive.id}" class="btn btn-outline-primary w-100">
                                        <i class="fas fa-info-circle me-2"></i>Details
                                    </a>
                                    ${actionButton}
                                </div>
                            </div>
                            ${isRegistered ? `
                            <div class="card-footer bg-success bg-opacity-10 text-success text-center py-2">
                                <small><i class="fas fa-check-circle me-2"></i>You're registered for this drive</small>
                            </div>
                            ` : ''}
                        </div>
                    </div>
                `);
            });
            
            // Add event listeners
            $('.register-drive').on('click', function() {
                const driveId = $(this).data('id');
                openRegistrationModal(driveId);
            });
            
            $('.cancel-registration').on('click', function() {
                const driveId = $(this).data('id');
                openCancellationModal(driveId);
            });
        }
        
        // Display pagination
        function displayPagination(meta) {
            const container = $('#paginationContainer');
            container.empty();
            
            if (meta.last_page <= 1) {
                return;
            }
            
            // Previous page button
            const prevDisabled = meta.current_page === 1 ? 'disabled' : '';
            container.append(`
                <li class="page-item ${prevDisabled}">
                    <a class="page-link" href="#" data-page="${meta.current_page - 1}" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
            `);
            
            // Page numbers
            const startPage = Math.max(1, meta.current_page - 2);
            const endPage = Math.min(meta.last_page, meta.current_page + 2);
            
            for (let i = startPage; i <= endPage; i++) {
                const active = i === meta.current_page ? 'active' : '';
                container.append(`
                    <li class="page-item ${active}">
                        <a class="page-link" href="#" data-page="${i}">${i}</a>
                    </li>
                `);
            }
            
            // Next page button
            const nextDisabled = meta.current_page === meta.last_page ? 'disabled' : '';
            container.append(`
                <li class="page-item ${nextDisabled}">
                    <a class="page-link" href="#" data-page="${meta.current_page + 1}" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            `);
            
            // Add event listener to pagination links
            $('.page-link').on('click', function(e) {
                e.preventDefault();
                if (!$(this).parent().hasClass('disabled')) {
                    currentPage = $(this).data('page');
                    loadBloodDrives();
                    // Scroll to top of drives
                    $('html, body').animate({
                        scrollTop: $('#drivesGrid').offset().top - 120
                    }, 300);
                }
            });
        }
        
        // Initialize calendar view
        function initCalendar() {
            if (calendar) {
                calendar.removeAllEvents();
                
                // Add blood drives as events
                const events = allDrives.map(drive => ({
                    id: drive.id,
                    title: drive.title,
                    start: drive.start_datetime,
                    end: drive.end_datetime,
                    extendedProps: {
                        location: drive.location,
                        registrations: drive.registrations_count,
                        capacity: drive.capacity,
                        is_full: drive.is_full,
                        is_registered: drive.is_registered
                    },
                    color: drive.is_registered ? '#28a745' : 
                          drive.is_full ? '#dc3545' : '#0d6efd'
                }));
                
                calendar.addEventSource(events);
                calendar.render();
                return;
            }
            
            const calendarEl = document.getElementById('bloodDrivesCalendar');
            calendar = new FullCalendar.Calendar(calendarEl, {
                initialView: 'dayGridMonth',
                headerToolbar: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'dayGridMonth,timeGridWeek,listMonth'
                },
                events: allDrives.map(drive => ({
                    id: drive.id,
                    title: drive.title,
                    start: drive.start_datetime,
                    end: drive.end_datetime,
                    extendedProps: {
                        location: drive.location,
                        registrations: drive.registrations_count,
                        capacity: drive.capacity,
                        is_full: drive.is_full,
                        is_registered: drive.is_registered
                    },
                    color: drive.is_registered ? '#28a745' : 
                           drive.is_full ? '#dc3545' : '#0d6efd'
                })),
                eventClick: function(info) {
                    const drive = allDrives.find(d => d.id == info.event.id);
                    if (drive) {
                        if (drive.is_registered) {
                            openCancellationModal(drive.id);
                        } else if (!drive.is_full) {
                            openRegistrationModal(drive.id);
                        } else {
                            window.location.href = `${base_url}/bloodbank/drives/${drive.id}`;
                        }
                    }
                },
                eventDidMount: function(info) {
                    $(info.el).tooltip({
                        title: `${info.event.title}\n${info.event.extendedProps.location}\n${info.event.extendedProps.registrations}/${info.event.extendedProps.capacity} registered`,
                        placement: 'top',
                        trigger: 'hover',
                        html: true
                    });
                }
            });
            
            calendar.render();
        }
        
        // Load user registrations
        function loadUserRegistrations() {
            if (!isAuthenticated) return;
            
            $('#userRegistrations').html(`
                <div class="text-center py-4">
                    <div class="spinner-border spinner-border-sm text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <span class="ms-2">Loading your registrations...</span>
                </div>
            `);
            
            axios.get(`${base_url}/webapi/bloodbank/drives/registrations`)
                .then(response => {
                    if (response.data.code === 200) {
                        const registrations = response.data.data;
                        displayUserRegistrations(registrations);
                    }
                })
                .catch(error => {
                    console.error('Error loading user registrations:', error);
                    $('#userRegistrations').html(`
                        <div class="alert alert-danger m-3">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            Error loading your registrations. Please try again later.
                        </div>
                    `);
                });
        }
        
        // Display user registrations
        function displayUserRegistrations(registrations) {
            const container = $('#userRegistrations');
            
            if (registrations.length === 0) {
                container.html(`
                    <div class="text-center py-4">
                        <p class="text-muted mb-0">You have no active registrations</p>
                        <small class="text-muted">Register for a blood drive above</small>
                    </div>
                `);
                return;
            }
            
            let html = `
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Blood Drive</th>
                                <th>Date</th>
                                <th>Time</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
            `;
            
            registrations.forEach(reg => {
                
                const startDate = moment(reg.blood_drive.start_datetime).format('MMM D, YYYY');
                const startTime = moment(reg.blood_drive.start_datetime).format('h:mm A');
                const endTime = moment(reg.blood_drive.end_datetime).format('h:mm A');
                const isPast = moment(reg.blood_drive.end_datetime).isBefore(moment());
                
                html += `
                    <tr>
                        <td>
                            <a href="${base_url}/bloodbank/drives/${reg.blood_drive_id}" class="text-decoration-none">
                                ${reg.blood_drive.title}
                            </a>
                        </td>
                        <td>${startDate}</td>
                        <td>${startTime} - ${endTime}</td>
                        <td>
                            <span class="badge bg-${reg.status === 'registered' ? 'success' : 'danger'}">
                                ${reg.status === 'registered' ? 'Registered' : 'Cancelled'}
                            </span>
                        </td>
                        <td>
                `;
                
                if (reg.status === 'registered' && !isPast) {
                    html += `
                        <button class="btn btn-sm btn-outline-danger cancel-registration" data-id="${reg.blood_drive_id}">
                            <i class="fas fa-times-circle"></i> Cancel
                        </button>
                    `;
                } else if (isPast && reg.status === 'registered') {
                    html += `
                        <span class="badge bg-secondary">Completed</span>
                    `;
                } else {
                    html += `
                        <span class="badge bg-secondary">Cancelled</span>
                    `;
                }
                
                html += `
                        </td>
                    </tr>
                `;
            });
            
            html += `
                        </tbody>
                    </table>
                </div>
            `;
            
            container.html(html);
            
            // Add event listeners
            $('.cancel-registration').on('click', function() {
                const driveId = $(this).data('id');
                openCancellationModal(driveId);
            });
        }
        
        // Open registration modal
        function openRegistrationModal(driveId) {
            if (!isAuthenticated) {
                showLoginPrompt();
                return;
            }
            
            const drive = allDrives.find(d => d.id == driveId);
            if (!drive) return;
            
            const startDate = moment(drive.start_datetime).format('dddd, MMMM D, YYYY');
            const startTime = moment(drive.start_datetime).format('h:mm A');
            const endTime = moment(drive.end_datetime).format('h:mm A');
            
            $('#driveId').val(driveId);
            $('#driveTitle').text(drive.title);
            $('#driveDate').text(startDate);
            $('#driveTime').text(`${startTime} - ${endTime}`);
            $('#driveLocation').text(drive.location);
            $('#driveRegistrations').text(drive.registrations_count);
            
            $('#registrationModal').modal('show');
        }
        
        // Submit registration
        function submitRegistration() {
            const driveId = $('#driveId').val();
            
            if (!$('#regTerms').is(':checked')) {
                showError('Please accept the terms and conditions');
                return;
            }
            
            // Show loading state
            const submitBtn = $('#submitRegistration');
            const originalText = submitBtn.html();
            submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Registering...').prop('disabled', true);
            
            // Submit registration
            axios.post(`${base_url}/webapi/bloodbank/drives/${driveId}/register`)
                .then(response => {
                    if (response.data.code === 201) {
                        showSuccess('Registration successful');
                        $('#registrationModal').modal('hide');
                        
                        // Reload drives after a brief delay
                        setTimeout(() => {
                            loadBloodDrives();
                        }, 1000);
                    }
                })
                .catch(error => {
                    console.error('Error submitting registration:', error);
                    showError(error.response?.data?.message || 'Error registering for blood drive. Please try again.');
                })
                .finally(() => {
                    submitBtn.html(originalText).prop('disabled', false);
                });
        }
        
        // Open cancellation modal
        function openCancellationModal(driveId) {
            const drive = allDrives.find(d => d.id == driveId);
            if (!drive) return;
            
            const startDate = moment(drive.start_datetime).format('dddd, MMMM D, YYYY');
            
            $('#cancelDriveId').val(driveId);
            $('#cancelDriveTitle').text(drive.title);
            $('#cancelDriveDate').text(startDate);
            
            $('#cancellationModal').modal('show');
        }
        
        // Confirm cancellation
        function confirmCancellation() {
            const driveId = $('#cancelDriveId').val();
            
            // Show loading state
            const submitBtn = $('#confirmCancellation');
            const originalText = submitBtn.html();
            submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Cancelling...').prop('disabled', true);
            
            // Submit cancellation
            axios.post(`${base_url}/webapi/bloodbank/drives/${driveId}/cancel-registration`)
                .then(response => {
                    if (response.data.code === 200) {
                        showSuccess('Registration cancelled successfully');
                        $('#cancellationModal').modal('hide');
                        
                        // Reload drives after a brief delay
                        setTimeout(() => {
                            loadBloodDrives();
                        }, 1000);
                    }
                })
                .catch(error => {
                    console.error('Error cancelling registration:', error);
                    showError(error.response?.data?.message || 'Error cancelling registration. Please try again.');
                })
                .finally(() => {
                    submitBtn.html(originalText).prop('disabled', false);
                });
        }
        
        // Utility Functions
        function showLoginPrompt() {
            myAlert.fire({
                title: 'Login Required',
                text: 'Please login to perform this action',
                icon: 'info',
                showCancelButton: true,
                confirmButtonText: 'Login',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = `${base_url}/login?redirect=${encodeURIComponent(window.location.href)}`;
                }
            });
        }
        
        function showSuccess(message) {
            myAlert.fire({
                icon: 'success',
                title: 'Success',
                text: message
            });
        }
        
        function showError(message) {
            myAlert.fire({
                icon: 'error',
                title: 'Error',
                text: message
            });
        }
    });
</script>
@endsection