<?php
session_start();
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);
include "db.php";

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

$user_id = $_SESSION['user_id'];
$course_id = isset($_GET['course']) ? intval($_GET['course']) : 0;
$selectedModuleId = isset($_GET['module']) ? intval($_GET['module']) : 0;
$error = null;

/* ================= FETCH COURSE ================= */
$stmt = $conn->prepare("SELECT * FROM courses WHERE id=?");
$stmt->bind_param("i", $course_id);
$stmt->execute();
$course = $stmt->get_result()->fetch_assoc();

if (!$course) {
    $error = "Course not found.";
}

/* ================= FETCH MODULES ================= */
$modules = [];
$modStmt = $conn->prepare(
    "SELECT * FROM modules WHERE course_id=? ORDER BY module_order ASC"
);
$modStmt->bind_param("i", $course_id);
$modStmt->execute();
$res = $modStmt->get_result();
while ($row = $res->fetch_assoc()) {
    $modules[] = $row;
}

/* ================= FETCH USER PROGRESS ================= */
$progress = [];
$pRes = $conn->query(
    "SELECT module_id, completed 
     FROM user_module_progress 
     WHERE user_id=$user_id AND course_id=$course_id"
);
while ($p = $pRes->fetch_assoc()) {
    $progress[$p['module_id']] = $p['completed'];
}

/* ================= CURRENT MODULE ================= */
$currentModule = null;

if ($selectedModuleId) {
    foreach ($modules as $m) {
        if ($m['id'] == $selectedModuleId) {
            $currentModule = $m;
            break;
        }
    }
}

if (!$currentModule && !empty($modules)) {
    foreach ($modules as $m) {
        if (!isset($progress[$m['id']]) || $progress[$m['id']] < 80) {
            $currentModule = $m;
            break;
        }
    }
}

if (!$currentModule && !empty($modules)) {
    $currentModule = $modules[0];
}

/* ===== MODULE POSITION ===== */
$currentIndex = 0;
foreach ($modules as $i => $m) {
    if ($m['id'] == $currentModule['id']) {
        $currentIndex = $i;
        break;
    }
}
$isLastModule = ($currentIndex === count($modules) - 1);
$nextModuleId = !$isLastModule ? $modules[$currentIndex + 1]['id'] : null;

/* ================= FETCH QUIZ ================= */
$quiz = null;
$quizQuestions = [];

