<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-primary text-white">
                    <h5 class="mb-0">Members Management</h5>
                </div>
                <div class="card-body">
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <button class="btn btn-success" id="addMemberBtn">
                                <i class="fas fa-plus-circle me-2"></i>Add New Member
                            </button>
                        </div>
                        <div class="col-md-6">
                            <div class="input-group">
                                <input type="text" class="form-control" id="searchInput" placeholder="Search members...">
                                <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>
                                                <option value="suspended">Suspended</option>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label for="dateFrom" class="form-label">Joined From</label>
                                            <input type="date" class="form-control" id="dateFrom">
                                        </div>
                                        <div class="col-md-3">
                                            <label for="dateTo" class="form-label">Joined 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="membersTable" 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>Join Date</th>
                                    <th>Expiry Date</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Member Modal -->
<div class="modal fade" id="addMemberModal" tabindex="-1" aria-labelledby="addMemberModalLabel" 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="addMemberModalLabel">
                    <i class="fas fa-user-plus me-2"></i>Add New Member
                </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="addMemberForm" 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 class="mb-3">
                                        <label for="dateOfBirth" class="form-label">Date of Birth</label>
                                        <input type="date" class="form-control" id="dateOfBirth" name="date_of_birth" max="{{ date('Y-m-d') }}">
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Membership 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>Membership Information</h6>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="joinDate" class="form-label">Join Date <span class="text-danger">*</span></label>
                                        <input type="date" class="form-control" id="joinDate" name="join_date" required value="{{ date('Y-m-d') }}">
                                        <div class="invalid-feedback">Please select a join date</div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="membershipExpiry" class="form-label">Membership Expiry</label>
                                        <input type="date" class="form-control" id="membershipExpiry" name="membership_expiry">
                                    </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>
                                            <option value="suspended">Suspended</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-info-circle me-2"></i>Additional Information</h6>
                                </div>
                                <div class="card-body">
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="address" class="form-label">Address</label>
                                                <textarea class="form-control" id="address" name="address" rows="2"></textarea>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="emergencyContact" class="form-label">Emergency Contact</label>
                                                <input type="text" class="form-control" id="emergencyContact" name="emergency_contact">
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="mb-3">
                                                <label for="healthNotes" class="form-label">Health Notes</label>
                                                <textarea class="form-control" id="healthNotes" name="health_notes" rows="2" placeholder="Any medical conditions, allergies, or special requirements"></textarea>
                                            </div>
                                        </div>
                                    </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="saveMemberBtn" 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 Member</span>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Member Modal -->
<div class="modal fade" id="editMemberModal" tabindex="-1" aria-labelledby="editMemberModalLabel" 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="editMemberModalLabel">Edit Member</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="editMemberForm">
                    <input type="hidden" id="editMemberId" 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 class="mb-3">
                                <label for="editDateOfBirth" class="form-label">Date of Birth</label>
                                <input type="date" class="form-control" id="editDateOfBirth" name="date_of_birth">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="editJoinDate" class="form-label">Join Date *</label>
                                <input type="date" class="form-control" id="editJoinDate" name="join_date" required>
                            </div>
                            <div class="mb-3">
                                <label for="editMembershipExpiry" class="form-label">Membership Expiry</label>
                                <input type="date" class="form-control" id="editMembershipExpiry" name="membership_expiry">
                            </div>
                            <div class="mb-3">
                                <label for="editAddress" class="form-label">Address</label>
                                <textarea class="form-control" id="editAddress" name="address" rows="2"></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="editEmergencyContact" class="form-label">Emergency Contact</label>
                                <input type="text" class="form-control" id="editEmergencyContact" name="emergency_contact">
                            </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>
                                    <option value="suspended">Suspended</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="editHealthNotes" class="form-label">Health Notes</label>
                        <textarea class="form-control" id="editHealthNotes" name="health_notes" rows="2"></textarea>
                    </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>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" id="updateMemberBtn" class="btn btn-primary">
                    <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                    <span class="btn-text">Update Member</span>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- View Member Modal -->
