<?php
// lesson.php - Complete Lesson Page with Access Control
require_once 'includes/config.php';
require_once 'includes/site-data.php';
if(file_exists('includes/check-certificate.php')) { require_once 'includes/check-certificate.php'; }

$lesson_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$course_id = isset($_GET['course']) ? (int)$_GET['course'] : 0;
$cert_message = '';
$quiz_result = null;

// Check login
if(!isset($_SESSION['user_id'])) { header('Location: auth.php'); exit; }
$user_id = $_SESSION['user_id'];

// Get lesson
$stmt = $pdo->prepare("SELECT * FROM lessons WHERE id = ? AND course_id = ?");
$stmt->execute([$lesson_id, $course_id]);
$lesson = $stmt->fetch();
if(!$lesson) { header('Location: courses.php'); exit; }

// Get course
$stmt = $pdo->prepare("SELECT * FROM courses WHERE id = ?");
$stmt->execute([$course_id]);
$course = $stmt->fetch();

// Enrollment check
$enrollment_status = 'none';
if(isset($_SESSION['user_role']) && $_SESSION['user_role'] == 'admin') {
    $enrollment_status = 'approved';
} else {
    $stmt = $pdo->prepare("SELECT payment_status FROM enrollments WHERE user_id = ? AND course_id = ? ORDER BY enrolled_at DESC LIMIT 1");
    $stmt->execute([$user_id, $course_id]);
    $enr = $stmt->fetch();
    if($enr) {
        if($enr['payment_status'] == 'completed') $enrollment_status = 'approved';
        elseif($enr['payment_status'] == 'pending') $enrollment_status = 'pending';
        elseif($enr['payment_status'] == 'rejected') $enrollment_status = 'rejected';
    }
}
if($lesson['is_free']) $enrollment_status = 'approved';

// Mark complete
$is_current_completed = false;
if(isset($_POST['mark_complete']) && $enrollment_status == 'approved') {
    $stmt = $pdo->prepare("INSERT INTO lesson_progress (user_id, lesson_id, completed, completed_at) VALUES (?, ?, 1, NOW()) ON DUPLICATE KEY UPDATE completed = 1, completed_at = NOW()");
    $stmt->execute([$user_id, $lesson_id]);
    if(function_exists('checkAndIssueCertificate')) {
        $r = checkAndIssueCertificate($pdo, $user_id, $course_id);
        if($r) $cert_message = '<div class="alert alert-success text-center py-3">অভিনন্দন! সার্টিফিকেট পেয়েছেন! <a href="admin/view-certificate.php?id='.$r.'" target="_blank" class="btn btn-sm btn-success ms-2 rounded-pill">দেখুন</a></div>';
    }
}

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

// PDF
$has_pdf = false; $pdf_url = '';
if($enrollment_status == 'approved' && !empty($lesson['attachment_file'])) {
    $ext = strtolower(pathinfo($lesson['attachment_file'], PATHINFO_EXTENSION));
    if($ext == 'pdf') { $has_pdf = true; $pdf_url = 'uploads/materials/' . $lesson['attachment_file']; }
}

// Quizzes
$quizzes = [];
if($enrollment_status == 'approved') {
    $stmt = $pdo->prepare("SELECT * FROM quizzes WHERE lesson_id = ?");
    $stmt->execute([$lesson_id]);
    $quizzes = $stmt->fetchAll();
}
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_quiz']) && count($quizzes) > 0) {
    $c = 0; foreach($quizzes as $q) { if(($_POST['quiz_'.$q['id']] ?? '') == $q['correct_answer']) $c++; }
    $quiz_result = ['correct' => $c, 'total' => count($quizzes), 'percentage' => count($quizzes) > 0 ? round(($c / count($quizzes)) * 100) : 0];
}

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

// Completed
$completed_ids = [];
if($enrollment_status == 'approved') {
    $stmt = $pdo->prepare("SELECT lesson_id FROM lesson_progress WHERE user_id = ? AND completed = 1");
    $stmt->execute([$user_id]);
    $completed_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);
}
$is_current_completed = in_array($lesson_id, $completed_ids);

