<?php
// pages/course_batch_picker.php
session_start();
require_once __DIR__ . '/../includes/db.php';

$db = isset($mysqli) && $mysqli instanceof mysqli ? $mysqli
   : (isset($conn) && $conn instanceof mysqli ? $conn : null);
if (!$db) { die('DB connection missing.'); }
$db->set_charset('utf8mb4');

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

// Preselects (optional): allow ?course_id=…&batch_id=…
$course_id = (int)($_GET['course_id'] ?? $_POST['course_id'] ?? 0);
$batch_id  = (int)($_GET['batch_id']  ?? $_POST['batch_id']  ?? 0);

// Load all courses
$courses = [];
$res = $db->query("SELECT id, course_name FROM courses ORDER BY course_name ASC");
while ($res && $row = $res->fetch_assoc()) $courses[] = $row;

// If course preselected, load its batches (server-side, for no-JS fallback)
$batches = [];
if ($course_id > 0) {
  $st = $db->prepare("SELECT id, batch_name FROM batches WHERE course_id=? ORDER BY batch_name ASC, id DESC");
  $st->bind_param("i", $course_id);
  $st->execute();
  $rs = $st->get_result();
  while ($rs && $r = $rs->fetch_assoc()) $batches[] = $r;
  $st->close();
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Select Course & Batch</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>.form-label{font-weight:600}</style>
</head>
<body class="bg-light">
<div class="container py-4" style="max-width:720px">
  <h4 class="mb-3">Enroll: Choose Course & Batch</h4>

  <form method="post" action="enroll_submit.php" class="card shadow-sm">
    <div class="card-body">
      <div class="mb-3">
        <label class="form-label">Course</label>
        <select class="form-select" name="course_id" id="course_id" required>
          <option value="">-- Select Course --</option>
          <?php foreach ($courses as $c): ?>
            <option value="<?= (int)$c['id'] ?>" <?= $course_id===$c['id'] ? 'selected' : '' ?>>
              <?= h($c['course_name']) ?>
            </option>
          <?php endforeach; ?>
        </select>
        <div class="form-text">Pick a course to see its batches.</div>
      </div>

      <div class="mb-3">
        <label class="form-label">Batch</label>
        <select class="form-select" name="batch_id" id="batch_id" <?= $course_id>0 ? '' : 'disabled' ?> required>
          <option value="">-- Select Batch --</option>
          <?php foreach ($batches as $b): ?>
            <option value="<?= (int)$b['id'] ?>" <?= $batch_id===$b['id'] ? 'selected' : '' ?>>
              <?= h($b['batch_name']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <!-- If you need to keep track of the student: -->
      <!-- <input type="hidden" name="student_id" value="<?= isset($_SESSION['student_id']) ? (int)$_SESSION['student_id'] : 0 ?>"> -->

      <div class="d-flex gap-2">
        <button class="btn btn-primary">Continue</button>
        <a class="btn btn-outline-secondary" href="dashboard.php">Cancel</a>
      </div>
    </div>
  </form>
</div>

<script>
  // AJAX-load batches when a course is selected
  $('#course_id').on('change', function() {
    const cid = $(this).val();
    const $batch = $('#batch_id');
    $batch.prop('disabled', true).html('<option value="">-- Select Batch --</option>');
    if (!cid) return;

    $.get('get_batches.php', { course_id: cid }, function(html){
      $batch.html(html).prop('disabled', false);
    }).fail(function(){
      alert('Failed to load batches.');
    });
  });
</script>
</body>
</html>
