<?php
// /admin/batches_list.php
require_once __DIR__ . '/_auth.php';
require_once __DIR__ . '/_layout.php';

/* Lookups */
$courseRs = mysqli_query($conn, "SELECT id,name FROM courses WHERE is_active=1 ORDER BY name");
$courses = [];
while($courseRs && $row = mysqli_fetch_assoc($courseRs)) $courses[] = $row;

$slotRs = mysqli_query($conn, "SELECT id,name,start_time,end_time,days FROM time_slots WHERE is_active=1 ORDER BY start_time");
$slots = [];
while($slotRs && $r = mysqli_fetch_assoc($slotRs)) $slots[] = $r;

/* Actions (update/delete) */
if ($_SERVER['REQUEST_METHOD']==='POST') {
  $action = $_POST['action'] ?? '';

  // UPDATE
  if ($action === 'update') {
    $id           = (int)($_POST['id'] ?? 0);
    $course_id    = (int)($_POST['course_id'] ?? 0);
    $name         = trim($_POST['name'] ?? '');
    $time_slot_id = (int)($_POST['time_slot_id'] ?? 0);
    $start_date   = $_POST['start_date'] ?? '';
    $end_date_raw = $_POST['end_date'] ?? '';
    $capacity     = (int)($_POST['capacity'] ?? 20);
    $status_in    = $_POST['status'] ?? 'Scheduled';
    $status       = in_array($status_in, ['Scheduled','Ongoing','Completed','Cancelled'], true) ? $status_in : 'Scheduled';

    if ($id>0 && $course_id && $name!=='' && $time_slot_id>0 && $start_date!=='') {
      $sql = "UPDATE batches
                SET course_id=?, name=?, time_slot_id=?, start_date=?, end_date= NULLIF(?, ''), capacity=?, status=?
              WHERE id=?";
      $st = mysqli_prepare($conn, $sql);
      if(!$st){ die("Prepare failed: ".mysqli_error($conn)); }
      if(!mysqli_stmt_bind_param($st, "isissisi", $course_id, $name, $time_slot_id, $start_date, $end_date_raw, $capacity, $status, $id)){
        die("Bind failed: ".mysqli_stmt_error($st));
      }
      if(!mysqli_stmt_execute($st)){ die("Execute failed: ".mysqli_stmt_error($st)); }
      mysqli_stmt_close($st);

      header("Location: batches_list.php?msg=".urlencode("Batch updated"));
      exit;
    } else {
      header("Location: batches_list.php?err=".urlencode("All fields required for update."));
      exit;
    }
  }

  // DELETE (only if not referenced by registrations)
  if ($action === 'delete') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
      $ck = mysqli_prepare($conn, "SELECT COUNT(*) c FROM registrations WHERE batch_id=?");
      mysqli_stmt_bind_param($ck, "i", $id);
      mysqli_stmt_execute($ck);
      $res = mysqli_stmt_get_result($ck);
      $num = (int)mysqli_fetch_assoc($res)['c'];
      mysqli_stmt_close($ck);

      if ($num > 0) {
        header("Location: batches_list.php?err=".urlencode("Cannot delete: batch has registrations"));
        exit;
      }

      $del = mysqli_prepare($conn, "DELETE FROM batches WHERE id=?");
      mysqli_stmt_bind_param($del, "i", $id);
      mysqli_stmt_execute($del);
      mysqli_stmt_close($del);

      header("Location: batches_list.php?msg=".urlencode("Batch deleted"));
      exit;
    }
  }
}

/* Filters (GET) */
$filter_course = (int)($_GET['course_id'] ?? 0);
$filter_status = $_GET['status'] ?? '';
$filter_q      = trim($_GET['q'] ?? '');

/* List query */
$where = " WHERE 1=1 ";
if ($filter_course > 0) {
  $where .= " AND b.course_id = ".$filter_course." ";
}
if (in_array($filter_status, ['Scheduled','Ongoing','Completed','Cancelled'], true)) {
  $where .= " AND b.status = '".mysqli_real_escape_string($conn,$filter_status)."' ";
}
if ($filter_q !== '') {
  $qesc = mysqli_real_escape_string($conn, $filter_q);
  $where .= " AND (b.name LIKE '%$qesc%' OR c.name LIKE '%$qesc%') ";
}

