<?php
// course-details.php - Complete Fixed 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
$stmt = $pdo->prepare("SELECT * FROM lessons WHERE course_id = ? ORDER BY order_number");
$stmt->execute([$course_id]);
$lessons = $stmt->fetchAll();

// Get reviews
$stmt = $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");
$stmt->execute([$course_id]);
$reviews = $stmt->fetchAll();

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

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

// Check enrollment
$is_enrolled = false;
$has_reviewed = false;
$progress_percent = 0;
$progress_done = 0;
$progress_total = 0;
$has_certificate = false;
$cert_id = 0;

if(isset($_SESSION['user_id'])) {
    $uid = $_SESSION['user_id'];
    
    // Enrollment
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM enrollments WHERE user_id = ? AND course_id = ? AND payment_status = 'completed'");
    $stmt->execute([$uid, $course_id]);
    $is_enrolled = $stmt->fetchColumn() > 0;
    
    // Review check
    $stmt = $pdo->prepare("SELECT id FROM reviews WHERE user_id = ? AND course_id = ?");
    $stmt->execute([$uid, $course_id]);
    $has_reviewed = $stmt->fetch() ? true : false;
    
    // Progress
    $stmt = $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 = ?
    ");
    $stmt->execute([$uid, $course_id]);
    $prog = $stmt->fetch();
    $progress_total = (int)($prog['total'] ?? 0);
    $progress_done = (int)($prog['done'] ?? 0);
    $progress_percent = $progress_total > 0 ? round(($progress_done / $progress_total) * 100) : 0;
    
    // Certificate
    $stmt = $pdo->prepare("SELECT id FROM certificates WHERE user_id = ? AND course_id = ?");
    $stmt->execute([$uid, $course_id]);
    $cert = $stmt->fetch();
    if($cert) { $has_certificate = true; $cert_id = $cert['id']; }
}

// Find next lesson for enrolled students
$next_lesson_id = null;
if($is_enrolled && !empty($lessons)) {
    $completed_ids = [];
    $stmt = $pdo->prepare("SELECT lesson_id FROM lesson_progress WHERE user_id = ? AND completed = 1");
    $stmt->execute([$_SESSION['user_id']]);
    $completed_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    foreach($lessons as $l) {
        if(!in_array($l['id'], $completed_ids)) {
            $next_lesson_id = $l['id'];
            break;
        }
    }
    if(!$next_lesson_id) $next_lesson_id = $lessons[0]['id'];
}

