<?php
/* ELMS Admin ▸ Courses ▸ Quick Add
 * - Add a Module (optional) + add one Content item fast
 * - Safe for mixed schemas (lms_modules/course_modules, lms_content/module_contents…)
 * - Respect elms_module_semesters (module_id, semester_no, position, updated_at)
 * - No RMS access.
 */
declare(strict_types=1);
if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/../../includes/db.php';
if (is_file(__DIR__ . '/../../includes/auth.php')) {
  require_once __DIR__ . '/../../includes/auth.php';
  if (function_exists('require_role')) require_role(['super_admin','branch_admin']);
}

/* ---------- helpers ---------- */
function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }
function t_exists(mysqli $db,string $t):bool{
  $t=$db->real_escape_string($t);
  $sql="SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='$t' LIMIT 1";
  $res=$db->query($sql); $ok=$res && $res->num_rows>0; if($res){$res->close();} return $ok;
}
function c_exists(mysqli $db,string $t,string $c):bool{
  $t=$db->real_escape_string($t); $c=$db->real_escape_string($c);
  $sql="SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='$t' AND COLUMN_NAME='$c' LIMIT 1";
  $res=$db->query($sql); $ok=$res && $res->num_rows>0; if($res){$res->close();} return $ok;
}
function first_col(mysqli $db,string $tbl,array $cands,string $fallback='id'): string {
  foreach ($cands as $c) if (c_exists($db,$tbl,$c)) return $c;
  return $fallback;
}
function ensure_dir(string $path): bool {
  return is_dir($path) || @mkdir($path, 0775, true);
}
function app_url_base(): string {
  // simple base guesser without app.php
  $proto = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
  $host  = $_SERVER['HTTP_HOST'] ?? 'localhost';
  $root  = rtrim(dirname(dirname($_SERVER['SCRIPT_NAME'] ?? '/elms/admin/')), '/'); // .. from /admin/courses
  return $proto.$host.$root;
}
function file_to_public_url(string $stored): string {
  $stored = ltrim(str_replace('\\','/',$stored), '/');
  $base   = rtrim(app_url_base(), '/');
  if (strpos($stored,'uploads/') === 0) return $base.'/'.$stored;
  return $base.'/uploads/content/'.$stored;
}
function redirect_self(array $params=[]): void {
  $q = $_GET;
  foreach($params as $k=>$v) $q[$k]=$v;
  $url = strtok($_SERVER['REQUEST_URI'], '?') . ($q?'?'.http_build_query($q):'');
  header("Location: $url"); exit;
}

/* ---------- discover tables/columns ---------- */
$MOD_TBL = t_exists($mysqli,'lms_modules') ? 'lms_modules' : (t_exists($mysqli,'course_modules') ? 'course_modules' : null);
if (!$MOD_TBL) { http_response_code(500); exit('No modules table.'); }
$MOD_ID   = 'id';
$MOD_TITLE= first_col($mysqli,$MOD_TBL,['title','module_name','name'],'id');
$MOD_ORDER= first_col($mysqli,$MOD_TBL,['sort_order','position','seq_no'],'id');

$CONTENT_TBL = null;
foreach (['lms_content','lms_contents','lms_module_contents','module_contents','lms_content_items'] as $x) {
  if (t_exists($mysqli,$x)) { $CONTENT_TBL=$x; break; }
}
if (!$CONTENT_TBL) { http_response_code(500); exit('No content table found.'); }
$C_ID     = c_exists($mysqli,$CONTENT_TBL,'id') ? 'id' : (c_exists($mysqli,$CONTENT_TBL,'content_id') ? 'content_id' : 'id');
$C_MID    = c_exists($mysqli,$CONTENT_TBL,'module_id') ? 'module_id' : (c_exists($mysqli,$CONTENT_TBL,'lms_module_id') ? 'lms_module_id' : null);
if (!$C_MID)         { http_response_code(500); exit('Content table missing module_id column.'); }
$C_TITLE  = first_col($mysqli,$CONTENT_TBL,['title','name','topic'],'title');
$C_DESC   = first_col($mysqli,$CONTENT_TBL,['description','details','desc'],'description');
$C_TYPE   = first_col($mysqli,$CONTENT_TBL,['type','content_type','file_type'],'type');
$C_URL    = first_col($mysqli,$CONTENT_TBL,['file_url','url','content_url','path','filename','file_path'],'url');
$C_ACTIVE = c_exists($mysqli,$CONTENT_TBL,'is_released') ? 'is_released' : (c_exists($mysqli,$CONTENT_TBL,'active') ? 'active' : null);
$C_PAID   = first_col($mysqli,$CONTENT_TBL,['require_paid','paid'],'require_paid');

