
<meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
<!-- In your <head> section -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet">

<!-- Before closing </body> tag -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script>
    toastr.options = {
        "closeButton": true,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "preventDuplicates": false,
        "showDuration": "300",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };
</script>
<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <h2 class="mb-0">Class Management</h2>
                <button class="btn btn-primary" id="addClassBtn">
                    <i class="fas fa-plus me-2"></i>Add New Class
                </button>
            </div>
        </div>
    </div>

    <!-- Filter Section -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card shadow-sm">
                <div class="card-body">
                    <div class="row g-3">
                        <div class="col-md-3">
                            <label for="statusFilter" class="form-label">Status</label>
                            <select id="statusFilter" class="form-select">
                                <option value="">All Statuses</option>
                                <option value="active">Active</option>
                                <option value="cancelled">Cancelled</option>
                                <option value="completed">Completed</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="trainerFilter" class="form-label">Trainer</label>
                            <select id="trainerFilter" class="form-select">
                                <option value="">All Trainers</option>
                                <!-- Will be populated via JS -->
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="dateFrom" class="form-label">From Date</label>
                            <input type="date" class="form-control" id="dateFrom">
                        </div>
                        <div class="col-md-3">
                            <label for="dateTo" class="form-label">To Date</label>
                            <input type="date" class="form-control" id="dateTo">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Classes Grid -->
    <div class="row" id="classesGrid">
        <!-- Classes will be loaded here via AJAX -->
        <div class="col-12 text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
        </div>
    </div>
</div>

<!-- Class Modal (for create/edit) -->
<div class="modal fade" id="classModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">Add New Class</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="classForm">
                <div class="modal-body">
                    <input type="hidden" id="classId">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label for="className" class="form-label">Class Name *</label>
                            <input type="text" class="form-control" id="className" required>
                        </div>
                        <div class="col-md-6">
                            <label for="trainerId" class="form-label">Trainer *</label>
                            <select class="form-select" id="trainerId" required>
                                <option value="">Select Trainer</option>
                                <!-- Will be populated via JS -->
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="classDate" class="form-label">Date *</label>
                            <input type="date" class="form-control" id="classDate" required>
                        </div>
                        <div class="col-md-6">
                            <label for="classTime" class="form-label">Time *</label>
                            <input type="time" class="form-control" id="classTime" required>
                        </div>
                        <div class="col-md-6">
                            <label for="duration" class="form-label">Duration (minutes) *</label>
                            <input type="number" class="form-control" id="duration" min="15" value="60" required>
                        </div>
                        <div class="col-md-6">
                            <label for="maxCapacity" class="form-label">Max Capacity *</label>
                            <input type="number" class="form-control" id="maxCapacity" min="1" value="20" required>
                        </div>
                        <div class="col-12">
                            <label for="description" class="form-label">Description</label>
                            <textarea class="form-control" id="description" rows="3"></textarea>
                        </div>
                        <div class="col-md-6">
                            <label for="status" class="form-label">Status</label>
                            <select class="form-select" id="status">
                                <option value="active">Active</option>
                                <option value="cancelled">Cancelled</option>
                                <option value="completed">Completed</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary" id="saveClassBtn">Save Class</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- View Class Modal -->
<div class="modal fade" id="viewClassModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Class Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="classDetailsContent">
                <!-- Content will be loaded via AJAX -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteClassModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">Confirm Deletion</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete this class? This action cannot be undone.</p>
                <input type="hidden" id="deleteClassId">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">Delete Class</button>
            </div>
        </div>
    </div>
</div>



<script>
    $.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
