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

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

$data = json_decode(file_get_contents("php://input"), true);

if (!isset($data['group_id']) || !isset($data['model_name'])) {
    echo json_encode(["success" => false, "message" => "Invalid request."]);
    exit;
}

$groupId = mysqli_real_escape_string($db2, $data['group_id']);
$modelName = mysqli_real_escape_string($db2, $data['model_name']);

// Find the Car ID by Model Name
$sqlFindCar = "SELECT id FROM jostj_vikrentcar_cars WHERE name = '$modelName' LIMIT 1";
$resultFindCar = mysqli_query($db2, $sqlFindCar);

if (!$resultFindCar || mysqli_num_rows($resultFindCar) == 0) {
    echo json_encode(["success" => false, "message" => "Model not found."]);
    exit;
}

$carRow = mysqli_fetch_assoc($resultFindCar);
$carId = $carRow['id'];

// Remove the Car from Group
$sqlDelete = "DELETE FROM car_availability_groups WHERE car_id = '$carId' AND avail_group = '$groupId'";
if (mysqli_query($db2, $sqlDelete)) {

    // Log the action
    $action = "Remove Model from Group";
    $details = "Removed model '$modelName' (ID: $carId) from group (ID: $groupId)";
    $logQuery = "INSERT INTO action_logs (action, details, user, timestamp) VALUES ('$action', '$details', '$userid', NOW())";
    mysqli_query($db2, $logQuery);

    echo json_encode(["success" => true, "message" => "Model removed successfully."]);
} else {
    echo json_encode(["success" => false, "message" => "Database error: " . mysqli_error($db2)]);
}
?>
