<?php
// course-details.php - Complete Dynamic Course Details
require_once 'includes/config.php';
require_once 'includes/site-data.php';

$course_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Get course
$stmt = $pdo->prepare("
    SELECT c.*, u.full_name as instructor_name, u.avatar as instructor_avatar, u.bio as instructor_bio,
           cat.name_bn as category_name, cat.slug as category_slug
    FROM courses c
    JOIN users u ON c.instructor_id = u.id
    JOIN categories cat ON c.category_id = cat.id
    WHERE c.id = ? AND c.status = 'published'
");
$stmt->execute([$course_id]);
$course = $stmt->fetch();

if(!$course) {
    header('Location: courses.php');
    exit;
}

// Get lessons
$lessons = $pdo->prepare("SELECT * FROM lessons WHERE course_id = ? ORDER BY order_number");
$lessons->execute([$course_id]);
$all_lessons = $lessons->fetchAll();

// Get reviews
$reviews = $pdo->prepare("
    SELECT r.*, u.full_name, u.avatar 
    FROM reviews r JOIN users u ON r.user_id = u.id 
    WHERE r.course_id = ? ORDER BY r.created_at DESC LIMIT 10
");
$reviews->execute([$course_id]);
$review_list = $reviews->fetchAll();

// Ratings
$rating_data = $pdo->prepare("SELECT AVG(rating) as avg, COUNT(*) as total FROM reviews WHERE course_id = ?");
$rating_data->execute([$course_id]);
$ratings = $rating_data->fetch();

// Students count
$student_count = $pdo->prepare("SELECT COUNT(*) FROM enrollments WHERE course_id = ? AND payment_status = 'completed'")->fetchColumn();
$student_count = $pdo->prepare("SELECT COUNT(*) FROM enrollments WHERE course_id = ? AND payment_status = 'completed'");
$student_count->execute([$course_id]);
$student_count = $student_count->fetchColumn();

// Check enrollment
$is_enrolled = false;
$has_reviewed = false;
if(isset($_SESSION['user_id'])) {
    $uid = $_SESSION['user_id'];
    $enr = $pdo->prepare("SELECT COUNT(*) FROM enrollments WHERE user_id=? AND course_id=? AND payment_status='completed'");
    $enr->execute([$uid, $course_id]);
    $is_enrolled = $enr->fetchColumn() > 0;
    
    $rev = $pdo->prepare("SELECT id FROM reviews WHERE user_id=? AND course_id=?");
    $rev->execute([$uid, $course_id]);
    $has_reviewed = $rev->fetch() ? true : false;
    
    // Get progress
    $prog = $pdo->prepare("
        SELECT COUNT(l.id) as total, COUNT(CASE WHEN lp.completed=1 THEN 1 END) as done
        FROM lessons l LEFT JOIN lesson_progress lp ON l.id=lp.lesson_id AND lp.user_id=?
        WHERE l.course_id=?
    ");
    $prog->execute([$uid, $course_id]);
    $progress = $prog->fetch();
    $progress_percent = $progress['total'] > 0 ? round(($progress['done']/$progress['total'])*100) : 0;
    $all_done = ($progress['total'] > 0 && $progress['done'] == $progress['total']);
    
    // Find next lesson
    $next_lesson_id = null;
    if(!empty($all_lessons)) {
        foreach($all_lessons as $l) {
            $lp = $pdo->prepare("SELECT completed FROM lesson_progress WHERE user_id=? AND lesson_id=?");
            $lp->execute([$uid, $l['id']]);
            $comp = $lp->fetch();
            if(!$comp || !$comp['completed']) { $next_lesson_id = $l['id']; break; }
        }
        if(!$next_lesson_id) $next_lesson_id = $all_lessons[0]['id'];
    }
    
    // Check certificate
    $has_cert = false; $cert_id = 0;
    if($all_done) {
        $crt = $pdo->prepare("SELECT id FROM certificates WHERE user_id=? AND course_id=?");
        $crt->execute([$uid, $course_id]);
        $cert = $crt->fetch();
        if($cert) { $has_cert = true; $cert_id = $cert['id']; }
    }
}

// YouTube preview from first lesson
$youtube_id = null;
if(!empty($all_lessons) && !empty($all_lessons[0]['youtube_url'])) {
    preg_match('/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/', $all_lessons[0]['youtube_url'], $m);
    $youtube_id = $m[1] ?? null;
}

// Handle review submission
if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['submit_review']) && isset($_SESSION['user_id'])) {
    $rating = (int)$_POST['rating'];
    $comment = trim($_POST['comment'] ?? '');
    if($rating >= 1 && $rating <= 5 && !empty($comment) && $is_enrolled && !$has_reviewed) {
        $pdo->prepare("INSERT INTO reviews (user_id, course_id, rating, comment) VALUES (?,?,?,?)")->execute([$uid, $course_id, $rating, $comment]);
        header("Location: course-details.php?id=$course_id&review=success");
        exit;
    }
}

// Dynamic settings
$st = $S['site_title'] ?? 'ONESBD LMS';
$lt = $S['logo_text'] ?? 'ONESBD LMS';
$li = $S['logo_icon'] ?? 'fa-graduation-cap';
$pc = $S['primary_color'] ?? '#6C5CE7';
$ui = $S['use_image_logo'] ?? '0';
$lim = $S['logo_image'] ?? '';
$ft = $S['footer_text'] ?? 'ONESBD LMS | সর্বস্বত্ব সংরক্ষিত';
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title><?=htmlspecialchars($course['title_bn'])?> - <?=htmlspecialchars($st)?></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:<?=$pc?>;--g1:linear-gradient(135deg,<?=$pc?>,<?=$pc?>dd);--g2:linear-gradient(135deg,#f093fb,#f5576c);--g3:linear-gradient(135deg,#4facfe,#00f2fe);--g4:linear-gradient(135deg,#43e97b,#38f9d7);--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;font-size:.9rem}
        
        .container{max-width:1200px;margin:0 auto;padding:20px}
        .breadcrumb{font-size:.85rem;color:#888;margin-bottom:15px}
        .breadcrumb a{color:var(--primary);text-decoration:none}
        
        .main-card{background:white;border-radius:18px;padding:25px;box-shadow:0 2px 12px rgba(0,0,0,.04);margin-bottom:20px}
        
        .video-wrap{position:relative;padding-bottom:56.25%;border-radius:16px;overflow:hidden;margin-bottom:20px;box-shadow:0 8px 30px rgba(0,0,0,.15);background:#000}
        .video-wrap iframe{position:absolute;top:0;left:0;width:100%;height:100%;border:none}
        
        .sidebar-card{background:white;border-radius:18px;padding:25px;box-shadow:0 2px 12px rgba(0,0,0,.04);position:sticky;top:85px}
        .price-display{font-size:2.5rem;font-weight:800;color:var(--primary)}.price-display.free{color:#11998e}
        
        .btn{font-weight:600;cursor:pointer;transition:.3s;border-radius:50px;padding:12px 25px;border:none;text-decoration:none;display:inline-flex;align-items:center;gap:8px;font-size:.9rem}
        .btn-primary{background:var(--g1);color:white}.btn-primary:hover{transform:translateY(-3px);box-shadow:0 10px 25px rgba(108,92,231,.35);color:white}
        .btn-success{background:#28a745;color:white}.btn-success:hover{transform:translateY(-3px);color:white}
        .btn-outline{border:2px solid var(--primary);color:var(--primary);background:white}
        .btn-warning{background:#ffc107;color:#333}
        
        .lesson-item{display:flex;align-items:center;padding:10px 14px;border-radius:10px;margin-bottom:4px;text-decoration:none;color:#555;transition:.2s;font-size:.88rem}
        .lesson-item:hover{background:#f8f9ff;color:var(--primary)}
        .lesson-item .num{width:28px;height:28px;border-radius:50%;background:#e8eaef;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:.75rem;margin-right:10px;flex-shrink:0}
        .lesson-item .num.done{background:var(--g4);color:#0d4d2b}
        
        .progress-wrap{margin:12px 0}
        .progress{height:7px;border-radius:10px;background:#e8eaef}
        .progress-bar{background:var(--g1);border-radius:10px}
        
        .review-card{background:#f8f9ff;border-radius:12px;padding:15px;margin-bottom:10px}
        .stars{color:#ffc107}
        
        .star-rating{display:flex;flex-direction:row-reverse;justify-content:center;gap:5px;font-size:2rem}
        .star-rating input{display:none}
        .star-rating label{cursor:pointer;color:#ddd;transition:.2s}
        .star-rating label:hover,.star-rating label:hover~label,.star-rating input:checked~label{color:#ffc107}
        
        .badge-custom{padding:5px 14px;border-radius:20px;font-weight:600;font-size:.78rem}
        
        .instructor-card{text-align:center;padding:20px;background:#f8f9ff;border-radius:16px;margin-top:15px}
        .instructor-card img{width:80px;height:80px;border-radius:50%;object-fit:cover;border:4px solid var(--primary)}
        
        footer{background:var(--dark);color:white;text-align:center;padding:25px;margin-top:40px}
        
        @media(max-width:768px){.sidebar-card{position:static;margin-top:20px}}
    </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($ui=='1' && !empty($lim) && file_exists('uploads/logo/'.$lim)): ?>
                <img src="uploads/logo/<?=$lim?>" alt="<?=htmlspecialchars($st)?>">
            <?php else: ?>
                <i class="fas <?=$li?> me-2"></i><?=htmlspecialchars($lt)?>
            <?php endif; ?>
        </a>
        <div style="display:flex;gap:12px">
            <a href="index.php" class="nav-link">হোম</a>
            <a href="courses.php" class="nav-link">কোর্স</a>
            <?php if(isset($_SESSION['user_id'])): ?><a href="dashboard.php" class="nav-link">ড্যাশবোর্ড</a><?php endif; ?>
        </div>
    </div>
</nav>

<div class="container">
    
    <div class="breadcrumb">
        <a href="index.php">হোম</a> › <a href="courses.php">কোর্স</a> › <?=htmlspecialchars(mb_substr($course['title_bn'],0,30))?>
    </div>
    
    <?php if(isset($_GET['review'])): ?>
        <div class="alert alert-success rounded-3 mb-3">✅ আপনার রিভিউ সফলভাবে জমা হয়েছে! ধন্যবাদ!</div>
    <?php endif; ?>
    
    <div class="row">
        <!-- MAIN -->
        <div class="col-lg-8">
            <!-- Video Preview -->
            <?php if($youtube_id): ?>
                <div class="video-wrap"><iframe src="https://www.youtube.com/embed/<?=$youtube_id?>?rel=0" allowfullscreen></iframe></div>
            <?php endif; ?>
            
            <!-- Course Info -->
            <div class="main-card">
                <div class="d-flex gap-2 mb-3">
                    <span class="badge-custom" style="background:var(--g1);color:white"><?=htmlspecialchars($course['category_name'])?></span>
                    <span class="badge-custom" style="background:<?=$course['level']=='beginner'?'#d4f5e9':($course['level']=='intermediate'?'#fff3e0':'#ffe4e8')?>;color:<?=$course['level']=='beginner'?'#11998e':($course['level']=='intermediate'?'#e67e22':'#e74c3c')?>"><?=$course['level']=='beginner'?'🟢 বিগিনার':($course['level']=='intermediate'?'🟡 ইন্টারমিডিয়েট':'🔴 অ্যাডভান্সড')?></span>
                    <?php if($course['duration']): ?><span class="badge-custom bg-secondary text-white">⏱️ <?=htmlspecialchars($course['duration'])?></span><?php endif; ?>
                </div>
                <h3 style="font-weight:700;color:var(--dark)"><?=htmlspecialchars($course['title_bn'])?></h3>
                <p class="text-muted"><?=htmlspecialchars($course['title_en'])?></p>
                
                <?php if($is_enrolled && isset($progress_percent)): ?>
                    <div class="progress-wrap">
                        <div class="d-flex justify-content-between small mb-1"><span>আপনার প্রগতি</span><strong><?=$progress_percent?>%</strong></div>
                        <div class="progress"><div class="progress-bar" style="width:<?=$progress_percent?>%"></div></div>
                        <small><?=$progress['done']?>/<?=$progress['total']?> লেসন</small>
                        <?php if($all_done && $has_cert): ?><span class="badge bg-warning text-dark mt-1">🏆 সার্টিফাইড</span><?php endif; ?>
                    </div>
                <?php endif; ?>
                
                <hr>
                <h5 class="fw-bold">📖 কোর্স সম্পর্কে</h5>
                <p style="line-height:1.8;color:#555"><?=nl2br(htmlspecialchars($course['description_bn']??'কোর্সের বিস্তারিত বিবরণ শীঘ্রই যোগ করা হবে।'))?></p>
            </div>
            
            <!-- Course Content / Lessons -->
            <div class="main-card">
                <h5 class="fw-bold mb-3">📚 কোর্স কন্টেন্ট (<?=count($all_lessons)?> টি লেসন)</h5>
                <?php if(count($all_lessons)>0): ?>
                    <?php foreach($all_lessons as $l): 
                        $done = false;
                        if($is_enrolled && isset($_SESSION['user_id'])) {
                            $lp = $pdo->prepare("SELECT completed FROM lesson_progress WHERE user_id=? AND lesson_id=?");
                            $lp->execute([$_SESSION['user_id'],$l['id']]);
                            $done = ($lp->fetch() && $lp->fetch()['completed']==1);
                        }
                    ?>
                        <div class="lesson-item">
                            <span class="num <?=$done?'done':''?>"><?=$done?'✓':$l['order_number']?></span>
                            <?php if($is_enrolled || $l['is_free']): ?>
                                <a href="lesson.php?id=<?=$l['id']?>&course=<?=$course_id?>"><?=htmlspecialchars($l['title_bn'])?></a>
                            <?php else: ?>
                                <span class="text-muted"><?=htmlspecialchars($l['title_bn'])?> 🔒</span>
                            <?php endif; ?>
                            <?php if($l['is_free']): ?><span class="badge bg-success ms-auto" style="font-size:.7rem">ফ্রি</span><?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p class="text-muted">শীঘ্রই লেসন যোগ করা হবে।</p>
                <?php endif; ?>
            </div>
            
            <!-- Reviews -->
            <div class="main-card">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="fw-bold">📝 রিভিউ (<?=$ratings['total']??0?>)</h5>
                    <?php if($is_enrolled && !$has_reviewed && isset($_SESSION['user_id'])): ?>
                        <button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#reviewModal">⭐ রিভিউ লিখুন</button>
                    <?php endif; ?>
                </div>
                <?php if(($ratings['total']??0)>0): ?>
                    <div class="text-center mb-3"><h2 class="text-warning">⭐ <?=round($ratings['avg'],1)?></h2></div>
                    <?php foreach($review_list as $r): ?>
                        <div class="review-card">
                            <strong><?=htmlspecialchars($r['full_name'])?></strong>
                            <span class="stars ms-2"><?=str_repeat('★',$r['rating']).str_repeat('☆',5-$r['rating'])?></span>
                            <p class="mb-0 mt-1 small"><?=htmlspecialchars($r['comment'])?></p>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?><p class="text-muted">প্রথম রিভিউ দিন!</p><?php endif; ?>
            </div>
            
            <!-- Instructor -->
            <div class="instructor-card">
                <img src="uploads/avatars/<?=$course['instructor_avatar']?:'default-avatar.png'?>" alt="<?=htmlspecialchars($course['instructor_name'])?>" onerror="this.src='https://ui-avatars.com/api/?name=<?=urlencode($course['instructor_name'])?>&background=<?=str_replace('#','',$pc)?>&color=fff&size=80'">
                <h5 class="mt-2"><?=htmlspecialchars($course['instructor_name'])?></h5>
                <p class="text-muted small"><?=htmlspecialchars($course['instructor_bio']??'অভিজ্ঞ ইন্সট্রাক্টর')?></p>
            </div>
        </div>
        
        <!-- SIDEBAR -->
        <div class="col-lg-4">
            <div class="sidebar-card text-center">
                <div class="price-display <?=$course['price']==0?'free':''?>">
                    <?=$course['price']==0?'বিনামূল্যে':'৳'.number_format($course['price'])?>
                </div>
                
                <?php if(!$is_enrolled && !isset($_SESSION['user_id'])): ?>
                    <a href="auth.php" class="btn btn-primary w-100 mt-3"><i class="fas fa-sign-in-alt"></i> লগইন করে এনরোল করুন</a>
                <?php elseif(!$is_enrolled): ?>
                    <a href="enroll.php?course=<?=$course_id?>" class="btn btn-primary w-100 mt-3">
                        <?=$course['price']>0?'💰 এখনই কিনুন':'🎉 বিনামূল্যে এনরোল করুন'?>
                    </a>
                    <small class="text-success mt-1 d-block">⚡ সাথে সাথে কোর্স শুরু করুন</small>
                <?php else: ?>
                    <?php if($next_lesson_id): ?>
                        <a href="lesson.php?id=<?=$next_lesson_id?>&course=<?=$course_id?>" class="btn btn-success w-100 mt-3">
                            <i class="fas fa-play-circle"></i> <?=$progress_percent>0?'▶️ চালিয়ে যান':'🚀 শুরু করুন'?>
                        </a>
                    <?php endif; ?>
                    <?php if($has_cert): ?>
                        <a href="admin/view-certificate.php?id=<?=$cert_id?>" target="_blank" class="btn btn-warning w-100 mt-2">🏆 সার্টিফিকেট দেখুন</a>
                    <?php endif; ?>
                <?php endif; ?>
                
                <hr>
                <div class="text-start">
                    <p><i class="fas fa-video text-primary me-2"></i> <strong><?=count($all_lessons)?></strong> টি লেসন</p>
                    <p><i class="fas fa-users text-primary me-2"></i> <strong><?=$student_count?></strong> জন শিক্ষার্থী</p>
                    <p><i class="fas fa-certificate text-primary me-2"></i> সার্টিফিকেট</p>
                    <p><i class="fas fa-infinity text-primary me-2"></i> লাইফটাইম অ্যাক্সেস</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Review Modal -->
<?php if($is_enrolled && !$has_reviewed && isset($_SESSION['user_id'])): ?>
<div class="modal fade" id="reviewModal" tabindex="-1">
    <div class="modal-dialog"><div class="modal-content border-0 rounded-4">
        <div class="modal-header" style="background:var(--g1);color:white;border-radius:15px 15px 0 0"><h6>⭐ রিভিউ লিখুন</h6><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
        <form method="POST">
            <input type="hidden" name="submit_review" value="1">
            <div class="modal-body text-center">
                <div class="star-rating mb-3">
                    <?php for($i=5;$i>=1;$i--): ?>
                        <input type="radio" id="star<?=$i?>" name="rating" value="<?=$i?>" required><label for="star<?=$i?>">★</label>
                    <?php endfor; ?>
                </div>
                <textarea name="comment" class="form-control" rows="3" placeholder="আপনার মতামত লিখুন..." required></textarea>
            </div>
            <div class="modal-footer"><button class="btn btn-secondary rounded-pill" data-bs-dismiss="modal">বাতিল</button><button type="submit" class="btn btn-primary rounded-pill">সাবমিট</button></div>
        </form>
    </div></div>
</div>
<?php endif; ?>

<footer><p>&copy; <?=date('Y')?> <?=htmlspecialchars($ft)?></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:700,once:true});</script>
</body>
</html>