<?php
session_start();
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);

include "../user/db.php";

/* ---------- AUTH ---------- */
if(!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin'){
    header("Location: ../login.php");
    exit;
}

/* ---------- UPLOAD CONFIG ---------- */
$UPLOAD_MODULES = "../uploads/modules/";
$UPLOAD_VIDEOS  = "../uploads/module_videos/";
$UPLOAD_COVERS  = "../uploads/covers/";
$UPLOAD_OUTLINES = "../uploads/course_outlines/";

foreach([$UPLOAD_MODULES,$UPLOAD_VIDEOS,$UPLOAD_COVERS,$UPLOAD_OUTLINES] as $dir){
    if(!is_dir($dir)) mkdir($dir,0755,true);
}

$message = '';

if(isset($_POST['save_course'])){
    $title = trim($_POST['course_title']);
    $tutor = trim($_POST['tutor']);
    $price = (float)$_POST['price'];
    $description = trim($_POST['course_description']);

    if(!$title || !$tutor){
        $message = "Course title and tutor are required.";
    } else {

        $coverPath = null;
        if(!empty($_FILES['course_cover']['name'])){
            $ext = strtolower(pathinfo($_FILES['course_cover']['name'],PATHINFO_EXTENSION));
            if(in_array($ext,['jpg','jpeg','png','webp'])){
                $coverPath = $UPLOAD_COVERS."cover_".uniqid().".".$ext;
                move_uploaded_file($_FILES['course_cover']['tmp_name'],$coverPath);
            }
        }

        $outlinePdf = null;
        if(!empty($_FILES['course_outline_pdf']['name'])){
            if(strtolower(pathinfo($_FILES['course_outline_pdf']['name'],PATHINFO_EXTENSION)) === 'pdf'){
                $outlinePdf = $UPLOAD_OUTLINES."outline_".uniqid().".pdf";
                move_uploaded_file($_FILES['course_outline_pdf']['tmp_name'],$outlinePdf);
            }
        }

        $stmt = $conn->prepare("
            INSERT INTO courses 
            (title,description,course_outline_pdf,tutor,price,cover,created_at)
            VALUES (?,?,?,?,?,?,NOW())
        ");
        $stmt->bind_param("ssssds",$title,$description,$outlinePdf,$tutor,$price,$coverPath);
        $stmt->execute();
        $course_id = $stmt->insert_id;
        $stmt->close();

        foreach($_POST['module_title'] as $i=>$moduleTitle){
            if(trim($moduleTitle)=='') continue;

            $moduleDesc = $_POST['module_description'][$i] ?? '';
            $pdfFile = null;
            $videoFile = null;

            if(!empty($_FILES['module_pdf']['name'][$i])){
                if(strtolower(pathinfo($_FILES['module_pdf']['name'][$i],PATHINFO_EXTENSION)) === 'pdf'){
                    $pdfFile = $UPLOAD_MODULES."mod_".uniqid().".pdf";
                    move_uploaded_file($_FILES['module_pdf']['tmp_name'][$i],$pdfFile);
                }
            }

            if(!empty($_FILES['module_video']['name'][$i])){
                $ext = strtolower(pathinfo($_FILES['module_video']['name'][$i],PATHINFO_EXTENSION));
                if(in_array($ext,['mp4','webm','ogg'])){
                    $videoFile = $UPLOAD_VIDEOS."vid_".uniqid().".".$ext;
                    move_uploaded_file($_FILES['module_video']['tmp_name'][$i],$videoFile);
                }
            }

            $order = $i + 1;
            $stmt = $conn->prepare("
                INSERT INTO modules 
                (course_id,title,description,pdf_file,video_file,module_order)
                VALUES (?,?,?,?,?,?)
            ");
            $stmt->bind_param("issssi",$course_id,$moduleTitle,$moduleDesc,$pdfFile,$videoFile,$order);
            $stmt->execute();
            $module_id = $stmt->insert_id;
            $stmt->close();

            if(!empty($_POST['quiz_title'][$i])){
                foreach($_POST['quiz_title'][$i] as $q=>$quizTitle){
                    if(trim($quizTitle)=='') continue;

                    $instructions = $_POST['quiz_instructions'][$i][$q] ?? '';
                    $duration = (int)($_POST['quiz_duration'][$i][$q] ?? 30);

                    $stmt = $conn->prepare("
                        INSERT INTO quizzes 
                        (module_id,title,instructions,duration_minutes,pass_mark,created_at)
                        VALUES (?,?,?,?,80,NOW())
                    ");
                    $stmt->bind_param("issi",$module_id,$quizTitle,$instructions,$duration);
                    $stmt->execute();
                    $quiz_id = $stmt->insert_id;
                    $stmt->close();

                    if(!empty($_POST['question_text'][$i][$q])){
                        foreach($_POST['question_text'][$i][$q] as $k=>$qText){
                            if(trim($qText)=='') continue;

                            $stmt = $conn->prepare("
                                INSERT INTO quiz_questions (quiz_id,question,created_at)
                                VALUES (?,?,NOW())
                            ");
                            $stmt->bind_param("is",$quiz_id,$qText);
                            $stmt->execute();
                            $question_id = $stmt->insert_id;
                            $stmt->close();

                            $correct = $_POST['correct_option'][$i][$q][$k];
                            foreach($_POST['options'][$i][$q][$k] as $o=>$opt){
                                $is_correct = ($o == ord($correct)-65) ? 1 : 0;
                                $stmt = $conn->prepare("
                                    INSERT INTO quiz_options 
                                    (question_id,option_text,is_correct,created_at)
                                    VALUES (?,?,?,NOW())
                                ");
                                $stmt->bind_param("isi",$question_id,$opt,$is_correct);
                                $stmt->execute();
                                $stmt->close();
                            }
                        }
                    }
                }
            }
        }

        $message = "Course saved successfully!";
    }
}
?>

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Add Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.tailwindcss.com"></script>
</head>

<body class="bg-slate-900 text-white p-6 max-w-6xl mx-auto">

<div id="loader" class="hidden fixed inset-0 bg-black/70 flex items-center justify-center z-50">
  <div class="animate-spin rounded-full h-16 w-16 border-4 border-yellow-400 border-t-transparent"></div>
</div>

<h1 class="text-2xl font-bold mb-4">Add Course</h1>

<?php if($message): ?>
<div class="bg-green-500 text-black p-2 rounded mb-4"><?=$message?></div>
<?php endif; ?>

<form method="post" enctype="multipart/form-data" onsubmit="showLoader()">

<section class="bg-slate-800 p-4 rounded mb-6">
<h2 class="font-semibold mb-3">Course Information</h2>
<input name="course_title" placeholder="Course Title" class="w-full p-2 mb-2 text-black" required>
<input name="tutor" placeholder="Tutor Name" class="w-full p-2 mb-2 text-black" required>
<input name="price" type="number" step="0.01" placeholder="Course Price" class="w-full p-2 mb-2 text-black">
<textarea name="course_description" placeholder="Short course description" class="w-full p-2 mb-2 text-black"></textarea>
<p class="text-sm text-slate-400 mb-1">Course Outline (PDF)</p>
<input type="file" name="course_outline_pdf" accept=".pdf" class="mb-2">
<p class="text-sm text-slate-400 mb-1">Course Cover Image</p>
<input type="file" name="course_cover" accept="image/*">
</section>

<section class="bg-slate-800 p-4 rounded mb-6">
<h2 class="font-semibold mb-3"> Course Modules</h2>
<div id="modules-container"></div>
<button type="button" onclick="addModule()" class="bg-yellow-400 text-black px-4 py-2 rounded">
➕ Add Module
</button>
</section>

<button name="save_course" class="bg-yellow-400 text-black px-6 py-2 rounded font-semibold">
Save Course
</button>

</form>

<script>
let moduleCount = 0;

function addModule(){
  const c = document.getElementById('modules-container');
  const d = document.createElement('div');
  d.className = 'border border-slate-600 p-4 rounded mb-4 bg-slate-900';
  d.innerHTML = `
<h3 class="font-semibold mb-2"> Module Details</h3>
<input name="module_title[]" placeholder="Module Title" class="w-full p-2 mb-2 text-black">
<textarea name="module_description[]" placeholder="What this module covers" class="w-full p-2 mb-2 text-black"></textarea>
<p class="text-sm text-slate-400 mb-1">Module PDF (optional)</p>
<input type="file" name="module_pdf[]" accept=".pdf" class="mb-2">
<p class="text-sm text-slate-400 mb-1">Module Video (optional)</p>
<input type="file" name="module_video[]" accept="video/*" class="mb-2">
<div class="quizzes-container mt-3"></div>
<button type="button" onclick="addQuiz(${moduleCount})" class="bg-blue-500 px-3 py-1 rounded mt-2">
➕ Add Quiz
</button>`;
  c.appendChild(d);
  moduleCount++;
}

function addQuiz(m){
  const c = document.querySelectorAll('#modules-container > div')[m].querySelector('.quizzes-container');
  const q = c.children.length;
  const d = document.createElement('div');
  d.className = 'border border-yellow-500 p-3 rounded mt-3 bg-slate-800';
  d.innerHTML = `
<h4 class="font-semibold mb-2"> Quiz Details</h4>
<input name="quiz_title[${m}][]" placeholder="Quiz Title" class="w-full p-2 mb-2 text-black">
<textarea name="quiz_instructions[${m}][]" placeholder="Quiz Instructions" class="w-full p-2 mb-2 text-black"></textarea>
<input name="quiz_duration[${m}][]" type="number" placeholder="Duration (minutes)" class="w-full p-2 mb-2 text-black">
<div class="questions-container"></div>
<button type="button" onclick="addQuestion(${m},${q})" class="bg-green-500 px-2 py-1 rounded">
➕ Add Question
</button>`;
  c.appendChild(d);
}

function addQuestion(m,q){
  const c = document.querySelectorAll('#modules-container > div')[m]
    .querySelectorAll('.border-yellow-500')[q]
    .querySelector('.questions-container');

  const i = c.children.length;
  const d = document.createElement('div');
  d.className = 'border border-emerald-500 p-3 rounded mb-2 bg-slate-900';
  d.innerHTML = `
<h5 class="font-semibold mb-1">❓ Question</h5>
<input name="question_text[${m}][${q}][]" placeholder="Question text" class="w-full p-2 mb-2 text-black">
<input name="options[${m}][${q}][${i}][]" placeholder="Option A" class="w-full p-2 mb-1 text-black">
<input name="options[${m}][${q}][${i}][]" placeholder="Option B" class="w-full p-2 mb-1 text-black">
<input name="options[${m}][${q}][${i}][]" placeholder="Option C" class="w-full p-2 mb-1 text-black">
<input name="options[${m}][${q}][${i}][]" placeholder="Option D" class="w-full p-2 mb-1 text-black">
<select name="correct_option[${m}][${q}][${i}]" class="w-full p-2 text-black">
<option>A</option><option>B</option><option>C</option><option>D</option>
</select>`;
  c.appendChild(d);
}

function showLoader(){
  document.getElementById('loader').classList.remove('hidden');
}
</script>

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