 <meta name="csrf-token" content="{{ csrf_token() }}">

<div class="dashboard-container">

    <!-- Quick Action Cards -->
    <div class="row quick-actions mb-4">
        <div class="col-md-3">
            <div class="card quick-action-card" data-bs-toggle="modal" data-bs-target="#addMemberModal">
                <div class="card-body text-center">
                    <div class="action-icon bg-primary">
                        <i class="fas fa-user-plus"></i>
                    </div>
                    <h5 class="action-title">Add Member</h5>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card quick-action-card" data-bs-toggle="modal" data-bs-target="#addTrainerModal">
                <div class="card-body text-center">
                    <div class="action-icon bg-success">
                        <i class="fas fa-chalkboard-teacher"></i>
                    </div>
                    <h5 class="action-title">Add Trainer</h5>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card quick-action-card" data-bs-toggle="modal" data-bs-target="#addClassModal">
                <div class="card-body text-center">
                    <div class="action-icon bg-info">
                        <i class="fas fa-calendar-plus"></i>
                    </div>
                    <h5 class="action-title">Add Class</h5>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card quick-action-card" data-bs-toggle="modal" data-bs-target="#addPaymentModal">
                <div class="card-body text-center">
                    <div class="action-icon bg-warning">
                        <i class="fas fa-money-bill-wave"></i>
                    </div>
                    <h5 class="action-title">Record Payment</h5>
                </div>
            </div>
        </div>
    </div>

    <!-- Stats Overview -->
    <div class="row stats-overview mb-4">
        <div class="col-md-3">
            <div class="card stat-card">
                <div class="card-body">
                    <div class="stat-icon">
                        <i class="fas fa-users"></i>
                    </div>
                    <div class="stat-content">
                        <h3 class="stat-value" id="totalMembers">0</h3>
                        <p class="stat-label">Total Members</p>
                        <div class="stat-change" id="memberChange">
                            <i class="fas fa-arrow-up text-success"></i>
                            <span>0%</span> from last month
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card stat-card">
                <div class="card-body">
                    <div class="stat-icon">
                        <i class="fas fa-user-check"></i>
                    </div>
                    <div class="stat-content">
                        <h3 class="stat-value" id="activeMembers">0</h3>
                        <p class="stat-label">Active Members</p>
                        <div class="stat-change">
                            <i class="fas fa-dumbbell text-primary"></i>
                            <span id="activeCheckins">0</span> checked in now
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card stat-card">
                <div class="card-body">
                    <div class="stat-icon">
                        <i class="fas fa-chalkboard-teacher"></i>
                    </div>
                    <div class="stat-content">
                        <h3 class="stat-value" id="totalTrainers">0</h3>
                        <p class="stat-label">Trainers</p>
                        <div class="stat-change">
                            <i class="fas fa-calendar-alt text-info"></i>
                            <span id="upcomingClassesCount">0</span> classes today
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card stat-card">
                <div class="card-body">
                    <div class="stat-icon">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                    <div class="stat-content">
                        <h3 class="stat-value" id="monthlyRevenue">$0</h3>
                        <p class="stat-label">Monthly Revenue</p>
                        <div class="stat-change">
                            <i class="fas fa-chart-line text-warning"></i>
                            <span id="revenueTrend">0%</span> from last month
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Checkin/Checkout Section -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="card-title">Member Check-In</h5>
                </div>
                <div class="card-body">
                    <div class="input-group mb-3">
                        <input type="text" class="form-control" id="checkinSearch" placeholder="Search member...">
                        <button class="btn btn-primary" id="checkinBtn">Check In</button>
                    </div>
                    <div id="checkinResults" class="list-group" style="max-height: 200px; overflow-y: auto;"></div>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="card-title">Currently Checked In</h5>
                    <button class="btn btn-sm btn-outline-primary" id="refreshCheckedIn">Refresh</button>
                </div>
                <div class="card-body">
                    <div id="checkedInList" class="list-group" style="max-height: 200px; overflow-y: auto;">
                        <div class="text-center py-4">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                        </div>
                    </div>
                    <div class="mt-2">
                        <button class="btn btn-sm btn-info w-100" id="viewDailyAttendance">
                            <i class="fas fa-chart-bar"></i> View Daily Attendance
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content Row -->
    <div class="row">
        <!-- Left Column -->
        <div class="col-lg-8">
            <!-- Revenue Chart -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="card-title">Monthly Revenue</h5>
                    <div class="chart-period">
                        <button class="btn btn-sm btn-outline-secondary active" data-period="monthly">Monthly</button>
                        <button class="btn btn-sm btn-outline-secondary" data-period="yearly">Yearly</button>
                    </div>
                </div>
                <div class="card-body">
                    <canvas id="revenueChart" height="250"></canvas>
                </div>
            </div>

            <!-- Members Growth Chart -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="card-title">Members Growth</h5>
                    <div class="chart-period">
                        <button class="btn btn-sm btn-outline-secondary active" data-period="monthly">30 Days</button>
                        <button class="btn btn-sm btn-outline-secondary" data-period="yearly">12 Months</button>
                    </div>
                </div>
                <div class="card-body">
                    <canvas id="membersChart" height="250"></canvas>
                </div>
            </div>
        </div>

        <!-- Right Column -->
        <div class="col-lg-4">
            <!-- Classes Distribution -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="card-title">Classes Distribution</h5>
                </div>
                <div class="card-body">
                    <canvas id="classesChart" height="250"></canvas>
                </div>
            </div>

            <!-- Upcoming Classes -->
            <div class="card mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="card-title">Upcoming Classes</h5>
                    <a href="#" data-page="/admin/pages/classes" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="card-body p-0">
                    <div class="upcoming-classes-list" id="upcomingClassesList">
                        <!-- Classes will be loaded here -->
                        <div class="text-center py-4">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Equipment Status -->
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="card-title">Equipment Status</h5>
                    <a href="#" data-page="/admin/pages/equipment" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="card-body">
                    <div class="equipment-stats">
                        <div class="equipment-stat-item">
                            <div class="stat-label">Total Equipment</div>
                            <div class="stat-value" id="totalEquipment">0</div>
                        </div>
                        <div class="equipment-stat-item">
                            <div class="stat-label">Needs Maintenance</div>
                            <div class="stat-value text-danger" id="maintenanceNeeded">0</div>
                        </div>
                        <div class="equipment-conditions mt-3">
                            <div class="condition-item">
                                <span class="condition-dot bg-success"></span>
                                <span>Excellent: <span id="excellentCount">0</span></span>
                            </div>
                            <div class="condition-item">
                                <span class="condition-dot bg-primary"></span>
                                <span>Good: <span id="goodCount">0</span></span>
                            </div>
                            <div class="condition-item">
                                <span class="condition-dot bg-warning"></span>
                                <span>Needs Maintenance: <span id="needsMaintenanceCount">0</span></span>
                            </div>
                            <div class="condition-item">
                                <span class="condition-dot bg-danger"></span>
                                <span>Out of Service: <span id="outOfServiceCount">0</span></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Daily Attendance Modal -->
