<?php
include('../include/lskfjwfe.php'); // Database connectivity

header('Content-Type: application/json');

$group_id = isset($_GET['group_id']) ? (int)$_GET['group_id'] : 0;

if ($group_id <= 0) {
    echo json_encode(["success" => false, "message" => "Invalid group ID"]);
    exit;
}

$query = "
    SELECT c.id AS car_id, 
           c.name AS model, 
           (SELECT COUNT(*) FROM fleet f WHERE f.veh_id = c.id AND f.active = 1) AS active_count 
    FROM car_availability_groups cag
    JOIN jostj_vikrentcar_cars c ON cag.car_id = c.id
    WHERE cag.avail_group = ?
";

$stmt = $db2->prepare($query);
$stmt->bind_param("i", $group_id);
$stmt->execute();
$result = $stmt->get_result();

$cars = [];
while ($row = $result->fetch_assoc()) {
    $cars[] = [
        "car_id" => $row["car_id"],
        "model" => $row["model"],
        "active_count" => $row["active_count"]
    ];
}

// Log the response for debugging
error_log("🚀 DEBUG: Response Data - " . json_encode($cars));

echo json_encode(["success" => true, "cars" => $cars]);

$stmt->close();
?>
