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

/* ========== Actions ========== */

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

  if ($action === 'add') {
    $name = trim($_POST['name'] ?? '');
    $start = trim($_POST['start_time'] ?? '');
    $end   = trim($_POST['end_time'] ?? '');
    $days  = trim($_POST['days'] ?? '');
    if ($name !== '' && $start !== '' && $end !== '' && $days !== '') {
      $st = mysqli_prepare($conn, "INSERT INTO time_slots(name,start_time,end_time,days,is_active) VALUES (?,?,?,?,1)");
      mysqli_stmt_bind_param($st, "ssss", $name, $start, $end, $days);
      mysqli_stmt_execute($st);
      mysqli_stmt_close($st);
      header("Location: time_slots.php?msg=" . urlencode("Time Slot added")); exit;
    }
  }

  if ($action === 'toggle') {
    $id = (int)($_POST['id'] ?? 0);
    $next = (int)($_POST['next'] ?? 0);
    if ($id > 0) {
      $st = mysqli_prepare($conn, "UPDATE time_slots SET is_active=? WHERE id=?");
      mysqli_stmt_bind_param($st, "ii", $next, $id);
      mysqli_stmt_execute($st);
      mysqli_stmt_close($st);
      header("Location: time_slots.php?msg=" . urlencode("Status updated")); exit;
    }
  }

  if ($action === 'delete') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
      // soft check: only delete if not referenced by batches.time_slot_id
      $ck = mysqli_prepare($conn, "SELECT COUNT(*) c FROM batches WHERE time_slot_id=?");
      mysqli_stmt_bind_param($ck, "i", $id);
      mysqli_stmt_execute($ck);
      $r = mysqli_stmt_get_result($ck);
      $num = (int)mysqli_fetch_assoc($r)['c'];
      mysqli_stmt_close($ck);
      if ($num === 0) {
        $del = mysqli_prepare($conn, "DELETE FROM time_slots WHERE id=?");
        mysqli_stmt_bind_param($del, "i", $id);
        mysqli_stmt_execute($del);
        mysqli_stmt_close($del);
        header("Location: time_slots.php?msg=" . urlencode("Time Slot deleted")); exit;
      } else {
        header("Location: time_slots.php?msg=" . urlencode("Cannot delete: slot linked to batches")); exit;
      }
    }
  }
}

// load
$slots = mysqli_query($conn, "SELECT id,name,start_time,end_time,days,is_active FROM time_slots ORDER BY is_active DESC, start_time ASC");
admin_header('Time Slots');
$msg = $_GET['msg'] ?? '';
?>
<h2 style="display:flex;align-items:center;gap:10px;margin:0 0 8px">
  Time Slots
  <span style="font-size:12px;font-weight:600;color:#2563eb;background:#dbeafe;border:1px solid #bfdbfe;border-radius:999px;padding:2px 8px">Create & manage</span>
</h2>

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