if ($currentModule) {

    $qzStmt = $conn->prepare(
        "SELECT * FROM quizzes WHERE module_id=? LIMIT 1"
    );
    $qzStmt->bind_param("i", $currentModule['id']);
    $qzStmt->execute();
    $quiz = $qzStmt->get_result()->fetch_assoc();

    if ($quiz) {
        $qqStmt = $conn->prepare(
            "SELECT * FROM quiz_questions WHERE quiz_id=? ORDER BY id ASC"
        );
        $qqStmt->bind_param("i", $quiz['id']);
        $qqStmt->execute();
        $qqRes = $qqStmt->get_result();

        while ($q = $qqRes->fetch_assoc()) {
            $optStmt = $conn->prepare(
                "SELECT id, option_text FROM quiz_options WHERE question_id=?"
            );
            $optStmt->bind_param("i", $q['id']);
            $optStmt->execute();
            $q['options'] = $optStmt->get_result()->fetch_all(MYSQLI_ASSOC);
            $quizQuestions[] = $q;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Study Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
:root{
 --bg:#f4f6fb;
 --card:#fff;
 --text:#0f172a;
 --muted:#64748b;
 --primary:#6366f1;
 --accent:#f5a425;
 --scroll-bg:#e5e7eb;
 --scroll-thumb:#6366f1;
}
*{box-sizing:border-box}
body{
 margin:0;
 font-family:Poppins,sans-serif;
 background:;
 color:var(--text);
}
.container{max-width:1000px;margin:20px auto 80px;padding:16px;}
.card{
 background:var(--card);
 border-radius:22px;
 padding:18px;
 box-shadow:0 15px 40px rgba(0,0,0,.08);
}
.course-cover{width:100%;max-height:260px;object-fit:cover;border-radius:16px;margin-bottom:18px;}
.module-list{display:flex;flex-wrap:wrap;gap:10px;margin-bottom:18px;}
.module-pill{padding:10px 14px;border-radius:14px;background:#e5e7eb;font-size:14px;cursor:pointer;transition:.3s;}
.module-pill:hover{transform:scale(1.03);}
.module-pill.completed{background:var(--primary);color:#fff;}
.module-pill.current{border:2px solid var(--primary);background:#eef2ff;}
.pdf-container,.video-container{
 width:100%;
 min-height:300px;
 border-radius:16px;
 overflow:auto;
 box-shadow:0 10px 30px rgba(0,0,0,.1);
 scroll-behavior:smooth;
 border:1px solid #ddd;
 background:#fff;
 margin-bottom:18px;
}
.pdf-container iframe,.video-container video{
 width:100%;
 height:100%;
 border:none;
 border-radius:16px;
}

/* Custom Scrollbar */
.pdf-container::-webkit-scrollbar,.video-container::-webkit-scrollbar{width:12px;}
.pdf-container::-webkit-scrollbar-track,.video-container::-webkit-scrollbar-track{background:var(--scroll-bg);border-radius:12px;}
.pdf-container::-webkit-scrollbar-thumb,.video-container::-webkit-scrollbar-thumb{background:var(--scroll-thumb);border-radius:12px;}
.pdf-container::-webkit-scrollbar-thumb:hover,.video-container::-webkit-scrollbar-thumb:hover{background:#4f46e5;}

button{
 width:100%;
 margin-top:18px;
 padding:14px;
 border:none;
 border-radius:18px;
 background:rgb(18,108,201);
 color:#fff;
 font-weight:600;
 cursor:pointer;
 transition:.3s;
}
button:hover{opacity:.9;}
button:disabled{opacity:.6;cursor:not-allowed;}
footer{text-align:center;margin-top:40px;color:var(--muted);font-size:14px;}
.modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.7);align-items:center;justify-content:center;z-index:999;padding:16px;}
.modal-content{background:#fff;width:100%;max-width:600px;max-height:90vh;overflow-y:auto;border-radius:20px;padding:18px;}
.close-btn{float:right;font-size:22px;cursor:pointer;}
.question{margin-bottom:20px;}
.options label{display:block;margin-bottom:8px;font-size:14px;}
#timer{font-weight:700;color:var(--primary);margin-bottom:16px;}
@media(max-width:600px){.pdf-container{height:55vh}.video-container{height:35vh}}
.pdf-container{
 position:relative;
}

.pdf-fullscreen-btn{
 position:absolute;
 top:12px;
 right:12px;
 z-index:10;
 background:rgba(0,0,0,.65);
 color:#fff;
 border:none;
 width:42px;
 height:42px;
 border-radius:50%;
 font-size:18px;
 cursor:pointer;
 display:flex;
 align-items:center;
 justify-content:center;
 transition:.2s;
}

.pdf-fullscreen-btn:hover{
 background:rgba(0,0,0,.85);
 transform:scale(1.05);
}

</style>
</head>

<body oncontextmenu="return false">

<div class="container">
<div class="card">

<?php if($error): ?>
<p style="color:red;text-align:center"><?= $error ?></p>
<?php else: ?>

<h2 style="text-align:center"><?= htmlspecialchars($course['title']) ?></h2>
<img src="<?= htmlspecialchars($course['cover']) ?>" class="course-cover">

<div class="module-list">
<?php foreach($modules as $m): ?>
<div class="module-pill
<?= (isset($progress[$m['id']]) && $progress[$m['id']]>=80) ? 'completed':'' ?>
<?= ($m['id']==$currentModule['id']) ? 'current':'' ?>"
onclick="loadModule(<?= $m['id'] ?>)">
<?= htmlspecialchars($m['title']) ?>
</div>
<?php endforeach; ?>
</div>

<!-- VIDEO -->
<?php if(!empty($currentModule['video_file']) && file_exists(__DIR__.'/'.$currentModule['video_file'])): ?>
<h3>Module Video</h3>
<div class="video-container">
<video controls controlsList="nodownload" oncontextmenu="return false">
  <source src="<?= $currentModule['video_file'] ?>" type="video/mp4">
  Your browser does not support the video tag.
</video>
</div>
<?php endif; ?>

<!-- PDF -->
<?php if(!empty($currentModule['pdf_file']) && file_exists(__DIR__.'/'.$currentModule['pdf_file'])): ?>
<h3>Module PDF</h3>
<div class="pdf-container">
    <button class="pdf-fullscreen-btn" onclick="openPdfFullscreen()">
        ⛶
    </button>
    <iframe id="pdfFrame" src="<?= $currentModule['pdf_file'] ?>#toolbar=0"></iframe>
</div>

<?php else: ?>
<p style="color:red">Module PDF not found.</p>
<?php endif; ?>

<button id="takeQuizBtn" <?= !$quiz ? 'disabled':'' ?>>
<?= $quiz ? 'Take Quiz' : 'No Quiz Available' ?>
</button>

<?php endif; ?>

</div>
</div>

<!-- QUIZ MODAL -->
<div id="quizModal" class="modal">
<div class="modal-content">
<span class="close-btn" onclick="closeQuiz()">&times;</span>

<h3><?= htmlspecialchars($currentModule['title']) ?> – Quiz</h3>
<div id="timer">Time: <span id="timeRemaining">00:00</span></div>

<?php if($quiz): ?>
<form id="quizForm">
<?php foreach($quizQuestions as $i=>$q): ?>
<div class="question">
<p><strong><?= ($i+1).'. '.htmlspecialchars($q['question']) ?></strong></p>
<div class="options">
<?php foreach($q['options'] as $opt): ?>
<label>
<input type="radio" name="q<?= $q['id'] ?>" value="<?= $opt['id'] ?>" required>
<?= htmlspecialchars($opt['option_text']) ?>
</label>
<?php endforeach; ?>
</div>
</div>
<?php endforeach; ?>
<button type="submit">Submit Quiz</button>
</form>
<?php endif; ?>
</div>
</div>



<script>
function loadModule(id){
 location.href="study.php?course=<?= $course_id ?>&module="+id;
}

const modal=document.getElementById('quizModal');
const btn=document.getElementById('takeQuizBtn');

if(btn){
 btn.onclick=()=>{ modal.style.display='flex'; startTimer(<?= $quiz['duration_minutes'] ?? 10 ?>*60); }
}
function closeQuiz(){ modal.style.display='none'; }

let interval;
function startTimer(sec){
 clearInterval(interval);
 let t=sec;
 interval=setInterval(()=>{
   let m=Math.floor(t/60), s=t%60;
   timeRemaining.textContent=`${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
   if(t<=0){ clearInterval(interval); submitQuiz(); }
   t--;
 },1000);
}

document.getElementById('quizForm')?.addEventListener('submit',e=>{
 e.preventDefault(); submitQuiz();
});

function submitQuiz(){
 clearInterval(interval);
 const fd=new FormData(document.getElementById('quizForm'));
 fd.append('module_id',<?= (int)$currentModule['id'] ?>);
 fd.append('course_id',<?= (int)$course_id ?>);

 fetch('submit_quiz.php',{method:'POST',body:fd})
 .then(r=>r.json())
 .then(d=>{
   if(!d.passed){
     alert(`❌ You scored ${d.score}%. Pass mark is ${d.pass_mark}%. Please retry.`);
     location.reload();
     return;
   }

   if(<?= $isLastModule ? 'true' : 'false' ?>){
     alert("🎓 Congratulations! Course completed. Redirecting to certificate...");
     location.href="certificate.php?course=<?= $course_id ?>";
   }else{
     alert("Passed! Moving to the next module.");
     location.href="study.php?course=<?= $course_id ?>&module=<?= $nextModuleId ?>";
   }
 })
 .catch(()=>alert('Submission failed'));
}


</script>
<script>
    function openPdfFullscreen(){
 const iframe = document.getElementById('pdfFrame');

 if (iframe.requestFullscreen) {
   iframe.requestFullscreen();
 } else if (iframe.webkitRequestFullscreen) {
   iframe.webkitRequestFullscreen(); // Safari
 } else if (iframe.msRequestFullscreen) {
   iframe.msRequestFullscreen(); // IE11
 }
}

</script>

</body>
</html>
<?php
include "footer.php";
?>
