<?php
// /elms/admin/assessments/assessmentcriteria.php — v9 (Edit + Delete actions)
// - Keeps your layout (admin_layout_top/bottom)
// - Adds Delete in the list Action column (with confirm + server-side handler)
// - Leaves everything else intact.

declare(strict_types=1);

/* -------------------- bootstrap & settings -------------------- */
if (session_status() === PHP_SESSION_NONE) session_start();
@ini_set('log_errors', '1'); @ini_set('display_errors', '0'); @error_reporting(E_ALL);

// CSRF helpers (tiny + compatible)
if (empty($_SESSION['csrf'])) { $_SESSION['csrf'] = bin2hex(random_bytes(16)); }
function csrf_token(): string { return $_SESSION['csrf']; }
function require_csrf(): void {
  if (!isset($_POST['csrf']) || !hash_equals($_SESSION['csrf'] ?? '', (string)$_POST['csrf'])) {
    http_response_code(403); exit('CSRF validation failed');
  }
}

// solid project root: /elms
if (!defined('APP_ROOT')) {
  define('APP_ROOT', realpath(dirname(__DIR__, 2)));
}

// auth (keep your roles)
$role = strtolower((string)($_SESSION['user']['role'] ?? $_SESSION['role'] ?? ''));
if (!in_array($role, ['super_admin','admin','coordinator','branch_admin'], true)) {
  http_response_code(403); echo 'Forbidden'; exit;
}
date_default_timezone_set('Asia/Colombo');

/* -------------------------- DB include ------------------------ */
require_once APP_ROOT . '/includes/db.php';
if (!isset($mysqli) || !($mysqli instanceof mysqli)) { if (isset($conn) && $conn instanceof mysqli) $mysqli = $conn; }
if (!isset($mysqli) || !($mysqli instanceof mysqli)) { http_response_code(500); echo 'DB not connected'; exit; }
@$mysqli->set_charset('utf8mb4');

/* ---------------------------- helpers ------------------------- */
function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }
function ensure_dir($p){ if(!is_dir($p)) @mkdir($p,0775,true); }
function t_exists(mysqli $db,string $t):bool{
  $t = $db->real_escape_string($t);
  $r = $db->query("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='$t'");
  $ok = $r && $r->num_rows>0; if($r) $r->free(); return $ok;
}
function col_exists(mysqli $db,string $t,string $c):bool{
  $t=str_replace('`','``',$t); $c=$db->real_escape_string($c);
  $r=$db->query("SHOW COLUMNS FROM `$t` LIKE '$c'"); $ok=$r && $r->num_rows>0; if($r) $r->free(); return $ok;
}
function first_tbl(mysqli $db,array $cands){ foreach($cands as $t){ if(t_exists($db,$t)) return $t; } return null; }
function first_col(mysqli $db,string $t,array $cands){ foreach($cands as $c){ if(col_exists($db,$t,$c)) return $c; } return null; }
function pick_title(mysqli $db,string $t,array $cands=['title','name','course_name','module_name']){
  foreach($cands as $c){ if(col_exists($db,$t,$c)) return $c; } return 'id';
}

