<?php
// admin/courses/quiz_builder.php
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';

function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

$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'); }

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

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']));
  if ($title!==''){
    $st=$mysqli->prepare("INSERT INTO lms_quizzes(course_id,module_id,title,description,time_limit_sec,max_attempts,pass_score,randomized,active)
                          VALUES (?,?,?,?,?,?,?,?,1)");
    $st->bind_param('iissiiis',$course_id,$module_id,$title,$desc,$time,$maxat,$pass,$rand);
    $st->execute(); $quiz_id=$st->insert_id; $st->close();
    $msg='Quiz created.';
  } else $err='Title required';
}

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); $st->execute(); $st->close();
    $msg='Question added.';
  } 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){ // make it single-correct: clear others
      $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); $st->execute(); $st->close();
    $msg='Option added.';
  } else $err='Option text required';
}

if ($action==='publish_to_content' && $quiz_id>0) {
  // Ensure a content row exists pointing to internal quiz player
  $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!==''){
    // try find existing content
    $chk=$mysqli->prepare("SELECT id FROM lms_content WHERE module_id=? AND quiz_id=?");
    $chk->bind_param('ii',$module_id,$quiz_id); $chk->execute(); $r=$chk->get_result()->fetch_assoc(); $chk->close();
    $url = "/student/quiz.php?quiz_id=".$quiz_id;
    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']); $u->execute(); $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();
      $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=''; $ins->bind_param('issssii',$module_id,$title,$ct='quiz',$desc,$url,$quiz_id,$ord);
      $ins->execute(); $ins->close();
    }
    $msg='Published to module content.';
  } else $err='Quiz not found';
}

/* ----- read quiz + questions ----- */
$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')));
      $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; ?>

<?php if(!$QUIZ && $quiz_id===0): ?>
  <div class="card mb-3">
    <div class="card-header">Create a new quiz</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 d-flex align-items-end">
          <label class="form-check me-3">
            <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 justify-content-between align-items-center">
      <div><strong><?= esc($QUIZ['title']) ?></strong></div>
      <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 class="card-body">
      <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(!$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">
              <?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>';