<div class="modal fade" id="dailyAttendanceModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Daily Attendance - <span id="attendanceDate"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>Member</th>
                                <th>Check-In Time</th>
                                <th>Check-Out Time</th>
                                <th>Duration</th>
                            </tr>
                        </thead>
                        <tbody id="attendanceList">
                            <!-- Attendance data will be loaded here -->
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </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">
                <h5 class="modal-title" id="addMemberModalLabel">Add New Member</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addMemberForm" enctype="multipart/form-data">
                    @csrf
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="firstName" class="form-label">First Name *</label>
                                <input type="text" class="form-control" id="firstName" name="first_name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="lastName" class="form-label">Last Name *</label>
                                <input type="text" class="form-control" id="lastName" name="last_name" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="email" class="form-label">Email *</label>
                                <input type="email" class="form-control" id="email" name="email" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="phone" class="form-label">Phone</label>
                                <input type="tel" class="form-control" id="phone" name="phone">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <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">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="joinDate" class="form-label">Join Date *</label>
                                <input type="date" class="form-control" id="joinDate" name="join_date" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <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>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="status" class="form-label">Status *</label>
                                <select class="form-select" id="status" 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="address" class="form-label">Address</label>
                        <input type="text" class="form-control" id="address" name="address">
                    </div>
                    <div class="row">
                        <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-md-6">
                            <div class="mb-3">
                                <label for="healthNotes" class="form-label">Health Notes</label>
                                <input type="text" class="form-control" id="healthNotes" name="health_notes">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="profileImage" class="form-label">Profile Image</label>
                        <input type="file" class="form-control" id="profileImage" name="profile_image" accept="image/*">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="saveMemberBtn">Save Member</button>
            </div>
        </div>
    </div>
</div>

<!-- Add Trainer Modal -->
<div class="modal fade" id="addTrainerModal" tabindex="-1" aria-labelledby="addTrainerModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addTrainerModalLabel">Add New Trainer</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addTrainerForm" enctype="multipart/form-data">
                    @csrf
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="trainerFirstName" class="form-label">First Name *</label>
                                <input type="text" class="form-control" id="trainerFirstName" name="first_name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="trainerLastName" class="form-label">Last Name *</label>
                                <input type="text" class="form-control" id="trainerLastName" name="last_name" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="trainerEmail" class="form-label">Email *</label>
                                <input type="email" class="form-control" id="trainerEmail" name="email" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="trainerPhone" class="form-label">Phone</label>
                                <input type="tel" class="form-control" id="trainerPhone" name="phone">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="specialization" class="form-label">Specialization *</label>
                        <input type="text" class="form-control" id="specialization" name="specialization" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="hireDate" class="form-label">Hire Date *</label>
                                <input type="date" class="form-control" id="hireDate" name="hire_date" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="trainerStatus" class="form-label">Status *</label>
                                <select class="form-select" id="trainerStatus" name="status" required>
                                    <option value="active">Active</option>
                                    <option value="inactive">Inactive</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="certifications" class="form-label">Certifications</label>
                        <textarea class="form-control" id="certifications" name="certifications" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="trainerProfileImage" class="form-label">Profile Image</label>
                        <input type="file" class="form-control" id="trainerProfileImage" name="profile_image" accept="image/*">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="saveTrainerBtn">Save Trainer</button>
            </div>
        </div>
    </div>
