<?php include 'header.php'; ?>

<!-- Normal Sub Header -->
<?php include 'template-parts/sub-header-trainer.php'; ?>

<div class="uk-container">
    <div class="uk-grid uk-grid-medium" uk-grid>

        <!-- Sidebar Area -->
        <div class="uk-width-2-6@m uk-visible@m">
            <div class="sidebar-sticky" uk-sticky="offset: 20; bottom: true">
                <?php include 'trainer-sidebar.php'; ?>
            </div>
        </div>

        <!-- Main Content Area -->
        <div class="uk-width-expand@m">

            <div class="profile-container">

                <!-- Sessions Header -->
                <div class="profile-header">
                    <h2 class="uk-heading-divider">My Sessions</h2>
                    <p class="uk-margin-small-top">View, manage, and conduct your training sessions.</p>
                </div>

                <!-- Sessions Summary Cards -->
                <div class="uk-grid uk-grid-medium uk-grid-match uk-child-width-1-2 uk-child-width-1-2@s uk-child-width-1-4@m" uk-grid>
                    <div>
                        <div class="cart-item-small">
                            <h3 class="uk-card-title uk-margin-remove uk-text-primary">8</h3>
                            <p class="f600 uk-margin-remove">Total Sessions</p>
                        </div>
                    </div>
                    <div>
                        <div class="cart-item-small">
                            <h3 class="uk-card-title uk-margin-remove uk-text-warning">3</h3>
                            <p class="f600 uk-margin-remove">Today's Sessions</p>
                        </div>
                    </div>
                    <div>
                        <div class="cart-item-small">
                            <h3 class="uk-card-title uk-margin-remove uk-text-success">127</h3>
                            <p class="f600 uk-margin-remove">Completed</p>
                        </div>
                    </div>
                    <div>
                        <div class="cart-item-small">
                            <h3 class="uk-card-title uk-margin-remove uk-text-secondary">4.9</h3>
                            <p class="f600 uk-margin-remove">Avg Rating</p>
                        </div>
                    </div>
                </div>

                <hr class="uk-margin-medium-top">

                <!-- Filters Section -->
                <div class="uk-margin-medium-top">
                    <div class="uk-grid uk-grid-small uk-flex-bottom" uk-grid>
                        <div class="uk-width-1-4@s">
                            <label class="form-label uk-margin-small-right">Filter by Status:</label>
                            <select class="uk-select uk-width-1-1" id="statusFilter">
                                <option value="all">All Sessions</option>
                                <option value="today">Today</option>
                                <option value="upcoming">Upcoming</option>
                                <option value="in-progress">In Progress</option>
                                <option value="completed">Completed</option>
                                <option value="cancelled">Cancelled</option>
                            </select>
                        </div>
                        <div class="uk-width-expand">
                            <label class="form-label uk-margin-small-right">By Client Name</label>
                            <div class="uk-search uk-search-default uk-width-1-1 uk-position-relative">
                                <span class="uk-form-icon" uk-icon="icon: search; ratio: .7"></span>
                                <input class="uk-input" type="search" placeholder="Enter client name" id="clientSearch">
                            </div>
                        </div>
                        <div class="uk-width-auto">
                            <button class="uk-button uk-button-small uk-button-default" onclick="refreshSessions()">
                                <span uk-icon="icon: refresh; ratio: 0.6"></span>
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Sessions Table -->
                <div class="order-table uk-margin-small-top">
                    <div class="uk-overflow-auto">
                        <table class="uk-table uk-table-hover uk-table uk-table-responsive uk-table-divider">
                            <thead>
                                <tr>
                                    <th>Session ID</th>
                                    <th>Client</th>
                                    <th>Date & Time</th>
                                    <th>Duration</th>
                                    <th>Price</th>
                                    <th>Status</th>
                                    <th class="uk-text-center">Actions</th>
                                </tr>
                            </thead>
                            <tbody id="sessionsTableBody">
                                <!-- Session 1 - In Progress -->
                                <tr data-session-id="ORD-002" data-status="in-progress" data-client="Mohammed Ali" data-date="today">
                                    <td class="uk-text-bold">#ORD-002</td>
                                    <td>Mohammed Ali</td>
                                    <td>Aug 21, 2025 - 11:00 AM</td>
                                    <td>60 minutes</td>
                                    <td class="uk-text-bold">500 SAR</td>
                                    <td><span class="session-status in-progress uk-flex gap-4"><span uk-icon="icon: play; ratio: .6" class="uk-icon" aria-hidden="true"></span>In Progress</span></td>
                                    <td>
                                        <button class="action-small-btn action-join-btn" uk-tooltip="Start Session" onclick="joinSession('ORD-002')">
                                            <span uk-icon="icon: video; ratio: 0.7"></span>
                                        </button>
                                        <button class="action-small-btn" uk-tooltip="End Session" onclick="endSession('ORD-002')">
                                            <span uk-icon="icon: check; ratio: 0.7"></span>
                                        </button>
                                        <button class="action-small-btn" uk-tooltip="Session Details" onclick="viewSessionDetails('ORD-002')">
                                            <span uk-icon="icon: eye; ratio: 0.7"></span>
                                        </button>
                                    </td>
                                </tr>

                                <!-- Session 2 - Upcoming Today -->
                                <tr data-session-id="ORD-001" data-status="upcoming" data-client="Sarah Ahmad" data-date="today">
                                    <td class="uk-text-bold">#ORD-001</td>
                                    <td>Sarah Ahmad</td>
                                    <td>Aug 21, 2025 - 2:00 PM</td>
                                    <td>45 minutes</td>
                                    <td class="uk-text-bold">400 SAR</td>
                                    <td><span class="session-status upcoming uk-flex gap-4"><span uk-icon="icon: clock; ratio: .6" class="uk-icon" aria-hidden="true"></span>Upcoming</span></td>
                                    <td>
                                        <button class="action-small-btn action-join-btn" uk-tooltip="Start Session" onclick="startSession('ORD-001')">
                                            <span uk-icon="icon: video; ratio: 0.7"></span>
                                        </button>
                                        <button class="action-small-btn" uk-tooltip="Session Details" onclick="viewSessionDetails('ORD-001')">
                                            <span uk-icon="icon: eye; ratio: 0.7"></span>
                                        </button>
                                        <button class="action-small-btn action-cancel-btn" uk-tooltip="Cancel Session" onclick="cancelSession('ORD-001')">
                                            <span uk-icon="icon: x-circle; ratio: 0.7"></span>
                                        </button>
                                    </td>
                                </tr>

                                <!-- Session 3 - Completed Today -->
                                <tr data-session-id="ORD-003" data-status="completed" data-client="Fatima Hassan" data-date="today">
                                    <td class="uk-text-bold">#ORD-003</td>
                                    <td>Fatima Hassan</td>
                                    <td>Aug 21, 2025 - 9:00 AM</td>
                                    <td>30 minutes</td>
                                    <td class="uk-text-bold">280 SAR</td>
                                    <td><span class="session-status completed uk-flex gap-4"><span uk-icon="icon: check; ratio: .6" class="uk-icon" aria-hidden="true"></span>Completed</span></td>
                                    <td>
                                        <button class="action-small-btn" uk-tooltip="Session Details" onclick="viewSessionDetails('ORD-003')">
                                            <span uk-icon="icon: eye; ratio: 0.7"></span>
                                        </button>
                                        <button class="action-small-btn" uk-tooltip="Add Note" onclick="addSessionNotes('ORD-003')">
                                            <span uk-icon="icon: pencil; ratio: 0.7"></span>
                                        </button>
                                    </td>
                                </tr>

                                <!-- Session 4 - Upcoming Tomorrow -->
                                <tr data-session-id="ORD-004" data-status="upcoming" data-client="Ahmad Rahman" data-date="upcoming">
                                    <td class="uk-text-bold">#ORD-004</td>
                                    <td>Ahmad Rahman</td>
                                    <td>Aug 22, 2025 - 10:00 AM</td>
                                    <td>45 minutes</td>
                                    <td class="uk-text-bold">400 SAR</td>
                                    <td><span class="session-status uk-flex gap-4"><span uk-icon="icon: calendar; ratio: .6" class="uk-icon" aria-hidden="true"></span>Tomorrow</span></td>
                                    <td>
                                        <button class="action-small-btn" uk-tooltip="Session Details" onclick="viewSessionDetails('ORD-004')">
                                            <span uk-icon="icon: eye; ratio: 0.7"></span>
                                        </button>
                                        <button class="action-small-btn" uk-tooltip="Add Note" onclick="addSessionNotes('ORD-004')">
                                            <span uk-icon="icon: pencil; ratio: 0.7"></span>
                                        </button>
                                        <button class="action-small-btn action-cancel-btn" uk-tooltip="Cancel Session" onclick="cancelSession('ORD-004')">
                                            <span uk-icon="icon: x-circle; ratio: 0.7"></span>
                                        </button>
                                    </td>
                                </tr>

                                <!-- Session 5 - Upcoming This Week -->
                                <tr data-session-id="ORD-005" data-status="upcoming" data-client="Nora Abdullah" data-date="upcoming">
                                    <td class="uk-text-bold">#ORD-005</td>
                                    <td>Nora Abdullah</td>
                                    <td>Aug 24, 2025 - 3:00 PM</td>
                                    <td>60 minutes</td>
                                    <td class="uk-text-bold">500 SAR</td>
                                    <td><span class="session-status uk-flex gap-4"><span uk-icon="icon: calendar; ratio: .6" class="uk-icon" aria-hidden="true"></span>This Week</span></td>
                                    <td>
                                        <button class="action-small-btn" uk-tooltip="Session Details" onclick="viewSessionDetails('ORD-005')">
                                            <span uk-icon="icon: eye; ratio: 0.7"></span>
                                        </button>
                                        <button class="action-small-btn" uk-tooltip="Add Note" onclick="addSessionNotes('ORD-005')">
                                            <span uk-icon="icon: pencil; ratio: 0.7"></span>
                                        </button>
                                        <button class="action-small-btn action-cancel-btn" uk-tooltip="Cancel Session" onclick="cancelSession('ORD-005')">
                                            <span uk-icon="icon: x-circle; ratio: 0.7"></span>
                                        </button>
                                    </td>
                                </tr>

                                <!-- Order 6 - Cancelled -->
                                <tr data-order-id="ORD-006" data-status="cancelled" data-client="Nora Abdullah">
                                    <td class="uk-text-bold">#ORD-006</td>
                                    <td>Nora Abdullah</td>
                                    <td>Aug 22, 2025 - 1:00 PM</td>
                                    <td>30 minutes</td>
                                    <td class="uk-text-bold">280 SAR</td>
                                    <td><span class="session-status cancelled uk-flex gap-4"><span uk-icon="icon: cancelled; ratio: .6" class="uk-icon" aria-hidden="true"></span>Cancelled</span></span></td>
                                    <td>
                                        <button class="action-small-btn" onclick="viewOrderDetails('ORD-006')">
                                            <span uk-icon="icon: eye; ratio: 0.7"></span>
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <!-- Empty State -->
                    <div id="emptyState" class="uk-text-center uk-padding-large" style="display: none;">
                        <span uk-icon="icon: search; ratio: 3" class="uk-text-muted"></span>
                        <h3 class="uk-text-muted">No sessions found</h3>
                        <p class="uk-text-muted">Try adjusting your search or filter criteria.</p>
                    </div>
                </div>

                <!-- Load More Button -->
                <div class="uk-margin-medium-top">
                    <button class="uk-button uk-button-default" onclick="loadMoreSessions()">
                        Load More Sessions
                    </button>
                </div>

            </div>

        </div>

    </div><!-- .uk-grid -->
