<?php
// admin/courses/quiz_builder.php — schema-aware MCQ builder + CSV import/export + EDIT (incl. max_questions)

if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once __DIR__.'/../../includes/auth.php';
require_role(['super_admin','branch_admin']);
require_once __DIR__.'/../../includes/db.php';
require_once __DIR__.'/../../includes/helpers.php';

$mysqli = $mysqli ?? ($conn ?? null);
if (!$mysqli instanceof mysqli) { http_response_code(500); exit('DB connection missing'); }

/* ------- local helpers (no redeclare collisions) ------- */
if (!function_exists('esc')) {
  function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
}
if (!function_exists('table_exists_local')) {
  function table_exists_local($table){
    global $mysqli;
    $stmt=$mysqli->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? LIMIT 1");
    $stmt->bind_param('s',$table);
    $stmt->execute();
    $ok=(bool)$stmt->get_result()->fetch_row();
    $stmt->close();
    return $ok;
  }
}
if (!function_exists('column_exists_local')) {
  function column_exists_local($table,$column){
    global $mysqli;
    $stmt=$mysqli->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ? LIMIT 1");
    $stmt->bind_param('ss',$table,$column);
    $stmt->execute();
    $ok=(bool)$stmt->get_result()->fetch_row();
    $stmt->close();
    return $ok;
  }
}
function norm($s){ return strtolower(preg_replace('/[^a-z0-9]+/','_',trim((string)$s))); }

/* ------- inputs ------- */
$course_id = (int)($_GET['course_id'] ?? $_POST['course_id'] ?? 0);
$module_id = (int)($_GET['module_id'] ?? $_POST['module_id'] ?? 0);
$quiz_id   = (int)($_GET['quiz_id']   ?? $_POST['quiz_id']   ?? 0);
if ($course_id<=0 || $module_id<=0){ http_response_code(400); exit('Missing course_id/module_id'); }

/* ------- detect module table / cols ------- */
$HAS_LMS_MODULES    = table_exists_local('lms_modules');
$HAS_COURSE_MODULES = table_exists_local('course_modules');
$MOD_TBL = $HAS_LMS_MODULES ? 'lms_modules' : ($HAS_COURSE_MODULES ? 'course_modules' : null);
if (!$MOD_TBL) { http_response_code(500); exit('No modules table found (lms_modules or course_modules).'); }

$TITLE_COL = $HAS_LMS_MODULES
  ? (column_exists_local('lms_modules','title') ? 'title' : (column_exists_local('lms_modules','name') ? 'name' : 'id'))
  : (column_exists_local('course_modules','title') ? 'title' : (column_exists_local('course_modules','name') ? 'name' : 'id'));
$ORDER_COL = $HAS_LMS_MODULES
  ? (column_exists_local('lms_modules','sort_order') ? 'sort_order' : 'id')
  : (column_exists_local('course_modules','sort_order') ? 'sort_order' : 'id');