</div>

<!-- Add Class Modal -->
<div class="modal fade" id="addClassModal" tabindex="-1" aria-labelledby="addClassModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addClassModalLabel">Add New Class</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addClassForm">
                    @csrf
                    <div class="mb-3">
                        <label for="className" class="form-label">Class Name *</label>
                        <input type="text" class="form-control" id="className" name="name" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="classTrainer" class="form-label">Trainer *</label>
                                <select class="form-select" id="classTrainer" name="trainer_id" required>
                                    <option value="">Select Trainer</option>
                                    <!-- Trainers will be loaded here -->
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="classCapacity" class="form-label">Max Capacity *</label>
                                <input type="number" class="form-control" id="classCapacity" name="max_capacity" min="1" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="classDate" class="form-label">Date *</label>
                                <input type="date" class="form-control" id="classDate" name="class_date" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="classTime" class="form-label">Time *</label>
                                <input type="time" class="form-control" id="classTime" name="class_time" required>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="classDuration" class="form-label">Duration (minutes) *</label>
                        <input type="number" class="form-control" id="classDuration" name="duration_minutes" min="15" required>
                    </div>
                    <div class="mb-3">
                        <label for="classDescription" class="form-label">Description</label>
                        <textarea class="form-control" id="classDescription" name="description" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="classStatus" class="form-label">Status</label>
                        <select class="form-select" id="classStatus" name="status">
                            <option value="active">Active</option>
                            <option value="cancelled">Cancelled</option>
                            <option value="completed">Completed</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="saveClassBtn">Save Class</button>
            </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">
                <h5 class="modal-title" id="addPaymentModalLabel">Record Payment</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addPaymentForm">
                    @csrf
                    <div class="mb-3">
                        <label for="paymentMember" class="form-label">Member *</label>
                        <select class="form-select" id="paymentMember" name="member_id" required>
                            <option value="">Select Member</option>
                            <!-- Members will be loaded here -->
                        </select>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="paymentAmount" class="form-label">Amount *</label>
                                <input type="number" class="form-control" id="paymentAmount" name="amount" min="0" step="0.01" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="paymentDate" class="form-label">Payment Date *</label>
                                <input type="date" class="form-control" id="paymentDate" name="payment_date" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="paymentType" class="form-label">Payment Type *</label>
                                <select class="form-select" id="paymentType" 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>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="paymentMethod" class="form-label">Payment Method *</label>
                                <select class="form-select" id="paymentMethod" 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>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <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 class="col-md-6">
                            <div class="mb-3">
                                <label for="paymentStatus" class="form-label">Status *</label>
                                <select class="form-select" id="paymentStatus" name="status" required>
                                    <option value="pending">Pending</option>
                                    <option value="completed">Completed</option>
                                    <option value="failed">Failed</option>
                                    <option value="refunded">Refunded</option>
                                </select>
                            </div>
                        </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="paymentNotes" class="form-label">Notes</label>
                        <textarea class="form-control" id="paymentNotes" name="notes" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="savePaymentBtn">Record Payment</button>
            </div>
        </div>
    </div>
</div>

<!-- Include Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>

<!-- Include Toastr for notifications -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

<script>
   // Global chart variables
let revenueChart, membersChart, classesChart;

$(document).ready(function() {
    // Load dashboard stats
    loadDashboardStats();
    
    // Initialize modals
    initAddMemberModal();
    initAddTrainerModal();
    initAddClassModal();
    initAddPaymentModal();
    
    // Initialize checkin/checkout system
    initCheckinSystem();
    
    // Set default dates in forms
    setDefaultDates();
});

