<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-warning text-white">
                    <h5 class="mb-0">Trainers Management</h5>
                </div>
                <div class="card-body">
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <button class="btn btn-success" id="addTrainerBtn">
                                <i class="fas fa-plus-circle me-2"></i>Add New Trainer
                            </button>
                        </div>
                        <div class="col-md-6">
                            <div class="input-group">
                                <input type="text" class="form-control" id="searchInput" placeholder="Search trainers...">
                                <button class="btn btn-primary" id="searchBtn">
                                    <i class="fas fa-search"></i>
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="card filter-card">
                                <div class="card-body">
                                    <div class="row g-3">
                                        <div class="col-md-3">
                                            <label for="statusFilter" class="form-label">Status</label>
                                            <select class="form-select" id="statusFilter">
                                                <option value="">All Statuses</option>
                                                <option value="active">Active</option>
                                                <option value="inactive">Inactive</option>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label for="dateFrom" class="form-label">Hired From</label>
                                            <input type="date" class="form-control" id="dateFrom">
                                        </div>
                                        <div class="col-md-3">
                                            <label for="dateTo" class="form-label">Hired To</label>
                                            <input type="date" class="form-control" id="dateTo">
                                        </div>
                                        <div class="col-md-3 d-flex align-items-end">
                                            <button class="btn btn-primary me-2" id="applyFilters">
                                                <i class="fas fa-filter me-2"></i>Apply
                                            </button>
                                            <button class="btn btn-secondary" id="resetFilters">
                                                <i class="fas fa-sync-alt me-2"></i>Reset
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="table-responsive">
                        <table id="trainersTable" class="table table-hover table-striped" style="width:100%">
                            <thead class="bg-primary text-white">
                                <tr>
                                    <th>ID</th>
                                    <th>Profile</th>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th>Phone</th>
                                    <th>Specialization</th>
                                    <th>Hire Date</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Trainer Modal -->
<div class="modal fade" id="addTrainerModal" tabindex="-1" aria-labelledby="addTrainerModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="addTrainerModalLabel">
                    <i class="fas fa-user-plus me-2"></i>Add New Trainer
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addTrainerForm" class="needs-validation" novalidate>
                    @csrf
                    <div class="row g-3">
                        <!-- Personal Information Column -->
                        <div class="col-md-6">
                            <div class="card h-100 border-0 shadow-sm">
                                <div class="card-header bg-light">
                                    <h6 class="mb-0"><i class="fas fa-user-circle me-2"></i>Personal Information</h6>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="firstName" class="form-label">First Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="firstName" name="first_name" required>
                                        <div class="invalid-feedback">Please enter the first name</div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="lastName" class="form-label">Last Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="lastName" name="last_name" required>
                                        <div class="invalid-feedback">Please enter the last name</div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="email" class="form-label">Email <span class="text-danger">*</span></label>
                                        <input type="email" class="form-control" id="email" name="email" required>
                                        <div class="invalid-feedback">Please enter a valid email</div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="phone" class="form-label">Phone Number</label>
                                        <input type="tel" class="form-control" id="phone" name="phone" pattern="[0-9]{10,15}">
                                        <div class="invalid-feedback">Please enter a valid phone number (10-15 digits)</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Professional Information Column -->
                        <div class="col-md-6">
                            <div class="card h-100 border-0 shadow-sm">
                                <div class="card-header bg-light">
                                    <h6 class="mb-0"><i class="fas fa-id-card me-2"></i>Professional Information</h6>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="specialization" class="form-label">Specialization <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="specialization" name="specialization" required>
                                        <div class="invalid-feedback">Please enter the trainer's specialization</div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="hireDate" class="form-label">Hire Date <span class="text-danger">*</span></label>
                                        <input type="date" class="form-control" id="hireDate" name="hire_date" required value="{{ date('Y-m-d') }}">
                                        <div class="invalid-feedback">Please select a hire date</div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="status" class="form-label">Status <span class="text-danger">*</span></label>
                                        <select class="form-select" id="status" name="status" required>
                                            <option value="" disabled selected>Select status</option>
                                            <option value="active">Active</option>
                                            <option value="inactive">Inactive</option>
                                        </select>
                                        <div class="invalid-feedback">Please select a status</div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="profileImage" class="form-label">Profile Photo</label>
                                        <input type="file" class="form-control" id="profileImage" name="profile_image" accept="image/*">
                                        <small class="text-muted">Max size: 2MB (JPG, PNG, GIF)</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Additional Information Row -->
                        <div class="col-12">
                            <div class="card border-0 shadow-sm">
                                <div class="card-header bg-light">
                                    <h6 class="mb-0"><i class="fas fa-certificate me-2"></i>Certifications</h6>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="certifications" class="form-label">Certifications & Qualifications</label>
                                        <textarea class="form-control" id="certifications" name="certifications" rows="3" placeholder="List any certifications or qualifications the trainer has"></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer bg-light">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-2"></i>Cancel
                </button>
                <button type="button" id="saveTrainerBtn" class="btn btn-primary">
                    <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                    <i class="fas fa-save me-2"></i>
                    <span class="btn-text">Save Trainer</span>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Trainer Modal -->