$HAS_SEM_MAP = t_exists($mysqli,'elms_module_semesters'); // (module_id PK, semester_no, position, updated_at)

/* ---------- load courses ---------- */
$courses=[];
if (t_exists($mysqli,'courses')) {
  $q = $mysqli->query("SELECT id, COALESCE(course_name, CONCAT('Course ',id)) AS label FROM courses ORDER BY label");
  while($r=$q->fetch_assoc()) $courses[] = $r;
}
$course_id = (int)($_GET['course_id'] ?? 0);
if (!$course_id && $courses) $course_id = (int)$courses[0]['id'];

/* ---------- load modules for selected course ---------- */
$modules=[];
if ($course_id>0) {
  $st=$mysqli->prepare("SELECT $MOD_ID AS id, `$MOD_TITLE` AS title FROM `$MOD_TBL` WHERE course_id=? ORDER BY `$MOD_ORDER`, id");
  $st->bind_param('i',$course_id); $st->execute();
  $rs=$st->get_result(); while($m=$rs->fetch_assoc()) $modules[]=$m; $st->close();
}

/* ---------- POST: add module ---------- */
if (($_SERVER['REQUEST_METHOD']??'')==='POST' && ($_POST['action']??'')==='add_module') {
  $cid = (int)($_POST['course_id'] ?? 0);
  $title = trim((string)($_POST['title'] ?? ''));
  $semno = max(1, (int)($_POST['semester_no'] ?? 1));

  if ($cid>0 && $title!=='') {
    // next order
    $next=1;
    if ($stmt=$mysqli->prepare("SELECT COALESCE(MAX(`$MOD_ORDER`),0)+1 FROM `$MOD_TBL` WHERE course_id=?")) {
      $stmt->bind_param('i',$cid); $stmt->execute(); $stmt->bind_result($next); $stmt->fetch(); $stmt->close();
    }
    $ins=$mysqli->prepare("INSERT INTO `$MOD_TBL`(course_id,`$MOD_TITLE`,`$MOD_ORDER`) VALUES (?,?,?)");
    $ins->bind_param('isi',$cid,$title,$next); $ins->execute(); $mid=$ins->insert_id; $ins->close();

    if ($mid && $HAS_SEM_MAP) {
      // position = next highest within this semester
      $pos=1;
      $q=$mysqli->prepare("SELECT COALESCE(MAX(position),0)+1 FROM elms_module_semesters WHERE semester_no=?");
      $q->bind_param('i',$semno); $q->execute(); $q->bind_result($pos); $q->fetch(); $q->close();

      // upsert by module_id PK
      $up=$mysqli->prepare("INSERT INTO elms_module_semesters (module_id, semester_no, position) VALUES (?,?,?)
                            ON DUPLICATE KEY UPDATE semester_no=VALUES(semester_no), position=VALUES(position)");
      $up->bind_param('iii',$mid,$semno,$pos); $up->execute(); $up->close();
    }
    redirect_self(['course_id'=>$cid,'ok'=>'module']);
  }
}

/* ---------- POST: add content ---------- */
if (($_SERVER['REQUEST_METHOD']??'')==='POST' && ($_POST['action']??'')==='add_content') {
  $cid = (int)($_POST['course_id'] ?? 0);
  $mid = (int)($_POST['module_id'] ?? 0);
  $title = trim((string)($_POST['c_title'] ?? ''));
  $type  = trim((string)($_POST['c_type'] ?? 'Link'));
  $desc  = trim((string)($_POST['c_desc'] ?? ''));
  $url   = trim((string)($_POST['c_url'] ?? ''));
  $active= isset($_POST['c_active']) ? 1 : 0;
  $paid  = isset($_POST['c_paid'])   ? 1 : 0;

  // file upload (optional) → /uploads/content
  if (!empty($_FILES['c_file']['name']) && is_uploaded_file($_FILES['c_file']['tmp_name'])) {
    $safeName = preg_replace('~[^a-zA-Z0-9._-]+~','_', $_FILES['c_file']['name']);
    $name = date('Ymd_His').'__'.substr(sha1($safeName.microtime(true)),0,6).'__'.$safeName;
    $destDir = dirname(__DIR__,2).'/uploads/content';
    if (ensure_dir($destDir)) {
      $destPath = rtrim($destDir,'/').'/'.$name;
      if (move_uploaded_file($_FILES['c_file']['tmp_name'], $destPath)) {
        $url = 'uploads/content/'.$name; // store relative path; we’ll render as absolute in student views
      }
    }
  }

  if ($cid>0 && $mid>0 && $title!=='') {
    // build dynamic insert according to discovered columns
    $cols = [$C_MID,$C_TITLE];
    $vals = ['?','?'];
    $bind = 'is';
    $args = [$mid,$title];

    if ($C_DESC)   { $cols[]=$C_DESC; $vals[]='?'; $bind.='s'; $args[]=$desc; }
    if ($C_TYPE)   { $cols[]=$C_TYPE; $vals[]='?'; $bind.='s'; $args[]=$type; }
    if ($C_URL)    { $cols[]=$C_URL;  $vals[]='?'; $bind.='s'; $args[]=$url;  }
    if ($C_ACTIVE) { $cols[]=$C_ACTIVE; $vals[]='?'; $bind.='i'; $args[]=$active; }
    if ($C_PAID)   { $cols[]=$C_PAID;   $vals[]='?'; $bind.='i'; $args[]=$paid;   }

    $sql = "INSERT INTO `$CONTENT_TBL` (`".implode('`,`',$cols)."`) VALUES (".implode(',',$vals).")";
    $stmt=$mysqli->prepare($sql);
    $stmt->bind_param($bind, ...$args);
    $stmt->execute(); $stmt->close();
    redirect_self(['course_id'=>$cid,'ok'=>'content','module_id'=>$mid]);
  }
}

/* ---------- layout (keeps your admin chrome) ---------- */
$PAGE_TITLE='Quick Add';
$ACTIVE_MENU='courses';
$__layoutOpened=false;
foreach(['../includes/admin_layout_top.php','../../includes/admin_layout_top.php','../../includes/layout_top.php','../../includes/header_admin.php'] as $try){
  $p = realpath(__DIR__.'/'.$try);
  if ($p && is_file($p)) { require $p; $__layoutOpened=true; break; }
}
if(!$__layoutOpened) echo '<div class="container-fluid p-3">';

?>
<style>
  .qa-card{background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:12px;margin-bottom:12px}
  .muted{color:#6b7280}
</style>

<div class="d-flex align-items-center justify-content-between mb-3">
  <h1 class="h5 m-0">Courses ▸ Quick Add</h1>
  <a class="btn btn-sm btn-outline-secondary" href="index.php">← Back</a>
</div>

<?php if (isset($_GET['ok'])): ?>
  <div class="alert alert-success py-2 mb-3">
    <?= $_GET['ok']==='module' ? 'Module added.' : 'Content added.' ?>
  </div>
<?php endif; ?>

<div class="qa-card">
  <form method="get" class="row g-2">
    <div class="col-sm-6 col-md-4">
      <label class="form-label">Course</label>
      <select name="course_id" class="form-select" onchange="this.form.submit()">
        <?php foreach($courses as $c): ?>
          <option value="<?= (int)$c['id'] ?>" <?= $course_id===(int)$c['id']?'selected':'' ?>>
            <?= esc($c['label']) ?>
          </option>
        <?php endforeach; ?>
      </select>
    </div>
  </form>
</div>

<?php if ($course_id<=0): ?>
  <div class="qa-card muted">Pick a course above.</div>
<?php else: ?>

  <!-- Add Module -->
  <div class="qa-card">
    <h6 class="mb-2">Add Module</h6>
    <form method="post" class="row g-2">
      <input type="hidden" name="action" value="add_module">
      <input type="hidden" name="course_id" value="<?= (int)$course_id ?>">
      <div class="col-md-6">
        <label class="form-label">Module title</label>
        <input type="text" name="title" class="form-control" placeholder="e.g. Fundamentals of Computing" required>
      </div>
      <div class="col-md-2">
        <label class="form-label">Semester No</label>
        <input type="number" name="semester_no" class="form-control" value="1" min="1">
        <?php if(!$HAS_SEM_MAP): ?>
          <div class="form-text">Tip: <code>elms_module_semesters</code> not found? Create it to group by number.</div>
        <?php endif; ?>
      </div>
      <div class="col-md-2 d-flex align-items-end">
        <button class="btn btn-primary">+ Add Module</button>
      </div>
    </form>
  </div>

  <!-- Add Content -->
  <div class="qa-card">
    <h6 class="mb-2">Add Content</h6>
    <form method="post" enctype="multipart/form-data" class="row g-2">
      <input type="hidden" name="action" value="add_content">
      <input type="hidden" name="course_id" value="<?= (int)$course_id ?>">

      <div class="col-md-4">
        <label class="form-label">Module</label>
        <select name="module_id" class="form-select" required>
          <option value="">— pick module —</option>
          <?php foreach($modules as $m): ?>
            <option value="<?= (int)$m['id'] ?>" <?= isset($_GET['module_id']) && (int)$_GET['module_id']===(int)$m['id'] ? 'selected':'' ?>>
              <?= esc($m['title']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="col-md-4">
        <label class="form-label">Title</label>
        <input type="text" name="c_title" class="form-control" placeholder="e.g. Binary Number Game" required>
      </div>

      <div class="col-md-2">
        <label class="form-label">Type</label>
        <select name="c_type" class="form-select">
          <option>Video</option>
          <option>PDF</option>
          <option>Image</option>
          <option>Audio</option>
          <option selected>Link</option>
          <option>Game</option>
          <option>Quiz</option>
        </select>
      </div>

      <div class="col-md-6">
        <label class="form-label">URL (Link / Game / Video …)</label>
        <input type="url" name="c_url" class="form-control" placeholder="https://… (or leave blank if uploading a file)">
      </div>

      <div class="col-md-4">
        <label class="form-label">Upload file (optional)</label>
        <input type="file" name="c_file" class="form-control">
        <div class="form-text">Stored under <code>/uploads/content</code></div>
      </div>

      <div class="col-md-8">
        <label class="form-label">Description</label>
        <textarea name="c_desc" class="form-control" rows="2" placeholder="Short description…"></textarea>
      </div>

      <div class="col-md-4 d-flex align-items-center gap-3">
        <div class="form-check">
          <input class="form-check-input" type="checkbox" name="c_active" id="c_active" checked>
          <label class="form-check-label" for="c_active">Active</label>
        </div>
        <div class="form-check">
          <input class="form-check-input" type="checkbox" name="c_paid" id="c_paid">
          <label class="form-check-label" for="c_paid">Require paid</label>
        </div>
      </div>

      <div class="col-12 d-flex justify-content-end">
        <button class="btn btn-success">+ Add Content</button>
      </div>
    </form>

    <div class="mt-2 small text-muted">
      Tip: for Games paste a URL (H5P, itch.io embed, Construct/Unity web build, Wordwall, etc.) or upload a packaged file
      and choose <em>Type = Game</em>.
    </div>
  </div>

<?php endif; ?>

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