<?php
// courses.php - Modern Animated Course Listing
require_once '../includes/config.php';
// Example: admin/add-course.php
require_once '../includes/config.php';
require_once '../includes/check-permission.php';

// Check specific permission
if(!can('can_create_course')) {
    header('Location: dashboard.php?msg=আপনার+এই+অ্যাকশনের+অনুমতি+নেই&type=danger');
    exit;
}

$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,
           (SELECT AVG(rating) FROM reviews WHERE course_id = c.id) 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 ? OR c.description_bn LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
}

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();

// Get categories for filter
$categories = $pdo->query("SELECT * FROM categories ORDER BY name_bn")->fetchAll();

// Helper

?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>কোর্সসমূহ - বাংলা LMS</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: #6C5CE7;
            --gradient-1: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --gradient-2: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            --gradient-3: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            --gradient-4: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
            --gradient-5: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
            --dark: #1a1a2e;
            --shadow: 0 5px 25px rgba(0,0,0,0.1);
            --shadow-lg: 0 20px 60px rgba(0,0,0,0.15);
        }
        
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            background: #f0f2f8;
            font-family: 'Segoe UI', 'Hind Siliguri', 'Noto Sans Bengali', Arial, sans-serif;
            overflow-x: hidden;
        }
        
        /* Animated Background */
        .bg-animation {
            position: fixed; top: 0; left: 0;
            width: 100%; height: 100%;
            z-index: 0; pointer-events: none;
        }
        .bg-blob {
            position: absolute; border-radius: 50%;
            opacity: 0.06; animation: blobFloat 25s infinite ease-in-out;
        }
        .bg-blob:nth-child(1) { width: 600px; height: 600px; background: #667eea; top: -200px; left: -200px; }
        .bg-blob:nth-child(2) { width: 400px; height: 400px; background: #f5576c; bottom: -100px; right: -100px; animation-delay: 8s; }
        .bg-blob:nth-child(3) { width: 300px; height: 300px; background: #4facfe; top: 50%; right: 5%; animation-delay: 16s; }
        
        @keyframes blobFloat {
            0%, 100% { transform: translate(0, 0) rotate(0deg) scale(1); }
            33% { transform: translate(50px, -50px) rotate(120deg) scale(1.15); }
            66% { transform: translate(-30px, 40px) rotate(240deg) scale(0.9); }
        }
        
        /* Navbar */
        .navbar {
            background: rgba(255,255,255,0.9);
            backdrop-filter: blur(20px);
            box-shadow: 0 2px 20px rgba(0,0,0,0.08);
            padding: 15px 0;
            position: sticky; top: 0; z-index: 1000;
        }
        .navbar-brand {
            font-weight: 800; font-size: 1.4rem;
            background: var(--gradient-1);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text; text-decoration: none;
        }
        .nav-link { color: #555; text-decoration: none; font-weight: 500; margin: 0 12px; transition: 0.3s; }
        .nav-link:hover, .nav-link.active { color: var(--primary); }
        
        /* Hero Section */
        .hero-courses {
            background: var(--gradient-1);
            color: white;
            padding: 60px 0 80px;
            text-align: center;
            position: relative;
            overflow: hidden;
        }
        .hero-courses::after {
            content: '';
            position: absolute; bottom: -30px; left: 50%;
            transform: translateX(-50%);
            width: 60px; height: 60px;
            background: #f0f2f8; border-radius: 50%;
        }
        .hero-courses h1 { font-size: 2.8rem; font-weight: 800; animation: fadeInUp 0.6s ease; }
        .hero-courses p { font-size: 1.1rem; opacity: 0.9; animation: fadeInUp 0.8s ease; }
        
        @keyframes fadeInUp {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .container { max-width: 1300px; margin: 0 auto; padding: 30px 20px; position: relative; z-index: 1; }
        
        /* Filter Card */
        .filter-card {
            background: white;
            border-radius: 20px;
            padding: 20px 25px;
            box-shadow: var(--shadow);
            margin-bottom: 30px;
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            align-items: center;
            position: sticky; top: 90px; z-index: 100;
        }
        .filter-card select, .filter-card input {
            border-radius: 50px;
            padding: 10px 20px;
            border: 2px solid #e8eaef;
            font-size: 0.9rem;
            transition: 0.3s;
            background: #fafbfd;
        }
        .filter-card select:focus, .filter-card input:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(108,92,231,0.08);
            outline: none;
        }
        .filter-card .btn-filter {
            background: var(--gradient-1);
            color: white;
            border: none;
            border-radius: 50px;
            padding: 10px 25px;
            font-weight: 600;
            cursor: pointer;
            transition: 0.3s;
        }
        .filter-card .btn-filter:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(108,92,231,0.3);
        }
        
        /* Category Pills */
        .category-pills {
            display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 25px;
        }
        .cat-pill {
            padding: 10px 22px;
            border-radius: 50px;
            background: white;
            border: 2px solid #e8eaef;
            font-weight: 600;
            font-size: 0.9rem;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            text-decoration: none;
            color: #555;
            white-space: nowrap;
        }
        .cat-pill:hover, .cat-pill.active {
            background: var(--gradient-1);
            color: white;
            border-color: transparent;
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(108,92,231,0.25);
        }
        .cat-pill i { margin-right: 6px; }
        
        /* Course Card */
        .course-card {
            background: white;
            border-radius: 24px;
            overflow: hidden;
            box-shadow: 0 3px 15px rgba(0,0,0,0.06);
            transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            height: 100%;
            position: relative;
            cursor: pointer;
        }
        .course-card:hover {
            transform: translateY(-12px);
            box-shadow: var(--shadow-lg);
        }
        .course-card::before {
            content: '';
            position: absolute; top: 0; left: 0;
            width: 100%; height: 5px;
            background: var(--gradient-1);
            transform: scaleX(0);
            transition: transform 0.5s ease;
        }
        .course-card:hover::before {
            transform: scaleX(1);
        }
        
        .course-thumb-wrapper {
            position: relative;
            overflow: hidden;
            height: 200px;
        }
        .course-thumb {
            width: 100%; height: 100%;
            object-fit: cover;
            transition: transform 0.6s ease;
        }
        .course-card:hover .course-thumb {
            transform: scale(1.1);
        }
        .course-thumb-placeholder {
            width: 100%; height: 200px;
            display: flex; align-items: center; justify-content: center;
            font-size: 3rem; color: white;
        }
        
        .course-badge {
            position: absolute;
            top: 12px; right: 12px;
            padding: 6px 16px;
            border-radius: 50px;
            font-weight: 700;
            font-size: 0.85rem;
            z-index: 2;
        }
        .badge-free { background: var(--gradient-4); color: #1a5c3a; }
        .badge-paid { background: var(--gradient-5); color: #7a3b10; }
        
        .course-overlay {
            position: absolute; top: 0; left: 0;
            width: 100%; height: 100%;
            background: rgba(0,0,0,0.6);
            display: flex; align-items: center; justify-content: center;
            opacity: 0; transition: opacity 0.4s ease;
        }
        .course-card:hover .course-overlay {
            opacity: 1;
        }
        .btn-preview {
            background: white;
            color: var(--primary);
            border-radius: 50px;
            padding: 12px 30px;
            font-weight: 700;
            text-decoration: none;
            transition: 0.3s;
        }
        .btn-preview:hover {
            background: var(--gradient-1);
            color: white;
            transform: scale(1.05);
        }
        
        .course-body {
            padding: 20px;
        }
        .course-level {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            margin-bottom: 8px;
        }
        .level-beginner { background: #d4f5e9; color: #11998e; }
        .level-intermediate { background: #fff3e0; color: #e67e22; }
        .level-advanced { background: #ffe4e8; color: #e74c3c; }
        
        .course-title {
            font-size: 1.15rem;
            font-weight: 700;
            margin-bottom: 8px;
            color: var(--dark);
            line-height: 1.4;
        }
        .course-title a {
            color: inherit;
            text-decoration: none;
            transition: 0.3s;
        }
        .course-title a:hover { color: var(--primary); }
        
        .course-meta {
            display: flex; gap: 15px; flex-wrap: wrap;
            font-size: 0.85rem; color: #888;
            margin-bottom: 12px;
        }
        .course-meta span { display: flex; align-items: center; gap: 5px; }
        
        .course-footer {
            display: flex; justify-content: space-between; align-items: center;
            padding-top: 15px;
            border-top: 1px solid #f0f0f0;
        }
        .course-price {
            font-size: 1.4rem; font-weight: 800;
        }
        .price-free { color: #11998e; }
        .price-paid { background: var(--gradient-1); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; }
        
        .course-instructor {
            display: flex; align-items: center; gap: 8px;
        }
        .instructor-avatar {
            width: 32px; height: 32px;
            border-radius: 50%; object-fit: cover;
            border: 2px solid var(--primary);
        }
        
        /* Rating Stars */
        .stars { color: #ffc107; font-size: 0.8rem; }
        .stars .empty { color: #ddd; }
        
        /* Empty State */
        .empty-state {
            text-align: center; padding: 80px 20px;
        }
        .empty-state i { font-size: 5rem; color: #ddd; margin-bottom: 20px; }
        
        /* Responsive */
        @media (max-width: 768px) {
            .hero-courses h1 { font-size: 1.8rem; }
            .filter-card { flex-direction: column; position: static; }
            .course-thumb-wrapper { height: 160px; }
        }
    </style>
</head>
<body>

<!-- Background Animation -->
<div class="bg-animation">
    <div class="bg-blob"></div>
    <div class="bg-blob"></div>
    <div class="bg-blob"></div>
</div>

<!-- Navbar -->
<nav class="navbar">
    <div class="container" style="display:flex;justify-content:space-between;align-items:center;">
        <a href="index.php" class="navbar-brand">
            <i class="fas fa-graduation-cap me-2"></i>বাংলা LMS
        </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="about.php" class="nav-link">আমাদের সম্পর্কে</a>
            <a href="contact.php" class="nav-link">যোগাযোগ</a>
            <?php if(isLoggedIn()): ?>
                <a href="<?= ($_SESSION['user_role']??'')=='admin'?'admin/dashboard.php':'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>

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

<div class="container">
    
    <!-- Category Pills -->
    <div class="category-pills" data-aos="fade-up">
        <a href="courses.php" class="cat-pill <?= !$category_slug?'active':'' ?>">
            <i class="fas fa-th-large"></i> সব
        </a>
        <?php 
        $cat_colors = ['#FF6B6B','#4ECDC4','#45B7D1','#96CEB4','#FFEAA7','#DDA0DD','#FF9FF3','#54A0FF'];
        $ci = 0;
        foreach($categories as $cat): 
        ?>
            <a href="?category=<?= $cat['slug'] ?>" class="cat-pill <?= $category_slug==$cat['slug']?'active':'' ?>"
               style="<?= $category_slug==$cat['slug']?'':'border-color:'.$cat_colors[$ci%8].';color:'.$cat_colors[$ci%8] ?>">
                <i class="fas <?= $cat['icon'] ?: 'fa-book' ?>"></i> <?= htmlspecialchars($cat['name_bn']) ?>
            </a>
        <?php $ci++; endforeach; ?>
    </div>
    
    <!-- Filter Bar -->
    <div class="filter-card" data-aos="fade-up">
        <form method="GET" style="display:flex;gap:10px;flex-wrap:wrap;width:100%;align-items:center;">
            <?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:200px;">
            <select name="level" style="flex:1;min-width:130px;">
                <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:130px;">
                <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:130px;">
                <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-filter">ফিল্টার করুন</button>
        </form>
    </div>
    
    <!-- Course Grid -->
    <div class="row g-4">
        <?php if(count($courses) > 0): ?>
            <?php foreach($courses as $course): 
                $youtube_id = null;
                $stmt2 = $pdo->prepare("SELECT youtube_url FROM lessons WHERE course_id = ? LIMIT 1");
                $stmt2->execute([$course['id']]);
                $lesson = $stmt2->fetch();
                if($lesson) $youtube_id = getYouTubeId($lesson['youtube_url']);
                
                $avg_rating = round($course['avg_rating'] ?? 0, 1);
                $review_count = $course['review_count'] ?? 0;
                
                $card_gradients = ['var(--gradient-1)','var(--gradient-2)','var(--gradient-3)','var(--gradient-4)','var(--gradient-5)'];
                $card_gradient = $card_gradients[$course['id'] % 5];
            ?>
                <div class="col-md-6 col-lg-4 col-xl-3" data-aos="fade-up" data-aos-delay="<?= ($course['id'] % 4) * 100 ?>">
                    <div class="course-card">
                        <div class="course-thumb-wrapper">
                            <?php if($youtube_id): ?>
                                <img src="https://img.youtube.com/vi/<?= $youtube_id ?>/maxresdefault.jpg" 
                                     class="course-thumb" alt="<?= htmlspecialchars($course['title_bn']) ?>">
                            <?php else: ?>
                                <div class="course-thumb-placeholder" style="background:<?= $card_gradient ?>;">
                                    <i class="fas fa-graduation-cap"></i>
                                </div>
                            <?php endif; ?>
                            
                            <span class="course-badge <?= $course['price']==0?'badge-free':'badge-paid' ?>">
                                <?= $course['price']==0?'🆓 ফ্রি':'৳'.number_format($course['price']) ?>
                            </span>
                            
                            <div class="course-overlay">
                                <a href="course-details.php?id=<?= $course['id'] ?>" class="btn-preview">
                                    <i class="fas fa-play-circle me-2"></i> বিস্তারিত দেখুন
                                </a>
                            </div>
                        </div>
                        
                        <div class="course-body">
                            <span class="course-level level-<?= $course['level'] ?>">
                                <?= $course['level']=='beginner'?'🟢 বিগিনার':($course['level']=='intermediate'?'🟡 ইন্টারমিডিয়েট':'🔴 অ্যাডভান্সড') ?>
                            </span>
                            
                            <span class="badge bg-secondary ms-1" style="font-size:0.7rem;"><?= htmlspecialchars($course['category_name']) ?></span>
                            
                            <h5 class="course-title">
                                <a href="course-details.php?id=<?= $course['id'] ?>">
                                    <?= htmlspecialchars(mb_substr($course['title_bn'], 0, 40)) ?>
                                    <?= mb_strlen($course['title_bn'])>40?'...':'' ?>
                                </a>
                            </h5>
                            
                            <div class="course-meta">
                                <span><i class="fas fa-video"></i> <?= $course['lesson_count'] ?></span>
                                <span><i class="fas fa-users"></i> <?= $course['student_count'] ?></span>
                                <?php if($avg_rating > 0): ?>
                                    <span class="stars">
                                        <?php for($i=1;$i<=5;$i++): ?>
                                            <i class="fas fa-star <?= $i<=round($avg_rating)?'':'empty' ?>"></i>
                                        <?php endfor; ?>
                                        (<?= $review_count ?>)
                                    </span>
                                <?php endif; ?>
                            </div>
                            
                            <div class="course-footer">
                                <div class="course-instructor">
                                    <img src="uploads/avatars/<?= $course['instructor_avatar']?:'default-avatar.png' ?>" 
                                         class="instructor-avatar"
                                         onerror="this.src='https://ui-avatars.com/api/?name=<?= urlencode($course['instructor_name']) ?>&background=6C5CE7&color=fff&size=32'">
                                    <small class="text-muted"><?= htmlspecialchars(mb_substr($course['instructor_name'],0,12)) ?></small>
                                </div>
                                <div class="course-price <?= $course['price']==0?'price-free':'price-paid' ?>">
                                    <?= $course['price']==0?'ফ্রি':'৳'.number_format($course['price']) ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="col-12">
                <div class="empty-state">
                    <i class="fas fa-search"></i>
                    <h3>কোন কোর্স পাওয়া যায়নি</h3>
                    <p class="text-muted">অনুগ্রহ করে ভিন্ন ফিল্টার ব্যবহার করুন</p>
                    <a href="courses.php" class="btn-filter" style="display:inline-block;text-decoration:none;padding:12px 30px;">সকল কোর্স দেখুন</a>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Footer -->
<footer style="background:var(--dark);color:white;text-align:center;padding:25px;margin-top:60px;">
    <p class="mb-0">&copy; <?= date('Y') ?> বাংলা LMS | সর্বস্বত্ব সংরক্ষিত</p>
</footer>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
<script>
AOS.init({ duration: 800, easing: 'ease-in-out', once: true });
</script>
</body>
</html>