function loadDashboardStats() {
    console.log('Loading dashboard statistics...'); // Debug log
    
    $.ajax({
        url: '/admin/stats',
        method: 'GET',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function(response) {
            console.log('API Response:', response); // Debug log
            
            if (response && response.success) {
                const data = response.data || {};
                
                // Debug log the received data
                console.log('Monthly Revenue Raw:', data.monthly_revenue);
                console.log('Revenue Trend Data:', data.revenue_trend);
                
                // Update basic stats with proper null checks
                $('#totalMembers').text(data.total_members || 0);
                $('#activeMembers').text(data.active_members || 0);
                $('#totalTrainers').text(data.total_trainers || 0);
                $('#activeCheckins').text(data.active_checkins || 0);
                $('#upcomingClassesCount').text(data.classes_today || 0);
                
                // Enhanced revenue handling
                try {
                    let monthlyRevenue = 0;
                    
                    // Handle different possible formats of monthly_revenue
                    if (typeof data.monthly_revenue === 'string') {
                        monthlyRevenue = parseFloat(data.monthly_revenue.replace(/[^0-9.-]/g, '')) || 0;
                    } else if (typeof data.monthly_revenue === 'number') {
                        monthlyRevenue = data.monthly_revenue;
                    }
                    
                    // Format with proper currency display
                    const formattedRevenue = new Intl.NumberFormat('en-US', {
                        style: 'currency',
                        currency: 'USD',
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2
                    }).format(monthlyRevenue);
                    
                    $('#monthlyRevenue').text(formattedRevenue);
                    console.log('Formatted Revenue:', formattedRevenue); // Debug log
                    
                } catch (e) {
                    console.error('Error formatting revenue:', e);
                    $('#monthlyRevenue').text('$0.00');
                }
                
                // Update member change percentage
                const changeElement = $('#memberChange');
                const memberChange = parseFloat(data.member_change) || 0;
                const trendElement = changeElement.find('span');
                const iconElement = changeElement.find('i');
                
                trendElement.text(Math.abs(memberChange) + '%');
                
                // Reset all classes first
                iconElement.removeClass('fa-arrow-up fa-arrow-down fa-equals text-success text-danger text-secondary');
                
                // Set appropriate classes based on value
                if (memberChange > 0) {
                    iconElement.addClass('fa-arrow-up text-success');
                } else if (memberChange < 0) {
                    iconElement.addClass('fa-arrow-down text-danger');
                } else {
                    iconElement.addClass('fa-equals text-secondary');
                }
                
                // Update equipment stats with optional chaining
                const equipmentStats = data.equipment_stats || {};
                $('#totalEquipment').text(equipmentStats.total || 0);
                $('#maintenanceNeeded').text(equipmentStats.needs_maintenance || 0);
                
                const conditions = equipmentStats.by_condition || {};
                $('#excellentCount').text(conditions.excellent || 0);
                $('#goodCount').text(conditions.good || 0);
                $('#needsMaintenanceCount').text(conditions.needs_maintenance || 0);
                $('#outOfServiceCount').text(conditions.out_of_service || 0);
                
                // Initialize charts with proper checks
                try {
                    if (data.revenue_trend && Array.isArray(data.revenue_trend)) {
                        initRevenueChart(data.revenue_trend);
                    } else {
                        console.warn('Invalid revenue trend data:', data.revenue_trend);
                    }
                    
                    if (data.members_chart && data.members_chart.labels && data.members_chart.data) {
                        initMembersChart(data.members_chart);
                    } else {
                        console.warn('Invalid members chart data:', data.members_chart);
                    }
                    
                    if (data.classes_stats && data.classes_stats.top_classes) {
                        initClassesChart(data.classes_stats);
                    } else {
                        console.warn('Invalid classes stats data:', data.classes_stats);
                    }
                } catch (chartError) {
                    console.error('Chart initialization error:', chartError);
                    toastr.error('Failed to initialize charts');
                }
                
                // Load additional data
                loadUpcomingClasses();
                loadCheckedInMembers();
                
            } else {
                console.error('Invalid API response format:', response);
                toastr.error('Invalid data received from server');
                setDefaultValues();
            }
        },
        error: function(xhr, status, error) {
            console.error('AJAX Error:', status, error, xhr.responseText);
            toastr.error('Failed to load dashboard statistics');
            setDefaultValues();
        }
    });
}

// Helper function to set default values
function setDefaultValues() {
    $('.stat-value').text('0');
    $('#monthlyRevenue').text('$0.00');
    $('#memberChange span').text('0%');
    $('#memberChange i').removeClass('fa-arrow-up fa-arrow-down').addClass('fa-equals text-secondary');
}

function initRevenueChart(revenueData) {
    const ctx = document.getElementById('revenueChart').getContext('2d');
    const labels = revenueData.map(item => item.date);
    const data = revenueData.map(item => item.revenue);
    
    if (revenueChart) {
        revenueChart.destroy();
    }
    
    revenueChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: 'Daily Revenue',
                data: data,
                backgroundColor: 'rgba(75, 192, 192, 0.7)',
                borderColor: 'rgba(75, 192, 192, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    max: 200000, // Set max value to 200,000
                    ticks: {
                        callback: function(value) {
                            return '$' + value.toLocaleString();
                        }
                    }
                }
            },
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return '$' + context.raw.toFixed(2).toLocaleString();
                        }
                    }
                }
            }
        }
    });
    
    // Handle period toggle
    $('.chart-period button[data-period="monthly"]').click(function() {
        loadRevenueData('monthly');
    });
    
    $('.chart-period button[data-period="yearly"]').click(function() {
        loadRevenueData('yearly');
    });
}