// Navigation
$ci = 0; foreach($all_lessons as $i => $l) { if($l['id'] == $lesson_id) { $ci = $i; break; } }
$prev = $ci > 0 ? $all_lessons[$ci - 1] : null;
$next = $ci < count($all_lessons) - 1 ? $all_lessons[$ci + 1] : null;

// Progress
$tl = count($all_lessons);
$cc = count(array_intersect(array_column($all_lessons, 'id'), $completed_ids));
$pp = $tl > 0 ? round(($cc / $tl) * 100) : 0;

// Certificate
$hc = false; $cid = 0;
$stmt = $pdo->prepare("SELECT id FROM certificates WHERE user_id = ? AND course_id = ?");
$stmt->execute([$user_id, $course_id]);
$cert = $stmt->fetch();
if($cert) { $hc = true; $cid = $cert['id']; }

// 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($lesson['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}
.container{max-width:1200px;margin:0 auto;padding:15px}
.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}
.main-card{background:white;border-radius:16px;padding:25px;box-shadow:0 2px 10px rgba(0,0,0,.04);margin-bottom:18px}
.pdf-viewer{border-radius:16px;overflow:hidden;box-shadow:0 8px 30px rgba(0,0,0,.15);margin-bottom:20px}
.pdf-toolbar{background:#f8f9fa;padding:12px 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #e0e0e0;flex-wrap:wrap;gap:8px}
.pdf-embed{width:100%;height:600px;border:none;background:#e8eaef}
.sidebar-card{background:white;border-radius:16px;padding:20px;box-shadow:0 2px 10px rgba(0,0,0,.04);position:sticky;top:85px}
.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:.85rem}
.lesson-item:hover{background:#f8f9ff;color:var(--primary)}
.lesson-item.active{background:var(--g1);color:white;font-weight:600}
.lesson-item .num{width:26px;height:26px;border-radius:50%;background:#e8eaef;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:.7rem;margin-right:8px;flex-shrink:0}
.lesson-item .num.done{background:#52b788;color:white}
.lesson-item.active .num{background:rgba(255,255,255,.3);color:white}
.progress{height:6px;border-radius:10px;background:#e8eaef;margin:10px 0}
.progress-bar{background:var(--g1);border-radius:10px}
.quiz-box{background:#f8f9ff;border-radius:12px;padding:18px;margin-bottom:12px;border:1px solid #e8e8ff}
.status-box{border-radius:16px;padding:30px;text-align:center;margin-bottom:20px}
.status-pending{background:#fff8e1;border:2px solid #ffc107}
.status-approved{background:#eaffea;border:2px solid #28a745}
.btn{font-weight:600;cursor:pointer;transition:.3s;border-radius:50px;padding:10px 22px;border:none;text-decoration:none;display:inline-flex;align-items:center;gap:6px;font-size:.9rem}
.btn:hover{transform:translateY(-2px)}
.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:14px 35px;font-size:1.1rem}.btn-sm{padding:6px 14px;font-size:.78rem}
.alert{border-radius:12px;padding:16px;margin-bottom:15px}
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}.pdf-embed{height:400px}}
</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>
    <a href="dashboard.php" class="btn btn-outline btn-sm"><i class="fas fa-arrow-left me-1"></i> ড্যাশবোর্ড</a>
</div></nav>

<div class="container py-2"><div class="row">

<!-- MAIN -->
<div class="col-lg-8">
    <?php if($cert_message) echo $cert_message; ?>
    
    <?php if($hc): ?>
        <div class="status-box status-approved"><h5>সার্টিফিকেট প্রস্তুত!</h5><a href="admin/view-certificate.php?id=<?=$cid?>" target="_blank" class="btn btn-success btn-lg mt-2">দেখুন</a></div>
    <?php endif; ?>
    
    <!-- APPROVED CONTENT -->
    <?php if($enrollment_status == 'approved'): ?>
        
        <!-- PDF -->
        <?php if($has_pdf): ?>
            <div class="pdf-viewer">
                <div class="pdf-toolbar"><h6 class="mb-0"><i class="fas fa-file-pdf text-danger me-2"></i>PDF ডকুমেন্ট</h6>
                <div><a href="<?=$pdf_url?>" target="_blank" class="btn btn-sm btn-outline me-1"><i class="fas fa-external-link-alt"></i></a><a href="<?=$pdf_url?>" download class="btn btn-sm btn-primary"><i class="fas fa-download"></i></a></div></div>
                <iframe src="<?=$pdf_url?>#toolbar=0" class="pdf-embed"></iframe>
            </div>
        <?php endif; ?>
        
        <!-- Video -->
        <?php if($youtube_id): ?><div class="video-wrap"><iframe src="https://www.youtube.com/embed/<?=$youtube_id?>?rel=0" allowfullscreen></iframe></div><?php endif; ?>
        
        <!-- Content -->
        <div class="main-card">
            <h4><?=htmlspecialchars($lesson['title_bn'])?></h4>
            <?php if(!empty($lesson['title_en'])):?><p class="text-muted"><?=htmlspecialchars($lesson['title_en'])?></p><?php endif;?>
            <?php if(!empty($lesson['description'])):?><div style="line-height:1.8;color:#555;margin:12px 0"><?=nl2br(htmlspecialchars($lesson['description']))?></div><?php endif;?>
            
            <div class="mt-4">
                <?php if(!$is_current_completed): ?>
                    <form method="POST"><button type="submit" name="mark_complete" class="btn btn-success btn-lg"><i class="fas fa-check-circle"></i> লেসন সম্পন্ন হয়েছে</button></form>
                <?php else: ?><span class="badge bg-success p-3 rounded-pill" style="font-size:.9rem"><i class="fas fa-check-circle me-1"></i> সম্পন্ন করা হয়েছে</span><?php endif; ?>
            </div>
            
            <div class="d-flex justify-content-between mt-4 pt-3 border-top">
                <?php if($prev):?><a href="lesson.php?id=<?=$prev['id']?>&course=<?=$course_id?>" class="btn btn-outline btn-sm"><i class="fas fa-arrow-left"></i> পূর্ববর্তী</a><?php else:?><span></span><?php endif;?>
                <?php if($next):?><a href="lesson.php?id=<?=$next['id']?>&course=<?=$course_id?>" class="btn btn-outline btn-sm">পরবর্তী <i class="fas fa-arrow-right"></i></a><?php endif;?>
            </div>
        </div>
        
        <!-- Quiz -->
        <?php if(count($quizzes) > 0): ?>
            <div class="main-card"><h5 class="mb-3"><i class="fas fa-question-circle" style="color:var(--primary)"></i> কুইজ</h5>
                <?php if($quiz_result): ?>
                    <div class="alert alert-<?=$quiz_result['percentage']>=70?'success':'warning'?>">ফলাফল: <?=$quiz_result['correct']?>/<?=$quiz_result['total']?> (<?=$quiz_result['percentage']?>%) <?=$quiz_result['percentage']>=70?'✅':'❌'?></div>
                    <a href="lesson.php?id=<?=$lesson_id?>&course=<?=$course_id?>" class="btn btn-outline btn-sm">পুনরায় কুইজ দিন</a>
                <?php else: ?>
                    <form method="POST"><?php foreach($quizzes as $i=>$q): ?><div class="quiz-box"><h6><?=$i+1?>. <?=htmlspecialchars($q['question_bn'])?></h6><?php foreach(['a'=>'ক','b'=>'খ','c'=>'গ','d'=>'ঘ'] as $o=>$l): if(!empty($q['option_'.$o])):?><div class="form-check"><input class="form-check-input" type="radio" name="quiz_<?=$q['id']?>" value="<?=$o?>" id="q<?=$q['id']?>_<?=$o?>" required><label for="q<?=$q['id']?>_<?=$o?>"><?=$l?>) <?=htmlspecialchars($q['option_'.$o])?></label></div><?php endif; endforeach;?></div><?php endforeach;?>
                    <button type="submit" name="submit_quiz" class="btn btn-primary"><i class="fas fa-check"></i> সাবমিট</button></form>
                <?php endif; ?>
            </div>
        <?php endif; ?>
        
    <!-- PENDING -->
    <?php elseif($enrollment_status == 'pending'): ?>
        <div class="status-box status-pending"><i class="fas fa-clock fa-4x text-warning mb-3"></i><h4>এনরোলমেন্ট অনুমোদনের অপেক্ষায়</h4><p>আপনার পেমেন্ট ভেরিফাই করা হচ্ছে। অ্যাডমিন অনুমোদন করলেই কন্টেন্ট দেখতে পারবেন।</p><a href="course-details.php?id=<?=$course_id?>" class="btn btn-warning mt-2">কোর্স পেজে ফিরুন</a></div>
    
    <!-- REJECTED -->
    <?php elseif($enrollment_status == 'rejected'): ?>
        <div class="status-box status-pending"><i class="fas fa-times-circle fa-4x text-danger mb-3"></i><h4>এনরোলমেন্ট গৃহীত হয়নি</h4><p>দুঃখিত, আপনার এনরোলমেন্ট অনুমোদন করা হয়নি। সাপোর্টে যোগাযোগ করুন।</p><a href="contact.php" class="btn btn-warning mt-2">সাপোর্ট</a></div>
    
    <!-- NOT ENROLLED -->
    <?php else: ?>
        <div class="status-box status-pending"><i class="fas fa-lock fa-4x text-warning mb-3"></i><h4><?=$course['price'] > 0 ? 'কোর্সটি কিনুন' : 'ফ্রি কোর্সে এনরোল করুন'?></h4><p><?=$course['price'] > 0 ? 'এই কন্টেন্ট দেখতে কোর্সটি কিনুন।' : 'ফ্রি কোর্সে এনরোল করে শেখা শুরু করুন।'?></p>
        <a href="enroll.php?course=<?=$course_id?>" class="btn btn-primary btn-lg mt-2"><i class="fas fa-shopping-cart me-2"></i><?=$course['price'] > 0 ? '৳'.number_format($course['price']).' - কিনুন' : 'বিনামূল্যে এনরোল'?></a></div>
    <?php endif; ?>
</div>

<!-- SIDEBAR -->
<div class="col-lg-4"><div class="sidebar-card">
    <h6 style="color:var(--dark);margin-bottom:8px">📚 <?=htmlspecialchars(mb_substr($course['title_bn']??'কোর্স',0,25))?></h6>
    <?php if($enrollment_status == 'approved'): ?>
        <div class="d-flex justify-content-between small mb-1"><span>প্রগতি</span><strong><?=$pp?>%</strong></div>
        <div class="progress"><div class="progress-bar" style="width:<?=$pp?>%"></div></div>
        <small class="text-muted"><?=$cc?>/<?=$tl?> লেসন</small>
        <?php if($hc):?><span class="badge bg-warning text-dark mt-1">সার্টিফাইড</span><?php endif;?>
        <hr>
    <?php endif; ?>
    <small class="text-muted d-block mb-2">লেসন তালিকা:</small>
    <?php foreach($all_lessons as $l): $done=in_array($l['id'],$completed_ids); $active=$l['id']==$lesson_id;?>
        <a href="lesson.php?id=<?=$l['id']?>&course=<?=$course_id?>" class="lesson-item <?=$active?'active':''?>"><span class="num <?=$done?'done':''?>"><?=$done?'✓':$l['order_number']?></span><?=htmlspecialchars(mb_substr($l['title_bn'],0,25))?></a>
    <?php endforeach; ?>
</div></div>

</div></div>

<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>