<?php
// get_batches_by_course.php
include("../includes/db.php");

$course_id = isset($_GET['course_id']) ? intval($_GET['course_id']) : 0;
$batches = [];

if ($course_id > 0) {
    $today = date('Y-m-d');
    $stmt = $conn->prepare("
        SELECT b.id, b.batch_name, b.batch_start_date, b.batch_end_date, 
               b.total_seat_count, 
               COUNT(e.id) AS filled_seats
        FROM batches b
        LEFT JOIN enrollments e ON e.batch_id = b.id
        WHERE b.course_id=? 
        AND b.registration_open_date <= ? 
        AND b.registration_close_date >= ?
        GROUP BY b.id
        ORDER BY b.batch_start_date ASC
    ");
    $stmt->bind_param("iss", $course_id, $today, $today);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $available = $row['total_seat_count'] - $row['filled_seats'];
        $row['available_seats'] = $available;
        $row['display_text'] = $row['batch_name'] . " (" . $row['batch_start_date'] . " - " . $row['batch_end_date'] . ") – Seats Left: " . $available;
        $batches[] = $row;
    }

    $stmt->close();
}

// Return JSON
header('Content-Type: application/json');
echo json_encode($batches);