function initMembersChart(membersData) {
    const ctx = document.getElementById('membersChart').getContext('2d');
    
    if (membersChart) {
        membersChart.destroy();
    }
    
    membersChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: membersData.labels,
            datasets: [{
                label: 'New Members',
                data: membersData.data,
                backgroundColor: 'rgba(52, 152, 219, 0.2)',
                borderColor: 'rgba(52, 152, 219, 1)',
                borderWidth: 2,
                tension: 0.4,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    max: 10, // Set max value to 10
                    ticks: {
                        precision: 0
                    }
                }
            },
            plugins: {
                legend: {
                    display: false
                }
            }
        }
    });
    
    // Handle period toggle
    $('.chart-period button[data-period="monthly"]').click(function() {
        loadMembersData('monthly');
    });
    
    $('.chart-period button[data-period="yearly"]').click(function() {
        loadMembersData('yearly');
    });
}
 function initMembersChart(membersData) {
        const ctx = document.getElementById('membersChart').getContext('2d');
        
        if (membersChart) {
            membersChart.destroy();
        }
        
        membersChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: membersData.labels,
                datasets: [{
                    label: 'New Members',
                    data: membersData.data,
                    backgroundColor: 'rgba(52, 152, 219, 0.2)',
                    borderColor: 'rgba(52, 152, 219, 1)',
                    borderWidth: 2,
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 10, // Set max to 10 members
                        ticks: {
                            precision: 0
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    }
                }
            }
        });
        
        // Handle period toggle
        $('.chart-period button[data-period="monthly"]').click(function() {
            loadMembersData('monthly');
        });
        
        $('.chart-period button[data-period="yearly"]').click(function() {
            loadMembersData('yearly');
        });
    }
    
    function loadMembersData(period) {
        $.ajax({
            url: '/admin/stats/members-growth',
            method: 'GET',
            data: { period: period },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                membersChart.data.labels = response.labels;
                membersChart.data.datasets[0].data = response.data;
                membersChart.options.scales.y.max = period === 'yearly' ? 50 : 10;
                membersChart.update();
                
                // Update active button
                $('.chart-period button').removeClass('active');
                $(`.chart-period button[data-period="${period}"]`).addClass('active');
            },
            error: function(xhr, status, error) {
                toastr.error('Failed to load members growth data');
            }
        });
    }
    
    function initClassesChart(classesStats) {
        const ctx = document.getElementById('classesChart').getContext('2d');
        const topClasses = classesStats.top_classes;
        
        // Sort classes by duration (assuming duration is in the class name or stats)
        const sortedClasses = [...topClasses].sort((a, b) => {
            // This is a placeholder - you'll need to adjust based on your actual data structure
            // Here we're assuming the class name contains duration info like "Yoga (60 min)"
            const durationA = parseInt(a.name.match(/\d+/)?.[0] || 0);
            const durationB = parseInt(b.name.match(/\d+/)?.[0] || 0);
            return durationB - durationA;
        });
        
        const labels = sortedClasses.map(item => item.name);
        const data = sortedClasses.map(item => item.count);
        
        // Generate distinct colors for each class
        const backgroundColors = [
            'rgba(231, 76, 60, 0.7)',
            'rgba(52, 152, 219, 0.7)',
            'rgba(46, 204, 113, 0.7)',
            'rgba(155, 89, 182, 0.7)',
            'rgba(241, 196, 15, 0.7)'
        ];
        
        if (classesChart) {
            classesChart.destroy();
        }
        
        classesChart = new Chart(ctx, {
            type: 'pie',
            data: {
                labels: labels,
                datasets: [{
                    data: data,
                    backgroundColor: backgroundColors,
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'right',
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const label = context.label || '';
                                const value = context.raw || 0;
                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                const percentage = Math.round((value / total) * 100);
                                return `${label}: ${value} (${percentage}%)`;
                            }
                        }
                    }
                }
            }
        });
    }
    
    function loadUpcomingClasses() {
        $.ajax({
            url: '/admin/stats/upcoming-classes',
            method: 'GET',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    const classes = response.data;
                    $('#upcomingClassesCount').text(classes.length);
                    
                    let html = '';
                    if (classes.length > 0) {
                        classes.forEach(cls => {
                            html += `
                                <div class="class-item">
                                    <div class="class-name">${cls.name}</div>
                                    <div class="class-trainer">With ${cls.trainer}</div>
                                    <div class="class-time">${cls.date} at ${cls.time} (${cls.duration} mins)</div>
                                    <div class="class-capacity">Capacity: ${cls.capacity}</div>
                                </div>
                            `;
                        });
                    } else {
                        html = '<div class="text-center py-4">No upcoming classes scheduled</div>';
                    }
                    
                    $('#upcomingClassesList').html(html);
                }
            },
            error: function(xhr, status, error) {
                toastr.error('Failed to load upcoming classes');
            }
        });
    }
    