</div><!-- .uk-container -->

<!-- Session Details Modal -->
<div id="sessionDetailsModal" uk-modal>
    <div class="uk-modal-dialog uk-modal-body">
        <button class="uk-modal-close-default" type="button" uk-close></button>
        <h2 class="uk-modal-title">Session Details</h2>

        <div id="sessionDetailsContent">
            <!-- Content will be populated by JavaScript -->
        </div>
    </div>
</div>

<div id="sessionNotesModal" uk-modal>
    <div class="uk-modal-dialog uk-modal-body">
        <button class="uk-modal-close-default" type="button" uk-close></button>
        <h2 class="uk-modal-title">Session Notes</h2>

        <form id="sessionNotesForm">
            <input type="hidden" id="notesSessionId" />

            <div class="uk-margin">
                <label class="form-label" for="sessionStrength">Strength</label>
                <input class="uk-input" id="sessionStrength" placeholder=""></input>
            </div>

            <div class="uk-margin">
                <label class="form-label" for="sessionRecommendations">Recommendations</label>
                <input class="uk-input" id="sessionRecommendations" placeholder=""></input>
            </div>

            <div class="uk-margin">
                <label class="form-label" for="sessionFile">Upload File</label>
                <div class="uk-width-1-1" uk-form-custom="target: true">
                    <input type="file" id="sessionFile">
                    <input class="uk-input" type="text" placeholder="Select file..." disabled>
                </div>
            </div>

            <div class="uk-margin">
                <label class="form-label" for="sessionNotesText">Add your notes for this session</label>
                <textarea class="uk-textarea" id="sessionNotesText" rows="8" placeholder="Add preparation notes, key points to cover, client background, or post-session feedback..."></textarea>
            </div>

            <div class="uk-margin uk-text-right">
                <button class="uk-button uk-button-default uk-modal-close uk-margin-small-right" type="button">Cancel</button>
                <button class="uk-button uk-button-primary" type="submit">Save Notes</button>
            </div>
        </form>
    </div>
