<?php
// courses.php - Updated Dynamic Course Listing
require_once 'includes/config.php';
require_once 'includes/site-data.php';

// Debug: Show if courses exist
$test = $pdo->query("SELECT COUNT(*) FROM courses WHERE status='published'")->fetchColumn();
echo "<!-- Published courses: $test -->";

// If site-data.php causes error, use this fallback
if(file_exists('includes/site-data.php')) {
    require_once 'includes/site-data.php';
} else {
    // Fallback settings
    $S = [
        'site_title' => 'ONESBD LMS',
        'logo_text' => 'ONESBD LMS', 
        'logo_icon' => 'fa-graduation-cap',
        'primary_color' => '#6C5CE7',
        'footer_text' => 'ONESBD LMS | সর্বস্বত্ব সংরক্ষিত',
        'use_image_logo' => '0',
        'logo_image' => '',
    ];
}
$category_slug = $_GET['category'] ?? '';
$search = $_GET['search'] ?? '';
$level = $_GET['level'] ?? '';
$sort = $_GET['sort'] ?? 'newest';
$price_filter = $_GET['price'] ?? '';

// Build query
$query = "
    SELECT c.*, u.full_name as instructor_name, u.avatar as instructor_avatar,
           cat.name_bn as category_name, cat.slug as category_slug,
           (SELECT COUNT(*) FROM lessons WHERE course_id = c.id) as lesson_count,
           (SELECT COUNT(*) FROM enrollments WHERE course_id = c.id AND payment_status = 'completed') as student_count,
           COALESCE((SELECT AVG(rating) FROM reviews WHERE course_id = c.id), 0) as avg_rating,
           (SELECT COUNT(*) FROM reviews WHERE course_id = c.id) as review_count
    FROM courses c
    JOIN users u ON c.instructor_id = u.id
    JOIN categories cat ON c.category_id = cat.id
    WHERE c.status = 'published'
";
$params = [];