/* ---------------- our table (create if missing) --------------- */
if (!t_exists($mysqli,'lms_assessment_criteria_sets')) {
  $mysqli->query("
    CREATE TABLE lms_assessment_criteria_sets(
      id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
      assessment_id INT NULL,
      course_id INT NULL,
      module_id INT NULL,
      template_type ENUM('assessment','course','module') NOT NULL DEFAULT 'assessment',
      title VARCHAR(200) DEFAULT NULL,
      info_json LONGTEXT NULL,
      image_path VARCHAR(255) DEFAULT NULL,
      status ENUM('active','archived') NOT NULL DEFAULT 'active',
      created_by INT NULL,
      created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      INDEX idx_assessment (assessment_id),
      INDEX idx_course (course_id),
      INDEX idx_module (module_id),
      INDEX idx_type (template_type)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  ");
}

/* ---- detect your courses/modules tables (read-only references) --- */
$COURSE_TBL = first_tbl($mysqli,['courses','course','lms_courses','programs']);
$MODULE_TBL = first_tbl($mysqli,['course_modules','modules','lms_modules','subjects','units','topics']);

$courseId   = $COURSE_TBL ? first_col($mysqli,$COURSE_TBL,['id','course_id']) : null;
$courseName = $COURSE_TBL ? pick_title($mysqli,$COURSE_TBL,['name','title','course_name']) : null;

$moduleId   = $MODULE_TBL ? first_col($mysqli,$MODULE_TBL,['id','module_id']) : null;
$moduleName = $MODULE_TBL ? pick_title($mysqli,$MODULE_TBL,['name','title','module_name','subject_name']) : null;
$modCourse  = $MODULE_TBL ? first_col($mysqli,$MODULE_TBL,['course_id','program_id','cid','courses_id','course']) : null;

/* ---- dynamic label for lms_assessments title/name/heading ------- */
$assTitleCol = null;
foreach (['title','assessment_title','name','subject','topic','module','assessment_name','heading'] as $c) {
  if (col_exists($mysqli, 'lms_assessments', $c)) { $assTitleCol = $c; break; }
}
$assLabelExprList = $assTitleCol ? "`$assTitleCol`"      : "CONCAT('Assessment #',id)";
$assLabelExprJoin = $assTitleCol ? "`a`.`$assTitleCol`"  : "CONCAT('Assessment #',a.id)";

/* ---------------------------- dropdowns ------------------------ */
$assessments=[]; 
$rs=$mysqli->query("SELECT id, $assLabelExprList AS t FROM lms_assessments ORDER BY id DESC");
if($rs){ while($r=$rs->fetch_assoc()){ $assessments[]=$r; } $rs->free(); }

$courses=[]; 
if($COURSE_TBL && $courseId && $courseName){
  $rs=$mysqli->query("SELECT `$courseId` AS id, `$courseName` AS t FROM `$COURSE_TBL` ORDER BY 2");
  if($rs){ while($r=$rs->fetch_assoc()){ $courses[]=$r; } $rs->free(); }
}

$modules=[]; $modsByCourse=[];
if($MODULE_TBL && $moduleId && $moduleName){
  $sql="SELECT `$moduleId` AS id, `$moduleName` AS t".($modCourse? ", `$modCourse` AS cid":"")." FROM `$MODULE_TBL` ORDER BY 2";
  $rs=$mysqli->query($sql);
  if($rs){ while($r=$rs->fetch_assoc()){ $modules[]=$r; if(isset($r['cid'])) $modsByCourse[(string)$r['cid']][]=$r; } $rs->free(); }
}

/* ----------------------------- routing ------------------------- */
$action = $_GET['action'] ?? 'list';
$id     = (int)($_GET['id'] ?? 0);
$msg='';

/* ----------------------------- save ---------------------------- */
$uploadDir = APP_ROOT.'/uploads/criteria';
ensure_dir($uploadDir);

if($_SERVER['REQUEST_METHOD']==='POST'){
  $post = $_POST['post_action'] ?? '';

  if ($post === 'delete') {            // <— NEW: hard delete
    require_csrf();
    $delId = (int)($_POST['id'] ?? 0);
    if ($delId > 0) {
      $st = $mysqli->prepare("DELETE FROM lms_assessment_criteria_sets WHERE id=?");
      if ($st) { $st->bind_param('i',$delId); $st->execute(); $st->close(); $msg='Deleted.'; }
    }
    $action='list';
  }

  if($post==='save'){
    $id = (int)($_POST['id'] ?? 0);
    $type = in_array($_POST['template_type'] ?? 'assessment',['assessment','course','module'],true) ? $_POST['template_type'] : 'assessment';
    $assessment_id = (int)($_POST['assessment_id'] ?? 0);
    $course_id = (int)($_POST['course_id'] ?? 0);
    $module_id = (int)($_POST['module_id'] ?? 0);
    if($type==='assessment'){ $course_id=0; $module_id=0; }
    if($type==='course'){ $module_id=0; }
    $title = trim((string)($_POST['title'] ?? ''));
    $info_json = (string)($_POST['info_json'] ?? '{"los":[]}');
    $status = in_array($_POST['status'] ?? 'active',['active','archived'],true) ? $_POST['status'] : 'active';
    $image_path = (string)($_POST['existing_image'] ?? '');

    if (!empty($_FILES['criteria_image']['name']) && is_uploaded_file($_FILES['criteria_image']['tmp_name'])) {
      $ext=strtolower(pathinfo($_FILES['criteria_image']['name'], PATHINFO_EXTENSION));
      if(!in_array($ext,['jpg','jpeg','png','gif','webp','pdf'])) $ext='bin';
      $fname='criteria_'.date('Ymd_His').'_'.($assessment_id?:$course_id?:$module_id).'.'.$ext;
      if(move_uploaded_file($_FILES['criteria_image']['tmp_name'], $uploadDir.'/'.$fname)) {
        $image_path='/uploads/criteria/'.$fname;
      }
    }

    if($id>0){
      $st=$mysqli->prepare("UPDATE lms_assessment_criteria_sets
        SET template_type=?, assessment_id=?, course_id=?, module_id=?, title=?, info_json=?, image_path=?, status=?
        WHERE id=?");
      if($st){
        $st->bind_param('siiissssi',$type,$assessment_id,$course_id,$module_id,$title,$info_json,$image_path,$status,$id);
        $ok=$st->execute(); $st->close();
        $msg=$ok?'Updated.':'Update failed.'; $action='edit';
      } else { $msg='Update prepare failed.'; $action='edit'; }
    } else {
      $uid=(int)($_SESSION['user']['id'] ?? 0);
      $st=$mysqli->prepare("INSERT INTO lms_assessment_criteria_sets
        (template_type,assessment_id,course_id,module_id,title,info_json,image_path,status,created_by)
        VALUES (?,?,?,?,?,?,?,?,?)");
      if($st){
        $st->bind_param('siiissssi',$type,$assessment_id,$course_id,$module_id,$title,$info_json,$image_path,$status,$uid);
        $ok=$st->execute(); $id=$ok?(int)$st->insert_id:0; $st->close();
        $msg=$ok?'Created.':'Create failed.'; $action='edit';
      } else { $msg='Create prepare failed.'; $action='edit'; }
    }
  }

  if($post==='archive' && $id>0){
    $st=$mysqli->prepare("UPDATE lms_assessment_criteria_sets SET status='archived' WHERE id=?");
    if($st){ $st->bind_param('i',$id); $st->execute(); $st->close(); }
    $msg='Archived.'; $action='list';
  }
}

/* --------------------------- fetch/edit ------------------------ */
$row=null;
if($action==='edit' && $id>0){
  $st=$mysqli->prepare("SELECT * FROM lms_assessment_criteria_sets WHERE id=?");
  if($st){ $st->bind_param('i',$id); $st->execute(); $row=$st->get_result()->fetch_assoc(); $st->close(); }
}

/* ---------------------------- list data ------------------------ */
$list=[];
if($action==='list'){
  $sql = "SELECT s.*, $assLabelExprJoin AS atitle
          FROM lms_assessment_criteria_sets s
          LEFT JOIN lms_assessments a ON a.id = s.assessment_id
          ORDER BY s.updated_at DESC, s.id DESC";
  $rs=$mysqli->query($sql);
  if($rs){ while($x=$rs->fetch_assoc()){ $list[]=$x; } $rs->free(); }
}
function map_ids($rows){ $m=[]; foreach($rows as $r){ $m[(string)$r['id']]=$r['t']; } return $m; }
$courseMap = map_ids($courses);
$moduleMap = map_ids($modules);

/* ------------------------ Admin layout hooks ------------------- */
$PAGE_TITLE  = 'Criteria Templates';
$ACTIVE_MENU = 'assessments';

$LAYOUT_TOP = APP_ROOT . '/includes/admin_layout_top.php';
$LAYOUT_BOT = APP_ROOT . '/includes/admin_layout_bottom.php';
if (!is_file($LAYOUT_TOP)) {
  foreach ([APP_ROOT.'/admin/includes/header.php', APP_ROOT.'/includes/admin-header.php', APP_ROOT.'/includes/header.php'] as $f) {
    if (is_file($f)) { $LAYOUT_TOP = $f; break; }
  }
}
if (!is_file($LAYOUT_BOT)) {
  foreach ([APP_ROOT.'/admin/includes/footer.php', APP_ROOT.'/includes/admin-footer.php', APP_ROOT.'/includes/footer.php'] as $f) {
    if (is_file($f)) { $LAYOUT_BOT = $f; break; }
  }
}

/* ------------------------------- VIEW -------------------------- */
// TOP
if (is_file($LAYOUT_TOP)) { require $LAYOUT_TOP; }
else {
  echo "<!doctype html><html><head><meta charset='utf-8'><title>".esc($PAGE_TITLE)."</title>";
  echo "<meta name='viewport' content='width=device-width, initial-scale=1'>";
  echo "<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css'>";
  echo "<style>.pill{display:inline-block;background:#eef2ff;color:#3730a3;font-weight:700;font-size:12px;padding:4px 10px;border-radius:999px}
  .code{min-width:38px;text-align:center;border:1px solid #cbd5e1;border-radius:6px;padding:4px 8px;background:#f8fafc}</style>";
  echo "</head><body><div class='container-fluid p-3'>";
}
?>
<div class="card shadow-sm">
  <div class="card-header bg-white">
    <h3 class="mb-0">Criteria Templates</h3>
    <div class="text-muted small">Templates for an <b>Assessment</b>, whole <b>Course</b>, or a <b>Course Module</b>.</div>
  </div>
  <div class="card-body">
<?php if($action==='list'): ?>
    <div class="table-responsive">
      <table class="table align-middle">
        <thead class="table-light">
          <tr><th>ID</th><th>Scope</th><th>Linked To</th><th>Title</th><th>Status</th><th>Updated</th><th style="width:140px">Action</th></tr>
        </thead>
        <tbody>
        <?php if(!$list): ?>
          <tr><td colspan="7" class="text-muted text-center py-4">No templates yet.</td></tr>
        <?php else: foreach($list as $x):
          $scope=strtoupper($x['template_type'] ?? 'assessment');
          $linked='';
          if(($x['template_type']??'')==='assessment'){ $linked=$x['atitle'] ?? ('#'.$x['assessment_id']); }
          if(($x['template_type']??'')==='course'){ $linked=$courseMap[(string)($x['course_id']??'')] ?? ('Course #'.(int)$x['course_id']); }
          if(($x['template_type']??'')==='module'){ $linked=($courseMap[(string)($x['course_id']??'')]??'Course ?').' → '.($moduleMap[(string)($x['module_id']??'')]??'Module ?'); }
        ?>
          <tr>
            <td><?= (int)$x['id'] ?></td>
            <td><span class="pill"><?= esc($scope) ?></span></td>
            <td><?= esc($linked) ?></td>
            <td><?= esc($x['title'] ?? '') ?></td>
            <td><span class="pill"><?= esc($x['status']) ?></span></td>
            <td class="text-muted small"><?= esc($x['updated_at']) ?></td>
            <td class="d-flex gap-2">
              <a class="btn btn-sm btn-primary" href="?action=edit&id=<?= (int)$x['id'] ?>">Edit</a>
              <form method="post" onsubmit="return confirm('Delete this template permanently?');">
                <input type="hidden" name="csrf" value="<?= esc(csrf_token()) ?>">
                <input type="hidden" name="post_action" value="delete">
                <input type="hidden" name="id" value="<?= (int)$x['id'] ?>">
                <button class="btn btn-sm btn-outline-danger">Delete</button>
              </form>
            </td>
          </tr>
        <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
<?php else:
  $cur=$row ?? ['id'=>0,'template_type'=>'assessment','assessment_id'=>0,'course_id'=>0,'module_id'=>0,'title'=>'','info_json'=>'{"los":[{"code":"LO1","text":"","codes":["P1","P2","M1","D1"]}]}','image_path'=>'','status'=>'active'];
  $info=json_decode((string)$cur['info_json'] ?: '{"los":[]}', true); if(!is_array($info)) $info=['los'=>[]]; $los=$info['los'] ?? [];
?>
    <?php if($msg): ?><div class="alert alert-success"><?= esc($msg) ?></div><?php endif; ?>
    <form id="criteriaForm" method="post" enctype="multipart/form-data">
      <input type="hidden" name="csrf" value="<?= esc(csrf_token()) ?>">
      <input type="hidden" name="post_action" value="save">
      <input type="hidden" name="id" value="<?= (int)$cur['id'] ?>">
      <input type="hidden" name="info_json" id="info_json">
      <input type="hidden" name="existing_image" value="<?= esc($cur['image_path'] ?? '') ?>">
      <div class="row g-3">
        <div class="col-md-2">
          <label class="form-label">Template Type</label>
          <select class="form-select" name="template_type" id="template_type">
            <?php foreach(['assessment'=>'Assessment','course'=>'Course','module'=>'Course Module'] as $k=>$v): ?>
              <option value="<?= $k ?>" <?= (($cur['template_type']??'assessment')===$k)?'selected':'' ?>><?= $v ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-3 scope scope-assessment">
          <label class="form-label">Assessment</label>
          <select class="form-select" name="assessment_id" id="assessment_id">
            <option value="0">— choose —</option>
            <?php foreach($assessments as $a): ?>
              <option value="<?= (int)$a['id'] ?>" <?= ((int)$cur['assessment_id']===(int)$a['id'])?'selected':'' ?>>#<?= (int)$a['id'] ?> — <?= esc($a['t']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-4 scope scope-course">
          <label class="form-label">Course</label>
          <select class="form-select" name="course_id" id="course_id">
            <option value="0">— choose —</option>
            <?php foreach($courses as $c): ?>
              <option value="<?= (int)$c['id'] ?>" <?= ((int)$cur['course_id']===(int)$c['id'])?'selected':'' ?>><?= esc($c['t']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-3 scope scope-module">
          <label class="form-label">Module (filtered by Course)</label>
          <select class="form-select" name="module_id" id="module_id"><option value="0">— choose —</option></select>
        </div>
        <div class="col-md-3">
          <label class="form-label">Status</label>
          <select class="form-select" name="status">
            <?php foreach(['active','archived'] as $st): ?>
              <option value="<?= $st ?>" <?= ($cur['status']===$st)?'selected':'' ?>><?= ucfirst($st) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-6">
          <label class="form-label">Title (optional)</label>
          <input class="form-control" name="title" value="<?= esc($cur['title'] ?? '') ?>">
        </div>
        <div class="col-md-6">
          <label class="form-label">Reference (image/PDF)</label>
          <input class="form-control" type="file" name="criteria_image" accept=".jpg,.jpeg,.png,.gif,.webp,.pdf">
          <?php if(!empty($cur['image_path'])): ?>
            <div class="form-text">Current: <a href="<?= esc($cur['image_path']) ?>" target="_blank"><?= esc($cur['image_path']) ?></a></div>
          <?php endif; ?>
        </div>
      </div>

      <div class="mt-3 p-2 bg-light border rounded">Covered Assessment Criteria</div>
      <div id="loContainer" class="mt-2"></div>

      <div class="d-flex gap-2 mt-2">
        <button id="btnAddLo" type="button" class="btn btn-outline-primary">+ Add LO</button>
      </div>

      <div class="d-grid gap-2 mt-3">
        <button class="btn btn-primary" id="btnSave">Save</button>
        <?php if((int)$cur['id']>0): ?>
          <button class="btn btn-secondary" name="post_action" value="archive" onclick="return confirm('Archive this template?')">Archive</button>
          <button class="btn btn-outline-danger" name="post_action" value="delete" onclick="return confirm('Delete this template permanently?')">Delete</button>
        <?php endif; ?>
      </div>

      <div class="mt-3 p-2 bg-light border rounded">Preview</div>
      <div id="preview" class="p-2 border rounded"></div>
    </form>

    <script>
    document.addEventListener('DOMContentLoaded', function(){
      const START_LOS  = Array.isArray(<?= json_encode($los, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>) ? <?= json_encode($los, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?> : [];
      const BYCOURSE   = <?= json_encode($modsByCourse, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?> || {};
      const curCourse  = <?= (int)($cur['course_id']??0) ?>;
      const curModule  = <?= (int)($cur['module_id']??0) ?>;

      const loCont   = document.getElementById('loContainer');
      const addBtn   = document.getElementById('btnAddLo');
      const form     = document.getElementById('criteriaForm');
      const infoJson = document.getElementById('info_json');
      const preview  = document.getElementById('preview');
      const scopeSel = document.getElementById('template_type');
      const courseSel= document.getElementById('course_id');
      const moduleSel= document.getElementById('module_id');

      function H(s){return (s||'').replace(/[&<>"']/g,m=>({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;' }[m]))}

      function rowTpl(i,lo){
        const code = lo.code || ('LO'+(i+1));
        const text = lo.text || '';
        const codes= (lo.codes||[]).join(',');
        return `<div class="row g-2 align-items-center mb-2" data-i="${i}">
          <div class="col-md-2"><input class="form-control lo-code" placeholder="LO code" value="${H(code)}"></div>
          <div class="col-md-7"><input class="form-control lo-text" placeholder="Learning outcome text" value="${H(text)}"></div>
          <div class="col-md-2"><input class="form-control lo-codes" placeholder="Codes (P1,P2,M1,D1)" value="${H(codes)}"></div>
          <div class="col-md-1 d-grid"><button type="button" class="btn btn-outline-secondary btn-del">Del</button></div>
        </div>`;
      }

      function normalize(){
        if (!Array.isArray(window._LOS)) {
          window._LOS = (START_LOS && START_LOS.length) ? JSON.parse(JSON.stringify(START_LOS)) : [{code:'LO1',text:'',codes:['P1','P2','M1','D1']}];
        }
      }

      function render(){
        normalize();
        loCont.innerHTML = window._LOS.map((lo,i)=>rowTpl(i,lo)).join('');
        buildPreview();
      }

      function addRow(){
        normalize();
        const next = 'LO'+(window._LOS.length+1);
        window._LOS.push({code:next,text:'',codes:[]});
        render();
      }

      function delRow(idx){
        normalize();
        window._LOS.splice(idx,1);
        render();
      }

      function collect(){
        normalize();
        const rows = [...loCont.querySelectorAll('[data-i]')];
        return {
          los: rows.map(r=>{
            const code  = r.querySelector('.lo-code').value.trim() || ('LO'+(Math.random()*1000|0));
            const text  = r.querySelector('.lo-text').value.trim();
            const codes = (r.querySelector('.lo-codes').value||'').split(',').map(s=>s.trim()).filter(Boolean);
            return {code,text,codes};
          })
        };
      }

      function buildPreview(){
        const d=collect(), out=[];
        out.push(`<div class="border rounded">`);
        out.push(`<div class="bg-light border-bottom p-2 fw-semibold">Covered Assessment Criteria –</div>`);
        d.los.forEach(lo=>{
          out.push(`<div class="p-2 border-bottom"><b>${H(lo.code)}:</b> ${H(lo.text||'')}</div>`);
          out.push(`<div class="p-2 d-flex flex-wrap gap-2">`+(lo.codes||[]).map(c=>`<span class="code">${H(c)}</span>`).join('')+`</div>`);
        });
        out.push(`</div>`);
        preview.innerHTML = out.join('');
      }

      function saveJson(){ infoJson.value = JSON.stringify(collect()); return true; }

      function toggleScopes(){
        const v = scopeSel.value;
        document.querySelectorAll('.scope').forEach(el=>el.style.display='none');
        if (v==='assessment') document.querySelector('.scope-assessment').style.display='';
        if (v==='course')     document.querySelector('.scope-course').style.display='';
        if (v==='module'){    document.querySelector('.scope-course').style.display=''; document.querySelector('.scope-module').style.display=''; }
      }

      function fillModules(){
        const cid = (courseSel && courseSel.value) ? String(courseSel.value) : '0';
        const rows = BYCOURSE[cid] || [];
        const opts = [`<option value="0">— choose —</option>`];
        rows.forEach(r=>opts.push(`<option value="${r.id}" ${(+r.id===curModule?'selected':'')}>${H(r.t)}</option>`));
        if (moduleSel) moduleSel.innerHTML = opts.join('');
      }

      addBtn.addEventListener('click', addRow);
      loCont.addEventListener('click', (e)=>{
        if (e.target && e.target.classList.contains('btn-del')) {
          const row = e.target.closest('[data-i]');
          if (row) delRow(parseInt(row.getAttribute('data-i'),10));
        }
      });
      form.addEventListener('submit', saveJson);
      if (courseSel) courseSel.addEventListener('change', fillModules);
      scopeSel.addEventListener('change', toggleScopes);

      render();
      toggleScopes();
      if (courseSel) { if (curCourse) courseSel.value = String(curCourse); fillModules(); }
    });
    </script>
<?php endif; ?>
  </div>
</div>
<?php
// BOTTOM
if (is_file($LAYOUT_BOT)) { require $LAYOUT_BOT; }
else { echo "</div></body></html>"; }