<div class="modal fade" id="editTrainerModal" tabindex="-1" aria-labelledby="editTrainerModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="editTrainerModalLabel">Edit Trainer</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editTrainerForm">
                    <input type="hidden" id="editTrainerId" name="id">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="editFirstName" class="form-label">First Name *</label>
                                <input type="text" class="form-control" id="editFirstName" name="first_name" required>
                            </div>
                            <div class="mb-3">
                                <label for="editLastName" class="form-label">Last Name *</label>
                                <input type="text" class="form-control" id="editLastName" name="last_name" required>
                            </div>
                            <div class="mb-3">
                                <label for="editEmail" class="form-label">Email *</label>
                                <input type="email" class="form-control" id="editEmail" name="email" required>
                            </div>
                            <div class="mb-3">
                                <label for="editPhone" class="form-label">Phone</label>
                                <input type="tel" class="form-control" id="editPhone" name="phone">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="editSpecialization" class="form-label">Specialization *</label>
                                <input type="text" class="form-control" id="editSpecialization" name="specialization" required>
                            </div>
                            <div class="mb-3">
                                <label for="editHireDate" class="form-label">Hire Date *</label>
                                <input type="date" class="form-control" id="editHireDate" name="hire_date" required>
                            </div>
                            <div class="mb-3">
                                <label for="editStatus" class="form-label">Status *</label>
                                <select class="form-select" id="editStatus" name="status" required>
                                    <option value="active">Active</option>
                                    <option value="inactive">Inactive</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="editProfileImage" class="form-label">Profile Image</label>
                                <input type="file" class="form-control" id="editProfileImage" name="profile_image" accept="image/*">
                                <div class="mt-2" id="currentImageContainer"></div>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="editCertifications" class="form-label">Certifications</label>
                        <textarea class="form-control" id="editCertifications" name="certifications" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" id="updateTrainerBtn" class="btn btn-primary">
                    <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                    <span class="btn-text">Update Trainer</span>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- View Trainer Modal -->
<div class="modal fade" id="viewTrainerModal" tabindex="-1" aria-labelledby="viewTrainerModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="viewTrainerModalLabel">Trainer Details</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-4 text-center mb-4">
                        <div class="trainer-avatar-container">
                            <img id="viewProfileImage" src="" alt="Profile Image" class="img-fluid rounded-circle mb-3" style="width: 150px; height: 150px; object-fit: cover;">
                        </div>
                        <h4 id="viewTrainerName" class="mb-1"></h4>
                        <span class="badge" id="viewTrainerStatus"></span>
                        <p class="text-muted" id="viewTrainerSpecialization"></p>
                    </div>
                    <div class="col-md-8">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Email</label>
                                    <p id="viewEmail" class="form-control-static"></p>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Phone</label>
                                    <p id="viewPhone" class="form-control-static"></p>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Hire Date</label>
                                    <p id="viewHireDate" class="form-control-static"></p>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Status</label>
                                    <p id="viewStatus" class="form-control-static"></p>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Certifications</label>
                            <p id="viewCertifications" class="form-control-static"></p>
                        </div>
                    </div>
                </div>
            </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="deleteConfirmationModal" tabindex="-1" aria-labelledby="deleteConfirmationModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="deleteConfirmationModalLabel">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 trainer? This action cannot be undone.</p>
                <input type="hidden" id="deleteTrainerId">
            </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 Trainer</button>
            </div>
        </div>
    </div>
</div>

