<?php
// /admin/batch_create.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;

/* Create (POST) */
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action'] ?? '')==='add') {
  $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       = 'Scheduled';

  if ($course_id && $name!=='' && $time_slot_id>0 && $start_date!=='') {
    $sql = "INSERT INTO batches (course_id,name,time_slot_id,start_date,end_date,capacity,status)
            VALUES (?,?,?,?,NULLIF(?, ''),?,?)";
    $st = mysqli_prepare($conn, $sql);
    if(!$st){ die("Prepare failed: ".mysqli_error($conn)); }
    if(!mysqli_stmt_bind_param($st, "isissis", $course_id, $name, $time_slot_id, $start_date, $end_date_raw, $capacity, $status)){
      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 created"));
    exit;
  } else {
    $err = "Please fill Course, Batch Name, Time Slot and Start Date.";
  }
}

admin_header('Create Batch');
?>
<h2 style="display:flex;align-items:center;gap:10px;margin:0 0 8px">
  Create Batch
  <a class="btn" href="batches_list.php">View All Batches</a>
</h2>

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

<div class="card col-12" style="position:relative;overflow:hidden">
  <div style="position:absolute;right:-24px;top:-24px;width:120px;height:120px;background:linear-gradient(135deg,#bfdbfe,#93c5fd);opacity:.25;border-radius:50%"></div>
  <h3 style="margin:0 0 12px;color:#2563eb">New Batch</h3>

  <form method="post" style="display:grid;gap:10px">
    <input type="hidden" name="action" value="add">

    <label>Course</label>
    <select name="course_id" required>
      <option value="">— Select Course —</option>
      <?php foreach($courses as $c): ?>
        <option value="<?=$c['id']?>"><?=h($c['name'])?></option>
      <?php endforeach; ?>
    </select>

    <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:10px">
      <div style="grid-column:span 6">
        <label>Batch Name</label>
        <input name="name" placeholder="WD-2025-A" required>
      </div>
      <div style="grid-column:span 6">
        <label>Time Slot</label>
        <select name="time_slot_id" required>
          <option value="">— Select —</option>
          <?php foreach($slots as $s):
            $label = $s['name'].' ('.substr($s['start_time'],0,5).'–'.substr($s['end_time'],0,5).', '.$s['days'].')';
          ?>
            <option value="<?=$s['id']?>"><?=$label?></option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>

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

    <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:10px">
      <div style="grid-column:span 6">
        <label>Capacity</label>
        <input type="number" name="capacity" value="20" min="1">
      </div>
      <div style="grid-column:span 6;display:flex;align-items:flex-end;justify-content:flex-end">
        <button class="btn primary" style="width:max-content">Create Batch</button>
      </div>
    </div>
  </form>
</div>

<?php admin_footer(); ?>
