<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-gradient-indigo text-white">
                    <h5 class="mb-0"><i class="fas fa-credit-card me-2"></i>Payments Management</h5>
                </div>
                <div class="card-body">
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <button class="btn btn-success" id="addPaymentBtn">
                                <i class="fas fa-plus-circle me-2"></i>Record New Payment
                            </button>
                            <div class="btn-group ms-2">
                                <button class="btn btn-outline-primary" id="exportPaymentsBtn">
                                    <i class="fas fa-file-export me-2"></i>Export
                                </button>
                                <button class="btn btn-outline-secondary" id="printPaymentsBtn">
                                    <i class="fas fa-print me-2"></i>Print
                                </button>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="input-group">
                                <input type="text" class="form-control" id="searchInput" placeholder="Search payments...">
                                <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">Payment Status</label>
                                            <select class="form-select" id="statusFilter">
                                                <option value="">All Statuses</option>
                                                <option value="completed">Completed</option>
                                                <option value="pending">Pending</option>
                                                <option value="failed">Failed</option>
                                                <option value="refunded">Refunded</option>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label for="typeFilter" class="form-label">Payment Type</label>
                                            <select class="form-select" id="typeFilter">
                                                <option value="">All Types</option>
                                                <option value="membership">Membership</option>
                                                <option value="class">Class</option>
                                                <option value="personal_training">Personal Training</option>
                                                <option value="other">Other</option>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label for="dateFrom" class="form-label">Date From</label>
                                            <input type="date" class="form-control" id="dateFrom">
                                        </div>
                                        <div class="col-md-3">
                                            <label for="dateTo" class="form-label">Date To</label>
                                            <input type="date" class="form-control" id="dateTo">
                                        </div>
                                        <div class="col-md-3">
                                            <label for="memberFilter" class="form-label">Member</label>
                                            <select class="form-select" id="memberFilter">
                                                <option value="">All Members</option>
                                                <!-- Will be populated dynamically -->
                                            </select>
                                        </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 Filters
                                            </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="paymentsTable" class="table table-hover table-striped" style="width:100%">
                            <thead class="bg-gradient-indigo text-white">
                                <tr>
                                    <th>ID</th>
                                    <th>Member</th>
                                    <th>Amount</th>
                                    <th>Payment Date</th>
                                    <th>Due Date</th>
                                    <th>Type</th>
                                    <th>Method</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Payment Modal -->
<div class="modal fade" id="addPaymentModal" tabindex="-1" aria-labelledby="addPaymentModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-gradient-indigo text-white">
                <h5 class="modal-title" id="addPaymentModalLabel">
                    <i class="fas fa-plus-circle me-2"></i>Record New Payment
                </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="addPaymentForm" class="needs-validation" novalidate>
                    <?php echo csrf_field(); ?>
                    <div class="row g-3">
                        <!-- Payment 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-info-circle me-2"></i>Payment Details</h6>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="memberId" class="form-label">Member <span class="text-danger">*</span></label>
                                        <select class="form-select" id="memberId" name="member_id" required>
                                            <option value="" disabled selected>Select Member</option>
                                            <!-- Will be populated dynamically -->
                                        </select>
                                        <div class="invalid-feedback">Please select a member</div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="amount" class="form-label">Amount ($) <span class="text-danger">*</span></label>
                                        <input type="number" class="form-control" id="amount" name="amount" min="0" step="0.01" required>
                                        <div class="invalid-feedback">Please enter a valid amount</div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="paymentDate" class="form-label">Payment Date <span class="text-danger">*</span></label>
                                        <input type="date" class="form-control" id="paymentDate" name="payment_date" required value="<?php echo e(date('Y-m-d')); ?>">
                                        <div class="invalid-feedback">Please select a payment date</div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="dueDate" class="form-label">Due Date</label>
                                        <input type="date" class="form-control" id="dueDate" name="due_date">
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Payment Method 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-credit-card me-2"></i>Payment Method</h6>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="paymentMethod" class="form-label">Payment Method <span class="text-danger">*</span></label>
                                        <select class="form-select" id="paymentMethod" name="payment_method" required>
                                            <option value="" disabled selected>Select Method</option>
                                            <option value="cash">Cash</option>
                                            <option value="credit_card">Credit Card</option>
                                            <option value="bank_transfer">Bank Transfer</option>
                                            <option value="other">Other</option>
                                        </select>
                                        <div class="invalid-feedback">Please select a payment method</div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="paymentType" class="form-label">Payment Type <span class="text-danger">*</span></label>
                                        <select class="form-select" id="paymentType" name="payment_type" required>
                                            <option value="" disabled selected>Select Type</option>
                                            <option value="membership">Membership</option>
                                            <option value="class">Class</option>
                                            <option value="personal_training">Personal Training</option>
                                            <option value="other">Other</option>
                                        </select>
                                        <div class="invalid-feedback">Please select a payment type</div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="transactionId" class="form-label">Transaction ID</label>
                                        <input type="text" class="form-control" id="transactionId" name="transaction_id">
                                    </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="completed" selected>Completed</option>
                                            <option value="pending">Pending</option>
                                            <option value="failed">Failed</option>
                                            <option value="refunded">Refunded</option>
                                        </select>
                                        <div class="invalid-feedback">Please select a status</div>
                                    </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-sticky-note me-2"></i>Additional Information</h6>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="notes" class="form-label">Notes</label>
                                        <textarea class="form-control" id="notes" name="notes" rows="3" placeholder="Any additional notes about this payment"></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="savePaymentBtn" 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">Record Payment</span>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Payment Modal -->