// YouTube preview
$youtube_id = null;
if(!empty($lessons) && !empty($lessons[0]['youtube_url'])) {
    preg_match('/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/', $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_val = (int)$_POST['rating'];
    $comment = trim($_POST['comment'] ?? '');
    if($rating_val >= 1 && $rating_val <= 5 && !empty($comment) && $is_enrolled && !$has_reviewed) {
        $stmt = $pdo->prepare("INSERT INTO reviews (user_id, course_id, rating, comment) VALUES (?, ?, ?, ?)");
        $stmt->execute([$_SESSION['user_id'], $course_id, $rating_val, $comment]);
        header("Location: course-details.php?id=$course_id&review=success");
        exit;
    }
}

// Dynamic
$st = $S['site_title'] ?? 'স্বাস্থ্য কানন LMS';
$lt = $S['logo_text'] ?? 'স্বাস্থ্য কানন';
$li = $S['logo_icon'] ?? 'fa-heartbeat';
$pc = $S['primary_color'] ?? '#2d6a4f';
$ui = $S['use_image_logo'] ?? '0';
$lim = $S['logo_image'] ?? '';
$ft = $S['footer_text'] ?? 'স্বাস্থ্য কানন';
?>
<!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">
<style>
:root{--primary:<?=$pc?>;--g1:linear-gradient(135deg,<?=$pc?>,#52b788);--dark:#1a1a2e}
*{margin:0;padding:0;box-sizing:border-box}
body{background:#f5faf7;font-family:'Segoe UI','Hind Siliguri',Arial,sans-serif}
.navbar{background:white;box-shadow:0 2px 10px rgba(0,0,0,.06);padding:12px 0;position:sticky;top:0;z-index:1000}
.navbar-brand{font-weight:800;font-size:1.1rem;color:var(--primary)!important;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:1100px;margin:0 auto;padding:20px}
.main-card{background:white;border-radius:16px;padding:25px;box-shadow:0 2px 10px 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:16px;padding:25px;box-shadow:0 2px 10px rgba(0,0,0,.04);position:sticky;top:85px;text-align:center}
.price-display{font-size:2.5rem;font-weight:800;color:var(--primary)}.price-display.free{color:#11998e}
.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:#52b788;color:white}
.review-card{background:#f8f9ff;border-radius:12px;padding:15px;margin-bottom:10px}
.stars{color:#ffc107}
.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-success{background:#28a745;color:white}
.btn-warning{background:#ffc107;color:#333}.btn-outline{border:2px solid var(--primary);color:var(--primary);background:white}
.btn-lg{padding:16px 35px;font-size:1.1rem;width:100%;justify-content:center}
.badge-custom{padding:5px 14px;border-radius:20px;font-weight:600;font-size:.78rem}
footer{background:var(--dark);color:white;text-align:center;padding:20px;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=""><?php else:?><i class="fas <?=$li?> me-2"></i><?=htmlspecialchars($lt)?><?php endif;?></a>
    <div style="display:flex;gap:10px"><a href="index.php" class="nav-link">হোম</a><a href="courses.php" class="nav-link">কোর্স</a></div>
</div></nav>

<div class="container"><div class="row">

<!-- MAIN -->
<div class="col-lg-8">
    <?php if(isset($_GET['review'])):?><div class="alert alert-success rounded-3">রিভিউ সফলভাবে জমা হয়েছে!</div><?php endif;?>
    
    <?php if($youtube_id): ?><div class="video-wrap"><iframe src="https://www.youtube.com/embed/<?=$youtube_id?>?rel=0" allowfullscreen></iframe></div><?php endif; ?>
    
    <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'?'#2d6a4f':($course['level']=='intermediate'?'#e67e22':'#e74c3c')?>"><?=$course['level']=='beginner'?'বিগিনার':($course['level']=='intermediate'?'ইন্টারমিডিয়েট':'অ্যাডভান্সড')?></span>
        </div>
        <h3 style="font-weight:700"><?=htmlspecialchars($course['title_bn'])?></h3>
        <p class="text-muted"><?=htmlspecialchars($course['title_en'])?></p>
        
        <?php if($is_enrolled): ?>
            <div class="mt-3 p-3 rounded-3" style="background:#f8f9ff">
                <div class="d-flex justify-content-between small mb-1"><span>আপনার প্রগতি</span><strong><?=$progress_percent?>%</strong></div>
                <div class="progress" style="height:8px"><div class="progress-bar bg-success" style="width:<?=$progress_percent?>%"></div></div>
                <small><?=$progress_done?>/<?=$progress_total?> লেসন সম্পন্ন</small>
            </div>
        <?php endif; ?>
        
        <hr>
        <h5 class="fw-bold">কোর্স সম্পর্কে</h5>
        <p style="line-height:1.8;color:#555"><?=nl2br(htmlspecialchars($course['description_bn']??'বিস্তারিত শীঘ্রই যোগ করা হবে।'))?></p>
    </div>
    
    <!-- Lessons -->
    <div class="main-card">
        <h5 class="fw-bold mb-3">কোর্স কন্টেন্ট (<?=count($lessons)?> লেসন)</h5>
        <?php if(count($lessons) > 0): ?>
            <?php 
            $completed_ids = [];
            if($is_enrolled) {
                $stmt = $pdo->prepare("SELECT lesson_id FROM lesson_progress WHERE user_id=? AND completed=1");
                $stmt->execute([$_SESSION['user_id']]);
                $completed_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);
            }
            ?>
            <?php foreach($lessons as $l): $done=in_array($l['id'],$completed_ids); ?>
                <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 mb-3"><h5 class="fw-bold">রিভিউ (<?=$rating['total']??0?>)</h5>
        <?php if($is_enrolled && !$has_reviewed):?><button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#reviewModal">⭐ রিভিউ লিখুন</button><?php endif;?>
        </div>
        <?php if(($rating['total']??0) > 0): ?>
            <div class="text-center mb-3"><h2 class="text-warning">⭐ <?=round($rating['avg_rating'],1)?></h2></div>
            <?php foreach($reviews 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="main-card text-center">
        <img src="uploads/avatars/<?=$course['instructor_avatar']?:'default-avatar.png'?>" style="width:80px;height:80px;border-radius:50%;object-fit:cover;border:4px solid var(--primary);margin-bottom:10px" onerror="this.src='https://ui-avatars.com/api/?name=<?=urlencode($course['instructor_name'])?>&background=2d6a4f&color=fff&size=80'">
        <h5><?=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">
        <div class="price-display <?=$course['price']==0?'free':''?>"><?=$course['price']==0?'বিনামূল্যে':'৳'.number_format($course['price'])?></div>
        
        <?php if($is_enrolled): ?>
            <?php if($next_lesson_id): ?>
                <a href="lesson.php?id=<?=$next_lesson_id?>&course=<?=$course_id?>" class="btn btn-success btn-lg mt-3"><i class="fas fa-play-circle me-2"></i>কোর্স চালিয়ে যান</a>
            <?php endif; ?>
            <?php if($has_certificate): ?>
                <a href="admin/view-certificate.php?id=<?=$cert_id?>" target="_blank" class="btn btn-warning btn-lg mt-2"><i class="fas fa-certificate me-2"></i>সার্টিফিকেট</a>
            <?php endif; ?>
        <?php else: ?>
            <a href="enroll.php?course=<?=$course_id?>" class="btn btn-primary btn-lg mt-3"><i class="fas fa-shopping-cart me-2"></i><?=$course['price']>0?'এখনই কিনুন':'বিনামূল্যে এনরোল করুন'?></a>
        <?php endif; ?>
        
        <hr>
        <div class="text-start">
            <p><i class="fas fa-video text-primary me-2"></i><strong><?=count($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):?>
<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="mb-3">
        <?php for($i=5;$i>=1;$i--):?><input type="radio" id="star<?=$i?>" name="rating" value="<?=$i?>" required><label for="star<?=$i?>" style="font-size:2rem;cursor:pointer;color:#ddd">★</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>&copy; <?=date('Y')?> <?=htmlspecialchars($ft)?></footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>