<?php
/* admin/courses/content.php — robust + schema-aware Content manager
 * Works whether you have lms_modules or course_modules, and auto-creates lms_content.
 * Drag-reorder, toggles, add/update/delete. JSON (fetch) and regular POST supported.
 */

/* ===== TEMP DEBUG SWITCH (visit with ?debug=1) ===== */
if (isset($_GET['debug']) && $_GET['debug'] === '1') {
    ini_set('display_errors', '1');
    error_reporting(E_ALL);
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    set_exception_handler(function(Throwable $e){
        error_log("COURSE_CONTENT fatal: ".$e->getMessage()."\n".$e->getTraceAsString());
        http_response_code(500);
        echo "<pre style='white-space:pre-wrap'>FATAL: ".$e->getMessage()."\n\n".$e->getTraceAsString()."</pre>";
        exit;
    });
}

if (session_status() === PHP_SESSION_NONE) session_start();

/* ---------- includes (guarded) ---------- */
$auth = __DIR__ . '/../../includes/auth.php';
$db   = __DIR__ . '/../../includes/db.php';
$hlp  = __DIR__ . '/../../includes/helpers.php';
if (is_file($auth)) require_once $auth;
if (function_exists('require_role')) require_role(['super_admin','branch_admin']);
if (is_file($hlp))  require_once $hlp;
require_once $db; // let it error if DB truly missing

/* ---------- local helpers (no redeclare) ---------- */
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;
  }
}

/* ---------- JSON body (for fetch) ---------- */
$RAW  = file_get_contents('php://input');
$JSON = null;
if (isset($_SERVER['CONTENT_TYPE']) && stripos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) {
  $JSON = json_decode($RAW, true);
  if (!is_array($JSON)) $JSON = null;
}

/* ---------- parameter helpers ---------- */
function first_module_of_course(int $cid): int {
  global $mysqli;
  foreach (['lms_modules','course_modules'] as $t) {
    if (!table_exists_local($t)) continue;
    $order = column_exists_local($t,'sort_order') ? 'sort_order, id' : 'id';
    $st = $mysqli->prepare("SELECT id FROM `$t` WHERE course_id=? ORDER BY $order LIMIT 1");
    $st->bind_param('i',$cid); $st->execute();
    if ($row = $st->get_result()->fetch_assoc()) { $st->close(); return (int)$row['id']; }
    $st->close();
  }
  return 0;
}
function derive_course_by_module(int $mid): int {
  global $mysqli;
  foreach (['lms_modules','course_modules'] as $t) {
    if (!table_exists_local($t)) continue;
    $st = $mysqli->prepare("SELECT course_id FROM `$t` WHERE id=? LIMIT 1");
    $st->bind_param('i',$mid); $st->execute();
    if ($row = $st->get_result()->fetch_assoc()) { $st->close(); return (int)$row['course_id']; }
    $st->close();
  }
  return 0;
}
function redirect_self($cid,$mid,$extra=''){ header("Location: content.php?course_id=$cid&module_id=$mid$extra"); exit; }

/* ---------- inputs (robust) ---------- */
$course_id = (int)($_GET['course_id'] ?? $_POST['course_id'] ?? ($JSON['course_id'] ?? 0));
$module_id = (int)($_GET['module_id'] ?? $_GET['id'] ?? $_POST['module_id'] ?? ($JSON['module_id'] ?? 0));
$q         = trim((string)($_GET['q'] ?? ''));

/* allow opening with only module_id -> derive course_id */
if ($module_id > 0 && $course_id <= 0) $course_id = derive_course_by_module($module_id);

/* course given but module missing -> jump to first module in that course */
if ($course_id > 0 && $module_id <= 0) {
  if ($first = first_module_of_course($course_id)) redirect_self($course_id,$first);
  header("Location: modules.php?course_id=$course_id&msg=" . urlencode('Create a module to add content.')); exit;
}

/* nothing given -> try first available pair or send to modules list */
if ($course_id <= 0 && $module_id <= 0) {
  foreach (['lms_modules','course_modules'] as $t) {
    if (!table_exists_local($t)) continue;
    $order = column_exists_local($t,'sort_order') ? 'sort_order, id' : 'id';
    $rs = $mysqli->query("SELECT id AS mid, course_id AS cid FROM `$t` ORDER BY $order LIMIT 1");
    if ($pair = $rs->fetch_assoc()) redirect_self((int)$pair['cid'], (int)$pair['mid']);
  }
  header("Location: modules.php?msg=" . urlencode('No modules found. Create one first.')); exit;
}

