<?php
// lesson.php - Modern Dynamic Lesson with PDF Viewer
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;

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

// In lesson.php, replace the enrollment check:
$stmt = $pdo->prepare("SELECT COUNT(*) FROM enrollments WHERE user_id = ? AND course_id = ? AND payment_status = 'completed' AND (expires_at IS NULL OR expires_at >= CURDATE())");
$stmt->execute([$user_id, $course_id]);
$is_enrolled = $stmt->fetchColumn() > 0;

// If not enrolled or payment pending/rejected, check if lesson is free
if(!$is_enrolled) {
    if($lesson['is_free']) {
        // Allow free preview
    } else {
        // Check if pending approval
        $stmt = $pdo->prepare("SELECT payment_status FROM enrollments WHERE user_id = ? AND course_id = ?");
        $stmt->execute([$user_id, $course_id]);
        $enr = $stmt->fetch();
        if($enr && $enr['payment_status'] == 'pending') {
            $approval_msg = '<div class="alert alert-warning">⏳ আপনার এনরোলমেন্ট অনুমোদনের জন্য অপেক্ষমান। অনুমোদিত হলে কোর্স দেখতে পারবেন।</div>';
        } elseif($enr && $enr['payment_status'] == 'rejected') {
            $approval_msg = '<div class="alert alert-danger">❌ আপনার এনরোলমেন্ট গৃহীত হয়নি। সাপোর্টে যোগাযোগ করুন।</div>';
        }
        header('Location: course-details.php?id=' . $course_id);
        exit;
    }
}
// YouTube ID
$youtube_id = null;
if(!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 file check
$has_pdf = false; $pdf_url = ''; $pdf_name = '';
if(!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'];
        $pdf_name = $lesson['attachment_name'] ?? 'PDF Document';
    }
}

// Other attachment
$has_attachment = false; $attachment_url = ''; $attachment_name = ''; $attachment_icon = '';
if(!empty($lesson['attachment_file']) && !$has_pdf) {
    $has_attachment = true;
    $attachment_url = 'uploads/materials/' . $lesson['attachment_file'];
    $attachment_name = $lesson['attachment_name'] ?? 'Download';
    $ext = strtolower(pathinfo($lesson['attachment_file'], PATHINFO_EXTENSION));
    $icons = ['zip'=>'fa-file-archive','rar'=>'fa-file-archive','doc'=>'fa-file-word','docx'=>'fa-file-word','ppt'=>'fa-file-powerpoint','pptx'=>'fa-file-powerpoint','xls'=>'fa-file-excel','xlsx'=>'fa-file-excel','txt'=>'fa-file-alt'];
    $attachment_icon = $icons[$ext] ?? 'fa-file-download';
}

// MARK COMPLETE
if(isset($_POST['mark_complete'])) {
    $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')) {
        $cert_result = checkAndIssueCertificate($pdo, $user_id, $course_id);
        if($cert_result) { $cert_message = '<div class="cert-alert">ЁЯОЙ ржЕржнрж┐ржиржирзНржжржи! рж╕рж╛рж░рзНржЯрж┐ржлрж┐ржХрзЗржЯ ржкрзЗржпрж╝рзЗржЫрзЗржи! <a href="admin/view-certificate.php?id='.$cert_result.'" target="_blank" class="btn btn-sm btn-success ms-2">ржжрзЗржЦрзБржи</a></div>'; }
    }
}