<!-- Required CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap5.min.css">
<style>
    .dataTables_wrapper .dt-buttons {
        margin-bottom: 1rem;
    }
    .toast {
        z-index: 1100;
         background-color:rgb(230, 164, 21);
        position: absolute;
            top: 10px;
            left: 40%;
            height: 80px;
    }
    .filter-card {
        border: none;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        border-radius: 8px;
    }
    .avatar-placeholder {
        font-weight: bold;
    }
    .trainer-avatar-container {
        border: 3px solid #e9ecef;
        border-radius: 50%;
        padding: 5px;
        display: inline-block;
    }
    .dataTables_wrapper .dataTables_filter input {
        border-radius: 20px;
        padding: 5px 15px;
        border: 1px solid #dee2e6;
    }
    .dataTables_wrapper .dataTables_length select {
        border-radius: 5px;
        padding: 5px;
        border: 1px solid #dee2e6;
    }
    .dt-buttons .btn {
        border-radius: 5px;
        margin-right: 5px;
    }
    .btn-primary {
        background-color: #2c3e50;
        border-color: #2c3e50;
    }
    .btn-primary:hover {
        background-color: #1a252f;
        border-color: #1a252f;
    }
    .btn-success {
        background-color:  #e74c3c;
        border-color: #e74c3c;
    }
    .btn-warning {
        background-color: #f39c12;
        border-color: #f39c12;
    }
    .btn-danger {
        background-color: #e74c3c;
        border-color: #e74c3c;
    }
    .badge {
        font-size: 0.85em;
        font-weight: 500;
        padding: 0.35em 0.65em;
    }
    .card-header {
        border-bottom: none;
    }
    #addTrainerModal .modal-content {
        border: none;
        border-radius: 10px;
        overflow: hidden;
    }
    #addTrainerModal .modal-header {
        padding: 1.2rem 1.5rem;
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    }
    #addTrainerModal .modal-body {
        padding: 1.5rem;
    }
    #addTrainerModal .modal-footer {
        padding: 1rem 1.5rem;
        border-top: 1px solid #eee;
    }
    #addTrainerModal .card {
        margin-bottom: 1rem;
        border-radius: 8px;
    }
    #addTrainerModal .card-header {
        padding: 0.75rem 1.25rem;
        background-color: #f8f9fa;
        border-bottom: 1px solid #eee;
    }
    #addTrainerModal .form-label {
        font-weight: 500;
        margin-bottom: 0.5rem;
    }
    #addTrainerModal .invalid-feedback {
        font-size: 0.85rem;
    }
    #addTrainerModal .text-danger {
        color: #dc3545;
    }
    #addTrainerModal .text-muted {
        font-size: 0.8rem;
    }
</style>
<meta name="csrf-token" content="{{ csrf_token() }}">