/* ---------- detect module table/columns ---------- */
$HAS_LMS_MODULES    = table_exists_local('lms_modules');
$HAS_COURSE_MODULES = table_exists_local('course_modules');
$MOD_TBL   = $HAS_LMS_MODULES ? 'lms_modules' : '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');
$HAS_GAMEMODE = $HAS_LMS_MODULES && column_exists_local('lms_modules','game_mode');

/* ---------- resolve course ---------- */
$labelCol = column_exists_local('courses','course_name') ? 'course_name'
          : (column_exists_local('courses','name') ? 'name'
          : (column_exists_local('courses','title') ? 'title' : 'id'));
$stmt=$mysqli->prepare("SELECT id,$labelCol AS label FROM courses WHERE id=?");
$stmt->bind_param('i',$course_id); $stmt->execute();
$COURSE=$stmt->get_result()->fetch_assoc(); $stmt->close();
if(!$COURSE){ http_response_code(404); exit('Course not found'); }

/* ---------- resolve module ---------- */
$sql = "SELECT id, {$TITLE_COL} AS title" . ($HAS_GAMEMODE ? ", game_mode" : ", 0 AS game_mode")
     . " FROM `$MOD_TBL` WHERE id=? AND course_id=?";
$stmt=$mysqli->prepare($sql);
$stmt->bind_param('ii',$module_id,$course_id);
$stmt->execute(); $MODULE=$stmt->get_result()->fetch_assoc(); $stmt->close();
if(!$MODULE){ http_response_code(404); exit('Module not found for this course'); }