/* ------- tiny migrations so the page works (incl. max_questions) ------- */
function ensure_quiz_schema(){
  global $mysqli;

  // lms_quizzes
  $mysqli->query("
    CREATE TABLE IF NOT EXISTS `lms_quizzes` (
      `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
      `course_id` INT UNSIGNED NOT NULL,
      `module_id` INT UNSIGNED NOT NULL,
      `title` VARCHAR(255) NOT NULL,
      `description` TEXT NULL,
      `time_limit_sec` INT NULL,
      `max_attempts` INT NULL,
      `pass_score` INT NULL,
      `max_questions` INT NULL,
      `randomized` TINYINT(1) NOT NULL DEFAULT 0,
      `active` TINYINT(1) NOT NULL DEFAULT 1,
      `created_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
      `updated_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      KEY `idx_course_module` (`course_id`,`module_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  ");
  // Ensure max_questions exists if table is old
  $res = $mysqli->query("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'lms_quizzes' AND COLUMN_NAME = 'max_questions' LIMIT 1");
  if ($res && $res->num_rows===0){
    $mysqli->query("ALTER TABLE lms_quizzes ADD COLUMN max_questions INT NULL AFTER pass_score");
  }
  if ($res) $res->close();

  // lms_quiz_questions
  $mysqli->query("
    CREATE TABLE IF NOT EXISTS `lms_quiz_questions` (
      `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
      `quiz_id` INT UNSIGNED NOT NULL,
      `question_text` TEXT NOT NULL,
      `points` INT NOT NULL DEFAULT 1,
      `sort_order` INT NOT NULL DEFAULT 0,
      PRIMARY KEY (`id`),
      KEY `idx_quiz` (`quiz_id`,`sort_order`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  ");

  // lms_quiz_options
  $mysqli->query("
    CREATE TABLE IF NOT EXISTS `lms_quiz_options` (
      `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
      `question_id` INT UNSIGNED NOT NULL,
      `option_text` TEXT NOT NULL,
      `is_correct` TINYINT(1) NOT NULL DEFAULT 0,
      `sort_order` INT NOT NULL DEFAULT 0,
      PRIMARY KEY (`id`),
      KEY `idx_question` (`question_id`,`sort_order`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  ");

  // lms_content with quiz_id
  $mysqli->query("
    CREATE TABLE IF NOT EXISTS `lms_content` (
      `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
      `module_id` INT UNSIGNED NOT NULL,
      `title` VARCHAR(255) NOT NULL,
      `content_type` VARCHAR(50) NOT NULL DEFAULT 'link',
      `description` TEXT NULL,
      `available_from` DATETIME NULL,
      `available_to` DATETIME NULL,
      `file_path` VARCHAR(255) NULL,
      `url` VARCHAR(500) NULL,
      `quiz_id` INT NULL,
      `duration_seconds` INT NULL,
      `sort_order` INT NOT NULL DEFAULT 0,
      `active` TINYINT(1) NOT NULL DEFAULT 1,
      `require_paid` TINYINT(1) NOT NULL DEFAULT 0,
      `created_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
      `updated_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      KEY `idx_module_order` (`module_id`,`sort_order`),
      KEY `idx_quiz` (`quiz_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  ");
  $res2 = $mysqli->query("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'lms_content' AND COLUMN_NAME = 'quiz_id' LIMIT 1");
  if ($res2 && $res2->num_rows===0){
    $mysqli->query("ALTER TABLE lms_content ADD COLUMN `quiz_id` INT NULL AFTER `url`, ADD KEY `idx_quiz` (`quiz_id`)");
  }
  if ($res2) $res2->close();
}
ensure_quiz_schema();

/* ------- CSV Template download ------- */
if (isset($_GET['download']) && $_GET['download'] === 'csv_template') {
  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename="quiz_template.csv"');
  $out = fopen('php://output','w');
  fputcsv($out, ['question','points','option_a','option_b','option_c','option_d','correct']);
  fputcsv($out, ['What is 2 + 2?', '1', '3', '4', '5', '22', 'B']);
  fputcsv($out, ['Capital of Sri Lanka?', '1', 'Colombo', 'Kandy', 'Sri Jayawardenepura Kotte', 'Galle', 'C']);
  fclose($out);
  exit;
}

/* ------- CSV EXPORT ------- */
if (isset($_GET['download']) && $_GET['download'] === 'quiz_csv') {
  $qid = (int)($_GET['quiz_id'] ?? 0);
  if ($qid <= 0) { http_response_code(400); exit('quiz_id missing'); }

  $qs = $mysqli->prepare("SELECT id, question_text, points FROM lms_quiz_questions WHERE quiz_id=? ORDER BY sort_order,id");
  $qs->bind_param('i',$qid);
  $qs->execute();
  $resQ = $qs->get_result();
  $questions = [];
  $maxOpts = 0;
  while($r = $resQ->fetch_assoc()){ $questions[] = $r; }
  $qs->close();

  $optsByQ = [];
  if ($questions){
    $ids = implode(',', array_map('intval', array_column($questions,'id')));
    $r = $mysqli->query("SELECT question_id, option_text, is_correct, sort_order FROM lms_quiz_options WHERE question_id IN ($ids) ORDER BY question_id, sort_order, id");
    while($o = $r->fetch_assoc()){
      $optsByQ[(int)$o['question_id']][] = $o;
    }
    foreach($questions as $q){
      $cnt = isset($optsByQ[(int)$q['id']]) ? count($optsByQ[(int)$q['id']]) : 0;
      if ($cnt > $maxOpts) $maxOpts = $cnt;
    }
  }
  if ($maxOpts < 2) $maxOpts = 2;

  $letters = range('A','Z');
  $hdr = ['question','points'];
  for ($i=0; $i<$maxOpts; $i++){ $hdr[] = 'option_'.strtolower($letters[$i]); }
  $hdr[] = 'correct';

  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename="quiz_'.$qid.'.csv"');
  $out = fopen('php://output','w');
  fputcsv($out, $hdr);

  foreach($questions as $q){
    $row = [];
    $row[] = $q['question_text'];
    $row[] = (int)$q['points'];
    $opts = $optsByQ[(int)$q['id']] ?? [];
    for ($i=0; $i<$maxOpts; $i++){
      $row[] = isset($opts[$i]['option_text']) ? $opts[$i]['option_text'] : '';
    }
    $correctPos = 1;
    for ($i=0; $i<count($opts); $i++){
      if (!empty($opts[$i]['is_correct'])){ $correctPos = $i+1; break; }
    }
    $row[] = $letters[$correctPos-1];
    fputcsv($out, $row);
  }
  fclose($out);
  exit;
}

/* ------- ensure module exists & belongs to course ------- */
$mod_row = null;
$chk = $mysqli->prepare("SELECT id, {$TITLE_COL} AS title FROM `$MOD_TBL` WHERE id=? AND course_id=?");
$chk->bind_param('ii',$module_id,$course_id);
$chk->execute();
$mod_row = $chk->get_result()->fetch_assoc();
$chk->close();

if (!$mod_row) {
  $mods = [];
  $ms = $mysqli->prepare("SELECT id, {$TITLE_COL} AS title FROM `$MOD_TBL` WHERE course_id=? ORDER BY {$ORDER_COL}, id");
  $ms->bind_param('i',$course_id);
  $ms->execute();
  $res = $ms->get_result();
  while($row=$res->fetch_assoc()) $mods[] = $row;
  $ms->close();

  echo "<div style='padding:16px;font-family:system-ui'>";
  echo "<h3 style='margin:0 0 8px'>Module not found</h3>";
  echo "<p style='margin:0 0 12px'>The <b>module_id ".(int)$module_id."</b> does not exist for <b>course_id ".(int)$course_id."</b>.</p>";
  if ($mods){
    echo "<p style='margin:0 0 6px'>Pick a valid module for this course:</p><ul>";
    foreach($mods as $m){
      $url = "quiz_builder.php?course_id=".$course_id."&module_id=".$m['id'];
      echo "<li><a href='".esc($url)."'>".esc($m['title'])." (id ".$m['id'].")</a></li>";
    }
    echo "</ul>";
    $backUrl = "../courses/content.php?course_id=".$course_id."&module_id=".$mods[0]['id'];
  } else {
    echo "<p>No modules exist for this course yet. Create a module first.</p>";
    $backUrl = "../courses/modules.php?course_id=".$course_id;
  }
  echo "<p style='margin-top:12px'><a href='".esc($backUrl)."'>Back</a></p>";
  echo "</div>";
  exit;
}

$msg=null; $err=null; $noticeHtml='';
$action = $_POST['action'] ?? '';

/* ----------------- actions ----------------- */

if ($action==='create_quiz') {
  $title = trim($_POST['title'] ?? '');
  $desc  = trim($_POST['description'] ?? '');
  $rand  = isset($_POST['randomized']) ? 1 : 0;
  $time  = ($_POST['time_limit_sec']===''? null : max(0,(int)$_POST['time_limit_sec']));
  $maxat = ($_POST['max_attempts']===''? null : max(1,(int)$_POST['max_attempts']));
  $pass  = ($_POST['pass_score']===''? null : max(0,(int)$_POST['pass_score']));
  $maxq  = ($_POST['max_questions']===''? null : max(1,(int)$_POST['max_questions']));

  if ($title!==''){
    $st=$mysqli->prepare("INSERT INTO lms_quizzes
      (course_id,module_id,title,description,time_limit_sec,max_attempts,pass_score,max_questions,randomized,active)
      VALUES (?,?,?,?,?,?,?,?,?,1)");
    $st->bind_param('iissiiiii', $course_id,$module_id,$title,$desc,$time,$maxat,$pass,$maxq,$rand);
    if ($st->execute()) { $quiz_id=$st->insert_id; $msg='Quiz created.'; }
    else { $err='DB error creating quiz: '.$mysqli->error; }
    $st->close();
  } else { $err='Title required'; }
}

if ($action==='update_quiz' && $quiz_id>0) {
  $title = trim($_POST['title'] ?? '');
  $desc  = trim($_POST['description'] ?? '');
  $rand  = isset($_POST['randomized']) ? 1 : 0;
  $time  = ($_POST['time_limit_sec']===''? null : max(0,(int)$_POST['time_limit_sec']));
  $maxat = ($_POST['max_attempts']===''? null : max(1,(int)$_POST['max_attempts']));
  $pass  = ($_POST['pass_score']===''? null : max(0,(int)$_POST['pass_score']));
  $maxq  = ($_POST['max_questions']===''? null : max(1,(int)$_POST['max_questions']));

  if ($title===''){ $err='Title required'; }
  else {
    $st=$mysqli->prepare("UPDATE lms_quizzes
      SET title=?, description=?, time_limit_sec=?, max_attempts=?, pass_score=?, max_questions=?, randomized=?, updated_at=NOW()
      WHERE id=? AND course_id=? AND module_id=?");
    $st->bind_param('ssiiiiiiii', $title,$desc,$time,$maxat,$pass,$maxq,$rand,$quiz_id,$course_id,$module_id);
    if ($st->execute()) $msg='Quiz updated.'; else $err='DB error: '.$mysqli->error;
    $st->close();
  }
}

if ($action==='add_question' && $quiz_id>0) {
  $qt = trim($_POST['question_text'] ?? '');
  $pts= max(1,(int)($_POST['points'] ?? 1));
  if ($qt!==''){
    $ord=1; $q=$mysqli->prepare("SELECT COALESCE(MAX(sort_order),0)+1 FROM lms_quiz_questions WHERE quiz_id=?");
    $q->bind_param('i',$quiz_id); $q->execute(); $q->bind_result($ord); $q->fetch(); $q->close();

    $st=$mysqli->prepare("INSERT INTO lms_quiz_questions(quiz_id,question_text,points,sort_order) VALUES (?,?,?,?)");
    $st->bind_param('isii',$quiz_id,$qt,$pts,$ord);
    if ($st->execute()) $msg='Question added.'; else $err='DB error: '.$mysqli->error;
    $st->close();
  } else { $err='Question text required'; }
}

if ($action==='add_option') {
  $qid=(int)($_POST['question_id'] ?? 0);
  $txt=trim($_POST['option_text'] ?? '');
  $ok =isset($_POST['is_correct']) ? 1 : 0;
  if ($qid>0 && $txt!==''){
    $ord=1; $q=$mysqli->prepare("SELECT COALESCE(MAX(sort_order),0)+1 FROM lms_quiz_options WHERE question_id=?");
    $q->bind_param('i',$qid); $q->execute(); $q->bind_result($ord); $q->fetch(); $q->close();

    if ($ok){ $mysqli->query("UPDATE lms_quiz_options SET is_correct=0 WHERE question_id=".$qid); }
    $st=$mysqli->prepare("INSERT INTO lms_quiz_options(question_id,option_text,is_correct,sort_order) VALUES (?,?,?,?)");
    $st->bind_param('isii',$qid,$txt,$ok,$ord);
    if ($st->execute()) $msg='Option added.'; else $err='DB error: '.$mysqli->error;
    $st->close();
  } else { $err='Option text required'; }
}

if ($action==='publish_to_content' && $quiz_id>0) {
  $title=''; $st=$mysqli->prepare("SELECT title FROM lms_quizzes WHERE id=? AND course_id=? AND module_id=?");
  $st->bind_param('iii',$quiz_id,$course_id,$module_id); $st->execute(); $st->bind_result($title); $st->fetch(); $st->close();

  if ($title!==''){
    $HAS_CONTENT_QUIZID = column_exists_local('lms_content','quiz_id');
    $url = "/student/quiz.php?quiz_id=".$quiz_id;

    if ($HAS_CONTENT_QUIZID) {
      $chk=$mysqli->prepare("SELECT id FROM lms_content WHERE module_id=? AND quiz_id=?");
      $chk->bind_param('ii',$module_id,$quiz_id); $chk->execute();
    } else {
      $chk=$mysqli->prepare("SELECT id FROM lms_content WHERE module_id=? AND url=?");
      $chk->bind_param('is',$module_id,$url); $chk->execute();
    }
    $r=$chk->get_result()->fetch_assoc(); $chk->close();

    if ($r){
      $u=$mysqli->prepare("UPDATE lms_content SET title=?, content_type='quiz', url=?, active=1 WHERE id=?");
      $u->bind_param('ssi',$title,$url,$r['id']);
      if ($u->execute()) $msg='Updated module content.'; else $err='DB error: '.$mysqli->error;
      $u->close();
    } else {
      $ord=1; $q=$mysqli->prepare("SELECT COALESCE(MAX(sort_order),0)+1 FROM lms_content WHERE module_id=?");
      $q->bind_param('i',$module_id); $q->execute(); $q->bind_result($ord); $q->fetch(); $q->close();

      if ($HAS_CONTENT_QUIZID) {
        $ins=$mysqli->prepare("INSERT INTO lms_content
          (module_id,title,content_type,description,url,quiz_id,sort_order,active,require_paid)
          VALUES (?,?,?,?,?,?,?,1,0)");
        $desc=''; $ct='quiz';
        $ins->bind_param('issssii', $module_id,$title,$ct,$desc,$url,$quiz_id,$ord);
      } else {
        $ins=$mysqli->prepare("INSERT INTO lms_content
          (module_id,title,content_type,description,url,sort_order,active,require_paid)
          VALUES (?,?,?,?,?,?,1,0)");
        $desc=''; $ct='quiz';
        $ins->bind_param('issssi', $module_id,$title,$ct,$desc,$url,$ord);
      }
      if ($ins->execute()) $msg='Published to module content.'; else $err='DB error inserting content: '.$mysqli->error;
      $ins->close();
    }
  } else { $err='Quiz not found for this course/module'; }
}

/* ----------------- CSV IMPORT (bulk) ----------------- */
if ($action==='upload_csv' && $quiz_id>0) {
  $mode = ($_POST['import_mode'] ?? 'append'); // append | replace
  $maxSize = 5 * 1024 * 1024; // 5MB
  if (!isset($_FILES['csv_file']) || !is_uploaded_file($_FILES['csv_file']['tmp_name'])) {
    $err = 'Please choose a CSV file.'; 
  } elseif ($_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
    $err = 'Upload error code: '.$_FILES['csv_file']['error'];
  } elseif ($_FILES['csv_file']['size'] > $maxSize) {
    $err = 'File too large. Max 5MB.';
  } else {
    $path = $_FILES['csv_file']['tmp_name'];
    $fh = fopen($path, 'r');
    if (!$fh) { $err='Unable to open uploaded file.'; }
    else {
      $header = fgetcsv($fh);
      if ($header === false) { $err='Empty CSV file.'; }
      else {
        $hn = array_map('norm', $header);
        $qIdx = array_search('question', $hn);
        if ($qIdx===false) foreach (['question_text','q','text','prompt'] as $alt){ if (($qIdx=array_search($alt,$hn))!==false) break; }
        if ($qIdx===false) { $err='Missing "question" column in header.'; }
        else {
          $ptsIdx = false; foreach (['points','score','marks','weight'] as $p) { $tmp=array_search($p,$hn); if ($tmp!==false){ $ptsIdx=$tmp; break; } }
          $correctIdx = false; foreach (['correct','answer','ans','key','correct_option','correct_answer'] as $c){ $tmp=array_search($c,$hn); if($tmp!==false){ $correctIdx=$tmp; break; } }

          $optCols = [];
          for ($i=0; $i<count($hn); $i++) {
            if ($i===$qIdx || $i===$ptsIdx || $i===$correctIdx) continue;
            if (trim((string)$header[$i])==='') continue;
            $optCols[] = $i;
          }
          if (count($optCols) < 2) {
            $err = 'Need at least 2 option columns (e.g., option_a, option_b, ...).';
          } else {
            if ($mode === 'replace') {
              $del1 = $mysqli->prepare("DELETE FROM lms_quiz_options WHERE question_id IN (SELECT id FROM lms_quiz_questions WHERE quiz_id=?)");
              $del1->bind_param('i',$quiz_id); $del1->execute(); $del1->close();
              $del2 = $mysqli->prepare("DELETE FROM lms_quiz_questions WHERE quiz_id=?");
              $del2->bind_param('i',$quiz_id); $del2->execute(); $del2->close();
            }

            $startOrd = 1;
            $q=$mysqli->prepare("SELECT COALESCE(MAX(sort_order),0)+1 FROM lms_quiz_questions WHERE quiz_id=?");
            $q->bind_param('i',$quiz_id); $q->execute(); $q->bind_result($startOrd); $q->fetch(); $q->close();

            $rowNum=1; $added=0; $skipped=0; $notes=[];
            while(($row = fgetcsv($fh)) !== false){
              $rowNum++;
              for ($i=0;$i<count($row);$i++){ if(!isset($row[$i])) $row[$i]=''; }
              $question = trim((string)($row[$qIdx] ?? ''));
              if ($question===''){ $skipped++; $notes[]="Row $rowNum: empty question → skipped."; continue; }

              $points = 1;
              if ($ptsIdx !== false) {
                $pv = trim((string)($row[$ptsIdx] ?? ''));
                if ($pv !== '' && is_numeric($pv)) $points = max(1,(int)$pv);
              }

              $opts = [];
              foreach ($optCols as $cidx){
                $ov = trim((string)($row[$cidx] ?? ''));
                if ($ov!=='') $opts[] = $ov;
              }
              if (count($opts) < 2){ $skipped++; $notes[]="Row $rowNum: needs ≥2 options → skipped."; continue; }

              $correctIndex = 1;
              if ($correctIdx !== false) {
                $cv = trim((string)($row[$correctIdx] ?? ''));
                if ($cv !== '') {
                  $cvU = strtoupper($cv);
                  $letters = ['A'=>1,'B'=>2,'C'=>3,'D'=>4,'E'=>5,'F'=>6,'G'=>7,'H'=>8,'I'=>9,'J'=>10];
                  if (isset($letters[$cvU])) { $correctIndex = min($letters[$cvU], count($opts)); }
                  elseif (ctype_digit($cvU)) { $n = (int)$cvU; if ($n>=1 && $n<=count($opts)) $correctIndex = $n; }
                  else { foreach ($opts as $k=>$optTxt){ if (strcasecmp($optTxt, $cv)===0){ $correctIndex = $k+1; break; } } }
                }
              }

              $st=$mysqli->prepare("INSERT INTO lms_quiz_questions(quiz_id,question_text,points,sort_order) VALUES (?,?,?,?)");
              $st->bind_param('isii', $quiz_id,$question,$points,$startOrd);
              if (!$st->execute()){ $skipped++; $notes[]="Row $rowNum: DB error on question."; $st->close(); continue; }
              $qid2 = $st->insert_id; $st->close();

              $opOrd=1;
              for ($i=0;$i<count($opts);$i++){
                $isC = (($i+1) === $correctIndex) ? 1 : 0;
                if ($isC){ $mysqli->query("UPDATE lms_quiz_options SET is_correct=0 WHERE question_id=".$qid2); }
                $oi=$mysqli->prepare("INSERT INTO lms_quiz_options(question_id,option_text,is_correct,sort_order) VALUES (?,?,?,?)");
                $oi->bind_param('isii',$qid2,$opts[$i],$isC,$opOrd);
                $oi->execute(); $oi->close();
                $opOrd++;
              }

              $added++; $startOrd++;
            }
            fclose($fh);

            $msg = "CSV import finished: $added added, $skipped skipped.";
            if ($notes){
              $noteList = '<ul class="mb-0">';
              foreach($notes as $n){ $noteList .= '<li>'.esc($n).'</li>'; }
              $noteList .= '</ul>';
              $noticeHtml = '<div class="alert alert-info">'.$noteList.'</div>';
            }
          }
        }
      }
      if (is_resource($fh)) fclose($fh);
    }
  }
}

/* ----------------- read ----------------- */

$QUIZ=null; $QUEST=[]; $OPTS=[];
if ($quiz_id>0){
  $st=$mysqli->prepare("SELECT * FROM lms_quizzes WHERE id=? AND course_id=? AND module_id=?");
  $st->bind_param('iii',$quiz_id,$course_id,$module_id); $st->execute();
  $QUIZ=$st->get_result()->fetch_assoc(); $st->close();

  if ($QUIZ){
    $rs=$mysqli->prepare("SELECT * FROM lms_quiz_questions WHERE quiz_id=? ORDER BY sort_order,id");
    $rs->bind_param('i',$quiz_id); $rs->execute(); $res=$rs->get_result();
    while($r=$res->fetch_assoc()) $QUEST[]=$r; $rs->close();

    if ($QUEST){
      $ids=implode(',',array_map('intval',array_column($QUEST,'id')));
      if ($ids!==''){
        $qq=$mysqli->query("SELECT * FROM lms_quiz_options WHERE question_id IN ($ids) ORDER BY question_id, sort_order, id");
        while($o=$qq->fetch_assoc()) $OPTS[(int)$o['question_id']][]=$o;
      }
    }
  }
}

/* ----------------- layout ----------------- */
$__layoutOpened=false;
foreach(['../../includes/admin_layout_top.php','../../includes/layout_top.php','../../includes/admin_header.php','../../includes/header_admin.php'] as $f){
  $p=__DIR__.'/'.$f; if(is_file($p)){ require_once $p; $__layoutOpened=true; break; }
}
if(!$__layoutOpened) echo '<div class="container p-3">';

?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h5 m-0">Quiz Builder</h1>
  <div>
    <a class="btn btn-outline-secondary btn-sm" href="../courses/content.php?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>">← Back to Content</a>
  </div>
</div>

<?php if($msg): ?><div class="alert alert-success py-2"><?= esc($msg) ?></div><?php endif; ?>
<?php if($err): ?><div class="alert alert-danger  py-2"><?= esc($err) ?></div><?php endif; ?>
<?= $noticeHtml ?>

<?php if(!$QUIZ && $quiz_id===0): ?>
  <div class="card mb-3">
    <div class="card-header">Create a new quiz for module “<?= esc($mod_row['title']) ?>”</div>
    <div class="card-body">
      <form method="post" class="row g-3">
        <input type="hidden" name="action" value="create_quiz">
        <input type="hidden" name="course_id" value="<?= (int)$course_id ?>">
        <input type="hidden" name="module_id" value="<?= (int)$module_id ?>">
        <div class="col-md-6">
          <label class="form-label">Title</label>
          <input class="form-control" name="title" required>
        </div>
        <div class="col-md-6">
          <label class="form-label">Time limit (sec)</label>
          <input class="form-control" name="time_limit_sec" type="number" min="0" placeholder="optional">
        </div>
        <div class="col-md-4">
          <label class="form-label">Max attempts</label>
          <input class="form-control" name="max_attempts" type="number" min="1" placeholder="optional">
        </div>
        <div class="col-md-4">
          <label class="form-label">Pass score</label>
          <input class="form-control" name="pass_score" type="number" min="0" placeholder="optional">
        </div>
        <div class="col-md-4">
          <label class="form-label">Max questions shown</label>
          <input class="form-control" name="max_questions" type="number" min="1" placeholder="optional">
        </div>
        <div class="col-12 d-flex align-items-center gap-3">
          <label class="form-check m-0">
            <input class="form-check-input" type="checkbox" name="randomized"> Randomize questions
          </label>
        </div>
        <div class="col-12">
          <label class="form-label">Description</label>
          <textarea class="form-control" name="description" rows="2"></textarea>
        </div>
        <div class="col-12">
          <button class="btn btn-primary">Create quiz</button>
        </div>
      </form>
    </div>
  </div>
<?php endif; ?>

<?php if($QUIZ): ?>
  <div class="card mb-3">
    <div class="card-header d-flex flex-wrap gap-2 justify-content-between align-items-center">
      <div><strong><?= esc($QUIZ['title']) ?></strong></div>
      <div class="d-flex gap-2">
        <a class="btn btn-outline-secondary btn-sm" href="?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>&quiz_id=<?= (int)$quiz_id ?>&download=csv_template">Download CSV Template</a>
        <a class="btn btn-outline-primary btn-sm" href="?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>&quiz_id=<?= (int)$quiz_id ?>&download=quiz_csv">Export CSV</a>
        <form method="post" class="d-inline">
          <input type="hidden" name="action" value="publish_to_content">
          <input type="hidden" name="course_id" value="<?= (int)$course_id ?>">
          <input type="hidden" name="module_id" value="<?= (int)$module_id ?>">
          <input type="hidden" name="quiz_id"   value="<?= (int)$quiz_id ?>">
          <button class="btn btn-success btn-sm">Publish to module content</button>
        </form>
      </div>
    </div>
    <div class="card-body">

      <!-- Edit quiz (NEW) -->
      <div class="border rounded p-3 mb-4">
        <h6 class="mb-2">Edit quiz settings</h6>
        <form method="post" class="row g-3">
          <input type="hidden" name="action" value="update_quiz">
          <input type="hidden" name="course_id" value="<?= (int)$course_id ?>">
          <input type="hidden" name="module_id" value="<?= (int)$module_id ?>">
          <input type="hidden" name="quiz_id"   value="<?= (int)$quiz_id ?>">

          <div class="col-md-6">
            <label class="form-label">Title</label>
            <input class="form-control" name="title" value="<?= esc($QUIZ['title'] ?? '') ?>" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Time limit (sec)</label>
            <input class="form-control" name="time_limit_sec" type="number" min="0" value="<?= esc($QUIZ['time_limit_sec'] ?? '') ?>">
          </div>

          <div class="col-md-4">
            <label class="form-label">Max attempts</label>
            <input class="form-control" name="max_attempts" type="number" min="1" value="<?= esc($QUIZ['max_attempts'] ?? '') ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label">Pass score</label>
            <input class="form-control" name="pass_score" type="number" min="0" value="<?= esc($QUIZ['pass_score'] ?? '') ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label">Max questions shown</label>
            <input class="form-control" name="max_questions" type="number" min="1" value="<?= esc($QUIZ['max_questions'] ?? '') ?>">
          </div>

          <div class="col-12 d-flex align-items-center gap-3">
            <label class="form-check m-0">
              <input class="form-check-input" type="checkbox" name="randomized" <?= !empty($QUIZ['randomized']) ? 'checked':'' ?>> Randomize questions
            </label>
          </div>

          <div class="col-12">
            <label class="form-label">Description</label>
            <textarea class="form-control" name="description" rows="2"><?= esc($QUIZ['description'] ?? '') ?></textarea>
          </div>

          <div class="col-12">
            <button class="btn btn-primary">Save changes</button>
          </div>
        </form>
      </div>

      <!-- Bulk CSV Import -->
      <div class="border rounded p-3 mb-4">
        <h6 class="mb-2">Bulk import questions (CSV)</h6>
        <p class="small text-muted mb-2">
          Required columns: <code>question</code>, at least two option columns (e.g. <code>option_a</code>, <code>option_b</code> …),
          optional <code>points</code>, and <code>correct</code> (A/B/C…, 1/2/3…, or exact option text).
        </p>
        <form method="post" enctype="multipart/form-data" class="row g-2 align-items-end">
          <input type="hidden" name="action" value="upload_csv">
          <input type="hidden" name="course_id" value="<?= (int)$course_id ?>">
          <input type="hidden" name="module_id" value="<?= (int)$module_id ?>">
          <input type="hidden" name="quiz_id"   value="<?= (int)$quiz_id ?>">
          <input type="hidden" name="MAX_FILE_SIZE" value="<?= 5*1024*1024 ?>">
          <div class="col-md-6">
            <label class="form-label">CSV file</label>
            <input class="form-control" type="file" name="csv_file" accept=".csv,text/csv" required>
          </div>
          <div class="col-md-3">
            <label class="form-label">Import mode</label>
            <select class="form-select" name="import_mode">
              <option value="append" selected>Append to existing</option>
              <option value="replace">Replace existing questions</option>
            </select>
          </div>
          <div class="col-md-3 d-grid">
            <button class="btn btn-primary">Upload & Import</button>
          </div>
        </form>
      </div>

      <!-- Manual add (single) -->
      <h6 class="mb-2">Add question</h6>
      <form method="post" class="row g-2 mb-3">
        <input type="hidden" name="action" value="add_question">
        <input type="hidden" name="course_id" value="<?= (int)$course_id ?>">
        <input type="hidden" name="module_id" value="<?= (int)$module_id ?>">
        <input type="hidden" name="quiz_id"   value="<?= (int)$quiz_id ?>">
        <div class="col-md-9">
          <input class="form-control" name="question_text" placeholder="Question text" required>
        </div>
        <div class="col-md-2">
          <input class="form-control" name="points" type="number" min="1" value="1" placeholder="Points">
        </div>
        <div class="col-md-1 d-grid">
          <button class="btn btn-primary">Add</button>
        </div>
      </form>

      <?php if(empty($QUEST)): ?>
        <div class="text-muted">No questions yet.</div>
      <?php else: foreach($QUEST as $q): ?>
        <div class="border rounded p-2 mb-2">
          <div class="fw-semibold mb-1">
            Q<?= (int)$q['sort_order'] ?>. <?= esc($q['question_text']) ?>
            <span class="text-muted">(<?= (int)$q['points'] ?> pt)</span>
          </div>
          <form method="post" class="row g-2">
            <input type="hidden" name="action" value="add_option">
            <input type="hidden" name="course_id" value="<?= (int)$course_id ?>">
            <input type="hidden" name="module_id" value="<?= (int)$module_id ?>">
            <input type="hidden" name="quiz_id"   value="<?= (int)$quiz_id ?>">
            <input type="hidden" name="question_id" value="<?= (int)$q['id'] ?>">
            <div class="col-md-9">
              <input class="form-control" name="option_text" placeholder="Add option..." required>
            </div>
            <div class="col-md-2 d-flex align-items-center">
              <label class="form-check m-0"><input class="form-check-input" type="checkbox" name="is_correct"> Correct</label>
            </div>
            <div class="col-md-1 d-grid">
              <button class="btn btn-outline-primary">Add</button>
            </div>
          </form>
          <?php if(!empty($OPTS[$q['id']])): ?>
            <ul class="mt-2 mb-0">
              <?php foreach($OPTS[$q['id']] as $op): ?>
                <li><?= esc($op['option_text']) ?> <?= $op['is_correct']? '<span class="badge bg-success">correct</span>':'' ?></li>
              <?php endforeach; ?>
            </ul>
          <?php endif; ?>
        </div>
      <?php endforeach; endif; ?>
    </div>
  </div>
<?php endif; ?>

<?php
$__layoutClosed=false;
foreach(['../../includes/admin_layout_bottom.php','../../includes/layout_bottom.php','../../includes/admin_footer.php','../../includes/footer_admin.php'] as $f){
  $p=__DIR__.'/'.$f; if(is_file($p)){ require_once $p; $__layoutClosed=true; break; }
}
if(!$__layoutClosed) echo '</div>';