<!-- Required JavaScript Libraries -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.colVis.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<!-- Bootstrap JS Bundle with Popper (includes tooltip functionality) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
   $(document).ready(function() {
    // Initialize DataTable with proper configuration
    const trainersTable = $('#trainersTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: "/admin/trainers/list",
            type: 'GET',
            data: function(d) {
                d.status = $('#statusFilter').val();
                d.dateFrom = $('#dateFrom').val();
                d.dateTo = $('#dateTo').val();
                d.search = $('#searchInput').val();
            },
            error: function(xhr, status, error) {
                console.error('DataTables error:', xhr.responseText);
                showToast('error', 'Failed to load trainers data');
            }
        },
        columns: [
            { data: 'id' },
            { 
                data: 'profile_image',
            render: function(data, type, row) {
                // Default avatar if no image
                const defaultAvatar = `https://ui-avatars.com/api/?name=${encodeURIComponent(row.first_name + ' ' + row.last_name)}&background=random&size=40`;
                
                if (!data) return `<img src="${defaultAvatar}" width="40" height="40" class="rounded-circle">`;
                
                // Remove any duplicate storage prefix
                const cleanPath = data.replace(/^\/?storage\//, '')
                                     .replace(/^http:\/\/[^\/]+\/storage\//, '');
                
                // Return the properly formatted URL
                return `<img src="/storage/${cleanPath}" width="40" height="40" class="rounded-circle">`;
            }
        },
            { 
                data: null,
                render: function(data, type, row) {
                    return `${row.first_name} ${row.last_name}`;
                }
            },
            { data: 'email' },
            { data: 'phone' },
            { data: 'specialization' },
            { 
                data: 'hire_date',
                render: function(data) {
                    return data ? new Date(data).toLocaleDateString() : '';
                }
            },
            { 
                data: 'status',
                render: function(data) {
                    return `<span class="badge ${data === 'active' ? 'bg-success' : 'bg-secondary'}">${data}</span>`;
                }
            },
            {
                data: 'id',
                render: function(data) {
                    return `
                        <div class="btn-group">
                            <button class="btn btn-sm btn-primary view-trainer" data-id="${data}">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn btn-sm btn-warning edit-trainer" data-id="${data}">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn btn-sm btn-danger delete-trainer" data-id="${data}">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    `;
                }
            }
        ]
    });

    // Add Trainer Modal Show
    $('#addTrainerBtn').click(function() {
        $('#addTrainerModal').modal('show');
    });

    // Save Trainer Form
    $('#saveTrainerBtn').click(function() {
        const form = $('#addTrainerForm')[0];
        
        // Validate form
        if (!form.checkValidity()) {
            form.classList.add('was-validated');
            return;
        }

        const btn = $(this);
        btn.prop('disabled', true);
        btn.find('.spinner-border').removeClass('d-none');
        btn.find('.btn-text').text('Saving...');

        // Create FormData object
        const formData = new FormData(form);

        $.ajax({
            url: "/admin/trainers",
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    showToast('success', 'Trainer added successfully');
                    $('#addTrainerModal').modal('hide');
                    trainersTable.ajax.reload();
                    form.reset();
                    form.classList.remove('was-validated');
                } else {
                    showToast('error', response.message || 'Failed to add trainer');
                }
            },
            error: function(xhr) {
                let errorMsg = 'An error occurred while adding trainer';
                if (xhr.responseJSON && xhr.responseJSON.errors) {
                    errorMsg = Object.values(xhr.responseJSON.errors).join('<br>');
                }
                showToast('error', errorMsg);
            },
            complete: function() {
                btn.prop('disabled', false);
                btn.find('.spinner-border').addClass('d-none');
                btn.find('.btn-text').text('Save Trainer');
            }
        });
    });

    // View Trainer
    $(document).on('click', '.view-trainer', function() {
        const trainerId = $(this).data('id');
        
        $.get(`/admin/trainers/${trainerId}`, function(response) {
            if (response.success) {
                const trainer = response.data;
                
                // Set modal title
                $('#viewTrainerModalLabel').text(`Trainer: ${trainer.first_name} ${trainer.last_name}`);
                
                // Set profile image
                if (trainer.profile_image) {
                    $('#viewProfileImage').attr('src', `/storage/${trainer.profile_image}`);
                } else {
                    $('#viewProfileImage').attr('src', 'https://ui-avatars.com/api/?name=' + 
                        encodeURIComponent(`${trainer.first_name} ${trainer.last_name}`) + '&background=random');
                }
                
                // Set trainer name, status and specialization
                $('#viewTrainerName').text(`${trainer.first_name} ${trainer.last_name}`);
                $('#viewTrainerStatus').text(trainer.status.charAt(0).toUpperCase() + trainer.status.slice(1));
                $('#viewTrainerStatus').removeClass('bg-success bg-secondary')
                    .addClass(trainer.status === 'active' ? 'bg-success' : 'bg-secondary');
                $('#viewTrainerSpecialization').text(trainer.specialization);
                
                // Set other details
                $('#viewEmail').text(trainer.email || 'N/A');
                $('#viewPhone').text(trainer.phone || 'N/A');
                $('#viewHireDate').text(trainer.hire_date ? new Date(trainer.hire_date).toLocaleDateString() : 'N/A');
                $('#viewStatus').text(trainer.status.charAt(0).toUpperCase() + trainer.status.slice(1));
                $('#viewCertifications').text(trainer.certifications || 'N/A');
                
                $('#viewTrainerModal').modal('show');
            } else {
                showToast('error', response.message || 'Failed to load trainer details');
            }
        }).fail(function() {
            showToast('error', 'Failed to load trainer details');
        });
    });

    // Edit Trainer - Load Data
    $(document).on('click', '.edit-trainer', function() {
        const trainerId = $(this).data('id');
        
        $.get(`/admin/trainers/${trainerId}`, function(response) {
            if (response.success) {
                const trainer = response.data;
                
                // Set modal title
                $('#editTrainerModalLabel').text(`Edit Trainer: ${trainer.first_name} ${trainer.last_name}`);
                
                // Fill form fields
                $('#editTrainerId').val(trainer.id);
                $('#editFirstName').val(trainer.first_name);
                $('#editLastName').val(trainer.last_name);
                $('#editEmail').val(trainer.email);
                $('#editPhone').val(trainer.phone);
                $('#editSpecialization').val(trainer.specialization);
                $('#editHireDate').val(trainer.hire_date);
                $('#editCertifications').val(trainer.certifications);
                $('#editStatus').val(trainer.status);
                
                // Show current profile image
                if (trainer.profile_image) {
                    $('#currentImageContainer').html(`
                        <p class="mb-1">Current Image:</p>
                        <img src="/storage/${trainer.profile_image}" class="img-thumbnail" style="max-width: 150px;">
                    `);
                } else {
                    $('#currentImageContainer').html(`
                        <p class="mb-1">No profile image</p>
                    `);
                }
                
                $('#editTrainerModal').modal('show');
            } else {
                showToast('error', response.message || 'Failed to load trainer details');
            }
        }).fail(function() {
            showToast('error', 'Failed to load trainer details');
        });
    });

    // Update Trainer
    $('#updateTrainerBtn').click(function() {
        const btn = $(this);
        btn.prop('disabled', true);
        btn.find('.spinner-border').removeClass('d-none');
        btn.find('.btn-text').text('Updating...');

        const formData = new FormData($('#editTrainerForm')[0]);
        const trainerId = $('#editTrainerId').val();
        
        // Add _method for PUT request
        formData.append('_method', 'PUT');

        $.ajax({
            url: `/admin/trainers/${trainerId}`,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    showToast('success', 'Trainer updated successfully');
                    $('#editTrainerModal').modal('hide');
                    trainersTable.ajax.reload();
                } else {
                    showToast('error', response.message || 'Failed to update trainer');
                }
            },
            error: function(xhr) {
                let errorMsg = 'An error occurred while updating trainer';
                if (xhr.responseJSON && xhr.responseJSON.errors) {
                    errorMsg = Object.values(xhr.responseJSON.errors).join('<br>');
                }
                showToast('error', errorMsg);
            },
            complete: function() {
                btn.prop('disabled', false);
                btn.find('.spinner-border').addClass('d-none');
                btn.find('.btn-text').text('Update Trainer');
            }
        });
    });

    // Delete Trainer - Confirmation
    $(document).on('click', '.delete-trainer', function() {
        const trainerId = $(this).data('id');
        $('#deleteTrainerId').val(trainerId);
        $('#deleteConfirmationModal').modal('show');
    });

    // Confirm Delete
    $('#confirmDeleteBtn').click(function() {
        const btn = $(this);
        btn.prop('disabled', true);
        btn.text('Deleting...');

        const trainerId = $('#deleteTrainerId').val();
        
        $.ajax({
            url: `/admin/trainers/${trainerId}`,
            type: 'DELETE',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    showToast('success', 'Trainer deleted successfully');
                    $('#deleteConfirmationModal').modal('hide');
                    trainersTable.ajax.reload();
                } else {
                    showToast('error', response.message || 'Failed to delete trainer');
                }
            },
            error: function(xhr) {
                const errorMsg = xhr.responseJSON?.message || 'An error occurred while deleting trainer';
                showToast('error', errorMsg);
            },
            complete: function() {
                btn.prop('disabled', false);
                btn.text('Delete Trainer');
            }
        });
    });

    // Apply Filters
    $('#applyFilters').click(function() {
        trainersTable.ajax.reload();
    });

    // Reset Filters
    $('#resetFilters').click(function() {
        $('#statusFilter').val('');
        $('#dateFrom').val('');
        $('#dateTo').val('');
        trainersTable.ajax.reload();
    });

    // Search Trainers
    $('#searchBtn').click(function() {
        trainersTable.ajax.reload();
    });

    // Allow search on Enter key
    $('#searchInput').keypress(function(e) {
        if (e.which === 13) {
            trainersTable.ajax.reload();
        }
    });

    // Helper function to show toast notifications
    function showToast(type, message) {
        const toast = $(`
            <div class="toast align-items-center text-white bg-${type} border-0 position-fixed bottom-0 end-0 m-3" role="alert" aria-live="assertive" aria-atomic="true">
                <div class="d-flex">
                    <div class="toast-body">
                        ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            </div>
        `);
        
        $('body').append(toast);
        const bsToast = new bootstrap.Toast(toast[0]);
        bsToast.show();
        
        toast.on('hidden.bs.toast', function() {
            $(this).remove();
        });
    }

    // Initialize date inputs with max date today
    $('input[type="date"]').attr('max', new Date().toISOString().split('T')[0]);
});
</script>