/* ---------- ensure lms_content schema ---------- */
function ensure_lms_content_schema(){
  global $mysqli;
  if (table_exists_local('lms_content')) return;
  $sql = "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` ENUM('link','pdf','video','text','quiz','game') NOT NULL DEFAULT 'link',
    `description` TEXT NULL,
    `available_from` DATETIME NULL,
    `available_to` DATETIME NULL,
    `file_path` VARCHAR(255) NULL,
    `url` VARCHAR(500) 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_active` (`active`)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
  $mysqli->query($sql);
}
ensure_lms_content_schema();

/* ---------- optional columns on lms_content ---------- */
$HAS_AF  = column_exists_local('lms_content','available_from');
$HAS_AT  = column_exists_local('lms_content','available_to');
$HAS_DUR = column_exists_local('lms_content','duration_seconds');

/* ---------- uploads ---------- */
/* PHYSICAL path must be: .../elms/uploads/content  */
$ELMS_ROOT    = dirname(__DIR__, 2);               // => /elms
$UPLOAD_DIR   = $ELMS_ROOT . '/uploads/content';

/* WEB base must be app-rooted (always "/elms/..."), not "/admin.../elms" */
$script = $_SERVER['SCRIPT_NAME'] ?? '';
if (preg_match('~^(.*/elms)(?:/|$)~', $script, $m)) {
  $APP_ROOT = rtrim($m[1], '/');                   // "/elms"
} else {
  $APP_ROOT = '/elms';
}
$PUBLIC_PREFIX = $APP_ROOT . '/uploads/content';

/* Allowed file types & max size */
$ALLOWED_EXT = ['pdf','mp4','mov','webm','mkv','avi','zip','ppt','pptx','doc','docx','xls','xlsx','png','jpg','jpeg','gif','txt','csv'];
$MAX_MB      = 200;

/* ---------- small helpers ---------- */
function next_sort_for_module($mid){
  global $mysqli; $q=$mysqli->prepare("SELECT COALESCE(MAX(sort_order),0)+1 FROM lms_content WHERE module_id=?");
  $q->bind_param('i',$mid); $q->execute(); $q->bind_result($n); $q->fetch(); $q->close(); return (int)$n;
}
function clean_filename($name){ $name = preg_replace('/[^A-Za-z0-9._-]+/','_',$name); return trim($name,'._'); }
function flash($k,$v=null){ if($v===null){ $x=$_SESSION['flash'][$k]??null; unset($_SESSION['flash'][$k]); return $x; } $_SESSION['flash'][$k]=$v; }

/* Normalize any stored file_path to a correct, openable web URL */
function admin_file_href(?string $p): string {
  if (!$p) return '';
  $p = str_replace('\\','/',$p);
  if (preg_match('#^https?://#i',$p)) return $p; // already absolute

  $script   = $_SERVER['SCRIPT_NAME'] ?? '/elms/admin/courses/content.php';
  $APP_BASE = rtrim(dirname(dirname(dirname($script))), '/'); // -> "/elms"

  if (strpos($p, $APP_BASE.'/uploads/') === 0) return $p;
  if (preg_match('#^/uploads/#i',$p)) return $APP_BASE.$p;
  if (preg_match('#^(uploads/|content/|assessments/|submissions/)#i',$p)) return $APP_BASE.'/'.ltrim($p,'/');
  if (substr($p,0,1)==='/') return $p;
  return $APP_BASE.'/'.ltrim($p,'/');
}

/* ---------- module list for switcher ---------- */
$MODS=[];
$stmt=$mysqli->prepare("SELECT id, {$TITLE_COL} AS title FROM `$MOD_TBL` WHERE course_id=? ORDER BY {$ORDER_COL}, id");
$stmt->bind_param('i',$course_id); $stmt->execute();
$r=$stmt->get_result(); while($row=$r->fetch_assoc()) $MODS[]=$row; $stmt->close();

/* ---------- Action routing (POST or JSON) ---------- */
$action = $_POST['action'] ?? ($JSON['action'] ?? '');

/* Drag reorder (JSON) */
if ($action === 'reorder_content') {
  header('Content-Type: application/json; charset=utf-8');
  $ids = $_POST['ids'] ?? ($JSON['ids'] ?? []);
  if (is_string($ids)) $ids = preg_split('/[,\s]+/', trim($ids), -1, PREG_SPLIT_NO_EMPTY);
  if (!is_array($ids)) $ids=[];
  $ids = array_values(array_unique(array_map('intval',$ids)));

  $allowed=[]; $q=$mysqli->prepare("SELECT id FROM lms_content WHERE module_id=?");
  $q->bind_param('i',$module_id); $q->execute(); $res=$q->get_result();
  while($row=$res->fetch_assoc()) $allowed[]=(int)$row['id']; $q->close();
  if(!$allowed){ echo json_encode(['ok'=>false,'error'=>'No content']); exit; }

  $set=array_flip($allowed); $ordered=[];
  foreach($ids as $id) if(isset($set[$id])) $ordered[]=$id;
  foreach($allowed as $id) if(!in_array($id,$ordered,true)) $ordered[]=$id;

  $mysqli->begin_transaction();
  try{
    $ord=1; $u=$mysqli->prepare("UPDATE lms_content SET sort_order=? WHERE id=? AND module_id=?");
    foreach($ordered as $id){ $u->bind_param('iii',$ord,$id,$module_id); $u->execute(); $ord++; }
    $u->close(); $mysqli->commit(); echo json_encode(['ok'=>true]);
  }catch(Throwable $e){ $mysqli->rollback(); echo json_encode(['ok'=>false,'error'=>'DB error']); }
  exit;
}

/* Inline toggles (form POST) */
if ($action === 'toggle' && isset($_POST['field'],$_POST['id'])) {
  header('Content-Type: application/json; charset=utf-8');
  $id=(int)$_POST['id']; $field=$_POST['field'];
  if(!in_array($field,['active','require_paid'],true)){ echo json_encode(['ok'=>false]); exit; }
  $stmt=$mysqli->prepare("UPDATE lms_content SET $field = 1 - $field WHERE id=? AND module_id=?");
  $stmt->bind_param('ii',$id,$module_id); $ok=$stmt->execute(); $stmt->close();
  echo json_encode(['ok'=>$ok]); exit;
}

/* Add / Update / Delete (form POST) */
if ($action && !in_array($action,['reorder_content','toggle'],true)) {
  if ($action === 'add' || $action === 'update') {
    $id      = (int)($_POST['id'] ?? 0);
    $title   = trim((string)($_POST['title'] ?? ''));
    $type    = strtolower((string)($_POST['content_type'] ?? 'link')); // video/pdf/link/text/quiz/game
    $desc    = trim((string)($_POST['description'] ?? ''));
    $url     = trim((string)($_POST['url'] ?? ''));
    $active  = isset($_POST['active']) ? 1 : 0;
    $paid    = isset($_POST['require_paid']) ? 1 : 0;

    $allowedTypes = ['video','pdf','link','text','quiz','game'];
    if (!in_array($type,$allowedTypes,true)) $type='link';

    // file upload (optional)
    $file_path = null;
    if (!empty($_FILES['file']['name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
      $ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
      if (!in_array($ext,$ALLOWED_EXT,true)) { flash('err','File type not allowed'); redirect_self($course_id,$module_id,'&edit='.$id); }
      if ($_FILES['file']['size'] > $MAX_MB*1024*1024) { flash('err',"File too large (max {$MAX_MB}MB)"); redirect_self($course_id,$module_id,'&edit='.$id); }
      if (!is_dir($UPLOAD_DIR)) @mkdir($UPLOAD_DIR,0775,true);
      $fname = date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . ($ext?'.'.$ext:'');
      $dest = rtrim($UPLOAD_DIR,'/\\') . DIRECTORY_SEPARATOR . clean_filename($fname);
      if (move_uploaded_file($_FILES['file']['tmp_name'], $dest)) {
        $file_path = rtrim($PUBLIC_PREFIX,'/') . '/' . basename($dest); // store app-rooted URL
      } else { flash('err','Upload failed'); redirect_self($course_id,$module_id,'&edit='.$id); }
    }

    $af = $at = null;  // available_from / available_to (future use)
    $dur = null;      // duration_seconds (future use)

    if ($action === 'add') {
      if ($title !== '') {
        $sort = next_sort_for_module($module_id);
        $stmt=$mysqli->prepare("INSERT INTO lms_content
          (module_id,title,content_type,description,available_from,available_to,file_path,url,duration_seconds,sort_order,active,require_paid)
          VALUES (?,?,?,?,?,?,?,?,?,?,?,?)");
        $fp=$file_path;
        $stmt->bind_param('isssssssiiii',$module_id,$title,$type,$desc,$af,$at,$fp,$url,$dur,$sort,$active,$paid);
        $stmt->execute(); $stmt->close(); flash('ok','Content added');
      }
    } else { // update
      if ($id>0 && $title!=='') {
        if ($file_path !== null) {
          $stmt=$mysqli->prepare("UPDATE lms_content
            SET title=?,content_type=?,description=?,available_from=?,available_to=?,file_path=?,url=?,duration_seconds=?,active=?,require_paid=?
            WHERE id=? AND module_id=?");
          $stmt->bind_param('sssssssiiiii',$title,$type,$desc,$af,$at,$file_path,$url,$dur,$active,$paid,$id,$module_id);
        } else {
          $stmt=$mysqli->prepare("UPDATE lms_content
            SET title=?,content_type=?,description=?,available_from=?,available_to=?,url=?,duration_seconds=?,active=?,require_paid=?
            WHERE id=? AND module_id=?");
          $stmt->bind_param('ssssssiiiii',$title,$type,$desc,$af,$at,$url,$dur,$active,$paid,$id,$module_id);
        }
        $stmt->execute(); $stmt->close(); flash('ok','Content updated');
      }
    }
    redirect_self($course_id,$module_id);
  }

  if ($action === 'delete') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id>0){
      $d=$mysqli->prepare("DELETE FROM lms_content WHERE id=? AND module_id=?");
      $d->bind_param('ii',$id,$module_id); $d->execute(); $d->close(); flash('ok','Deleted');
    }
    redirect_self($course_id,$module_id);
  }
}

/* ---------- list items ---------- */
$items=[];
$sql="SELECT id,title,content_type,description,file_path,url,sort_order,active,require_paid
      FROM lms_content WHERE module_id=?";
if ($q!=='') { $sql .= " AND (title LIKE CONCAT('%',?,'%') OR description LIKE CONCAT('%',?,'%'))"; }
$sql .= " ORDER BY sort_order,id";
if ($q!=='') { $st=$mysqli->prepare($sql); $st->bind_param('iss',$module_id,$q,$q); }
else { $st=$mysqli->prepare($sql); $st->bind_param('i',$module_id); }
$st->execute(); $rs=$st->get_result(); while($r=$rs->fetch_assoc()) $items[]=$r; $st->close();

$edit_id = isset($_GET['edit']) ? (int)$_GET['edit'] : 0;
$editing = null; foreach($items as $it){ if ((int)$it['id']===$edit_id){ $editing=$it; break; } }

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

<style>
  .content-row { cursor: grab; user-select: none; }
  .content-row.dragging { opacity: .6; }
  .badge-soft { background: #eef2ff; color: #3b5bdb; }
</style>

<div class="d-flex align-items-center justify-content-between mb-3">
  <div class="d-flex align-items-center gap-3">
    <h1 class="h5 m-0">Content — <span class="text-muted"><?= esc($COURSE['label']) ?></span></h1>
    <form method="get" class="d-flex align-items-center gap-2">
      <input type="hidden" name="course_id" value="<?= (int)$course_id ?>">
      <select name="module_id" class="form-select form-select-sm" onchange="this.form.submit()">
        <?php foreach($MODS as $m): ?>
          <option value="<?= (int)$m['id'] ?>" <?= (int)$m['id']===$module_id?'selected':'' ?>><?= esc($m['title']) ?></option>
        <?php endforeach; ?>
      </select>
      <input type="text" class="form-control form-control-sm" name="q" placeholder="Search..." value="<?= esc($q) ?>">
    </form>
  </div>

  <div class="d-flex align-items-center gap-2">
    <a class="btn btn-sm btn-primary"
       href="quiz_builder.php?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>">Create Quiz</a>
    <a class="btn btn-sm btn-info"
       href="game_builder.php?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>">Game Builder</a>
  </div>

  <div>
    <a href="modules.php?course_id=<?= (int)$course_id ?>" class="btn btn-outline-secondary btn-sm">← Back to Modules</a>
  </div>
</div>

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

<div class="card mb-3">
  <div class="card-header d-flex justify-content-between align-items-center">
    <div>
      <strong>Module:</strong> <?= esc($MODULE['title']) ?>
      <?php if (!empty($MODULE['game_mode']) && $HAS_GAMEMODE): ?>
        <span class="badge badge-soft ms-2">Game Mode ON</span>
      <?php endif; ?>
    </div>
  </div>
  <div class="card-body p-0">
    <?php if (!$items): ?>
      <div class="p-3 text-muted">No content yet. Use the form below to add.</div>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table align-middle mb-0">
          <thead>
            <tr>
              <th style="width:34px;"></th>
              <th>Title</th>
              <th>Type</th>
              <th>Source</th>
              <th>Active</th>
              <th>Paid?</th>
              <th class="text-end">Actions</th>
            </tr>
          </thead>
          <tbody id="content-list">
            <?php foreach ($items as $it): $cid=(int)$it['id']; ?>
              <tr class="content-row" draggable="true" data-id="<?= $cid ?>">
                <td class="text-muted">☰</td>
                <td class="fw-semibold"><?= esc($it['title']) ?></td>
                <td><?= esc(strtoupper($it['content_type'])) ?></td>
                <td>
                  <?php if ($it['url']): ?>
                    <a href="<?= esc($it['url']) ?>" target="_blank" rel="noopener">URL</a>
                  <?php elseif ($it['file_path']): ?>
                    <a href="<?= esc(admin_file_href($it['file_path'])) ?>" target="_blank" rel="noopener">File</a>
                  <?php else: ?>
                    <span class="text-muted">—</span>
                  <?php endif; ?>
                </td>
                <td>
                  <button class="btn btn-sm <?= $it['active']?'btn-success':'btn-outline-secondary' ?> toggle"
                          data-id="<?= $cid ?>" data-field="active">
                    <?= $it['active']?'On':'Off' ?>
                  </button>
                </td>
                <td>
                  <button class="btn btn-sm <?= $it['require_paid']?'btn-warning':'btn-outline-secondary' ?> toggle"
                          data-id="<?= $cid ?>" data-field="require_paid">
                    <?= $it['require_paid']?'Yes':'No' ?>
                  </button>
                </td>
                <td class="text-end">
                  <a class="btn btn-sm btn-outline-primary"
                     href="content.php?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>&edit=<?= $cid ?>">Edit</a>
                  <form method="post" class="d-inline" onsubmit="return confirm('Delete this item?');">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?= $cid ?>">
                    <button class="btn btn-sm btn-outline-danger">Delete</button>
                  </form>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <div class="p-2 d-flex justify-content-end">
        <button id="btn-save-order" class="btn btn-sm btn-primary d-none">Save Order</button>
      </div>
    <?php endif; ?>
  </div>
</div>

<div class="card">
  <div class="card-header"><?= $editing ? 'Edit Content' : 'Add New Content' ?></div>
  <div class="card-body">
    <form method="post" enctype="multipart/form-data" class="row g-3">
      <input type="hidden" name="action" value="<?= $editing ? 'update' : 'add' ?>">
      <?php if ($editing): ?><input type="hidden" name="id" value="<?= (int)$editing['id'] ?>"><?php endif; ?>

      <div class="col-md-6">
        <label class="form-label">Title</label>
        <input type="text" name="title" class="form-control" required
               value="<?= esc($editing['title'] ?? '') ?>">
      </div>

      <div class="col-md-6">
        <label class="form-label">Type</label>
        <select name="content_type" class="form-select">
          <?php
          $types=['link'=>'Link','pdf'=>'PDF','video'=>'Video','text'=>'Text','quiz'=>'Quiz','game'=>'Game'];
          $cur=$editing['content_type']??'link';
          foreach($types as $k=>$v){
            $sel = ($k===$cur) ? 'selected' : '';
            echo "<option value=\"".esc($k)."\" $sel>".esc($v)."</option>";
          }
          ?>
        </select>
      </div>

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

      <div class="col-md-6">
        <label class="form-label">URL (Link/Video/Quiz/Game)</label>
        <input type="url" name="url" class="form-control" placeholder="https://..."
               value="<?= esc($editing['url'] ?? '') ?>">
      </div>
      <div class="col-md-6">
        <label class="form-label">Upload file (optional)</label>
        <input type="file" name="file" class="form-control">
        <?php if (!empty($editing['file_path'])): ?>
          <small class="text-muted">Current:
            <a href="<?= esc(admin_file_href($editing['file_path'])) ?>" target="_blank" rel="noopener">download</a>
          </small>
        <?php endif; ?>
      </div>

      <div class="col-12 d-flex align-items-center gap-4">
        <label class="form-check">
          <input class="form-check-input" type="checkbox" name="active" <?= !empty($editing['active'])?'checked':'' ?>> Active
        </label>
        <label class="form-check">
          <input class="form-check-input" type="checkbox" name="require_paid" <?= !empty($editing['require_paid'])?'checked':'' ?>> Require paid
        </label>
      </div>

      <div class="col-12">
        <button class="btn btn-primary"><?= $editing ? 'Update' : 'Add Content' ?></button>
        <?php if ($editing): ?>
          <a class="btn btn-outline-secondary" href="content.php?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>">Cancel</a>
        <?php endif; ?>
      </div>
    </form>
  </div>
</div>

<script>
(function(){
  const list = document.getElementById('content-list');
  const saveBtn = document.getElementById('btn-save-order');

  if (list) {
    function markDirty(){ saveBtn.classList.remove('d-none'); }
    list.addEventListener('dragstart', e=>{
      const tr = e.target.closest('.content-row'); if (!tr) return;
      tr.classList.add('dragging'); e.dataTransfer.effectAllowed='move';
      e.dataTransfer.setData('text/plain', tr.dataset.id);
    });
    list.addEventListener('dragend', e=>{
      const tr = e.target.closest('.content-row'); if (tr) tr.classList.remove('dragging');
      markDirty();
    });
    list.addEventListener('dragover', e=>{
      e.preventDefault();
      const after = getAfter(list, e.clientY);
      const dragging = list.querySelector('.content-row.dragging');
      if (!dragging) return;
      if (after == null) list.appendChild(dragging);
      else list.insertBefore(dragging, after);
    });
    saveBtn.addEventListener('click', ()=>{
      const ids = Array.from(list.querySelectorAll('.content-row')).map(r=>r.dataset.id);
      fetch('content.php?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>', {
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body: JSON.stringify({ action:'reorder_content', ids })
      }).then(r=>r.json()).then(j=>{
        if (!j || !j.ok) alert((j && j.error) || 'Failed to save order');
        else saveBtn.classList.add('d-none');
      }).catch(err=>alert('Network error: '+err));
    });
  }

  function getAfter(container, y){
    const rows = [...container.querySelectorAll('.content-row:not(.dragging)')];
    let closest = { offset: Number.NEGATIVE_INFINITY, element: null };
    for (const row of rows){
      const box = row.getBoundingClientRect();
      const offset = y - box.top - box.height/2;
      if (offset < 0 && offset > closest.offset) closest = { offset, element: row };
    }
    return closest.element;
  }

  // Inline toggles (active/paid)
  document.addEventListener('click', (e)=>{
    const btn = e.target.closest('.toggle'); if (!btn) return;
    e.preventDefault();
    const id = btn.dataset.id, field = btn.dataset.field;
    const form = new FormData(); form.append('action','toggle'); form.append('id',id); form.append('field',field);
    fetch(location.href, { method:'POST', body:form })
      .then(r=>r.json()).then(j=>{
        if (j && j.ok) location.reload();
        else alert('Failed to toggle');
      }).catch(()=>alert('Network error'));
  });
})();
</script>

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