function initCheckinSystem() {
    // Search members for checkin
    $('#checkinSearch').on('input', function() {
        const query = $(this).val();
        if (query.length < 2) {
            $('#checkinResults').empty();
            return;
        }
        
        $.ajax({
            url: '/admin/members/search',
            method: 'GET',
            data: { query: query },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                let html = '';
                if (response.length > 0) {
                    response.forEach(member => {
                        html += `
                            <a href="#" class="list-group-item list-group-item-action member-checkin-item" 
                               data-member-id="${member.id}" 
                               data-member-name="${member.first_name} ${member.last_name}">
                                ${member.first_name} ${member.last_name}
                            </a>
                        `;
                    });
                } else {
                    html = '<div class="list-group-item">No members found</div>';
                }
                $('#checkinResults').html(html);
            },
            error: function() {
                toastr.error('Failed to search members');
            }
        });
    });
    
    // Handle member selection for checkin
    $(document).on('click', '.member-checkin-item', function(e) {
        e.preventDefault();
        const memberId = $(this).data('member-id');
        const memberName = $(this).data('member-name');
        
        // Set the member in the input field
        $('#checkinSearch').val(memberName);
        $('#checkinResults').empty();
        
        // Check in the member
        checkinMember(memberId, memberName);
    });
    
    // Handle checkin button click
    $('#checkinBtn').click(function() {
        const memberName = $('#checkinSearch').val();
        if (!memberName) {
            toastr.error('Please select a member first');
            return;
        }
        
        // Find the member ID from the search results
        const memberItem = $('.member-checkin-item').filter(function() {
            return $(this).data('member-name') === memberName;
        }).first();
        
        if (memberItem.length) {
            const memberId = memberItem.data('member-id');
            checkinMember(memberId, memberName);
        } else {
            toastr.error('Member not found in search results');
        }
    });
    
    // Refresh checked in list
    $('#refreshCheckedIn').click(function() {
        loadCheckedInMembers();
    });
    
    // View daily attendance
    $('#viewDailyAttendance').click(function() {
        loadDailyAttendance();
    });
    
    // View monthly attendance
    $('#viewMonthlyAttendance').click(function() {
        loadMonthlyAttendance();
    });
    
    // Handle checkout button click
    $(document).on('click', '.checkout-btn', function() {
        const memberId = $(this).data('member-id');
        const memberName = $(this).data('member-name');
        const $listItem = $(this).closest('.list-group-item');
        
        $.ajax({
            url: '/admin/checkin/checkout',
            method: 'POST',
            data: { member_id: memberId },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            beforeSend: function() {
                $listItem.css('opacity', '0.5');
            },
            success: function(response) {
                if (response.success) {
                    toastr.success(`${memberName} checked out successfully`);
                    
                    // Fade out and remove the member from the checked-in list
                    $listItem.fadeOut(300, function() {
                        $(this).remove();
                        
                        // Update the active checkins count
                        const currentCount = parseInt($('#activeCheckins').text());
                        $('#activeCheckins').text(currentCount - 1);
                        
                        // If no members left, show empty state
                        if ($('#checkedInList .list-group-item').length === 0) {
                            $('#checkedInList').html('<div class="list-group-item text-center py-4">No members currently checked in</div>');
                        }
                    });
                } else {
                    $listItem.css('opacity', '1');
                    toastr.error(response.message);
                }
            },
            error: function(xhr) {
                $listItem.css('opacity', '1');
                toastr.error('Failed to check out member');
            }
        });
    });
}

function checkinMember(memberId, memberName) {
    $.ajax({
        url: '/admin/checkin',
        method: 'POST',
        data: { member_id: memberId },
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function(response) {
            if (response.success) {
                toastr.success(`${memberName} checked in successfully`);
                loadDashboardStats();
                $('#checkinSearch').val('');
                $('#checkinResults').empty();
            } else {
                toastr.error(response.message);
            }
        },
        error: function(xhr) {
            toastr.error('Failed to check in member');
        }
    });
}