// QUIZZES
$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){
    $correct=0; $total=count($quizzes);
    foreach($quizzes as $q){ if(($_POST['quiz_'.$q['id']]??'')==$q['correct_answer']) $correct++; }
    $quiz_result = ['correct'=>$correct,'total'=>$total,'percentage'=>$total>0?round(($correct/$total)*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
$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);

// NAVIGATION
$current_index = 0;
foreach($all_lessons as $i=>$l){ if($l['id']==$lesson_id){$current_index=$i;break;} }
$prev_lesson = $current_index>0 ? $all_lessons[$current_index-1] : null;
$next_lesson = $current_index<count($all_lessons)-1 ? $all_lessons[$current_index+1] : null;

// PROGRESS
$total_lessons = count($all_lessons);
$completed_count = count(array_intersect(array_column($all_lessons,'id'),$completed_ids));
$progress_percent = $total_lessons>0?round(($completed_count/$total_lessons)*100):0;
$is_current_completed = in_array($lesson_id, $completed_ids);

// CERTIFICATE
$has_certificate = false; $cert_id = 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){ $has_certificate=true; $cert_id=$cert['id']; }

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

// DYNAMIC
$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($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?>,<?=$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:10px 0;position:sticky;top:0;z-index:1000}
        .navbar-brand{font-weight:800;font-size:1.1rem;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:32px}
        
        .container{max-width:1300px;margin:0 auto;padding:15px}
        
        .lesson-layout{display:grid;grid-template-columns:1fr 360px;gap:20px}
        
        .main-area{min-width:0}
        .main-card{background:white;border-radius:16px;padding:22px;box-shadow:0 2px 10px rgba(0,0,0,.04);margin-bottom:18px}
        
        .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}
        
        /* PDF Viewer */
        .pdf-viewer{border-radius:16px;overflow:hidden;box-shadow:0 8px 30px rgba(0,0,0,.15);background:white;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-toolbar h6{margin:0;font-size:.9rem}
        .pdf-actions{display:flex;gap:6px}
        .pdf-embed{width:100%;height:600px;border:none;background:#e8eaef}
        .pdf-fullscreen{position:fixed;top:0;left:0;width:100%;height:100%;z-index:9999;background:white}
        .pdf-fullscreen .pdf-embed{height:100vh}
        .pdf-fullscreen .pdf-toolbar{position:absolute;top:0;left:0;right:0;z-index:1}
        
        .material-card{background:linear-gradient(135deg,#f8f9ff,#e8ecf5);border-radius:14px;padding:18px;display:flex;align-items:center;gap:15px;margin-bottom:15px;border:1px solid #e0e0e0;transition:.3s;cursor:pointer;text-decoration:none;color:inherit}
        .material-card:hover{box-shadow:0 5px 20px rgba(0,0,0,.1);transform:translateY(-2px)}
        .material-icon{width:55px;height:55px;border-radius:14px;display:flex;align-items:center;justify-content:center;font-size:1.5rem;color:white;flex-shrink:0}
        
        .quiz-box{background:#f8f9ff;border-radius:12px;padding:18px;margin-bottom:12px;border:1px solid #e8e8ff}
        
        .sidebar-card{background:white;border-radius:16px;padding:20px;box-shadow:0 2px 10px rgba(0,0,0,.04);position:sticky;top:75px;max-height:85vh;overflow-y:auto}
        .lesson-item{display:flex;align-items:center;padding:10px 12px;border-radius:10px;margin-bottom:3px;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:var(--g4);color:#0d4d2b}
        .lesson-item.active .num{background:rgba(255,255,255,.3);color:white}
        
        .progress-wrap{margin:8px 0}
        .progress{height:6px;border-radius:10px;background:#e8eaef}
        .progress-bar{background:var(--g1);border-radius:10px}
        
        .cert-alert{background:#eaffea;border:2px solid var(--g4);border-radius:14px;padding:18px;text-align:center;margin-bottom:18px;animation:glow 2s infinite}
        @keyframes glow{0%,100%{box-shadow:0 0 10px rgba(67,233,123,.3)}50%{box-shadow:0 0 25px rgba(67,233,123,.6)}}
        
        .nav-buttons{display:flex;justify-content:space-between;margin-top:15px;padding-top:15px;border-top:1px solid #eee}
        
        .btn{font-weight:600;cursor:pointer;transition:.3s;border-radius:50px;padding:8px 20px;border:none;text-decoration:none;display:inline-flex;align-items:center;gap:6px;font-size:.85rem}
        .btn-primary{background:var(--g1);color:white}.btn-primary:hover{transform:translateY(-2px);box-shadow:0 8px 20px rgba(108,92,231,.3);color:white}
        .btn-success{background:#28a745;color:white}.btn-outline{border:2px solid var(--primary);color:var(--primary);background:white}
        .btn-sm{padding:5px 12px;font-size:.78rem}
        .btn-xs{padding:4px 10px;font-size:.7rem}
        
        .badge-status{padding:3px 10px;border-radius:20px;font-size:.7rem;font-weight:600}
        
        @media(max-width:992px){.lesson-layout{grid-template-columns:1fr}.sidebar-card{position:static;max-height:none}}
    </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>
        <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="lesson-layout">
        
        <!-- MAIN CONTENT -->
        <div class="main-area">
            
            <?php if($cert_message){ echo $cert_message; } ?>
            
            <!-- PDF VIEWER -->
            <?php if($has_pdf): ?>
                <div class="pdf-viewer" id="pdfViewer">
                    <div class="pdf-toolbar">
                        <h6><i class="fas fa-file-pdf text-danger me-2"></i><?=htmlspecialchars($pdf_name)?></h6>
                        <div class="pdf-actions">
                            <button class="btn btn-xs btn-outline" onclick="toggleFullscreen()" title="ржлрзБрж▓рж╕рзНржХрзНрж░рж┐ржи"><i class="fas fa-expand"></i></button>
                            <a href="<?=$pdf_url?>" class="btn btn-xs btn-outline" download title="ржбрж╛ржЙржирж▓рзЛржб"><i class="fas fa-download"></i></a>
                        </div>
                    </div>
                    <iframe src="<?=$pdf_url?>#toolbar=0&navpanes=0" class="pdf-embed" id="pdfEmbed"></iframe>
                </div>
            <?php endif; ?>
            
            <!-- VIDEO PLAYER -->
            <?php if($youtube_id): ?>
                <div class="video-wrap">
                    <iframe src="https://www.youtube.com/embed/<?=$youtube_id?>?rel=0" allowfullscreen></iframe>
                </div>
            <?php endif; ?>
            
            <!-- LESSON CONTENT -->
            <div class="main-card">
                <h4 style="color:var(--dark)"><?=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; ?>
                
                <!-- Other Attachment -->
                <?php if($has_attachment): ?>
                    <a href="<?=$attachment_url?>" class="material-card" download>
                        <div class="material-icon" style="background:var(--g3)"><i class="fas <?=$attachment_icon?>"></i></div>
                        <div>
                            <strong><?=htmlspecialchars($attachment_name)?></strong>
                            <br><small class="text-muted">ржбрж╛ржЙржирж▓рзЛржб ржХрж░рждрзЗ ржХрзНрж▓рж┐ржХ ржХрж░рзБржи</small>
                        </div>
                        <i class="fas fa-download ms-auto" style="color:var(--primary)"></i>
                    </a>
                <?php endif; ?>
                
                <!-- Mark Complete -->
                <?php if($is_enrolled): ?>
                    <div class="mt-3">
                        <?php if(!$is_current_completed): ?>
                            <form method="POST"><button type="submit" name="mark_complete" class="btn btn-success"><i class="fas fa-check-circle"></i> рж▓рзЗрж╕ржи рж╕ржорзНржкржирзНржи рж╣ржпрж╝рзЗржЫрзЗ</button></form>
                        <?php else: ?>
                            <span class="badge-status bg-success text-white" style="padding:8px 16px;font-size:.85rem"><i class="fas fa-check-circle me-1"></i> рж╕ржорзНржкржирзНржи</span>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
                
                <!-- Navigation -->
                <div class="nav-buttons">
                    <?php if($prev_lesson): ?><a href="lesson.php?id=<?=$prev_lesson['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_lesson): ?><a href="lesson.php?id=<?=$next_lesson['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 && $is_enrolled): ?>
                <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'?> rounded-3">ржлрж▓рж╛ржлрж▓: <?=$quiz_result['correct']?>/<?=$quiz_result['total']?> (<?=$quiz_result['percentage']?>%) <?=$quiz_result['percentage']>=70?'тЬЕ':'тЭМ'?></div>
                    <?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; ?>
        </div>
        
        <!-- SIDEBAR -->
        <div class="sidebar-area">
            <div class="sidebar-card">
                <h6 style="color:var(--dark);margin-bottom:8px">ЁЯУЪ <?=htmlspecialchars(mb_substr($course['title_bn']??'ржХрзЛрж░рзНрж╕',0,25))?></h6>
                <div class="progress-wrap">
                    <div class="d-flex justify-content-between small"><span>ржкрзНрж░ржЧрждрж┐</span><strong><?=$progress_percent?>%</strong></div>
                    <div class="progress"><div class="progress-bar" style="width:<?=$progress_percent?>%"></div></div>
                    <small class="text-muted"><?=$completed_count?>/<?=$total_lessons?> рж▓рзЗрж╕ржи</small>
                </div>
                <?php if($has_certificate): ?><span class="badge bg-warning text-dark mt-1">ЁЯПЖ рж╕рж╛рж░рзНржЯрж┐ржлрж╛ржЗржб</span><?php endif; ?>
                <hr>
                <?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>

<script>
function toggleFullscreen(){
    var v=document.getElementById('pdfViewer');
    v.classList.toggle('pdf-fullscreen');
    var btn=v.querySelector('.fa-expand,.fa-compress');
    if(v.classList.contains('pdf-fullscreen')){btn.classList.replace('fa-expand','fa-compress');}
    else{btn.classList.replace('fa-compress','fa-expand');}
}
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>