<div class="modal fade" id="editPaymentModal" tabindex="-1" aria-labelledby="editPaymentModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-gradient-indigo text-white">
                <h5 class="modal-title" id="editPaymentModalLabel">Edit Payment</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="editPaymentForm">
                    <input type="hidden" id="editPaymentId" name="id">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="editMemberId" class="form-label">Member *</label>
                                <select class="form-select" id="editMemberId" name="member_id" required>
                                    <!-- Will be populated dynamically -->
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="editAmount" class="form-label">Amount ($) *</label>
                                <input type="number" class="form-control" id="editAmount" name="amount" min="0" step="0.01" required>
                            </div>
                            <div class="mb-3">
                                <label for="editPaymentDate" class="form-label">Payment Date *</label>
                                <input type="date" class="form-control" id="editPaymentDate" name="payment_date" required>
                            </div>
                            <div class="mb-3">
                                <label for="editDueDate" class="form-label">Due Date</label>
                                <input type="date" class="form-control" id="editDueDate" name="due_date">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="editPaymentMethod" class="form-label">Payment Method *</label>
                                <select class="form-select" id="editPaymentMethod" name="payment_method" required>
                                    <option value="cash">Cash</option>
                                    <option value="credit_card">Credit Card</option>
                                    <option value="bank_transfer">Bank Transfer</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="editPaymentType" class="form-label">Payment Type *</label>
                                <select class="form-select" id="editPaymentType" name="payment_type" required>
                                    <option value="membership">Membership</option>
                                    <option value="class">Class</option>
                                    <option value="personal_training">Personal Training</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="editTransactionId" class="form-label">Transaction ID</label>
                                <input type="text" class="form-control" id="editTransactionId" name="transaction_id">
                            </div>
                            <div class="mb-3">
                                <label for="editStatus" class="form-label">Status *</label>
                                <select class="form-select" id="editStatus" name="status" required>
                                    <option value="completed">Completed</option>
                                    <option value="pending">Pending</option>
                                    <option value="failed">Failed</option>
                                    <option value="refunded">Refunded</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="editNotes" class="form-label">Notes</label>
                        <textarea class="form-control" id="editNotes" name="notes" 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="updatePaymentBtn" class="btn btn-primary">
                    <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                    <span class="btn-text">Update Payment</span>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- View Payment Modal -->
