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

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

<div class="uk-container">

    <!-- Page Header -->
    <div class="page-header uk-margin-medium-bottom">
        <div class="uk-grid uk-grid-small" uk-grid>

            <div class="uk-width-expand@s">
                <div class="header-left uk-flex uk-flex-middle gap-16">
                    <div class="header-icon">
                        <span uk-icon="icon: sessions; ratio: 1.6" class="uk-icon"></span>
                    </div>
                    <div>
                        <h1 class="header-title">My Sessions</h1>
                        <p class="header-subtitle uk-margin-remove">Manage your consultation sessions</p>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <!-- Filter Section -->
    <div class="filter-section uk-margin-medium-bottom">
        <div class="filter-grid uk-grid uk-grid-small uk-flex-bottom" uk-grid>

            <div class="uk-width-expand@s">
                <div class="uk-grid uk-grid-small uk-child-width-1-3@s" uk-grid>

                    <div class="filter-group">
                        <label class="form-label" for="statusFilter">Status</label>
                        <select class="uk-select" id="statusFilter">
                            <option value="">All Sessions</option>
                            <option value="upcoming">Upcoming</option>
                            <option value="completed">Completed</option>
                            <option value="cancelled">Cancelled</option>
                        </select>
                    </div>

                    <div class="filter-group">
                        <label class="form-label" for="trainerFilter">Trainer</label>
                        <select class="uk-select" id="trainerFilter">
                            <option value="">All Trainers</option>
                            <option value="noor-abdullah">Noor Abdullah</option>
                            <option value="mohammed-ali">Mohammed Ali</option>
                            <option value="fatima-hassan">Fatima Hassan</option>
                        </select>
                    </div>

                    <div class="filter-group">
                        <label class="form-label" for="dateRange">Date Range</label>
                        <input type="date" class="uk-input" id="dateRange">
                    </div>
                </div>

            </div>

            <div class="uk-width-auto@s">
                <div class="filter-group">
                    <button class="btn-filter uk-button uk-button-secondary uk-width-1-1 uk-flex uk-flex-middle uk-flex-center gap-8"
                        onclick="applyFilters()"
                        aria-describedby="filter-help">
                        <span uk-icon="icon: filter; ratio: .7" class="uk-icon" aria-hidden="true"></span>
                        <span>Filter</span>
                    </button>
                </div>
            </div>

        </div>
    </div>

    <!-- Session Tabs -->
    <div class="filter-tabs uk-margin-medium-bottom">
        <ul class="uk-tab uk-flex-center" uk-tab>
            <li class="uk-active"><a href="#" onclick="filterByTab('all')">All Sessions (4)</a></li>
            <li><a href="#" onclick="filterByTab('upcoming')">Upcoming (4)</a></li>
            <li><a href="#" onclick="filterByTab('completed')">Completed (3)</a></li>
            <li><a href="#" onclick="filterByTab('cancelled')">Cancelled (1)</a></li>
        </ul>
    </div>

    <!-- Sessions List -->
    <h2 class="uk-heading-divider uk-h4 f600 uk-margin-small-bottom">Your Sessions</h2>

    <div id="sessionsList" class="sessions-list">
        <!-- Session items will be populated here -->
    </div>

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

<!-- Cancel Session Modal -->
<div id="cancel-modal" uk-modal>
    <div class="uk-modal-dialog uk-modal-body">
        <h2 class="uk-modal-title">Cancel Session</h2>

        <p>Are you sure you want to cancel this session? This action cannot be undone.</p>

        <div class="uk-alert-danger" uk-alert>
            <p>Cancellation fees may apply depending on when you cancel.</p>
        </div>

        <p class="uk-text-right">
            <button class="uk-button uk-button-default" type="button" onclick="confirmCancelSession()">Cancel</button>
            <button class="uk-button uk-button-secondary uk-modal-close" type="button">Keep Session</button>
        </p>
    </div>
</div>