function loadCheckedInMembers() {
    $.ajax({
        url: '/admin/checkin/today',
        method: 'GET',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function(response) {
            let html = '';
            if (response.data && response.data.length > 0) {
                // Filter only members who are currently checked in (no checkout time)
                const checkedInMembers = response.data.filter(checkin => !checkin.checkout_time);
                
                if (checkedInMembers.length > 0) {
                    checkedInMembers.forEach(checkin => {
                        const checkinTime = new Date(checkin.checkin_time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                        html += `
                            <div class="list-group-item d-flex justify-content-between align-items-center">
                                <div>
                                    <strong>${checkin.member_name}</strong>
                                    <div class="text-muted small">Checked in at ${checkinTime}</div>
                                </div>
                                <button class="btn btn-sm btn-outline-danger checkout-btn" 
                                        data-member-id="${checkin.member_id}" 
                                        data-member-name="${checkin.member_name}">
                                    <i class="fas fa-sign-out-alt"></i> Check Out
                                </button>
                            </div>
                        `;
                    });
                } else {
                    html = '<div class="list-group-item text-center py-4">No members currently checked in</div>';
                }
            } else {
                html = '<div class="list-group-item text-center py-4">No members currently checked in</div>';
            }
            $('#checkedInList').html(html);
        },
        error: function() {
            toastr.error('Failed to load checked in members');
        }
    });
}

function loadDailyAttendance() {
    $.ajax({
        url: '/admin/checkin/history',
        method: 'GET',
        data: { date: new Date().toISOString().split('T')[0] },
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function(response) {
            if (response.success) {
                const today = new Date();
                $('#attendanceDate').text(today.toDateString());
                
                let html = '';
                if (response.data.length > 0) {
                    response.data.forEach(record => {
                        const checkinTime = new Date(record.checkin_time).toLocaleTimeString();
                        const checkoutTime = record.checkout_time 
                            ? new Date(record.checkout_time).toLocaleTimeString() 
                            : 'Still in gym';
                            
                        // Calculate duration if checked out
                        let duration = '';
                        if (record.checkout_time) {
                            const checkin = new Date(record.checkin_time);
                            const checkout = new Date(record.checkout_time);
                            const diffMs = checkout - checkin;
                            const diffMins = Math.round(diffMs / 60000);
                            duration = `${diffMins} mins`;
                        } else {
                            duration = 'N/A';
                        }
                        
                        html += `
                            <tr>
                                <td>${record.member_name}</td>
                                <td>${checkinTime}</td>
                                <td>${checkoutTime}</td>
                                <td>${duration}</td>
                            </tr>
                        `;
                    });
                } else {
                    html = '<tr><td colspan="4" class="text-center py-4">No attendance records for today</td></tr>';
                }
                
                $('#attendanceList').html(html);
                $('#dailyAttendanceModal').modal('show');
            }
        },
        error: function() {
            toastr.error('Failed to load daily attendance');
        }
    });
}

function loadMonthlyAttendance() {
    const today = new Date();
    const month = today.getMonth() + 1;
    const year = today.getFullYear();
    
    $.ajax({
        url: '/admin/checkin/monthly',
        method: 'GET',
        data: { month: month, year: year },
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function(response) {
            if (response.success) {
                $('#attendanceMonth').text(`${today.toLocaleString('default', { month: 'long' })} ${year}`);
                
                let html = '';
                if (response.data.length > 0) {
                    response.data.forEach(member => {
                        // Convert total duration from minutes to hours and minutes
                        const hours = Math.floor(member.total_duration / 60);
                        const minutes = member.total_duration % 60;
                        const totalDuration = hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
                        
                        const avgHours = Math.floor(member.average_duration / 60);
                        const avgMinutes = Math.round(member.average_duration % 60);
                        const avgDuration = avgHours > 0 ? `${avgHours}h ${avgMinutes}m` : `${avgMinutes}m`;
                        
                        html += `
                            <tr>
                                <td>${member.member_name}</td>
                                <td>${member.total_visits}</td>
                                <td>${totalDuration}</td>
                                <td>${avgDuration}</td>
                            </tr>
                        `;
                    });
                } else {
                    html = '<tr><td colspan="4" class="text-center py-4">No attendance records for this month</td></tr>';
                }
                
                $('#monthlyAttendanceList').html(html);
                $('#monthlyAttendanceModal').modal('show');
            }
        },
        error: function() {
            toastr.error('Failed to load monthly attendance');
        }
    });
}
  function initAddMemberModal() {
        $('#addMemberModal').on('shown.bs.modal', function() {
            // Set default join date to today
            $('#joinDate').val(new Date().toISOString().split('T')[0]);
            
            // Calculate default membership expiry (1 month from today)
            const expiryDate = new Date();
            expiryDate.setMonth(expiryDate.getMonth() + 1);
            $('#membershipExpiry').val(expiryDate.toISOString().split('T')[0]);
        });
        
        $('#saveMemberBtn').click(function() {
            const formData = new FormData($('#addMemberForm')[0]);
            
            $.ajax({
                url: '/admin/members',
                method: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.success) {
                        $('#addMemberModal').modal('hide');
                        $('#addMemberForm')[0].reset();
                        loadDashboardStats();
                        
                        // Show success message
                        toastr.success('Member added successfully');
                    }
                },
                error: function(xhr) {
                    if (xhr.status === 422) {
                        const errors = xhr.responseJSON.errors;
                        Object.keys(errors).forEach(field => {
                            toastr.error(errors[field][0]);
                        });
                    } else {
                        toastr.error('Failed to add member');
                    }
                }
            });
        });
    }
    
    function initAddTrainerModal() {
        $('#addTrainerModal').on('shown.bs.modal', function() {
            // Set default hire date to today
            $('#hireDate').val(new Date().toISOString().split('T')[0]);
        });
        
        $('#saveTrainerBtn').click(function() {
            const formData = new FormData($('#addTrainerForm')[0]);
            
            $.ajax({
                url: '/admin/trainers',
                method: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.success) {
                        $('#addTrainerModal').modal('hide');
                        $('#addTrainerForm')[0].reset();
                        loadDashboardStats();
                        
                        // Show success message
                        toastr.success('Trainer added successfully');
                    }
                },
                error: function(xhr) {
                    if (xhr.status === 422) {
                        const errors = xhr.responseJSON.errors;
                        Object.keys(errors).forEach(field => {
                            toastr.error(errors[field][0]);
                        });
                    } else {
                        toastr.error('Failed to add trainer');
                    }
                }
            });
        });
    }
    
    function initAddClassModal() {
        // Load trainers for dropdown
        $.ajax({
            url: '/admin/trainers/active/list',
            method: 'GET',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                let options = '<option value="">Select Trainer</option>';
                response.forEach(trainer => {
                    options += `<option value="${trainer.id}">${trainer.first_name} ${trainer.last_name}</option>`;
                });
                $('#classTrainer').html(options);
            },
            error: function() {
                toastr.error('Failed to load trainers');
            }
        });
        
        $('#addClassModal').on('shown.bs.modal', function() {
            // Set default class date to today
            $('#classDate').val(new Date().toISOString().split('T')[0]);
            
            // Set default time to next hour
            const now = new Date();
            const nextHour = new Date(now.getTime() + 60 * 60 * 1000);
            $('#classTime').val(nextHour.toTimeString().substring(0, 5));
        });
        
        $('#saveClassBtn').click(function() {
            const formData = {
                name: $('#className').val(),
                trainer_id: $('#classTrainer').val(),
                class_date: $('#classDate').val(),
                class_time: $('#classTime').val(),
                duration_minutes: $('#classDuration').val(),
                max_capacity: $('#classCapacity').val(),
                description: $('#classDescription').val(),
                status: $('#classStatus').val(),
                _token: $('meta[name="csrf-token"]').attr('content')
            };
            
            $.ajax({
                url: '/admin/classes',
                method: 'POST',
                data: formData,
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.success) {
                        $('#addClassModal').modal('hide');
                        $('#addClassForm')[0].reset();
                        loadDashboardStats();
                        
                        // Show success message
                        toastr.success('Class added successfully');
                    }
                },
                error: function(xhr) {
                    if (xhr.status === 422) {
                        const errors = xhr.responseJSON.errors;
                        Object.keys(errors).forEach(field => {
                            toastr.error(errors[field][0]);
                        });
                    } else {
                        toastr.error('Failed to add class');
                    }
                }
            });
        });
    }
    
    function initAddPaymentModal() {
        // Load members for dropdown
        $.ajax({
            url: '/admin/members/active',
            method: 'GET',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                let options = '<option value="">Select Member</option>';
                response.forEach(member => {
                    options += `<option value="${member.id}">${member.first_name} ${member.last_name}</option>`;
                });
                $('#paymentMember').html(options);
            },
            error: function() {
                toastr.error('Failed to load members');
            }
        });
        
        $('#addPaymentModal').on('shown.bs.modal', function() {
            // Set default payment date to today
            $('#paymentDate').val(new Date().toISOString().split('T')[0]);
            
            // Set default due date to 1 month from today
            const dueDate = new Date();
            dueDate.setMonth(dueDate.getMonth() + 1);
            $('#dueDate').val(dueDate.toISOString().split('T')[0]);
        });
        
        $('#savePaymentBtn').click(function() {
            const formData = {
                member_id: $('#paymentMember').val(),
                amount: $('#paymentAmount').val(),
                payment_date: $('#paymentDate').val(),
                payment_type: $('#paymentType').val(),
                payment_method: $('#paymentMethod').val(),
                status: $('#paymentStatus').val(),
                transaction_id: $('#transactionId').val(),
                notes: $('#paymentNotes').val(),
                due_date: $('#dueDate').val(),
                _token: $('meta[name="csrf-token"]').attr('content')
            };
            
            $.ajax({
                url: '/admin/payments',
                method: 'POST',
                data: formData,
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.success) {
                        $('#addPaymentModal').modal('hide');
                        $('#addPaymentForm')[0].reset();
                        loadDashboardStats();
                        
                        // Show success message
                        toastr.success('Payment recorded successfully');
                    }
                },
                error: function(xhr) {
                    if (xhr.status === 422) {
                        const errors = xhr.responseJSON.errors;
                        Object.keys(errors).forEach(field => {
                            toastr.error(errors[field][0]);
                        });
                    } else {
                        toastr.error('Failed to record payment');
                    }
                }
            });
        });
    }
    
    function setDefaultDates() {
        const today = new Date().toISOString().split('T')[0];
        const nextMonth = new Date();
        nextMonth.setMonth(nextMonth.getMonth() + 1);
        const nextMonthFormatted = nextMonth.toISOString().split('T')[0];
        
        // Set default dates in member form
        $('#joinDate').val(today);
        $('#membershipExpiry').val(nextMonthFormatted);
        
        // Set default dates in trainer form
        $('#hireDate').val(today);
        
        // Set default dates in payment form
        $('#paymentDate').val(today);
        $('#dueDate').val(nextMonthFormatted);
    }
</script>