</div>

<!-- Cancel Session Modal -->
<div id="cancelSessionModal" uk-modal>
    <div class="uk-modal-dialog uk-modal-body">
        <button class="uk-modal-close-default" type="button" uk-close></button>
        <h2 class="uk-modal-title uk-text-danger">Cancel Session</h2>

        <form id="cancelSessionForm">
            <input type="hidden" id="cancelSessionId" />

            <div class="uk-margin">
                <label class="form-label" for="cancellationReason">Reason for Cancellation</label>
                <select class="uk-select" id="cancellationReason" required>
                    <option value="">Select a reason</option>
                    <option value="schedule_conflict">Schedule Conflict</option>
                    <option value="technical_issues">Technical Issues</option>
                    <option value="client_request">Client Request</option>
                    <option value="emergency">Emergency</option>
                    <option value="other">Other</option>
                </select>
            </div>

            <div class="uk-margin">
                <label class="form-label" for="cancellationNotes">Additional Notes</label>
                <textarea class="uk-textarea" id="cancellationNotes" rows="3" placeholder="Please provide additional details about the cancellation..."></textarea>
            </div>

            <div class="uk-alert uk-alert-warning uk-margin">
                <p class="uk-margin-remove"><strong>Important:</strong> Cancelling this session will trigger an automatic refund to the client. This action cannot be undone.</p>
            </div>

            <div class="uk-margin uk-text-right">
                <button class="uk-button uk-button-default uk-modal-close uk-margin-small-right" type="button">Keep Session</button>
                <button class="uk-button uk-button-danger" type="submit">Cancel Session</button>
            </div>
        </form>
    </div>