<!-- Edit Session Modal -->
<div id="edit-session-modal" 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">Edit Session</h2>

        <form id="editSessionForm" class="uk-form-stacked">
            <div class="uk-grid uk-grid-small uk-child-width-1-2@s" uk-grid>

                <div>
                    <label class="uk-form-label" for="editSessionDate">Date</label>
                    <input class="uk-input" type="date" id="editSessionDate" required>
                </div>

                <div>
                    <label class="uk-form-label" for="editSessionTime">Time</label>
                    <input class="uk-input" type="time" id="editSessionTime" required>
                </div>

            </div>

            <div class="uk-margin">
                <label class="uk-form-label" for="editSessionNotes">Session Notes (Optional)</label>
                <textarea class="uk-textarea" id="editSessionNotes" rows="3" placeholder="Any specific requirements or notes for this session..."></textarea>
            </div>

            <div class="uk-alert uk-alert-warning">
                <span uk-icon="icon: warning; ratio: .8"></span>
                <strong>Note:</strong> Changes made less than 24 hours before the session may incur additional fees.
            </div>

            <div class="uk-text-right uk-margin-top">
                <button class="uk-button uk-button-default uk-modal-close" type="button">Cancel</button>
                <button class="uk-button uk-button-secondary" type="submit">Save Changes</button>
            </div>
        </form>
    </div>
</div>

<!-- Reschedule Confirmation Modal -->
<div id="reschedule-confirmation-modal" uk-modal>
    <div class="uk-modal-dialog uk-modal-body">
        <h2 class="uk-modal-title">Confirm Changes</h2>
        <div id="changesPreview"></div>
        <div class="uk-alert uk-alert-primary">
            <p>
                <strong>Additional Fee:</strong>
                A reschedule fee of 50 SAR will be applied for changes made within 24 hours.
            </p>
        </div>
        <p class="uk-text-right">
            <button class="uk-button uk-button-default uk-modal-close" type="button">Go Back</button>
            <button class="uk-button uk-button-primary" type="button" onclick="confirmSessionChanges()">Confirm Changes</button>
        </p>
    </div>
</div>