$sqlList = "
SELECT 
  b.id, b.name, b.start_date, b.end_date, b.status, b.capacity,
  c.name AS course,
  ts.name AS slot_name, ts.start_time, ts.end_time, ts.days
FROM batches b
JOIN courses c ON c.id=b.course_id
LEFT JOIN time_slots ts ON ts.id=b.time_slot_id
$where
ORDER BY b.start_date DESC, b.id DESC
LIMIT 300
";
$rows = mysqli_query($conn, $sqlList);

admin_header('All Batches');
$msg = $_GET['msg'] ?? '';
$err = $_GET['err'] ?? '';
?>
<h2 style="display:flex;align-items:center;gap:10px;margin:0 0 8px">
  All Batches
  <a class="btn" href="batch_create.php">+ Create Batch</a>
</h2>

<?php if(!empty($msg)): ?>
  <div class="card mt-3" style="background:#eff6ff;border-color:#bfdbfe;color:#1e40af"><?= h($msg) ?></div>
<?php endif; ?>
<?php if(!empty($err)): ?>
  <div class="card mt-3" style="background:#fff1f2;border-color:#fecaca;color:#991b1b"><?= h($err) ?></div>
<?php endif; ?>

<div class="card col-12">
  <div style="display:flex;align-items:center;gap:8px;justify-content:space-between;margin-bottom:10px;flex-wrap:wrap">
    <h3 style="margin:0;color:#2563eb">Filter</h3>
    <form method="get" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
      <select name="course_id">
        <option value="0">Course: All</option>
        <?php foreach($courses as $c): ?>
          <option value="<?=$c['id']?>" <?=$filter_course==$c['id']?'selected':''?>><?=h($c['name'])?></option>
        <?php endforeach; ?>
      </select>
      <select name="status">
        <option value="">Status: All</option>
        <?php foreach(['Scheduled','Ongoing','Completed','Cancelled'] as $st): ?>
          <option <?=$filter_status===$st?'selected':''?>><?=$st?></option>
        <?php endforeach; ?>
      </select>
      <input name="q" value="<?=h($filter_q)?>" placeholder="Search batch/course..." style="max-width:220px">
      <button class="btn">Apply</button>
      <a class="btn" href="batches_list.php">Reset</a>
    </form>
  </div>

  <div style="overflow:auto;border-radius:10px;border:1px solid var(--border)">
    <table id="batchesTable" style="min-width:980px">
      <thead>
        <tr>
          <th>#</th>
          <th style="text-align:left">Batch</th>
          <th style="text-align:left">Course</th>
          <th style="text-align:left">Time Slot</th>
          <th>Start</th>
          <th>End</th>
          <th>Status</th>
          <th>Capacity</th>
          <th style="width:210px">Actions</th>
        </tr>
      </thead>
      <tbody>
      <?php
      $hasRows = false;
      while($r = mysqli_fetch_assoc($rows)):
        $hasRows = true;
        $slotLabel = '';
        if (!empty($r['slot_name'])) {
          $slotLabel = $r['slot_name'].' ('.substr($r['start_time'],0,5).'–'.substr($r['end_time'],0,5).', '.$r['days'].')';
        }
        $stBadge =
          $r['status']==='Ongoing'   ? '<span class="badge ok">Ongoing</span>' :
          ($r['status']==='Completed'? '<span class="badge blue" style="color:#0f172a">Completed</span>' :
          ($r['status']==='Cancelled'? '<span class="badge danger">Cancelled</span>' :
                                        '<span class="badge warn">Scheduled</span>'));
      ?>
        <tr class="row" id="row-<?=$r['id']?>">
          <td style="text-align:center"><?= (int)$r['id'] ?></td>
          <td class="bname" style="font-weight:600"><?= h($r['name']) ?></td>
          <td class="cname"><?= h($r['course']) ?></td>
          <td><?= h($slotLabel) ?></td>
          <td style="text-align:center"><?= h($r['start_date']) ?></td>
          <td style="text-align:center"><?= h($r['end_date'] ?: '-') ?></td>
          <td style="text-align:center"><?= $stBadge ?></td>
          <td style="text-align:right"><?= (int)$r['capacity'] ?></td>
          <td style="text-align:center;white-space:nowrap">
            <button class="btn editBtn" data-id="<?=$r['id']?>" style="padding:6px 10px;border-color:#bfdbfe">Edit</button>
            <form method="post" style="display:inline" onsubmit="return confirm('Delete this batch? This action cannot be undone.');">
              <input type="hidden" name="action" value="delete">
              <input type="hidden" name="id" value="<?=$r['id']?>">
              <button class="btn" style="padding:6px 10px;margin-left:6px;border-color:#fecaca;color:#991b1b">Delete</button>
            </form>
          </td>
        </tr>

        <!-- Inline editor -->
        <tr id="edit-<?=$r['id']?>" class="editRow" style="display:none;background:#f8fafc">
          <td colspan="9">
            <form method="post" style="display:grid;gap:10px">
              <input type="hidden" name="action" value="update">
              <input type="hidden" name="id" value="<?=$r['id']?>">

              <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:10px">
                <div style="grid-column:span 3">
                  <label>Course</label>
                  <select name="course_id" required>
                    <?php foreach($courses as $c): ?>
                      <option value="<?=$c['id']?>" <?=$c['name']===$r['course']?'selected':''?>><?=h($c['name'])?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div style="grid-column:span 3">
                  <label>Batch Name</label>
                  <input name="name" value="<?=h($r['name'])?>" required>
                </div>
                <div style="grid-column:span 3">
                  <label>Time Slot</label>
                  <select name="time_slot_id" required>
                    <?php foreach($slots as $s):
                      $label2 = $s['name'].' ('.substr($s['start_time'],0,5).'–'.substr($s['end_time'],0,5).', '.$s['days'].')';
                    ?>
                      <option value="<?=$s['id']?>" <?=(strpos($slotLabel,$s['name'])===0?'selected':'')?>><?=$label2?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div style="grid-column:span 3">
                  <label>Status</label>
                  <select name="status">
                    <?php foreach(['Scheduled','Ongoing','Completed','Cancelled'] as $st): ?>
                      <option <?=$r['status']===$st?'selected':''?>><?=$st?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
              </div>

              <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:10px">
                <div style="grid-column:span 3">
                  <label>Start Date</label>
                  <input type="date" name="start_date" value="<?=h($r['start_date'])?>" required>
                </div>
                <div style="grid-column:span 3">
                  <label>End Date</label>
                  <input type="date" name="end_date" value="<?=h($r['end_date'])?>">
                </div>
                <div style="grid-column:span 3">
                  <label>Capacity</label>
                  <input type="number" name="capacity" value="<?= (int)$r['capacity'] ?>" min="1">
                </div>
                <div style="grid-column:span 3; display:flex;align-items:flex-end;justify-content:flex-end">
                  <button class="btn primary" style="height:38px">Save</button>
                </div>
              </div>
            </form>
          </td>
        </tr>
      <?php endwhile; ?>

      <?php if(!$hasRows): ?>
        <tr><td colspan="9" style="text-align:center;padding:24px;color:#64748b">No batches found.</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<script>
// Toggle inline editor
document.querySelectorAll('.editBtn').forEach(btn=>{
  btn.addEventListener('click', ()=>{
    const id = btn.dataset.id;
    const row = document.getElementById('edit-'+id);
    document.querySelectorAll('.editRow').forEach(r=>{ if(r!==row) r.style.display='none'; });
    row.style.display = (row.style.display==='none' || row.style.display==='') ? 'table-row' : 'none';
    row.scrollIntoView({behavior:'smooth', block:'center'});
  });
});
</script>

<?php admin_footer(); ?>