<div class="grid mt-3">
  <!-- Add Slot -->
  <div class="card col-6" style="position:relative;overflow:hidden">
    <div style="position:absolute;right:-20px;top:-20px;width:110px;height:110px;background:linear-gradient(135deg,#bfdbfe,#93c5fd);opacity:.25;border-radius:50%"></div>
    <h3 style="margin:0 0 12px;color:#2563eb">Add Time Slot</h3>

    <form method="post" style="display:grid;gap:10px">
      <input type="hidden" name="action" value="add">
      <label>Name</label>
      <input name="name" placeholder="e.g. Morning, Evening" required>

      <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:10px">
        <div style="grid-column:span 6">
          <label>Start</label>
          <input type="time" name="start_time" required>
        </div>
        <div style="grid-column:span 6">
          <label>End</label>
          <input type="time" name="end_time" required>
        </div>
      </div>

      <label>Days</label>
      <select name="days" required>
        <option value="">— Select —</option>
        <option>Mon-Fri</option>
        <option>Sat-Sun</option>
        <option>Daily</option>
        <option>Mon, Wed, Fri</option>
        <option>Tue, Thu</option>
      </select>

      <button class="btn primary mt-2" style="width:max-content">Add Slot</button>
      <div style="font-size:12px;color:#475569">Tip: Active slots will be available when creating batches/admissions.</div>
    </form>
  </div>

  <!-- List Slots -->
  <div class="card col-6">
    <div style="display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:10px">
      <h3 style="margin:0;color:#2563eb">All Time Slots</h3>
      <input id="slotSearch" placeholder="Search by name/day..." style="max-width:240px">
    </div>

    <div style="overflow:auto;border-radius:10px;border:1px solid var(--border)">
      <table id="slotsTable" style="min-width:680px">
        <thead>
          <tr>
            <th style="background:#f1f5f9">#</th>
            <th style="background:#f1f5f9;text-align:left">Name</th>
            <th style="background:#f1f5f9">Start</th>
            <th style="background:#f1f5f9">End</th>
            <th style="background:#f1f5f9;text-align:left">Days</th>
            <th style="background:#f1f5f9">Status</th>
            <th style="background:#f1f5f9;width:200px">Actions</th>
          </tr>
        </thead>
        <tbody>
        <?php
        $has = false;
        while($s = mysqli_fetch_assoc($slots)):
          $has = true;
          $active = (int)$s['is_active'] === 1;
          $badge = $active
            ? '<span style="background:#dcfce7;color:#166534;border:1px solid #86efac;padding:3px 8px;border-radius:999px;font-size:12px;font-weight:700">Active</span>'
            : '<span style="background:#fee2e2;color:#991b1b;border:1px solid #fecaca;padding:3px 8px;border-radius:999px;font-size:12px;font-weight:700">Inactive</span>';
        ?>
          <tr class="row">
            <td style="text-align:center"><?= (int)$s['id'] ?></td>
            <td class="name" style="font-weight:600"><?= h($s['name']) ?></td>
            <td style="text-align:center"><?= substr($s['start_time'],0,5) ?></td>
            <td style="text-align:center"><?= substr($s['end_time'],0,5) ?></td>
            <td class="days"><?= h($s['days']) ?></td>
            <td style="text-align:center"><?= $badge ?></td>
            <td style="text-align:center; white-space:nowrap">
              <form method="post" style="display:inline">
                <input type="hidden" name="action" value="toggle">
                <input type="hidden" name="id" value="<?= (int)$s['id'] ?>">
                <input type="hidden" name="next" value="<?= $active ? 0 : 1 ?>">
                <button class="btn" style="padding:6px 10px" onclick="return confirm('<?= $active? 'Deactivate':'Activate' ?> this slot?')">
                  <?= $active ? 'Deactivate' : 'Activate' ?>
                </button>
              </form>

              <form method="post" style="display:inline;margin-left:6px" onsubmit="return confirm('Delete this slot?');">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?= (int)$s['id'] ?>">
                <button class="btn" style="padding:6px 10px;border-color:#fecaca;color:#991b1b">Delete</button>
              </form>
            </td>
          </tr>
        <?php endwhile; ?>
        <?php if(!$has): ?>
          <tr><td colspan="7" style="text-align:center;padding:24px;color:#64748b">No time slots yet. Add from the left.</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>

    <div style="display:flex;justify-content:flex-end;font-size:12px;color:#64748b;margin-top:8px">
      Tip: Use the search box to quickly filter slots.
    </div>
  </div>
</div>

<script>
// filter by name/days
const s = document.getElementById('slotSearch');
const rows = [...document.querySelectorAll('#slotsTable tbody tr.row')];
s.addEventListener('input', () => {
  const q = s.value.trim().toLowerCase();
  rows.forEach(r => {
    const name = (r.querySelector('.name')?.textContent || '').toLowerCase();
    const days = (r.querySelector('.days')?.textContent || '').toLowerCase();
    r.style.display = (name.includes(q) || days.includes(q)) ? '' : 'none';
  });
});
</script>

<?php admin_footer(); ?>