<script>
    // Sessions data
    const sessions = [{
            id: 'MS-2025-001',
            title: 'Technical Interview Preparation',
            trainer: {
                name: 'Noor Abdullah',
                expertise: 'Sales Director & Business Development Expert',
                avatar: 'assets/images/trainers/noor-abdullah.jpg'
            },
            date: '2025-01-15',
            time: '2:00 PM',
            duration: '45 minutes',
            language: 'English',
            price: '300 SAR',
            status: 'upcoming',
            note: 'Session starts in 2 hours 30 minutes'
        },
        {
            id: 'MS-2024-098',
            title: 'Data Science Interview Prep',
            trainer: {
                name: 'Mohammed Ali',
                expertise: 'HR & Leadership Expert',
                avatar: 'assets/images/trainers/mohammed-ali.jpg'
            },
            date: '2025-01-09',
            time: '10:00 AM',
            duration: '60 minutes',
            language: 'Arabic',
            price: '450 SAR',
            status: 'completed',
            rating: 5,
            canRate: true,
            sessionReport: {
                strengths: [
                    'Strong grasp of data science fundamentals and algorithms.',
                    'Excellent communication skills when explaining complex concepts.'
                ],
                recommendations: [
                    'Focus on practical application of algorithms in real-world scenarios.',
                    'Practice behavioral questions to improve confidence and response structure.'
                ],
                note: 'A follow-up session is recommended to review progress and address any new questions.',
                attachedFile: 'interview_prep_report.pdf'
            }
        },
        {
            id: 'MS-2024-097',
            title: 'Management Interview Coaching',
            trainer: {
                name: 'Mohammed Ali',
                expertise: 'HR & Leadership Expert',
                avatar: 'assets/images/trainers/mohammed-ali.jpg'
            },
            date: '2025-01-08',
            time: '3:00 PM',
            duration: '45 minutes',
            language: 'Arabic',
            price: '320 SAR',
            status: 'completed',
            rating: 3,
            sessionReport: {
                strengths: [
                    'Strong grasp of data science fundamentals and algorithms.',
                    'Excellent communication skills when explaining complex concepts.'
                ],
                recommendations: [
                    'Focus on practical application of algorithms in real-world scenarios.',
                    'Practice behavioral questions to improve confidence and response structure.'
                ],
                note: 'A follow-up session is recommended to review progress and address any new questions.',
                attachedFile: 'interview_prep_report.pdf'
            }
        },
        {
            id: 'MS-2025-002',
            title: 'Career Development Session',
            trainer: {
                name: 'Fatima Hassan',
                expertise: 'Sales & Marketing Expert',
                avatar: 'assets/images/trainers/fatima-hassan.jpg'
            },
            date: '2025-01-20',
            time: '11:00 AM',
            duration: '60 minutes',
            language: 'English',
            price: '400 SAR',
            status: 'upcoming',
            note: 'Session starts in 5 days'
        },
        {
            id: 'MS-2024-095',
            title: 'Sales Interview Preparation',
            trainer: {
                name: 'Fatima Hassan',
                expertise: 'Sales & Marketing Expert',
                avatar: 'assets/images/trainers/fatima-hassan.jpg'
            },
            date: '2025-01-05',
            scheduledDate: '2025-01-15',
            cancelledBy: 'You',
            refund: '200 SAR',
            status: 'cancelled',
            cancellationReason: 'Personal emergency - unable to attend scheduled session'
        }
    ];

    let filteredSessions = [...sessions];
    let currentTab = 'all';
    let currentSessionToCancel = null;
    let currentSessionToEdit = null;
    let pendingChanges = null;

    // Trainer data mapping
    const trainerData = {
        'noor-abdullah': {
            name: 'Noor Abdullah',
            expertise: 'Sales Director & Business Development Expert',
            avatar: 'assets/images/trainers/noor-abdullah.jpg'
        },
        'mohammed-ali': {
            name: 'Mohammed Ali',
            expertise: 'HR & Leadership Expert',
            avatar: 'assets/images/trainers/mohammed-ali.jpg'
        },
        'fatima-hassan': {
            name: 'Fatima Hassan',
            expertise: 'Sales & Marketing Expert',
            avatar: 'assets/images/trainers/fatima-hassan.jpg'
        }
    };

    // Get sessions count by status
    function getSessionCounts() {
        const counts = {
            all: sessions.length,
            upcoming: sessions.filter(s => s.status === 'upcoming').length,
            completed: sessions.filter(s => s.status === 'completed').length,
            cancelled: sessions.filter(s => s.status === 'cancelled').length
        };
        return counts;
    }

    // Update tab labels with counts
    function updateTabCounts() {
        const counts = getSessionCounts();
        const tabs = document.querySelectorAll('.uk-tab li a');
        tabs[0].textContent = `All Sessions (${counts.all})`;
        tabs[1].textContent = `Upcoming (${counts.upcoming})`;
        tabs[2].textContent = `Completed (${counts.completed})`;
        tabs[3].textContent = `Cancelled (${counts.cancelled})`;
    }

    // Format date
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('en-US', {
            month: 'short',
            day: 'numeric',
            year: 'numeric'
        });
    }

    // Convert 12-hour time to 24-hour format
    function convertTo24Hour(time12h) {
        const [time, period] = time12h.split(' ');
        let [hours, minutes] = time.split(':');

        if (period === 'PM' && hours !== '12') {
            hours = parseInt(hours, 10) + 12;
        } else if (period === 'AM' && hours === '12') {
            hours = '00';
        }

        return `${hours.toString().padStart(2, '0')}:${minutes}`;
    }

    // Convert 24-hour time to 12-hour format
    function convertTo12Hour(time24h) {
        const [hours, minutes] = time24h.split(':');
        const hour = parseInt(hours, 10);
        const period = hour >= 12 ? 'PM' : 'AM';
        const displayHour = hour === 0 ? 12 : hour > 12 ? hour - 12 : hour;

        return `${displayHour}:${minutes} ${period}`;
    }

    // Generate star rating HTML
    function generateStarRating(rating = 0, interactive = false, sessionId = null) {
        let starsHTML = '';
        for (let i = 1; i <= 5; i++) {
            const filled = i <= rating;
            starsHTML += `<span class="star ${filled ? '' : 'empty'}" ${interactive ? `onclick="setRating(${i}, '${sessionId}')"` : ''}><span uk-icon="icon: star-bold; ratio: 1" class="uk-icon" aria-hidden="true"></span></span>`;
        }
        return starsHTML;
    }

    // Edit session function
    function editSession(sessionId) {
        const session = sessions.find(s => s.id === sessionId);
        if (!session) return;

        currentSessionToEdit = sessionId;

        // Populate form with current session data
        document.getElementById('editSessionDate').value = session.date;

        // Convert time format (from "2:00 PM" to "14:00")
        const time24 = convertTo24Hour(session.time);
        document.getElementById('editSessionTime').value = time24;

        // Clear notes field
        document.getElementById('editSessionNotes').value = '';

        // Show modal
        UIkit.modal('#edit-session-modal').show();
    }

    // Handle edit form submission
    document.getElementById('editSessionForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const originalSession = sessions.find(s => s.id === currentSessionToEdit);
        if (!originalSession) return;

        // Get form data
        const date = document.getElementById('editSessionDate').value;
        const time24 = document.getElementById('editSessionTime').value;
        const notes = document.getElementById('editSessionNotes').value;

        // Convert time back to 12-hour format
        const time12 = convertTo12Hour(time24);

        // Prepare changes object
        pendingChanges = {
            sessionId: currentSessionToEdit,
            changes: {
                // No need to set title, trainer, duration, or language as they are no longer editable
                date: date,
                time: time12,
                notes: notes
            }
        };

        // Show changes preview
        showChangesPreview(originalSession, pendingChanges.changes);

        // Close edit modal and show confirmation
        UIkit.modal('#edit-session-modal').hide();
        UIkit.modal('#reschedule-confirmation-modal').show();
    });


    // Show changes preview
    function showChangesPreview(original, changes) {
        const preview = document.getElementById('changesPreview');
        let changesHTML = '<h4 class="uk-h5">Summary of Changes:</h4><ul>';


        if (original.date !== changes.date) {
            changesHTML += `<li><strong>Date:</strong> ${formatDate(original.date)} → ${formatDate(changes.date)}</li>`;
        }

        if (original.time !== changes.time) {
            changesHTML += `<li><strong>Time:</strong> ${original.time} → ${changes.time}</li>`;
        }

        if (changes.notes) {
            changesHTML += `<li><strong>Notes:</strong> ${changes.notes}</li>`;
        }

        changesHTML += '</ul>';
        preview.innerHTML = changesHTML;
    }

    // Confirm session changes
    function confirmSessionChanges() {
        if (!pendingChanges) return;

        // Find and update the session
        const sessionIndex = sessions.findIndex(s => s.id === pendingChanges.sessionId);
        if (sessionIndex !== -1) {
            // Update session with new data
            Object.assign(sessions[sessionIndex], pendingChanges.changes);

            // Add edit timestamp or note
            sessions[sessionIndex].lastModified = new Date().toISOString();
            sessions[sessionIndex].note = 'Session details updated';
        }

        // Close modal
        UIkit.modal('#reschedule-confirmation-modal').hide();

        // Refresh the display
        renderSessions();

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

        // Clear pending changes
        pendingChanges = null;
        currentSessionToEdit = null;
    }

    // Cancel session
    function cancelSession(sessionId) {
        currentSessionToCancel = sessionId;
        UIkit.modal('#cancel-modal').show();
    }

    // Confirm cancel session
    function confirmCancelSession() {
        if (currentSessionToCancel) {
            // Find and update the session status
            const sessionIndex = sessions.findIndex(s => s.id === currentSessionToCancel);
            if (sessionIndex !== -1) {
                sessions[sessionIndex].status = 'cancelled';
                sessions[sessionIndex].cancelledBy = 'You';
                sessions[sessionIndex].refund = sessions[sessionIndex].price;
                sessions[sessionIndex].cancellationReason = 'Cancelled by user';
            }

            // Close modal
            UIkit.modal('#cancel-modal').hide();

            // Refresh the display
            updateTabCounts();
            renderSessions();

            // Show notification
            UIkit.notification({
                message: 'Session cancelled successfully',
                status: 'success',
                pos: 'top-center',
                timeout: 3000
            });

            currentSessionToCancel = null;
        }
    }

    // Submit rating and comment
    function submitRating(sessionId) {
        const ratingSection = document.querySelector(`[data-session-id="${sessionId}"] .rating-section`);
        const selectedStars = ratingSection.querySelectorAll('.star:not(.empty)').length;
        const comment = ratingSection.querySelector('textarea').value.trim();

        if (selectedStars === 0) {
            UIkit.notification({
                message: 'Please select a rating',
                status: 'warning',
                pos: 'top-center',
                timeout: 3000
            });
            return;
        }

        // Find and update the session
        const sessionIndex = sessions.findIndex(s => s.id === sessionId);
        if (sessionIndex !== -1) {
            sessions[sessionIndex].rating = selectedStars;
            sessions[sessionIndex].comment = comment;
            sessions[sessionIndex].canRate = false;
        }

        // Refresh the display
        renderSessions();

        // Show notification
        UIkit.notification({
            message: 'Rating submitted successfully',
            status: 'success',
            pos: 'top-center',
            timeout: 3000
        });
    }

    // Render sessions
    function renderSessions(sessionsToRender = filteredSessions) {
        const container = document.getElementById('sessionsList');

        if (sessionsToRender.length === 0) {
            container.innerHTML = `
                <div class="empty-state">
                    <div class="empty-icon">
                        <span uk-icon="icon: sessions; ratio: 3" class="uk-icon"></span>
                    </div>
                    <div class="empty-title">No sessions found</div>
                    <div class="empty-description">Try adjusting your filters or book a new session</div>
                </div>
            `;
            return;
        }

        container.innerHTML = sessionsToRender.map(session => {
            let actionsHTML = '';
            let ratingHTML = '';
            let noteHTML = '';
            let reportHTML = '';
            let cancellationHTML = '';

            // Add note for upcoming sessions
            if (session.status === 'upcoming' && session.note) {
                noteHTML = `<div class="session-note gap-6"><span uk-icon="icon: time-left; ratio: 1.2" class="uk-icon" aria-hidden="true"></span> ${session.note}</div>`;
            }

            // Add session report for completed sessions
            if (session.status === 'completed' && session.sessionReport) {
                reportHTML = `
                    <div uk-alert class="session-report uk-alert uk-alert-success uk-margin-medium">
                        <h3 class="uk-h4 f600">Session Report</h3>
                        <div class="report-content uk-margin-small-top">
                            <h4 class="uk-h5 f600">Strengths</h4>
                            <ul>
                                ${session.sessionReport.strengths.map(strength => `<li>${strength}</li>`).join('')}
                            </ul>
                            <h4 class="uk-h5 f600">Recommendations</h4>
                            <ul>
                                ${session.sessionReport.recommendations.map(rec => `<li>${rec}</li>`).join('')}
                            </ul>
                            ${session.sessionReport.note ?
                                `<p><h4 class="uk-h5 f600">Note:</h4> ${session.sessionReport.note}</p>`
                                : ''}
                            ${session.sessionReport.attachedFile ? 
                                `<p><h4 class="uk-h5 f600">Attached File:<small><a href="#">${session.sessionReport.attachedFile}</a></small></h4></p>` 
                                : ''}
                        </div>
                    </div>
                `;
            }

            // Add cancellation reason for cancelled sessions
            if (session.status === 'cancelled' && session.cancellationReason) {
                cancellationHTML = `
                    <div uk-alert class="cancellation-reason uk-alert uk-alert-danger uk-margin-medium">
                        <div class="cancellation-title f600 uk-margin-remove">Cancellation Reason</div>
                        <div class="cancellation-content uk-margin-small-top">${session.cancellationReason}</div>
                    </div>
                `;
            }

            // Generate actions based on status
            if (session.status === 'upcoming') {
                actionsHTML = `
                    <div class="uk-flex uk-flex-middle gap-12">
                        <button class="uk-button uk-button-primary">
                            <span uk-icon="icon: sessions; ratio: 0.8"></span> Join Session
                        </button>
                        <button class="uk-button uk-button-secondary" onclick="editSession('${session.id}')">
                            <span uk-icon="icon: pencil; ratio: 0.8"></span> Edit Session
                        </button>
                        <button class="uk-button uk-button-default" onclick="cancelSession('${session.id}')">
                            <span uk-icon="icon: close; ratio: 0.8"></span> Cancel Session
                        </button>
                    </div>
                `;
            } else if (session.status === 'completed') {
                if (session.canRate) {
                    ratingHTML = `
                        <div class="rating-section" data-session-id="${session.id}">
                            <div class="rating-title f600 uk-margin-remove">Rate Your Session</div>
                            <div class="star-rating">
                                ${generateStarRating(0, true, session.id)}
                            </div>
                            <div class="uk-margin-medium-top uk-margin-small-bottom">
                                <label class="uk-form-label">Your Comment (Optional)</label>
                                <textarea class="uk-textarea" rows="3" placeholder="Share your experience with this session..."></textarea>
                            </div>
                            <button class="uk-button uk-button-primary uk-button-small" onclick="submitRating('${session.id}')">Submit Rating</button>
                        </div>
                    `;
                } else if (session.rating) {
                    ratingHTML = `
                        <div class="rating-section">
                            <div class="rating-title f600 uk-margin-remove">Your Rating</div>
                            <div class="rate-is-done">
                                ${generateStarRating(session.rating)}
                            </div>
                            ${session.comment ? `<div class="rating-comment uk-text-muted"><strong>Your comment:</strong> ${session.comment}</div>` : ''}
                        </div>
                    `;
                }
            }

            return `
                <div class="session-item session-item-${session.status}" data-session-id="${session.id}">
                    <div class="session-header uk-margin-medium-bottom uk-grid uk-flex-top" uk-grid>
                        <div class="uk-width-expand@s">
                            <div class="session-id">${session.id}</div>
                            <h3 class="session-title uk-margin-remove">${session.title}</h3>
                        </div>
                        <div class="uk-width-auto@s">
                        <span class="session-status gap-4 ${session.status}"><span uk-icon="icon: ${session.status}; ratio: .6" class="uk-icon" aria-hidden="true"></span>${session.status}</span>
                        </div>
                    </div>

                    <div class="trainer-info uk-flex uk-flex-middle gap-16">
                        <img src="assets/svg/avatar-small.svg" width="60" height="60" alt="${session.trainer.name}" class="trainer-avatar uk-border-circle">
                        <div class="trainer-details">
                            <h4 class="uk-margin-remove f600">${session.trainer.name}</h4>
                            <p class="uk-margin-remove">${session.trainer.expertise}</p>
                        </div>
                    </div>

                    ${noteHTML}

                    <div class="session-details uk-grid uk-grid-small uk-child-width-1-2 uk-child-width-1-5@s uk-margin-medium uk-grid-match" uk-grid>
                        ${session.status !== 'cancelled' ? `
                        <div>
                            <div class="detail-item">
                                <div class="detail-label">Date</div>
                                <div class="detail-value">${formatDate(session.date)}</div>
                            </div>
                        </div>
                        <div>
                            <div class="detail-item">
                                <div class="detail-label">Time</div>
                                <div class="detail-value">${session.time}</div>
                            </div>
                        </div>
                        <div>
                            <div class="detail-item">
                                <div class="detail-label">Duration</div>
                                <div class="detail-value">${session.duration}</div>
                            </div>
                        </div>
                        <div>
                        <div class="detail-item">
                                <div class="detail-label">Language</div>
                                <div class="detail-value">${session.language}</div>
                            </div>
                        </div>
                        <div>
                            <div class="detail-item">
                                <div class="detail-label">Price</div>
                                <div class="detail-value">${session.price}</div>
                            </div>
                        </div>
                        ` : `
                        <div>
                            <div class="detail-item">
                                <div class="detail-label">Original Date</div>
                                <div class="detail-value">${formatDate(session.date)}</div>
                            </div>
                        </div>
                        <div>
                            <div class="detail-item">
                                <div class="detail-label">Scheduled Date</div>
                                <div class="detail-value">${formatDate(session.scheduledDate)}</div>
                            </div>
                        </div>
                        <div>
                            <div class="detail-item">
                                <div class="detail-label">Cancelled By</div>
                                <div class="detail-value">${session.cancelledBy}</div>
                            </div>
                        </div>
                        <div>
                            <div class="detail-item">
                                <div class="detail-label">Refund</div>
                                <div class="detail-value">${session.refund}</div>
                            </div>
                        </div>
                        `}
                    </div>

                    ${reportHTML}
                    ${cancellationHTML}
                    ${ratingHTML}

                    <div class="session-actions">
                        ${actionsHTML}
                    </div>
                </div>
            `;
        }).join('');
    }

    // Filter by tab
    function filterByTab(tab) {
        currentTab = tab;

        // Update active tab
        document.querySelectorAll('.uk-tab li').forEach(li => li.classList.remove('uk-active'));
        event.target.parentElement.classList.add('uk-active');

        // Filter sessions
        if (tab === 'all') {
            filteredSessions = [...sessions];
        } else {
            filteredSessions = sessions.filter(session => session.status === tab);
        }

        renderSessions(filteredSessions);
    }

    // Apply filters
    function applyFilters() {
        const statusFilter = document.getElementById('statusFilter').value;
        const trainerFilter = document.getElementById('trainerFilter').value;
        const dateRange = document.getElementById('dateRange').value;

        filteredSessions = sessions.filter(session => {
            // Status filter
            if (statusFilter && session.status !== statusFilter) {
                return false;
            }

            // Trainer filter
            if (trainerFilter) {
                const trainerSlug = session.trainer.name.toLowerCase().replace(/\s+/g, '-');
                if (trainerSlug !== trainerFilter) {
                    return false;
                }
            }

            // Date filter (simple date comparison)
            if (dateRange) {
                const sessionDate = new Date(session.date);
                const filterDate = new Date(dateRange);
                if (sessionDate.toDateString() !== filterDate.toDateString()) {
                    return false;
                }
            }

            return true;
        });

        renderSessions(filteredSessions);

        UIkit.notification({
            message: `Found ${filteredSessions.length} sessions`,
            status: 'primary',
            pos: 'top-center',
            timeout: 2000
        });
    }

    // Set rating (for interactive rating)
    function setRating(rating, sessionId) {
        const ratingSection = document.querySelector(`[data-session-id="${sessionId}"] .rating-section`);
        const stars = ratingSection.querySelectorAll('.star');

        stars.forEach((star, index) => {
            if (index < rating) {
                star.classList.remove('empty');
            } else {
                star.classList.add('empty');
            }
        });
    }

    // Initialize page
    document.addEventListener('DOMContentLoaded', function() {
        // Update tab counts
        updateTabCounts();

        // Render initial sessions
        renderSessions();
    });
</script>

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