<div class="modal fade" id="viewMemberModal" tabindex="-1" aria-labelledby="viewMemberModalLabel" 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="viewMemberModalLabel">Member 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="member-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="viewMemberName" class="mb-1"></h4>
                        <span class="badge" id="viewMemberStatus"></span>
                    </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 class="mb-3">
                                    <label class="form-label fw-bold">Date of Birth</label>
                                    <p id="viewDateOfBirth" class="form-control-static"></p>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Join Date</label>
                                    <p id="viewJoinDate" class="form-control-static"></p>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Membership Expiry</label>
                                    <p id="viewMembershipExpiry" class="form-control-static"></p>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Emergency Contact</label>
                                    <p id="viewEmergencyContact" class="form-control-static"></p>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Address</label>
                            <p id="viewAddress" class="form-control-static"></p>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Health Notes</label>
                            <p id="viewHealthNotes" 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 member? This action cannot be undone.</p>
                <input type="hidden" id="deleteMemberId">
            </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 Member</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(21, 230, 49);
        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;
    }
    .member-avatar-container {
        border: 3px solidrgb(28, 91, 155);
        border-radius: 50%;
        padding: 5px;
        display: inline-block;
    }
    .dataTables_wrapper .dataTables_filter input {
        border-radius: 20px;
        padding: 5px 15px;
        border: 1px solidrgb(114, 161, 207);
    }
    .dataTables_wrapper .dataTables_length select {
        border-radius: 5px;
        padding: 5px;
        border: 1px solidrgb(9, 108, 207);
    }
    .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: #27ae60;
        border-color: #27ae60;
    }
    .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;
    }
    #addMemberModal .modal-content {
        border: none;
        border-radius: 10px;
        overflow: hidden;
    }
    #addMemberModal .modal-header {
        padding: 1.2rem 1.5rem;
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    }
    #addMemberModal .modal-body {
        padding: 1.5rem;
    }
    #addMemberModal .modal-footer {
        padding: 1rem 1.5rem;
        border-top: 1px solid #eee;
    }
    #addMemberModal .card {
        margin-bottom: 1rem;
        border-radius: 8px;
    }
    #addMemberModal .card-header {
        padding: 0.75rem 1.25rem;
        background-color: #f8f9fa;
        border-bottom: 1px solid #eee;
    }
    #addMemberModal .form-label {
        font-weight: 500;
        margin-bottom: 0.5rem;
    }
    #addMemberModal .invalid-feedback {
        font-size: 0.85rem;
    }
    #addMemberModal .text-danger {
        color: #dc3545;
    }
    #addMemberModal .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
    const membersTable = $('#membersTable').DataTable({
    processing: true,
    serverSide: true,
    ajax: {
        url: '/admin/members/list',
        type: 'GET',
        data: function(d) {
            // Add filter parameters to the request
            d.status = $('#statusFilter').val();
            d.dateFrom = $('#dateFrom').val();
            d.dateTo = $('#dateTo').val();
            d.search = $('#searchInput').val();
        },
        error: function(xhr, error, thrown) {
            console.error('DataTables error:', xhr, error, thrown);
            // You can show a user-friendly message here
            alert('Failed to load data. Please try again or contact support.');
        }
    },
        columns: [
            { data: 'id', name: 'id' },
            { 
                data: 'profile_image', 
                name: 'profile_image',
                render: function(data, type, row) {
                    if (data) {
                        return `<img src="/storage/${data}" class="rounded-circle" width="40" height="40" alt="Profile Image">`;
                    } else {
                        // Create initials avatar if no image
                        const initials = `${row.first_name.charAt(0)}${row.last_name.charAt(0)}`.toUpperCase();
                        return `<div class="avatar-placeholder rounded-circle d-flex align-items-center justify-content-center bg-primary text-white" style="width:40px;height:40px">${initials}</div>`;
                    }
                }
            },
            { 
                data: null,
                render: function(data, type, row) {
                    return `${row.first_name} ${row.last_name}`;
                }
            },
            { data: 'email', name: 'email' },
            { data: 'phone', name: 'phone' },
            { 
                data: 'join_date', 
                name: 'join_date',
                render: function(data) {
                    return data ? new Date(data).toLocaleDateString() : '';
                }
            },
            { 
                data: 'membership_expiry', 
                name: 'membership_expiry',
                render: function(data) {
                    return data ? new Date(data).toLocaleDateString() : '';
                }
            },
            { 
                data: 'status', 
                name: 'status',
                render: function(data) {
                    let badgeClass = 'bg-secondary';
                    if (data === 'active') badgeClass = 'bg-success';
                    if (data === 'suspended') badgeClass = 'bg-danger';
                    return `<span class="badge ${badgeClass}">${data.charAt(0).toUpperCase() + data.slice(1)}</span>`;
                }
            },
            {
                data: null,
                orderable: false,
                render: function(data, type, row) {
                    return `
                        <div class="btn-group" role="group">
                            <button class="btn btn-sm btn-primary view-member" data-id="${row.id}" title="View">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn btn-sm btn-warning edit-member" data-id="${row.id}" title="Edit">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn btn-sm btn-danger delete-member" data-id="${row.id}" title="Delete">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    `;
                }
            }
        ],
        dom: 'Bfrtip',
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print', 'colvis'
        ],
        responsive: true,
        language: {
            search: "_INPUT_",
            searchPlaceholder: "Search members...",
        },
        initComplete: function() {
            $('.dataTables_filter input').addClass('form-control');
            $('.dataTables_length select').addClass('form-select');
        }
    });

    // Add Member Modal
    $('#addMemberBtn').click(function() {
        $('#addMemberModal').modal('show');
    });

    // Save Member Form
    $('#saveMemberBtn').click(function() {
        const form = $('#addMemberForm')[0];
        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...');

        const formData = new FormData(form);

        $.ajax({
            url: '/admin/members',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    showToast('success', 'Member added successfully');
                    $('#addMemberModal').modal('hide');
                    membersTable.ajax.reload();
                    form.reset();
                    form.classList.remove('was-validated');
                } else {
                    showToast('error', response.message || 'Failed to add member');
                }
            },
            error: function(xhr) {
                const errorMsg = xhr.responseJSON?.message || 'An error occurred while adding member';
                showToast('error', errorMsg);
            },
            complete: function() {
                btn.prop('disabled', false);
                btn.find('.spinner-border').addClass('d-none');
                btn.find('.btn-text').text('Save Member');
            }
        });
    });

    // View Member
    $('#membersTable').on('click', '.view-member', function() {
        const memberId = $(this).data('id');
        
        $.get(`/admin/members/${memberId}`, function(response) {
            if (response.success) {
                const member = response.data;
                
                // Set modal title
                $('#viewMemberModalLabel').text(`Member: ${member.first_name} ${member.last_name}`);
                
                // Set profile image
                if (member.profile_image) {
                    $('#viewProfileImage').attr('src', `/storage/${member.profile_image}`);
                } else {
                    $('#viewProfileImage').attr('src', 'https://ui-avatars.com/api/?name=' + 
                        encodeURIComponent(`${member.first_name} ${member.last_name}`) + '&background=random');
                }
                
                // Set member name and status
                $('#viewMemberName').text(`${member.first_name} ${member.last_name}`);
                $('#viewMemberStatus').text(member.status.charAt(0).toUpperCase() + member.status.slice(1));
                $('#viewMemberStatus').removeClass('bg-success bg-danger bg-secondary')
                    .addClass(member.status === 'active' ? 'bg-success' : 
                             member.status === 'suspended' ? 'bg-danger' : 'bg-secondary');
                
                // Set other details
                $('#viewEmail').text(member.email || 'N/A');
                $('#viewPhone').text(member.phone || 'N/A');
                $('#viewDateOfBirth').text(member.date_of_birth ? new Date(member.date_of_birth).toLocaleDateString() : 'N/A');
                $('#viewJoinDate').text(member.join_date ? new Date(member.join_date).toLocaleDateString() : 'N/A');
                $('#viewMembershipExpiry').text(member.membership_expiry ? new Date(member.membership_expiry).toLocaleDateString() : 'N/A');
                $('#viewEmergencyContact').text(member.emergency_contact || 'N/A');
                $('#viewAddress').text(member.address || 'N/A');
                $('#viewHealthNotes').text(member.health_notes || 'N/A');
                
                $('#viewMemberModal').modal('show');
            } else {
                showToast('error', response.message || 'Failed to load member details');
            }
        }).fail(function() {
            showToast('error', 'Failed to load member details');
        });
    });

    // Edit Member - Load Data
    $('#membersTable').on('click', '.edit-member', function() {
        const memberId = $(this).data('id');
        
        $.get(`/admin/members/${memberId}/edit`, function(response) {
            if (response.success) {
                const member = response.data;
                
                // Set modal title
                $('#editMemberModalLabel').text(`Edit Member: ${member.first_name} ${member.last_name}`);
                
                // Fill form fields
                $('#editMemberId').val(member.id);
                $('#editFirstName').val(member.first_name);
                $('#editLastName').val(member.last_name);
                $('#editEmail').val(member.email);
                $('#editPhone').val(member.phone);
                $('#editDateOfBirth').val(member.date_of_birth);
                $('#editJoinDate').val(member.join_date);
                $('#editMembershipExpiry').val(member.membership_expiry);
                $('#editAddress').val(member.address);
                $('#editEmergencyContact').val(member.emergency_contact);
                $('#editHealthNotes').val(member.health_notes);
                $('#editStatus').val(member.status);
                
                // Show current profile image
                if (member.profile_image) {
                    $('#currentImageContainer').html(`
                        <p class="mb-1">Current Image:</p>
                        <img src="/storage/${member.profile_image}" class="img-thumbnail" style="max-width: 150px;">
                    `);
                } else {
                    $('#currentImageContainer').html(`
                        <p class="mb-1">No profile image</p>
                    `);
                }
                
                $('#editMemberModal').modal('show');
            } else {
                showToast('error', response.message || 'Failed to load member details for editing');
            }
        }).fail(function() {
            showToast('error', 'Failed to load member details for editing');
        });
    });

    // Update Member
    $('#updateMemberBtn').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($('#editMemberForm')[0]);
        const memberId = $('#editMemberId').val();
        
        $.ajax({
            url: `/admin/members/${memberId}`,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            headers: {
                'X-HTTP-Method-Override': 'PUT'
            },
            success: function(response) {
                if (response.success) {
                    showToast('success', 'Member updated successfully');
                    $('#editMemberModal').modal('hide');
                    membersTable.ajax.reload();
                } else {
                    showToast('error', response.message || 'Failed to update member');
                }
            },
            error: function(xhr) {
                const errorMsg = xhr.responseJSON?.message || 'An error occurred while updating member';
                showToast('error', errorMsg);
            },
            complete: function() {
                btn.prop('disabled', false);
                btn.find('.spinner-border').addClass('d-none');
                btn.find('.btn-text').text('Update Member');
            }
        });
    });
    $.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

    // Delete Member - Confirmation
    $('#membersTable').on('click', '.delete-member', function() {
        const memberId = $(this).data('id');
        $('#deleteMemberId').val(memberId);
        $('#deleteConfirmationModal').modal('show');
    });

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

        const memberId = $('#deleteMemberId').val();
        
        $.ajax({
            url: `/admin/members/${memberId}`,
            type: 'DELETE',
            success: function(response) {
                if (response.success) {
                    showToast('success', 'Member deleted successfully');
                    $('#deleteConfirmationModal').modal('hide');
                    membersTable.ajax.reload();
                } else {
                    showToast('error', response.message || 'Failed to delete member');
                }
            },
            error: function(xhr) {
                const errorMsg = xhr.responseJSON?.message || 'An error occurred while deleting member';
                showToast('error', errorMsg);
            },
            complete: function() {
                btn.prop('disabled', false);
                btn.text('Delete Member');
            }
        });
    });

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

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

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

    // Allow search on Enter key
    $('#searchInput').keypress(function(e) {
        if (e.which === 13) {
            membersTable.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>