<div class="modal fade" id="viewPaymentModal" tabindex="-1" aria-labelledby="viewPaymentModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-gradient-indigo text-white">
                <h5 class="modal-title" id="viewPaymentModalLabel">Payment 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="payment-icon-container">
                            <i class="fas fa-receipt" style="font-size: 5rem; color: #4e73df;"></i>
                        </div>
                        <h4 id="viewPaymentId" class="mb-1"></h4>
                        <span class="badge" id="viewPaymentStatus"></span>
                        <p class="text-muted" id="viewPaymentType"></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">Member</label>
                                    <p id="viewMemberName" class="form-control-static"></p>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Amount</label>
                                    <p id="viewAmount" class="form-control-static"></p>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Payment Method</label>
                                    <p id="viewPaymentMethod" class="form-control-static"></p>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Payment Date</label>
                                    <p id="viewPaymentDate" class="form-control-static"></p>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Due Date</label>
                                    <p id="viewDueDate" class="form-control-static"></p>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Transaction ID</label>
                                    <p id="viewTransactionId" class="form-control-static"></p>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Notes</label>
                            <p id="viewNotes" 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>
                <button type="button" class="btn btn-primary" id="printReceiptBtn">
                    <i class="fas fa-print me-2"></i>Print Receipt
                </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 payment record? This action cannot be undone.</p>
                <input type="hidden" id="deletePaymentId">
            </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 Payment</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">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
    /* Custom Color Scheme */
    .bg-gradient-indigo {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
    }
    
    .btn-primary {
        background-color: #4e73df;
        border-color: #4e73df;
    }
    
    .btn-primary:hover {
        background-color: #2e59d9;
        border-color: #2653d4;
    }
    
    .btn-success {
        background-color: #1cc88a;
        border-color: #1cc88a;
    }
    
    .btn-success:hover {
        background-color: #17a673;
        border-color: #169b6b;
    }
    
    .btn-danger {
        background-color: #e74a3b;
        border-color: #e74a3b;
    }
    
    .btn-danger:hover {
        background-color: #d52a1a;
        border-color: #ca2819;
    }
    
    .btn-warning {
        background-color: #f6c23e;
        border-color: #f6c23e;
    }
    
    .btn-warning:hover {
        background-color: #dda20a;
        border-color: #d5990b;
    }
    
    /* Status Badges */
    .badge.bg-success {
        background-color: #1cc88a !important;
    }
    
    .badge.bg-warning {
        background-color: #f6c23e !important;
        color: #1a1a1a;
    }
    
    .badge.bg-danger {
        background-color: #e74a3b !important;
    }
    
    .badge.bg-secondary {
        background-color: #858796 !important;
    }
    
    /* Table Styling */
    .table thead th {
        border-bottom: none;
    }
    
    .table-hover tbody tr:hover {
        background-color: rgba(78, 115, 223, 0.05);
    }
    
    /* Card Styling */
    .card {
        border-radius: 0.5rem;
        box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
    }
    
    .card-header {
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    }
    
    /* Form Styling */
    .form-control, .form-select {
        border-radius: 0.35rem;
    }
    
    /* Filter Card */
    .filter-card {
        background-color: #f8f9fc;
        border: 1px solid #e3e6f0;
    }
    
    /* Payment Icon Container */
    .payment-icon-container {
        border: 3px solid #e3e6f0;
        border-radius: 50%;
        padding: 20px;
        display: inline-block;
        width: 120px;
        height: 120px;
        line-height: 70px;
        background-color: #f8f9fc;
    }
    
    /* Responsive Adjustments */
    @media (max-width: 768px) {
        .payment-icon-container {
            width: 90px;
            height: 90px;
            line-height: 50px;
        }
        
        .payment-icon-container i {
            font-size: 3rem !important;
        }
    }
    
    /* Toast Notifications */
    .toast {
        z-index: 1100;
    }
    
    /* DataTables Buttons */
    .dataTables_wrapper .dt-buttons {
        margin-bottom: 1rem;
    }
    
    .dt-buttons .btn {
        border-radius: 0.35rem;
        margin-right: 0.5rem;
    }
    
    /* Modal Header Gradient */
    .modal-header.bg-gradient-indigo {
        border-bottom: none;
    }
</style>
<meta name="csrf-token" content="<?php echo e(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>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.colVis.min.js"></script>