if($category_slug) { $query .= " AND cat.slug = ?"; $params[] = $category_slug; }
if($search) { $query .= " AND (c.title_bn LIKE ? OR c.title_en LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; }
if($level) { $query .= " AND c.level = ?"; $params[] = $level; }
if($price_filter == 'free') { $query .= " AND c.price = 0"; }
elseif($price_filter == 'paid') { $query .= " AND c.price > 0"; }

switch($sort) {
    case 'price_low': $query .= " ORDER BY c.price ASC"; break;
    case 'price_high': $query .= " ORDER BY c.price DESC"; break;
    case 'popular': $query .= " ORDER BY student_count DESC"; break;
    case 'rating': $query .= " ORDER BY avg_rating DESC"; break;
    default: $query .= " ORDER BY c.created_at DESC";
}

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$courses = $stmt->fetchAll();

$categories = $pdo->query("SELECT * FROM categories ORDER BY name_bn")->fetchAll();
$total_courses = count($courses);

// Dynamic settings
$site_title = $S['site_title'] ?? 'বাংলা LMS';
$logo_text = $S['logo_text'] ?? 'বাংলা LMS';
$logo_icon = $S['logo_icon'] ?? 'fa-graduation-cap';
$primary_color = $S['primary_color'] ?? '#6C5CE7';
$use_image = $S['use_image_logo'] ?? '0';
$logo_image = $S['logo_image'] ?? '';
$footer_text = $S['footer_text'] ?? 'বাংলা LMS | সর্বস্বত্ব সংরক্ষিত';


?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>কোর্সসমূহ - <?= htmlspecialchars($site_title) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/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">
    <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
    <style>
        :root{--primary:<?=$primary_color?>;--g1:linear-gradient(135deg,<?=$primary_color?>,<?=$primary_color?>dd);--dark:#1a1a2e;--shadow:0 4px 20px rgba(0,0,0,0.06)}
        *{margin:0;padding:0;box-sizing:border-box}
        body{background:#f0f2f8;font-family:'Segoe UI','Hind Siliguri',Arial,sans-serif}
        
        .navbar{background:rgba(255,255,255,.95);backdrop-filter:blur(15px);box-shadow:0 2px 20px rgba(0,0,0,.06);padding:12px 0;position:sticky;top:0;z-index:1000}
        .navbar-brand{font-weight:800;font-size:1.2rem;background:var(--g1);-webkit-background-clip:text;-webkit-text-fill-color:transparent;text-decoration:none;display:flex;align-items:center;gap:8px}
        .navbar-brand img{height:34px}
        .nav-link{color:#555;text-decoration:none;font-weight:500;margin:0 8px;transition:.3s;font-size:.9rem}
        .nav-link:hover,.nav-link.active{color:var(--primary)}
        
        .hero{background:var(--g1);color:white;padding:60px 0 80px;text-align:center;position:relative;overflow:hidden}
        .hero::after{content:'';position:absolute;bottom:-28px;left:50%;transform:translateX(-50%);width:56px;height:56px;background:#f0f2f8;border-radius:50%}
        .hero h1{font-size:2.5rem;font-weight:800}
        
        .container{max-width:1200px;margin:0 auto;padding:30px 20px}
        
        .filter-bar{background:white;border-radius:16px;padding:15px 20px;box-shadow:var(--shadow);display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin-bottom:25px}
        .filter-bar select,.filter-bar input{border-radius:50px;padding:9px 18px;border:2px solid #e8eaef;font-size:.9rem;background:#fafbfd}
        .filter-bar select:focus,.filter-bar input:focus{border-color:var(--primary);outline:none}
        .btn-f{background:var(--g1);color:white;border:none;border-radius:50px;padding:9px 22px;font-weight:600;cursor:pointer}
        
        .course-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:22px}
        
        .course-card{background:white;border-radius:18px;overflow:hidden;box-shadow:0 3px 15px rgba(0,0,0,.05);transition:all .4s ease}
        .course-card:hover{transform:translateY(-10px);box-shadow:0 20px 50px rgba(0,0,0,.15)}
        .card-img-wrap{position:relative;overflow:hidden;height:190px;background:#e8eaef}
        .card-img{width:100%;height:100%;object-fit:cover;transition:.5s}
        .course-card:hover .card-img{transform:scale(1.1)}
        .card-placeholder{width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-size:3rem;color:white;background:var(--g1)}
        .card-badge{position:absolute;top:12px;right:12px;padding:6px 15px;border-radius:50px;font-weight:700;font-size:.8rem;z-index:2}
        .badge-free{background:rgba(67,233,123,.9);color:#0d4d2b}.badge-paid{background:rgba(250,112,154,.9);color:white}
        .card-body{padding:18px}
        .card-title{font-weight:700;color:var(--dark);margin-bottom:8px}
        .card-title a{color:inherit;text-decoration:none}.card-title a:hover{color:var(--primary)}
        .card-meta{font-size:.8rem;color:#888;margin-bottom:10px}
        .card-footer{display:flex;justify-content:space-between;align-items:center;padding-top:12px;border-top:1px solid #f0f0f0}
        .price{font-weight:800;font-size:1.2rem}.price-free{color:#11998e}.price-paid{color:var(--primary)}
        
        footer{background:var(--dark);color:white;text-align:center;padding:25px;margin-top:50px}
        
        @media(max-width:768px){.hero h1{font-size:1.8rem}.course-grid{grid-template-columns:1fr}}
    </style>
</head>
<body>

<nav class="navbar">
    <div class="container" style="display:flex;justify-content:space-between;align-items:center">
        <a href="index.php" class="navbar-brand">
            <?php if($use_image=='1' && !empty($logo_image) && file_exists('uploads/logo/'.$logo_image)): ?>
                <img src="uploads/logo/<?=$logo_image?>" alt="<?=htmlspecialchars($site_title)?>">
            <?php else: ?>
                <i class="fas <?=$logo_icon?> me-2"></i><?=htmlspecialchars($logo_text)?>
            <?php endif; ?>
        </a>
        <div style="display:flex;gap:15px;flex-wrap:wrap">
            <a href="index.php" class="nav-link">হোম</a>
            <a href="courses.php" class="nav-link active">কোর্স</a>
            <a href="packages.php" class="nav-link">প্যাকেজ</a>
            <a href="instructors.php" class="nav-link">ইন্সট্রাক্টর</a>
            <a href="about.php" class="nav-link">আমাদের সম্পর্কে</a>
            <a href="contact.php" class="nav-link">যোগাযোগ</a>
            <?php if(isset($_SESSION['user_id'])): ?>
                <a href="dashboard.php" class="nav-link">ড্যাশবোর্ড</a>
            <?php else: ?>
                <a href="auth.php" class="nav-link" style="color:var(--primary);font-weight:700">লগইন</a>
            <?php endif; ?>
        </div>
    </div>
</nav>

<section class="hero">
    <h1>📚 আমাদের কোর্সসমূহ</h1>
    <p><?=$total_courses?> টি কোর্স থেকে আপনার পছন্দের কোর্সটি বেছে নিন</p>
</section>

<div class="container">
    
    <!-- Filter -->
    <form method="GET" class="filter-bar" data-aos="fade-up">
        <?php if($category_slug): ?><input type="hidden" name="category" value="<?=$category_slug?>"><?php endif; ?>
        <input type="text" name="search" placeholder="🔍 কোর্স খুঁজুন..." value="<?=htmlspecialchars($search)?>" style="flex:2;min-width:150px">
        <select name="level" style="flex:1;min-width:110px">
            <option value="">সকল লেভেল</option>
            <option value="beginner" <?=$level=='beginner'?'selected':''?>>🟢 বিগিনার</option>
            <option value="intermediate" <?=$level=='intermediate'?'selected':''?>>🟡 ইন্টারমিডিয়েট</option>
            <option value="advanced" <?=$level=='advanced'?'selected':''?>>🔴 অ্যাডভান্সড</option>
        </select>
        <select name="price" style="flex:1;min-width:100px">
            <option value="">সকল মূল্য</option>
            <option value="free" <?=$price_filter=='free'?'selected':''?>>🆓 ফ্রি</option>
            <option value="paid" <?=$price_filter=='paid'?'selected':''?>>💰 পেইড</option>
        </select>
        <select name="sort" style="flex:1;min-width:110px">
            <option value="newest" <?=$sort=='newest'?'selected':''?>>🆕 নতুন</option>
            <option value="popular" <?=$sort=='popular'?'selected':''?>>🔥 জনপ্রিয়</option>
            <option value="rating" <?=$sort=='rating'?'selected':''?>>⭐ রেটিং</option>
            <option value="price_low" <?=$sort=='price_low'?'selected':''?>>⬆️ সস্তা</option>
            <option value="price_high" <?=$sort=='price_high'?'selected':''?>>⬇️ দামি</option>
        </select>
        <button type="submit" class="btn-f">ফিল্টার</button>
    </form>
    
    <!-- Course Grid -->
    <div class="course-grid">
        <?php if(count($courses) > 0): ?>
            <?php foreach($courses as $c): 
                $yt = null;
                $stmt2 = $pdo->prepare("SELECT youtube_url FROM lessons WHERE course_id = ? LIMIT 1");
                $stmt2->execute([$c['id']]);
                $l = $stmt2->fetch();
                if($l) $yt = getYouTubeId($l['youtube_url']);
            ?>
                <div class="course-card" data-aos="fade-up">
                    <div class="card-img-wrap">
                        <?php if($yt): ?>
                            <img src="https://img.youtube.com/vi/<?=$yt?>/maxresdefault.jpg" class="card-img" alt="<?=htmlspecialchars($c['title_bn'])?>" loading="lazy">
                        <?php else: ?>
                            <div class="card-placeholder"><i class="fas fa-graduation-cap"></i></div>
                        <?php endif; ?>
                        <span class="card-badge <?=$c['price']==0?'badge-free':'badge-paid'?>"><?=$c['price']==0?'🆓 ফ্রি':'৳'.number_format($c['price'])?></span>
                    </div>
                    <div class="card-body">
                        <span class="badge bg-secondary mb-1" style="font-size:.7rem"><?=htmlspecialchars($c['category_name'])?></span>
                        <h5 class="card-title"><a href="course-details.php?id=<?=$c['id']?>"><?=htmlspecialchars(mb_substr($c['title_bn'],0,40))?></a></h5>
                        <div class="card-meta">
                            <span><i class="fas fa-video"></i> <?=$c['lesson_count']?></span> |
                            <span><i class="fas fa-users"></i> <?=$c['student_count']?></span>
                            <?php if($c['avg_rating']>0): ?> | ⭐<?=round($c['avg_rating'],1)?><?php endif; ?>
                        </div>
                        <div class="card-footer">
                            <small class="text-muted"><?=htmlspecialchars(mb_substr($c['instructor_name'],0,14))?></small>
                            <span class="price <?=$c['price']==0?'price-free':'price-paid'?>"><?=$c['price']==0?'ফ্রি':'৳'.number_format($c['price'])?></span>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div style="grid-column:1/-1;text-align:center;padding:60px;color:#888">
                <i class="fas fa-search fa-3x mb-3" style="opacity:.3"></i>
                <h5>কোন কোর্স পাওয়া যায়নি</h5>
                <p class="mb-3">ডাটাবেসে কোন পাবলিশড কোর্স নেই। অ্যাডমিন প্যানেল থেকে কোর্স যোগ করুন।</p>
                <a href="admin/add-course.php" class="btn-f" style="display:inline-block;text-decoration:none">➕ নতুন কোর্স যোগ করুন</a>
            </div>
        <?php endif; ?>
    </div>
</div>

<footer><p>&copy; <?=date('Y')?> <?=htmlspecialchars($footer_text)?></p></footer>

<script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
<script>AOS.init({duration:700,once:true});</script>
</body>
</html>