$(document).ready(function() {
    // Initialize Toastr if not already available
    if (typeof toastr === 'undefined') {
        console.warn('Toastr not loaded - loading now');
        loadToastr().then(initializeApp).catch(handleInitError);
    } else {
        initializeApp();
    }

    function loadToastr() {
        return new Promise((resolve, reject) => {
            const toastrCSS = document.createElement('link');
            toastrCSS.rel = 'stylesheet';
            toastrCSS.href = 'https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css';
            
            const toastrJS = document.createElement('script');
            toastrJS.src = 'https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js';
            toastrJS.onload = resolve;
            toastrJS.onerror = reject;
            
            document.head.appendChild(toastrCSS);
            document.body.appendChild(toastrJS);
        });
    }

    function handleInitError(error) {
        console.error('Initialization failed:', error);
        // Fallback to console logging if toastr fails
        window.showToast = function(type, message) {
            console.log(`${type.toUpperCase()}: ${message}`);
        };
    }

    function initializeApp() {
        // Initialize variables
        let classes = [];
        let trainers = [];
        let trainersCache = null;

        // Initialize modals
        const classModal = new bootstrap.Modal(document.getElementById('classModal'));
        const viewClassModal = new bootstrap.Modal(document.getElementById('viewClassModal'));
        const deleteClassModal = new bootstrap.Modal(document.getElementById('deleteClassModal'));

        // Event listeners
        $('#addClassBtn').click(showAddClassModal);
        $('#classForm').submit(handleClassFormSubmit);
        $('#confirmDeleteBtn').click(deleteClass);
        
        // Filter events
        $('#statusFilter, #trainerFilter, #dateFrom, #dateTo').change(applyFilters);
        
        // Load initial data
        loadInitialData();

        function loadInitialData() {
            showLoading('#classesGrid');
            
            // Load trainers first, then classes
            loadTrainers()
                .then(loadClasses)
                .catch(error => {
                    console.error('Initialization error:', error);
                    showToast('error', 'Failed to load initial data');
                    loadClasses(); // Try to load classes even if trainers failed
                });
        }

        function showToast(type, message) {
            if (typeof toastr !== 'undefined') {
                toastr[type](message);
            } else {
                console.log(`${type.toUpperCase()}: ${message}`);
            }
        }

        function showLoading(selector) {
            $(selector).addClass('loading-state').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">Loading data...</p>
                </div>
            `);
        }

        function hideLoading(selector) {
            $(selector).removeClass('loading-state');
        }

        function loadTrainers() {
            return new Promise((resolve, reject) => {
                if (trainersCache) {
                    trainers = trainersCache;
                    populateTrainerDropdowns();
                    resolve();
                    return;
                }

                $.ajax({
                    url: '/admin/trainers/active/list',
                    type: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        try {
                            if (Array.isArray(response)) {
                                trainers = response;
                                trainersCache = response;
                                populateTrainerDropdowns();
                                resolve();
                            } else {
                                throw new Error('Invalid trainers data format');
                            }
                        } catch (e) {
                            reject(e);
                        }
                    },
                    error: function(xhr) {
                        reject(new Error(xhr.responseText || 'Failed to load trainers'));
                    }
                });
            });
        }

        function populateTrainerDropdowns() {
            if (!Array.isArray(trainers)) {
                console.error('Trainers data is not an array:', trainers);
                return;
            }

            // Populate modal dropdown
            const trainerSelect = $('#trainerId');
            trainerSelect.empty().append('<option value="">Select Trainer</option>');
            
            trainers.forEach(trainer => {
                trainerSelect.append(
                    `<option value="${trainer.id}">
                        ${trainer.first_name} ${trainer.last_name}
                    </option>`
                );
            });
            
            // Populate filter dropdown
            const trainerFilter = $('#trainerFilter');
            trainerFilter.empty().append('<option value="">All Trainers</option>');
            
            trainers.forEach(trainer => {
                trainerFilter.append(
                    `<option value="${trainer.id}">
                        ${trainer.first_name} ${trainer.last_name}
                    </option>`
                );
            });
        }

        function loadClasses() {
            showLoading('#classesGrid');
            
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: '/admin/classes/list',
                    type: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        try {
                            if (response && response.success && Array.isArray(response.data)) {
                                classes = response.data;
                                renderClasses(classes);
                                resolve();
                            } else {
                                throw new Error(response?.message || 'Invalid data format');
                            }
                        } catch (e) {
                            console.error('Class data processing error:', e);
                            showToast('error', 'Failed to process classes');
                            reject(e);
                        }
                    },
                    error: function(xhr) {
                        const errorMsg = xhr.responseJSON?.message || 'Failed to load classes';
                        console.error('Error loading classes:', errorMsg);
                        showToast('error', errorMsg);
                        reject(new Error(errorMsg));
                    },
                    complete: function() {
                        hideLoading('#classesGrid');
                    }
                });
            });
        }

        function renderClasses(classesToRender) {
            if (!Array.isArray(classesToRender)) {
                $('#classesGrid').html(`
                    <div class="col-12 text-center py-5">
                        <div class="alert alert-danger">Invalid classes data format</div>
                    </div>
                `);
                return;
            }

            if (classesToRender.length === 0) {
                $('#classesGrid').html(`
                    <div class="col-12 text-center py-5">
                        <div class="alert alert-info">No classes found matching your criteria.</div>
                    </div>
                `);
                return;
            }

            let html = '';
            
            classesToRender.forEach(cls => {
                try {
                    const schedule = typeof cls.schedule === 'string' 
                        ? JSON.parse(cls.schedule) 
                        : cls.schedule || {};
                    const date = new Date(schedule.date || null);
                    const time = schedule.time || 'N/A';
                    const trainer = trainers.find(t => t.id == cls.trainer_id) || {};
                    
                    let statusBadgeClass = 'bg-secondary';
                    switch(cls.status) {
                        case 'active': statusBadgeClass = 'bg-success'; break;
                        case 'cancelled': statusBadgeClass = 'bg-danger'; break;
                        case 'completed': statusBadgeClass = 'bg-info'; break;
                    }
                    
                    html += `
                        <div class="col-md-4 mb-4">
                            <div class="card h-100 shadow-sm class-card" data-id="${cls.id}">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="card-title mb-0">${cls.name || 'Unnamed Class'}</h5>
                                    <span class="badge ${statusBadgeClass}">
                                        ${cls.status ? cls.status.charAt(0).toUpperCase() + cls.status.slice(1) : 'Unknown'}
                                    </span>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <h6 class="text-muted">Trainer</h6>
                                        <p>${trainer.first_name || 'No'} ${trainer.last_name || 'trainer'}</p>
                                    </div>
                                    <div class="mb-3">
                                        <h6 class="text-muted">Schedule</h6>
                                        <p>
                                            ${date instanceof Date && !isNaN(date) ? date.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }) : 'No date set'}<br>
                                            ${time}
                                        </p>
                                    </div>
                                    <div class="row">
                                        <div class="col-6">
                                            <h6 class="text-muted">Duration</h6>
                                            <p>${cls.duration_minutes || 0} mins</p>
                                        </div>
                                        <div class="col-6">
                                            <h6 class="text-muted">Capacity</h6>
                                            <p>${cls.max_capacity || 0}</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-footer bg-transparent border-top-0">
                                    <div class="d-flex justify-content-between">
                                        <button class="btn btn-sm btn-outline-primary view-class-btn" data-id="${cls.id}">
                                            <i class="fas fa-eye"></i> View
                                        </button>
                                        <div>
                                            <button class="btn btn-sm btn-outline-secondary edit-class-btn" data-id="${cls.id}">
                                                <i class="fas fa-edit"></i> Edit
                                            </button>
                                            <button class="btn btn-sm btn-outline-danger delete-class-btn" data-id="${cls.id}">
                                                <i class="fas fa-trash"></i> Delete
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                } catch (e) {
                    console.error('Error rendering class:', cls, e);
                }
            });

            $('#classesGrid').html(html);
            attachClassCardEvents();
        }

        function attachClassCardEvents() {
            $('.view-class-btn').off('click').click(function() {
                const classId = $(this).data('id');
                viewClass(classId);
            });
            
            $('.edit-class-btn').off('click').click(function() {
                const classId = $(this).data('id');
                showEditClassModal(classId);
            });
            
            $('.delete-class-btn').off('click').click(function() {
                const classId = $(this).data('id');
                showDeleteConfirmation(classId);
            });
        }

        function showAddClassModal() {
            $('#modalTitle').text('Add New Class');
            $('#classForm')[0].reset();
            $('#classId').val('');
            $('#status').val('active');
            classModal.show();
        }

        function showEditClassModal(classId) {
            const cls = classes.find(c => c.id == classId);
            if (!cls) {
                showToast('error', 'Class not found');
                return;
            }
            
            try {
                const schedule = typeof cls.schedule === 'string' 
                    ? JSON.parse(cls.schedule) 
                    : cls.schedule || {};
                
                $('#modalTitle').text('Edit Class');
                $('#classId').val(cls.id);
                $('#className').val(cls.name);
                $('#trainerId').val(cls.trainer_id);
                $('#classDate').val(schedule.date || '');
                $('#classTime').val(schedule.time || '');
                $('#duration').val(cls.duration_minutes || 60);
                $('#maxCapacity').val(cls.max_capacity || 20);
                $('#description').val(cls.description || '');
                $('#status').val(cls.status || 'active');
                
                classModal.show();
            } catch (e) {
                console.error('Error preparing edit form:', e);
                showToast('error', 'Failed to load class data');
            }
        }

        function handleClassFormSubmit(e) {
            e.preventDefault();
            
            const classId = $('#classId').val();
            const isEdit = !!classId;
            
            const formData = {
                name: $('#className').val(),
                trainer_id: $('#trainerId').val(),
                class_date: $('#classDate').val(),
                class_time: $('#classTime').val(),
                duration_minutes: $('#duration').val(),
                max_capacity: $('#maxCapacity').val(),
                description: $('#description').val(),
                status: $('#status').val()
            };
            
            // Validate required fields
            if (!formData.name || !formData.trainer_id || !formData.class_date || !formData.class_time) {
                showToast('error', 'Please fill in all required fields');
                return;
            }
            
            const $saveBtn = $('#saveClassBtn');
            $saveBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Processing...');
            
            const url = isEdit ? `/admin/classes/${classId}` : '/admin/classes';
            const method = isEdit ? 'PUT' : 'POST';
            
            $.ajax({
                url: url,
                type: method,
                data: formData,
                success: function(response) {
                    if (response.success) {
                        showToast('success', `Class ${isEdit ? 'updated' : 'created'} successfully`);
                        classModal.hide();
                        loadClasses();
                    } else {
                        throw new Error(response.message || 'Operation failed');
                    }
                },
                error: function(xhr) {
                    const errorMsg = xhr.responseJSON?.message || 'Failed to save class';
                    console.error('Error saving class:', errorMsg);
                    showToast('error', errorMsg);
                },
                complete: function() {
                    $saveBtn.prop('disabled', false).html('Save Class');
                }
            });
        }

        function viewClass(classId) {
            const cls = classes.find(c => c.id == classId);
            if (!cls) {
                showToast('error', 'Class not found');
                return;
            }
            
            try {
                const schedule = typeof cls.schedule === 'string' 
                    ? JSON.parse(cls.schedule) 
                    : cls.schedule || {};
                const trainer = trainers.find(t => t.id == cls.trainer_id) || {};
                const date = new Date(schedule.date || null);
                
                let html = `
                    <div class="mb-4">
                        <h4>${cls.name || 'Unnamed Class'}</h4>
                        <span class="badge ${cls.status === 'active' ? 'bg-success' : cls.status === 'cancelled' ? 'bg-danger' : 'bg-secondary'}">
                            ${cls.status ? cls.status.charAt(0).toUpperCase() + cls.status.slice(1) : 'Unknown'}
                        </span>
                    </div>
                    
                    <div class="mb-3">
                        <h6 class="text-muted">Trainer</h6>
                        <p>${trainer.first_name || 'No'} ${trainer.last_name || 'trainer assigned'}</p>
                    </div>
                    
                    <div class="mb-3">
                        <h6 class="text-muted">Schedule</h6>
                        <p>
                            ${date instanceof Date && !isNaN(date) ? date.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }) : 'No date set'}<br>
                            ${schedule.time || 'No time set'}
                        </p>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-6">
                            <h6 class="text-muted">Duration</h6>
                            <p>${cls.duration_minutes || 0} minutes</p>
                        </div>
                        <div class="col-6">
                            <h6 class="text-muted">Max Capacity</h6>
                            <p>${cls.max_capacity || 0} participants</p>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <h6 class="text-muted">Description</h6>
                        <p>${cls.description || 'No description provided'}</p>
                    </div>
                `;
                
                $('#classDetailsContent').html(html);
                viewClassModal.show();
            } catch (e) {
                console.error('Error viewing class:', e);
                showToast('error', 'Failed to load class details');
            }
        }

        function showDeleteConfirmation(classId) {
            $('#deleteClassId').val(classId);
            deleteClassModal.show();
        }

        function deleteClass() {
            const classId = $('#deleteClassId').val();
            
            const $deleteBtn = $('#confirmDeleteBtn');
            $deleteBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Deleting...');
            
            $.ajax({
                url: `/admin/classes/${classId}`,
                type: 'DELETE',
                success: function(response) {
                    if (response.success) {
                        showToast('success', 'Class deleted successfully');
                        deleteClassModal.hide();
                        loadClasses();
                    } else {
                        throw new Error(response.message || 'Deletion failed');
                    }
                },
                error: function(xhr) {
                    const errorMsg = xhr.responseJSON?.message || 'Failed to delete class';
                    console.error('Error deleting class:', errorMsg);
                    showToast('error', errorMsg);
                },
                complete: function() {
                    $deleteBtn.prop('disabled', false).html('Delete Class');
                }
            });
        }

        function applyFilters() {
            const status = $('#statusFilter').val();
            const trainerId = $('#trainerFilter').val();
            const dateFrom = $('#dateFrom').val();
            const dateTo = $('#dateTo').val();
            
            let filteredClasses = [...classes];
            
            if (status) {
                filteredClasses = filteredClasses.filter(c => c.status === status);
            }
            
            if (trainerId) {
                filteredClasses = filteredClasses.filter(c => c.trainer_id == trainerId);
            }
            
            if (dateFrom) {
                filteredClasses = filteredClasses.filter(c => {
                    try {
                        const schedule = typeof c.schedule === 'string' 
                            ? JSON.parse(c.schedule) 
                            : c.schedule || {};
                        const classDate = new Date(schedule.date || null);
                        return classDate instanceof Date && !isNaN(classDate) 
                            ? classDate >= new Date(dateFrom) 
                            : false;
                    } catch (e) {
                        return false;
                    }
                });
            }
            
            if (dateTo) {
                filteredClasses = filteredClasses.filter(c => {
                    try {
                        const schedule = typeof c.schedule === 'string' 
                            ? JSON.parse(c.schedule) 
                            : c.schedule || {};
                        const classDate = new Date(schedule.date || null);
                        return classDate instanceof Date && !isNaN(classDate) 
                            ? classDate <= new Date(dateTo) 
                            : false;
                    } catch (e) {
                        return false;
                    }
                });
            }
            
            renderClasses(filteredClasses);
        }
    }
});
</script><?php /**PATH C:\laravel projects\gym-management-system\resources\views/admin/pages/classes.blade.php ENDPATH**/ ?>