</div>

<script>
    // Sample session data
    const sessionsData = {
        'ORD-001': {
            id: 'ORD-001',
            client: 'Sarah Ahmad',
            email: 'sarah.ahmad@email.com',
            phone: '+966 50 123 4567',
            date: 'Aug 21, 2025',
            time: '2:00 PM',
            duration: '45 minutes',
            price: '400 SAR',
            status: 'upcoming',
            sessionType: 'Technical Interview Preparation',
            meetingLink: 'https://zoom.us/j/123456789',
            notes: 'Client wants to focus on system design and coding challenges for FAANG companies.',
            focus: 'System design and coding challenges'
        },
        'ORD-002': {
            id: 'ORD-002',
            client: 'Mohammed Ali',
            email: 'mohammed.ali@email.com',
            phone: '+966 55 987 6543',
            date: 'Aug 21, 2025',
            time: '11:00 AM',
            duration: '60 minutes',
            price: '500 SAR',
            status: 'in-progress',
            sessionType: 'System Design Interview',
            meetingLink: 'https://zoom.us/j/987654321',
            notes: 'Currently in session - discussing scalable web architecture.',
            focus: 'Scalable system architecture'
        },
        'ORD-003': {
            id: 'ORD-003',
            client: 'Fatima Hassan',
            email: 'fatima.hassan@email.com',
            phone: '+966 56 111 2233',
            date: 'Aug 21, 2025',
            time: '9:00 AM',
            duration: '30 minutes',
            price: '280 SAR',
            status: 'completed',
            sessionType: 'Coding Interview Practice',
            meetingLink: 'https://zoom.us/j/555666777',
            notes: 'Excellent session! Client showed strong problem-solving skills. Recommended practicing more dynamic programming problems.',
            focus: 'Data structures and algorithms',
            rating: 5
        },
        'ORD-004': {
            id: 'ORD-004',
            client: 'Ahmad Rahman',
            email: 'ahmad.rahman@email.com',
            phone: '+966 50 444 5555',
            date: 'Aug 22, 2025',
            time: '10:00 AM',
            duration: '45 minutes',
            price: '400 SAR',
            status: 'upcoming',
            sessionType: 'Behavioral Interview Coaching',
            meetingLink: 'https://zoom.us/j/888999000',
            notes: 'Focus on STAR method and leadership stories',
            focus: 'STAR method and leadership stories'
        },
        'ORD-005': {
            id: 'ORD-005',
            client: 'Nora Abdullah',
            email: 'nora.abdullah@email.com',
            phone: '+966 55 777 8888',
            date: 'Aug 24, 2025',
            time: '3:00 PM',
            duration: '60 minutes',
            price: '500 SAR',
            status: 'upcoming',
            sessionType: 'Algorithm Problem Solving',
            meetingLink: 'https://zoom.us/j/333444555',
            notes: 'Focus on dynamic programming and graph algorithms',
            focus: 'Dynamic programming and graph algorithms'
        },
        'ORD-005': {
            id: 'ORD-005',
            client: 'Nora Abdullah',
            email: 'nora.abdullah@email.com',
            phone: '+966 55 777 8888',
            date: 'Aug 22, 2025',
            time: '1:00 PM',
            duration: '30 minutes',
            price: '280 SAR',
            status: 'cancelled',
            sessionType: 'Algorithm Problem Solving',
            meetingLink: '',
            notes: 'Cancelled due to client emergency. Refund processed.'
        }
    };

    // Start session
    function startSession(sessionId) {
        UIkit.notification({
            message: 'Starting session...',
            status: 'primary',
            pos: 'top-center',
            timeout: 2000
        });

        setTimeout(() => {
            UIkit.notification({
                message: 'Session started! Opening meeting room...',
                status: 'success',
                pos: 'top-center',
                timeout: 3000
            });

            updateSessionStatus(sessionId, 'in-progress');

            const session = sessionsData[sessionId];
            if (session && session.meetingLink) {
                window.open(session.meetingLink, '_blank');
            }
        }, 1500);
    }

    // Join session
    function joinSession(sessionId) {
        const session = sessionsData[sessionId];
        if (session && session.meetingLink) {
            window.open(session.meetingLink, '_blank');
            UIkit.notification({
                message: 'Opening meeting room...',
                status: 'success',
                pos: 'top-center',
                timeout: 2000
            });
        }
    }

    // End session
    function endSession(sessionId) {
        UIkit.notification({
            message: 'Ending session...',
            status: 'primary',
            pos: 'top-center',
            timeout: 2000
        });

        setTimeout(() => {
            UIkit.notification({
                message: 'Session ended successfully!',
                status: 'success',
                pos: 'top-center',
                timeout: 3000
            });

            updateSessionStatus(sessionId, 'completed');
        }, 1500);
    }

    // Update session status in UI
    function updateSessionStatus(sessionId, newStatus) {
        const row = document.querySelector(`tr[data-session-id="${sessionId}"]`);
        if (row) {
            row.setAttribute('data-status', newStatus);

            const statusCell = row.querySelector('td:nth-child(6)');
            const actionsCell = row.querySelector('td:last-child');

            let statusHtml = '';
            let actionsHtml = '';

            switch (newStatus) {
                case 'in-progress':
                    statusHtml = '<span class="session-status in-progress uk-flex gap-4"><span uk-icon="icon: play; ratio: .6" class="uk-icon" aria-hidden="true"></span>In Progress</span>';
                    actionsHtml = `
                    <button class="action-small-btn action-join-btn" onclick="joinSession('${sessionId}')">
                        <span uk-icon="icon: video; ratio: 0.7"></span>
                    </button>
                    <button class="action-small-btn" onclick="endSession('${sessionId}')">
                        <span uk-icon="icon: check; ratio: 0.7"></span>
                    </button>
                    <button class="action-small-btn" onclick="viewSessionDetails('${sessionId}')">
                        <span uk-icon="icon: eye; ratio: 0.7"></span>
                    </button>
                `;
                    break;
                case 'completed':
                    statusHtml = '<span class="session-status completed uk-flex gap-4"><span uk-icon="icon: check; ratio: .6" class="uk-icon" aria-hidden="true"></span>Completed</span>';
                    actionsHtml = `
                    <button class="action-small-btn" onclick="viewSessionDetails('${sessionId}')">
                        <span uk-icon="icon: eye; ratio: 0.7"></span>
                    </button>
                    <button class="action-small-btn" onclick="addSessionNotes('${sessionId}')">
                        <span uk-icon="icon: pencil; ratio: 0.7"></span>
                    </button>
                `;
                    break;
                case 'cancelled':
                    statusHtml = '<span class="session-status cancelled uk-flex gap-4"><span uk-icon="icon: x-circle; ratio: .6" class="uk-icon" aria-hidden="true"></span>Cancelled</span>';
                    actionsHtml = `
                    <button class="action-small-btn" onclick="viewSessionDetails('${sessionId}')">
                        <span uk-icon="icon: eye; ratio: 0.7"></span>
                    </button>
                `;
                    break;
            }

            if (statusCell) statusCell.innerHTML = statusHtml;
            if (actionsCell) actionsCell.innerHTML = actionsHtml;
        }
    }

    // View session details
    function viewSessionDetails(sessionId) {
        const session = sessionsData[sessionId];
        if (!session) return;

        const content = `
        <div class="uk-grid uk-grid-small" uk-grid>
            <div class="uk-width-1-2@s">
                <h4 class="uk-h5 uk-margin-small-bottom f600">Client Information</h4>
                <dl class="uk-description-list uk-description-list-divider">
                    <dt>Name</dt>
                    <dd>${session.client}</dd>
                    <dt>Email</dt>
                    <dd>${session.email}</dd>
                    <dt>Phone</dt>
                    <dd>${session.phone}</dd>
                    <dt>Session Focus</dt>
                    <dd>${session.focus}</dd>
                    <dt>Uploaded CV</dt><dd><a href="${session.cvLink}" target="_blank" class="uk-link">View CV</a></dd>
                    ${/* session.cvLink ? `<dt>Uploaded CV</dt><dd><a href="${session.cvLink}" target="_blank" class="uk-link">View CV</a></dd>` : '' */''}
                </dl>
            </div>
            <div class="uk-width-1-2@s">
                <h4 class="uk-h5 uk-margin-small-bottom f600">Session Details</h4>
                <dl class="uk-description-list uk-description-list-divider">
                    <dt>Date & Time</dt>
                    <dd>${session.date} - ${session.time}</dd>
                    <dt>Duration</dt>
                    <dd>${session.duration}</dd>
                    <dt>Price</dt>
                    <dd class="uk-text-bold">${session.price}</dd>
                    <dt>Session Type</dt>
                    <dd>${session.sessionType}</dd>
                    ${session.meetingLink ? `<dt>Meeting Link</dt><dd><a href="${session.meetingLink}" target="_blank" class="uk-link">${session.meetingLink}</a></dd>` : ''}
                </dl>
            </div>
        </div>

        ${session.status === 'upcoming' ? `
        <div class="uk-margin-medium-top">
            <h4 class="uk-h5 uk-margin-small-bottom f600">Pre-Session Notes</h4>
            <textarea class="uk-textarea" id="sessionNotes_${sessionId}" rows="4" placeholder="Add any notes or preparation points for this session...">${session.notes}</textarea>
            <button class="uk-button uk-button-primary uk-margin-small-top" onclick="saveSessionNotes('${sessionId}')">Save Notes</button>
        </div>
        ` : ''}

        ${session.status === 'completed' ? `
        <div class="uk-margin-medium-top">
            <h4 class="uk-h5 uk-margin-small-bottom f600">Session Notes</h4>
            <div class="uk-padding-small uk-background-muted br-8">
                <p class="uk-margin-remove">${session.notes || 'No notes available for this session.'}</p>
            </div>
        </div>
        ` : ''}

        ${session.rating ? `
        <div class="uk-margin-medium-top">
            <h4 class="uk-h5 uk-margin-small-bottom f600">Client Rating</h4>
            <div class="uk-flex uk-flex-middle">
                <div class="uk-margin-small-right star-rate ">
                    ${'<span uk-icon="icon: star-bold; ratio: .6" class="uk-icon" aria-hidden="true">'.repeat(session.rating)}${'<span uk-icon="icon: star; ratio: .6" class="uk-icon" aria-hidden="true"></span>'.repeat(5-session.rating)}
                </div>
                <span class="uk-text-bold">${session.rating}/5 stars</span>
            </div>
        </div>
        ` : ''}
    `;

        document.getElementById('sessionDetailsContent').innerHTML = content;
        UIkit.modal('#sessionDetailsModal').show();
    }

    // Save session notes
    function saveSessionNotes(sessionId) {
        const notesTextarea = document.getElementById(`sessionNotes_${sessionId}`);
        const notes = notesTextarea.value;

        sessionsData[sessionId].notes = notes;

        UIkit.notification({
            message: 'Session notes saved successfully!',
            status: 'success',
            pos: 'top-center',
            timeout: 3000
        });
    }

    // Add session notes
    function addSessionNotes(sessionId) {
        const session = sessionsData[sessionId];
        if (!session) return;

        document.getElementById('notesSessionId').value = sessionId;
        document.getElementById('sessionNotesText').value = session.notes || '';
        UIkit.modal('#sessionNotesModal').show();
    }

    // Handle session notes form submission
    document.getElementById('sessionNotesForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const sessionId = document.getElementById('notesSessionId').value;
        const strength = document.getElementById('sessionStrength').value;
        const recommendations = document.getElementById('sessionRecommendations').value;
        const notes = document.getElementById('sessionNotesText').value;
        const uploadedFile = document.getElementById('sessionFile').files[0]; // Get the uploaded file

        if (sessionsData[sessionId]) {
            // Update the session data with the new text notes
            sessionsData[sessionId].strength = strength;
            sessionsData[sessionId].recommendations = recommendations;
            sessionsData[sessionId].notes = notes;

            // Log the file name. You'd replace this with an actual upload process.
            if (uploadedFile) {
                console.log(`File uploaded for session ${sessionId}: ${uploadedFile.name}`);
                sessionsData[sessionId].uploadedFile = uploadedFile.name; // Store the file name in the data
            } else {
                sessionsData[sessionId].uploadedFile = null;
            }
        }

        UIkit.modal('#sessionNotesModal').hide();

        UIkit.notification({
            message: 'Session notes saved successfully!',
            status: 'success',
            pos: 'top-center',
            timeout: 3000
        });
    });

    // Cancel session
    function cancelSession(sessionId) {
        document.getElementById('cancelSessionId').value = sessionId;
        UIkit.modal('#cancelSessionModal').show();
    }

    // Handle cancel session form submission
    document.getElementById('cancelSessionForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const sessionId = document.getElementById('cancelSessionId').value;
        const reason = document.getElementById('cancellationReason').value;
        const notes = document.getElementById('cancellationNotes').value;

        if (!reason) {
            UIkit.notification({
                message: 'Please select a cancellation reason',
                status: 'warning',
                pos: 'top-center',
                timeout: 3000
            });
            return;
        }

        UIkit.notification({
            message: 'Processing cancellation...',
            status: 'primary',
            pos: 'top-center',
            timeout: 2000
        });

        setTimeout(() => {
            sessionsData[sessionId].status = 'cancelled';
            sessionsData[sessionId].notes = `Cancelled: ${reason}. ${notes}`;

            updateSessionStatus(sessionId, 'cancelled');

            UIkit.modal('#cancelSessionModal').hide();
            document.getElementById('cancelSessionForm').reset();

            UIkit.notification({
                message: 'Session cancelled successfully! Client has been notified and refund will be processed.',
                status: 'success',
                pos: 'top-center',
                timeout: 5000
            });

            updateSummaryCards();

        }, 1500);
    });

    // Refresh sessions
    function refreshSessions() {
        UIkit.notification({
            message: 'Refreshing sessions...',
            status: 'primary',
            pos: 'top-center',
            timeout: 2000
        });

        setTimeout(() => {
            UIkit.notification({
                message: 'Sessions updated successfully!',
                status: 'success',
                pos: 'top-center',
                timeout: 3000
            });
        }, 1500);
    }

    // Filter and search functionality
    function filterSessions() {
        const statusFilter = document.getElementById('statusFilter').value;
        const searchTerm = document.getElementById('clientSearch').value.toLowerCase();
        const rows = document.querySelectorAll('#sessionsTableBody tr');
        let visibleCount = 0;

        rows.forEach(row => {
            const status = row.getAttribute('data-status');
            const client = row.getAttribute('data-client').toLowerCase();
            const sessionDate = row.getAttribute('data-date');

            let statusMatch = true;
            let clientMatch = true;

            // Filter by status
            if (statusFilter !== 'all') {
                if (statusFilter === 'today') {
                    statusMatch = sessionDate === 'today';
                } else {
                    statusMatch = status === statusFilter;
                }
            }

            // Filter by client name
            if (searchTerm) {
                clientMatch = client.includes(searchTerm);
            }

            if (statusMatch && clientMatch) {
                row.style.display = '';
                visibleCount++;
            } else {
                row.style.display = 'none';
            }
        });

        // Show empty state if no results
        const emptyState = document.getElementById('emptyState');
        const table = document.querySelector('.uk-table');

        if (visibleCount === 0) {
            emptyState.style.display = 'block';
            table.style.display = 'none';
        } else {
            emptyState.style.display = 'none';
            table.style.display = 'table';
        }
    }

    // Update summary cards
    function updateSummaryCards() {
        const totalSessions = document.querySelectorAll('#sessionsTableBody tr').length;
        const todaySessions = document.querySelectorAll('tr[data-date="today"]').length;
        const completedSessions = document.querySelectorAll('tr[data-status="completed"]').length;

        // Update the summary cards
        const cards = document.querySelectorAll('.cart-item-small .uk-card-title');
        if (cards.length >= 3) {
            cards[0].textContent = totalSessions;
            cards[1].textContent = todaySessions;
            cards[2].textContent = completedSessions;
        }
    }

    // Load more sessions
    function loadMoreSessions() {
        UIkit.notification({
            message: 'Loading more sessions...',
            status: 'primary',
            pos: 'bottom-center',
            timeout: 2000
        });

        setTimeout(() => {
            UIkit.notification({
                message: 'No more sessions to load',
                status: 'warning',
                pos: 'bottom-center',
                timeout: 2000
            });
        }, 1500);
    }

    // Event listeners
    document.getElementById('statusFilter').addEventListener('change', filterSessions);
    document.getElementById('clientSearch').addEventListener('input', filterSessions);

    // Auto-refresh sessions every 2 minutes
    setInterval(function() {
        console.log('Auto-checking for session updates...');
    }, 120000);

    // Real-time session timer for in-progress sessions
    function startSessionTimer() {
        const inProgressSessions = document.querySelectorAll('[data-status="in-progress"]');

        inProgressSessions.forEach(sessionRow => {
            // In a real app, you'd track actual start time and update accordingly
            setInterval(() => {
                console.log('Updating session timer...');
            }, 60000);
        });
    }

    // Initialize
    document.addEventListener('DOMContentLoaded', function() {
        updateSummaryCards();
        startSessionTimer();
        console.log('Sessions dashboard loaded');
    });

    // Keyboard shortcuts
    document.addEventListener('keydown', function(e) {
        if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
            e.preventDefault();
            refreshSessions();
        }
    });
</script>

<?php include 'footer.php'; ?>