<?php require_once __DIR__ . '/_site_content.php';
header('Location: academy.php', true, 301); exit;
// Load courses from LMS and prepare region-aware lists
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../classes/Course.php';
$courseModel = new Course();
// Featured courses (up to 3) and initial page of courses (12)
$featuredCourses = $courseModel->getCourses(['featured' => 1, 'region' => $region], 3, 0);
$allCoursesInitial = $courseModel->getCourses(['region' => $region], 12, 0);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php sc_text('courses', 'meta_title', 'Courses - SmartThink', $region); ?></title>
    <!-- Core CSS frameworks -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Project styles -->
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/modern-ux.css">
    <link rel="stylesheet" href="../assets/css/capgemini-theme.css">
    <link rel="stylesheet" href="../assets/css/page-styles.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
</head>
<body>
    <!-- Scroll Progress Bar -->
    <div class="scroll-progress" id="scrollProgress"></div>
    
    <!-- Utility Bar - Top -->
    <div class="utility-bar">
        <div class="container">
            <div class="utility-links">
                <a href="contact.php">Contact us</a>
                <a href="#">Investors <i class="fas fa-external-link-alt" style="font-size: 0.7em;"></i></a>
            </div>
            <div class="utility-right">
                <div class="global-dropdown" id="globalDropdown">
                    <button class="global-dropdown-toggle" onclick="toggleGlobalDropdown()">
                        <i class="fas fa-globe"></i>
                        <span>Global | EN</span>
                        <i class="fas fa-chevron-down" style="font-size: 0.7em;"></i>
                    </button>
                    <div class="global-dropdown-menu">
                        <div class="global-dropdown-header">
                            <h4>Select your region</h4>
                        </div>
                        <div class="global-dropdown-regions">
                            <div class="region-group">
                                <div class="region-group-title">Americas</div>
                                <div class="region-options-list">
                                    <a href="#" class="region-option active" onclick="selectRegion('usa', this)">
                                        <span class="region-flag">🇺🇸</span>
                                        <span class="region-name">United States</span>
                                    </a>
                                    <a href="#" class="region-option" onclick="selectRegion('canada', this)">
                                        <span class="region-flag">🇨🇦</span>
                                        <span class="region-name">Canada</span>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="utility-item">
                    <i class="fas fa-search"></i>
                    <span>Search</span>
                </div>
                <div class="theme-toggle" onclick="toggleTheme()">
                    <i class="fas fa-moon" id="themeIcon"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Capgemini-Style Header -->
    <header class="cap-header">
        <div class="container">
            <a class="cap-brand" href="index.php">
                <img src="../assets/images/logo.jpeg" alt="SmartThink" class="cap-logo">
                <span class="cap-brand-text">SmartThink</span>
            </a>
            
            <nav>
                <ul class="cap-nav">
                    <li class="cap-nav-item"><a class="cap-nav-link" href="index.php">Home</a></li>
                    <li class="cap-nav-item"><a class="cap-nav-link" href="about.php">About us</a></li>
                    <li class="cap-nav-item has-dropdown">
                        <a class="cap-nav-link" href="services.php">
                            Services
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <div class="cap-dropdown">
                            <a class="cap-dropdown-link" href="advisory_it_solutions.php">Advisory and IT Solutions</a>
                            <a class="cap-dropdown-link" href="training.php">Training</a>
                            <a class="cap-dropdown-link" href="recruitment.php">Recruitment</a>
                        </div>
                    </li>
                    <li class="cap-nav-item"><a class="cap-nav-link active" href="courses.php">Courses</a></li>
                    <li class="cap-nav-item"><a class="cap-nav-link" href="careers.php">Careers</a></li>
                    <li class="cap-nav-item has-dropdown">
                        <a class="cap-nav-link" href="training.php">
                            Training
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <div class="cap-dropdown">
                            <a class="cap-dropdown-link" href="cyber_grc.php">Cyber GRC</a>
                            <a class="cap-dropdown-link" href="ai_governance.php">AI Governance</a>
                        </div>
                    </li>
                </ul>
            </nav>

            <div class="d-flex align-items-center">
                <!-- Auth Buttons -->
                <div class="cap-auth ms-4">
                    <a href="../lms/login.php" class="btn-cap-login">Login</a>
                    <a href="../lms/register.php" class="btn-cap-register">Register</a>
                </div>
                
                <button class="navbar-toggler d-lg-none ms-3" type="button" style="background: transparent; border: none; color: white;" onclick="document.querySelector('.cap-nav').classList.toggle('open')">
                    <i class="fas fa-bars"></i>
                </button>
            </div>
        </div>
    </header>

    <!-- Courses Hero Section -->
    <section class="page-hero">
        <div class="hero-background">
            <div class="hero-overlay"></div>
        </div>
        <div class="container">
            <div class="row align-items-center min-vh-100">
                <div class="col-lg-8 mx-auto text-center">
                    <div class="hero-content-modern">
                        <div class="hero-badge">
                            <span class="badge-text"><?php sc_text('courses', 'hero_badge', '500+ Courses', $region); ?></span>
                        </div>
                        <h1 class="hero-title-modern"><?php sc_text('courses', 'hero_title', 'Discover Your Learning Path', $region); ?></h1>
                        <p class="hero-subtitle-modern"><?php sc_html('courses', 'hero_subtitle', 'Explore our comprehensive catalog of professional courses designed to accelerate your career growth and unlock new opportunities.', $region); ?></p>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- Course Filters Section -->
    <section class="course-filters">
        <div class="container">
            <div class="filter-tabs">
                <button class="filter-tab active" data-filter="all">All Courses</button>
                <button class="filter-tab" data-filter="business">Business</button>
                <button class="filter-tab" data-filter="technology">Technology</button>
                <button class="filter-tab" data-filter="design">Design</button>
                <button class="filter-tab" data-filter="marketing">Marketing</button>
                <button class="filter-tab" data-filter="personal">Personal Development</button>
            </div>
            
            <div class="search-bar">
                <div class="search-input-wrapper">
                    <i class="fas fa-search"></i>
                    <input type="text" id="courseSearch" placeholder="Search for courses...">
                </div>
                <div class="filter-dropdowns">
                    <select id="levelFilter">
                        <option value="">All Levels</option>
                        <option value="beginner">Beginner</option>
                        <option value="intermediate">Intermediate</option>
                        <option value="advanced">Advanced</option>
                    </select>
                    <select id="durationFilter">
                        <option value="">All Durations</option>
                        <option value="short">Under 2 hours</option>
                        <option value="medium">2-6 hours</option>
                        <option value="long">6+ hours</option>
                    </select>
                    <select id="priceFilter">
                        <option value="">All Prices</option>
                        <option value="free">Free</option>
                        <option value="paid">Paid</option>
                    </select>
                </div>
            </div>
        </div>
    </section>

    <!-- Featured Courses Section -->
    <section class="featured-courses">
        <div class="container">
            <div class="section-header-modern">
                <h2 class="section-title-modern"><?php sc_text('courses', 'featured_title', 'Featured Courses', $region); ?></h2>
                <p class="section-subtitle-modern"><?php sc_html('courses', 'featured_subtitle', 'Hand-picked courses to kickstart your learning journey', $region); ?></p>
            </div>
            
            <div class="row g-4" id="featuredCourses">
                <?php if (empty($featuredCourses)): ?>
                    <div class="col-12">
                        <p class="text-muted">No featured courses available for this region.</p>
                    </div>
                <?php else: foreach ($featuredCourses as $c): ?>
                    <div class="col-lg-4 col-md-6">
                        <?php $catSlug = strtolower(preg_replace('/[^a-zA-Z0-9]+/','', $c['category_name'] ?? '')); ?>
                    <div class="course-card" data-category="<?php echo $catSlug; ?>" data-level="<?php echo htmlspecialchars($c['level'] ?? ''); ?>" data-duration="<?php echo htmlspecialchars($c['duration'] ?? 'medium'); ?>" data-price="<?php echo ($c['price'] > 0) ? 'paid' : 'free'; ?>">
                            <div class="course-image">
                                <?php
                                    $thumb = $c['thumbnail'] ?? '';
                                    $thumbLocal = $thumb ? __DIR__ . '/../' . ltrim($thumb, '/') : '';
                                    $baseUrl = defined('APP_URL') ? rtrim(APP_URL, '/') : '';
                                    if ($thumb && file_exists($thumbLocal)) {
                                        $thumbSrc = (stripos($thumb, 'http') === 0) ? $thumb : $baseUrl . '/' . ltrim($thumb, '/');
                                    } else {
                                        $thumbSrc = $baseUrl . '/assets/images/course-placeholder.jpg';
                                    }
                                ?>
                                <img src="<?php echo htmlspecialchars($thumbSrc); ?>" alt="<?php echo htmlspecialchars($c['title']); ?>" class="img-fluid">
                                <div class="course-badge"><?php echo (!empty($c['featured']) ? 'Featured' : (!empty($c['is_new']) ? 'New' : '')); ?></div>
                                <div class="course-overlay">
                                    <button class="play-button"><i class="fas fa-play"></i></button>
                                </div>
                            </div>
                            <div class="course-content">
                                <div class="course-meta">
                                    <span class="course-category"><?php echo htmlspecialchars($c['category_name']); ?></span>
                                    <span class="course-level"><?php echo htmlspecialchars(ucfirst($c['level'] ?? '')); ?></span>
                                </div>
                                <h3 class="course-title"><?php echo htmlspecialchars($c['title']); ?></h3>
                                <p class="course-description"><?php echo htmlspecialchars($c['short_description'] ?? substr($c['description'] ?? '', 0, 120)); ?></p>
                                <div class="course-info">
                                    <div class="info-item"><i class="fas fa-calendar-alt"></i><span>
                                        <?php
                                            if (!empty($c['start_date']) && !empty($c['end_date'])) {
                                                echo htmlspecialchars(date('M j', strtotime($c['start_date'])) . ' - ' . date('M j, Y', strtotime($c['end_date'])));
                                            } elseif (!empty($c['start_date'])) {
                                                echo htmlspecialchars('Starts ' . date('M j, Y', strtotime($c['start_date'])));
                                            } else {
                                                echo 'Schedule TBA';
                                            }
                                        ?>
                                    </span></div>
                                    <div class="info-item"><i class="fas fa-signal"></i><span><?php echo htmlspecialchars(ucfirst($c['level'] ?? '')); ?></span></div>
                                    <div class="info-item"><i class="fas fa-users"></i><span><?php echo (int)($c['enrollment_count'] ?? 0); ?> students</span></div>
                                </div>
                                <div class="course-instructor">
                                    <img src="<?php echo htmlspecialchars($c['instructor_avatar'] ?? '../assets/images/instructor-placeholder.jpg'); ?>" alt="Instructor" class="instructor-avatar">
                                    <div class="instructor-info">
                                        <span class="instructor-name"><?php echo htmlspecialchars($c['first_name'] . ' ' . $c['last_name']); ?></span>
                                        <div class="instructor-rating"><i class="fas fa-star"></i><span><?php echo round((float)($c['rating'] ?? 0), 1); ?></span></div>
                                    </div>
                                </div>
                                <div class="course-price">
                                    <span class="price-current" data-price="<?php echo htmlspecialchars($c['price'] ?? 0); ?>"><?php echo ($c['price'] > 0) ? ('$' . number_format($c['price'], 2)) : 'Free'; ?></span>
                                </div>
                                <a href="<?php echo APP_URL . '/website/course.php?course_id=' . (int)$c['id']; ?>" class="btn btn-primary w-100">View Course</a>
                            </div>
                        </div>
                    </div>
                <?php endforeach; endif; ?>
            </div>
        </div>
    </section>

    <!-- All Courses Section -->
    <section class="all-courses">
        <div class="container">
            <div class="section-header-modern">
                <h2 class="section-title-modern"><?php sc_text('courses', 'all_courses_title', 'All Courses', $region); ?></h2>
                <p class="section-subtitle-modern"><?php sc_html('courses', 'all_courses_subtitle', 'Browse our complete collection of courses', $region); ?></p>
            </div>
            
            <?php
                // Server-side pagination values
                $perPage = 12;
                $page = 1;
                $totalCourses = $courseModel->countCourses(['region' => $region]);
                $totalPages = max(1, (int)ceil($totalCourses / $perPage));
            ?>
            <div class="row g-4" id="allCourses">
                <?php if (empty($allCoursesInitial)): ?>
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body text-center text-muted">No courses available for this region.</div>
                        </div>
                    </div>
                <?php else: foreach ($allCoursesInitial as $c): ?>
                    <div class="col-lg-4 col-md-6">
                        <?php $catSlug = strtolower(preg_replace('/[^a-zA-Z0-9]+/','', $c['category_name'] ?? '')); ?>
                        <div class="course-card" data-category="<?php echo $catSlug; ?>" data-level="<?php echo htmlspecialchars($c['level'] ?? ''); ?>" data-duration="<?php echo htmlspecialchars($c['duration'] ?? 'medium'); ?>" data-price="<?php echo ($c['price'] > 0) ? 'paid' : 'free'; ?>">
                            <div class="course-image">
                                <?php
                                    $thumb = $c['thumbnail'] ?? '';
                                    $thumbLocal = $thumb ? __DIR__ . '/../' . ltrim($thumb, '/') : '';
                                    $baseUrl = defined('APP_URL') ? rtrim(APP_URL, '/') : '';
                                    if ($thumb && file_exists($thumbLocal)) {
                                        $thumbSrc = (stripos($thumb, 'http') === 0) ? $thumb : $baseUrl . '/' . ltrim($thumb, '/');
                                    } else {
                                        $thumbSrc = $baseUrl . '/assets/images/course-placeholder.jpg';
                                    }
                                ?>
                                <img src="<?php echo htmlspecialchars($thumbSrc); ?>" alt="<?php echo htmlspecialchars($c['title']); ?>" class="img-fluid">
                            </div>
                            <div class="course-content">
                                <div class="course-meta">
                                    <span class="course-category"><?php echo htmlspecialchars($c['category_name']); ?></span>
                                    <span class="course-level"><?php echo htmlspecialchars(ucfirst($c['level'] ?? '')); ?></span>
                                </div>
                                <h3 class="course-title"><?php echo htmlspecialchars($c['title']); ?></h3>
                                <p class="course-description"><?php echo htmlspecialchars($c['short_description'] ?? substr($c['description'] ?? '', 0, 120)); ?></p>
                                <div class="course-info">
                                    <div class="info-item"><i class="fas fa-calendar-alt"></i><span>
                                        <?php
                                            if (!empty($c['start_date']) && !empty($c['end_date'])) {
                                                echo htmlspecialchars(date('M j', strtotime($c['start_date'])) . ' - ' . date('M j, Y', strtotime($c['end_date'])));
                                            } elseif (!empty($c['start_date'])) {
                                                echo htmlspecialchars('Starts ' . date('M j, Y', strtotime($c['start_date'])));
                                            } else {
                                                echo 'Schedule TBA';
                                            }
                                        ?>
                                    </span></div>
                                    <div class="info-item"><i class="fas fa-users"></i><span><?php echo (int)($c['enrollment_count'] ?? 0); ?> students</span></div>
                                </div>
                                <div class="course-price">
                                    <span class="price-current"><?php echo ($c['price'] > 0) ? ('$' . number_format($c['price'], 2)) : 'Free'; ?></span>
                                </div>
                                <a href="<?php echo APP_URL . '/website/course.php?course_id=' . (int)$c['id']; ?>" class="btn btn-primary w-100">View Course</a>
                            </div>
                        </div>
                    </div>
                <?php endforeach; endif; ?>
            </div>

            <div class="text-center mt-5">
                <?php if ($totalPages > 1): ?>
                    <button class="btn btn-outline btn-lg" id="loadMoreCourses" data-page="1" data-per-page="<?php echo $perPage; ?>" data-total-pages="<?php echo $totalPages; ?>">
                        <i class="fas fa-plus"></i> Load More Courses
                    </button>
                <?php endif; ?>
            </div>
            
            <div class="text-center mt-5">
                <button class="btn btn-outline btn-lg" id="loadMoreCourses">
                    <i class="fas fa-plus"></i> Load More Courses
                </button>
            </div>
        </div>
    </section>

    <!-- Learning Paths Section -->
    <section class="learning-paths">
        <div class="container">
            <div class="section-header-modern">
                <h2 class="section-title-modern"><?php sc_text('courses', 'learning_paths_title', 'Learning Paths', $region); ?></h2>
                <p class="section-subtitle-modern"><?php sc_html('courses', 'learning_paths_subtitle', 'Structured learning journeys for career advancement', $region); ?></p>
            </div>
            
            <div class="row g-4">
                <div class="col-lg-4">
                    <div class="path-card">
                        <div class="path-icon">
                            <i class="fas fa-code"></i>
                        </div>
                        <h3>Full Stack Developer</h3>
                        <p>Become a proficient full stack developer with our comprehensive learning path.</p>
                        <div class="path-stats">
                            <span>12 Courses</span>
                            <span>48 Hours</span>
                        </div>
                        <button class="btn btn-outline">Start Path</button>
                    </div>
                </div>
                
                <div class="col-lg-4">
                    <div class="path-card">
                        <div class="path-icon">
                            <i class="fas fa-chart-line"></i>
                        </div>
                        <h3>Digital Marketing Expert</h3>
                        <p>Master digital marketing strategies and become an industry expert.</p>
                        <div class="path-stats">
                            <span>8 Courses</span>
                            <span>32 Hours</span>
                        </div>
                        <button class="btn btn-outline">Start Path</button>
                    </div>
                </div>
                
                <div class="col-lg-4">
                    <div class="path-card">
                        <div class="path-icon">
                            <i class="fas fa-paint-brush"></i>
                        </div>
                        <h3>UI/UX Designer</h3>
                        <p>Learn design principles and create stunning user experiences.</p>
                        <div class="path-stats">
                            <span>10 Courses</span>
                            <span>40 Hours</span>
                        </div>
                        <button class="btn btn-outline">Start Path</button>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- WhatsApp Widget -->
    <div class="whatsapp-widget" id="whatsappWidget">
        <div class="whatsapp-button">
            <i class="fab fa-whatsapp"></i>
        </div>
        <div class="whatsapp-chat">
            <div class="chat-header">
                <h4>SmartThink Support</h4>
                <span class="status">Online</span>
            </div>
            <div class="chat-messages" id="chatMessages">
                <div class="message bot">
                    Hello! How can I help you find the right course today?
                </div>
            </div>
            <div class="chat-input">
                <input type="text" id="chatInput" placeholder="Type your message...">
                <button id="sendMessage"><i class="fas fa-paper-plane"></i></button>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="cap-footer">
        <div class="container">
            <div class="footer-main">
                <div class="row">
                    <div class="col-lg-4">
                        <div class="footer-brand-cap">
                            <img src="../assets/images/logo.jpeg" alt="SmartThink" class="footer-logo-cap">
                            <p><?php sc_html('home', 'footer_about', 'Empowering learners globally with cutting-edge educational technology and world-class content.', $region); ?></p>
                            <div class="footer-social-cap">
                                <a href="#"><i class="fab fa-linkedin"></i></a>
                                <a href="#"><i class="fab fa-twitter"></i></a>
                                <a href="#"><i class="fab fa-facebook"></i></a>
                                <a href="#"><i class="fab fa-youtube"></i></a>
                                <a href="#"><i class="fab fa-instagram"></i></a>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-2 col-md-4">
                        <div class="footer-links-cap">
                            <h4>About us</h4>
                            <ul>
                                <li><a href="about.php">Who we are</a></li>
                                <li><a href="leadership.php">Leadership</a></li>
                                <li><a href="sustainability.php">Sustainability</a></li>
                                <li><a href="awards.php">Awards</a></li>
                            </ul>
                        </div>
                    </div>
                    
                    <div class="col-lg-2 col-md-4">
                        <div class="footer-links-cap">
                            <h4>Services</h4>
                            <ul>
                                <li><a href="training.php">Training</a></li>
                                <li><a href="consulting.php">Consulting</a></li>
                                <li><a href="recruitment.php">Recruitment</a></li>
                                <li><a href="support.php">Support</a></li>
                            </ul>
                        </div>
                    </div>
                    
                    <div class="col-lg-2 col-md-4">
                        <div class="footer-links-cap">
                            <h4>Insights</h4>
                            <ul>
                                <li><a href="blog.php">Blog</a></li>
                                <li><a href="research.php">Research</a></li>
                                <li><a href="case-studies.php">Case studies</a></li>
                                <li><a href="events.php">Events</a></li>
                            </ul>
                        </div>
                    </div>

                    <div class="col-lg-2 col-md-4">
                        <div class="footer-links-cap">
                            <h4>Careers</h4>
                            <ul>
                                <li><a href="jobs.php">Search jobs</a></li>
                                <li><a href="culture.php">Our culture</a></li>
                                <li><a href="students.php">Students</a></li>
                                <li><a href="professionals.php">Professionals</a></li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="footer-bottom-cap">
                <div class="row align-items-center">
                    <div class="col-md-6">
                        <p class="copyright-cap">&copy; 2026 SmartThink. All rights reserved.</p>
                    </div>
                    <div class="col-md-6">
                        <div class="footer-bottom-links-cap">
                            <a href="privacy-policy.php">Data Privacy Policy</a>
                            <a href="training-agreement.php">Training Non-Compete &amp; Materials</a>
                            <a href="payment-policy.php">Non-Refundable Payment Policy</a>
                            <a href="sitemap.php">Sitemap</a>
                        </div>
                    </div>
                </div>
            </div>

            <div class="footer-newsletter">
                <div class="row align-items-center">
                    <div class="col-md-6 mb-3 mb-md-0">
                        <h4>Stay ahead in cybersecurity</h4>
                        <p>Get updates on new courses, insights, and security trends straight to your inbox.</p>
                    </div>
                    <div class="col-md-6">
                        <form class="footer-newsletter-form" action="#" method="post">
                            <input type="email" name="newsletter_email" placeholder="Work email address" required>
                            <button type="submit">Subscribe</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </footer>

    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/js/all.min.js"></script>
    <script src="../assets/js/main.js"></script>
    <script src="../assets/js/modern-interactions.js"></script>
    <script src="../assets/js/global-theme.js"></script>
    <script>
        // Course filtering functionality
        document.addEventListener('DOMContentLoaded', function() {
            const filterTabs = document.querySelectorAll('.filter-tab');
            const courseCards = document.querySelectorAll('.course-card');
            const searchInput = document.getElementById('courseSearch');
            const levelFilter = document.getElementById('levelFilter');
            const durationFilter = document.getElementById('durationFilter');
            const priceFilter = document.getElementById('priceFilter');

            function filterCourses() {
                const activeFilter = document.querySelector('.filter-tab.active').dataset.filter;
                const searchTerm = searchInput.value.toLowerCase();
                const levelValue = levelFilter.value;
                const durationValue = durationFilter.value;
                const priceValue = priceFilter.value;

                courseCards.forEach(card => {
                    const category = card.dataset.category;
                    const level = card.dataset.level;
                    const duration = card.dataset.duration;
                    const price = card.dataset.price;
                    const title = card.querySelector('.course-title').textContent.toLowerCase();
                    const description = card.querySelector('.course-description').textContent.toLowerCase();

                    let matchesFilter = activeFilter === 'all' || category === activeFilter;
                    let matchesSearch = title.includes(searchTerm) || description.includes(searchTerm);
                    let matchesLevel = !levelValue || level === levelValue;
                    let matchesDuration = !durationValue || duration === durationValue;
                    let matchesPrice = !priceValue || price === priceValue;

                    if (matchesFilter && matchesSearch && matchesLevel && matchesDuration && matchesPrice) {
                        card.style.display = 'block';
                    } else {
                        card.style.display = 'none';
                    }
                });
            }

            filterTabs.forEach(tab => {
                tab.addEventListener('click', function() {
                    filterTabs.forEach(t => t.classList.remove('active'));
                    this.classList.add('active');
                    filterCourses();
                });
            });

            searchInput.addEventListener('input', filterCourses);
            levelFilter.addEventListener('change', filterCourses);
            durationFilter.addEventListener('change', filterCourses);
            priceFilter.addEventListener('change', filterCourses);

            // Load More (AJAX) pagination
            const loadMoreBtn = document.getElementById('loadMoreCourses');
            if (loadMoreBtn) {
                loadMoreBtn.addEventListener('click', function() {
                    const btn = this;
                    let page = parseInt(btn.dataset.page, 10) || 1;
                    const perPage = parseInt(btn.dataset.perPage, 10) || 12;
                    const totalPages = parseInt(btn.dataset.totalPages, 10) || 1;

                    const nextPage = page + 1;
                    if (nextPage > totalPages) {
                        btn.style.display = 'none';
                        return;
                    }

                    // include client-side filter values in request for consistency
                    const params = new URLSearchParams();
                    params.set('page', nextPage);
                    params.set('per_page', perPage);
                    const q = searchInput.value.trim(); if (q) params.set('search', q);
                    const lev = levelFilter.value; if (lev) params.set('level', lev);
                    const dur = durationFilter.value; if (dur) params.set('duration', dur);
                    const price = priceFilter.value; if (price === 'free') params.set('free_only', '1');
                    // region remembered server-side; pass optionally
                    const url = 'api/courses.php?' + params.toString();

                    btn.disabled = true;
                    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Loading...';

                    fetch(url).then(resp => resp.json()).then(data => {
                        if (data && data.success) {
                            const container = document.getElementById('allCourses');
                            const tmp = document.createElement('div');
                            tmp.innerHTML = data.html;
                            // append child nodes preserving column wrappers
                            while (tmp.firstChild) container.appendChild(tmp.firstChild);

                            // update button page
                            btn.dataset.page = nextPage;

                            // hide if last
                            if (nextPage >= data.total_pages) {
                                btn.style.display = 'none';
                            }
                        } else {
                            alert('Failed to load more courses.');
                        }
                    }).catch(() => {
                        alert('Failed to load more courses.');
                    }).finally(() => {
                        btn.disabled = false;
                        btn.innerHTML = '<i class="fas fa-plus"></i> Load More Courses';
                    });
                });
            }

            // Region selector - set region via API (persists to session and user profile) and reload
            const regionButtons = document.querySelectorAll('.region-btn');
            regionButtons.forEach(btn => {
                btn.addEventListener('click', function() {
                    regionButtons.forEach(b => b.classList.remove('active'));
                    this.classList.add('active');
                    const region = this.getAttribute('data-region');

                    fetch('api/set_region.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: new URLSearchParams({ region })
                    }).then(resp => resp.json()).then(data => {
                        if (data && data.success) {
                            // reload page to show region-specific content
                            const url = new URL(window.location);
                            url.searchParams.set('region', data.region);
                            url.searchParams.delete('page');
                            window.location = url.toString();
                        } else {
                            alert('Failed to set region.');
                        }
                    }).catch(() => {
                        alert('Failed to set region.');
                    });
                });
            });
        });
    </script>
</body>
</html>