<script>
  $(document).ready(function() {
    // Initialize DataTable
    const paymentsTable = $('#paymentsTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: "/admin/payments/list",
            type: 'GET',
            data: function(d) {
                return {
                    ...d,
                    status: $('#statusFilter').val(),
                    type: $('#typeFilter').val(),
                    dateFrom: $('#dateFrom').val(),
                    dateTo: $('#dateTo').val(),
                    memberId: $('#memberFilter').val(),
                    search: $('#searchInput').val()
                };
            },
            error: function(xhr, error, thrown) {
                console.error('DataTables error:', xhr, error, thrown);
                showToast('error', 'Failed to load payments data');
            }
        },
        columns: [
            { data: 'id' },
            { 
                data: 'member',
                render: function(data, type, row) {
                    return data ? `${data.first_name} ${data.last_name}` : 'N/A';
                }
            },
            { 
                data: 'amount',
                render: function(data) {
                    return `$${parseFloat(data).toFixed(2)}`;
                }
            },
            { 
                data: 'payment_date',
                render: function(data) {
                    return data ? new Date(data).toLocaleDateString() : 'N/A';
                }
            },
            { 
                data: 'due_date',
                render: function(data) {
                    return data ? new Date(data).toLocaleDateString() : 'N/A';
                }
            },
            { 
                data: 'payment_type',
                render: function(data) {
                    const types = {
                        'membership': 'Membership',
                        'class': 'Class',
                        'personal_training': 'Personal Training',
                        'other': 'Other'
                    };
                    return types[data] || data;
                }
            },
            { 
                data: 'payment_method',
                render: function(data) {
                    const methods = {
                        'cash': 'Cash',
                        'credit_card': 'Credit Card',
                        'bank_transfer': 'Bank Transfer',
                        'other': 'Other'
                    };
                    return methods[data] || data;
                }
            },
            { 
                data: 'status',
                render: function(data) {
                    let badgeClass = 'bg-secondary';
                    if (data === 'completed') badgeClass = 'bg-success';
                    else if (data === 'pending') badgeClass = 'bg-warning';
                    else if (data === 'failed') badgeClass = 'bg-danger';
                    
                    return `<span class="badge ${badgeClass}">${data.charAt(0).toUpperCase() + data.slice(1)}</span>`;
                }
            },
            {
                data: 'id',
                orderable: false,
                render: function(data, type, row) {
                    return `
                        <div class="btn-group">
                            <button class="btn btn-sm btn-primary view-payment" data-id="${data}" title="View">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn btn-sm btn-warning edit-payment" data-id="${data}" title="Edit">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn btn-sm btn-danger delete-payment" data-id="${data}" title="Delete">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    `;
                }
            }
        ],
        dom: '<"row"<"col-md-6"B><"col-md-6"f>>rt<"row"<"col-md-6"i><"col-md-6"p>>',
        buttons: [
            {
                extend: 'copy',
                className: 'btn btn-sm btn-outline-secondary'
            },
            {
                extend: 'csv',
                className: 'btn btn-sm btn-outline-primary'
            },
            {
                extend: 'excel',
                className: 'btn btn-sm btn-outline-success'
            },
            {
                extend: 'pdf',
                className: 'btn btn-sm btn-outline-danger'
            },
            {
                extend: 'print',
                className: 'btn btn-sm btn-outline-info'
            },
            {
                extend: 'colvis',
                className: 'btn btn-sm btn-outline-dark'
            }
        ],
        drawCallback: function(settings) {
            // Re-initialize tooltips after table redraw
            $('[title]').tooltip({
                trigger: 'hover',
                placement: 'top'
            });
        }
    });

    // Load active members for dropdowns
    function loadActiveMembers() {
        $.get('/admin/members/active')
            .done(function(response) {
                // Populate member dropdown in add payment modal
                $('#memberId').empty().append('<option value="" disabled selected>Select Member</option>');
                response.forEach(member => {
                    $('#memberId').append(`<option value="${member.id}">${member.first_name} ${member.last_name}</option>`);
                });
                
                // Populate member filter dropdown
                $('#memberFilter').empty().append('<option value="">All Members</option>');
                response.forEach(member => {
                    $('#memberFilter').append(`<option value="${member.id}">${member.first_name} ${member.last_name}</option>`);
                });
            })
            .fail(function(xhr) {
                console.error('Failed to load members:', xhr);
                showToast('error', 'Failed to load member data');
            });
    }
    
    // Load active members when page loads
    loadActiveMembers();

    // Add Payment Modal Show
    $('#addPaymentBtn').click(function() {
        $('#addPaymentModal').modal('show');
    });

    // Save Payment Form
    $('#savePaymentBtn').click(function() {
        const form = $('#addPaymentForm')[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...');

        $.ajax({
            url: "/admin/payments",
            type: "POST",
            data: $('#addPaymentForm').serialize(),
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    showToast('success', 'Payment recorded successfully');
                    $('#addPaymentModal').modal('hide');
                    paymentsTable.ajax.reload(null, false);
                    form.reset();
                    form.classList.remove('was-validated');
                } else {
                    showToast('error', response.message || 'Failed to record payment');
                }
            },
            error: function(xhr) {
                let errorMsg = 'An error occurred while recording payment';
                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('Record Payment');
            }
        });
    });

    // View Payment
    $(document).on('click', '.view-payment', function() {
        const paymentId = $(this).data('id');
        
        $.get(`/admin/payments/${paymentId}`)
            .done(function(response) {
                if (response.success) {
                    const payment = response.data;
                    
                    // Set modal title
                    $('#viewPaymentModalLabel').text(`Payment #${payment.id}`);
                    
                    // Set payment details
                    $('#viewPaymentId').text(`Payment #${payment.id}`);
                    $('#viewPaymentStatus').text(payment.status.charAt(0).toUpperCase() + payment.status.slice(1));
                    $('#viewPaymentStatus').removeClass('bg-success bg-warning bg-danger bg-secondary')
                        .addClass(
                            payment.status === 'completed' ? 'bg-success' :
                            payment.status === 'pending' ? 'bg-warning' :
                            payment.status === 'failed' ? 'bg-danger' : 'bg-secondary'
                        );
                    
                    const paymentTypes = {
                        'membership': 'Membership',
                        'class': 'Class',
                        'personal_training': 'Personal Training',
                        'other': 'Other'
                    };
                    $('#viewPaymentType').text(paymentTypes[payment.payment_type] || payment.payment_type);
                    
                    // Set other details
                    $('#viewMemberName').text(payment.member ? `${payment.member.first_name} ${payment.member.last_name}` : 'N/A');
                    $('#viewAmount').text(`$${parseFloat(payment.amount).toFixed(2)}`);
                    
                    const paymentMethods = {
                        'cash': 'Cash',
                        'credit_card': 'Credit Card',
                        'bank_transfer': 'Bank Transfer',
                        'other': 'Other'
                    };
                    $('#viewPaymentMethod').text(paymentMethods[payment.payment_method] || payment.payment_method);
                    
                    $('#viewPaymentDate').text(payment.payment_date ? new Date(payment.payment_date).toLocaleDateString() : 'N/A');
                    $('#viewDueDate').text(payment.due_date ? new Date(payment.due_date).toLocaleDateString() : 'N/A');
                    $('#viewTransactionId').text(payment.transaction_id || 'N/A');
                    $('#viewNotes').text(payment.notes || 'N/A');
                    
                    $('#viewPaymentModal').modal('show');
                } else {
                    showToast('error', response.message || 'Failed to load payment details');
                }
            })
            .fail(function(xhr) {
                console.error('Failed to load payment:', xhr);
                showToast('error', 'Failed to load payment details');
            });
    });

    // Edit Payment - Load Data
    $(document).on('click', '.edit-payment', function() {
        const paymentId = $(this).data('id');
        
        $.get(`/admin/payments/${paymentId}/edit`)
            .done(function(response) {
                if (response.success) {
                    const payment = response.data;
                    
                    // Set modal title
                    $('#editPaymentModalLabel').text(`Edit Payment #${payment.id}`);
                    
                    // Fill form fields
                    $('#editPaymentId').val(payment.id);
                    $('#editAmount').val(payment.amount);
                    $('#editPaymentDate').val(payment.payment_date);
                    $('#editDueDate').val(payment.due_date || '');
                    $('#editTransactionId').val(payment.transaction_id || '');
                    $('#editNotes').val(payment.notes || '');
                    $('#editPaymentMethod').val(payment.payment_method);
                    $('#editPaymentType').val(payment.payment_type);
                    $('#editStatus').val(payment.status);
                    
                    // Clear and populate member dropdown
                    $('#editMemberId').empty();
                    
                    // First add the current member if exists
                    if (payment.member) {
                        $('#editMemberId').append(`<option value="${payment.member.id}">${payment.member.first_name} ${payment.member.last_name}</option>`);
                    }
                    
                    // Then load all active members
                    $.get('/admin/members/active')
                        .done(function(members) {
                            members.forEach(member => {
                                if (!payment.member || member.id !== payment.member.id) {
                                    $('#editMemberId').append(`<option value="${member.id}">${member.first_name} ${member.last_name}</option>`);
                                }
                            });
                            
                            // Set selected value
                            if (payment.member) {
                                $('#editMemberId').val(payment.member.id);
                            }
                        })
                        .fail(function(xhr) {
                            console.error('Failed to load members:', xhr);
                        });
                    
                    $('#editPaymentModal').modal('show');
                } else {
                    showToast('error', response.message || 'Failed to load payment details');
                }
            })
            .fail(function(xhr) {
                console.error('Failed to load payment:', xhr);
                showToast('error', 'Failed to load payment details');
            });
    });

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

        const paymentId = $('#editPaymentId').val();
        
        $.ajax({
            url: `/admin/payments/${paymentId}`,
            type: 'PUT',
            data: $('#editPaymentForm').serialize(),
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    showToast('success', 'Payment updated successfully');
                    $('#editPaymentModal').modal('hide');
                    paymentsTable.ajax.reload(null, false);
                } else {
                    showToast('error', response.message || 'Failed to update payment');
                }
            },
            error: function(xhr) {
                let errorMsg = 'An error occurred while updating payment';
                if (xhr.responseJSON) {
                    if (xhr.responseJSON.errors) {
                        errorMsg = Object.values(xhr.responseJSON.errors).join('<br>');
                    } else if (xhr.responseJSON.message) {
                        errorMsg = xhr.responseJSON.message;
                    }
                }
                showToast('error', errorMsg);
                console.error('Update error:', xhr.responseJSON);
            },
            complete: function() {
                btn.prop('disabled', false);
                btn.find('.spinner-border').addClass('d-none');
                btn.find('.btn-text').text('Update Payment');
            }
        });
    });

    // Delete Payment - Confirmation
    $(document).on('click', '.delete-payment', function() {
        const paymentId = $(this).data('id');
        $('#deletePaymentId').val(paymentId);
        $('#deleteConfirmationModal').modal('show');
    });

    // Confirm Delete
    $('#confirmDeleteBtn').click(function() {
        const btn = $(this);
        btn.prop('disabled', true);
        btn.html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Deleting...');

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

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

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

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

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

    // Export Payments
    $('#exportPaymentsBtn').click(function() {
        paymentsTable.button('.buttons-excel').trigger();
    });

    // Print Payments
    $('#printPaymentsBtn').click(function() {
        paymentsTable.button('.buttons-print').trigger();
    });

    // Print Receipt
    $('#printReceiptBtn').click(function() {
        // Implement receipt printing logic here
        const printContent = $('#viewPaymentModal .modal-body').html();
        const originalContent = $('body').html();
        
        $('body').html(printContent);
        window.print();
        $('body').html(originalContent);
    });

    // Helper function to show toast notifications
    function showToast(type, message) {
        const toastId = 'toast-' + Date.now();
        const toast = $(`
            <div id="${toastId}" 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();
        });
        
        // Auto-hide after 5 seconds
        setTimeout(() => {
            bsToast.hide();
        }, 5000);
    }

    // Initialize date inputs with max date today
    const today = new Date().toISOString().split('T')[0];
    $('input[type="date"]').attr('max', today);
    
    // Initialize tooltips
    $('[title]').tooltip({
        trigger: 'hover',
        placement: 'top'
    });
});
</script><?php /**PATH C:\laravel projects\gym-management-system\resources\views/admin/pages/payments.blade.php ENDPATH**/ ?>