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

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

$groupId = $_POST['group_id'] ?? null;
$modelId = $_POST['model_id'] ?? null;

if (!$groupId || !$modelId) {
    echo json_encode(["success" => false, "message" => "Missing required data."]);
    exit;
}

// Check if the model is already in the group
$checkQuery = "SELECT * FROM car_availability_groups WHERE car_id = '$modelId' AND avail_group = '$groupId'";
$resultCheck = mysqli_query($db2, $checkQuery);

if (mysqli_num_rows($resultCheck) > 0) {
    echo json_encode(["success" => false, "message" => "Model is already in this group."]);
    exit;
}

// Insert the model into the group
$insertQuery = "INSERT INTO car_availability_groups (car_id, avail_group) VALUES ('$modelId', '$groupId')";
if (mysqli_query($db2, $insertQuery)) {

    // Log the action
    $action = "Add Model to Group";
    $details = "Added model ID '$modelId' to 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 added successfully."]);
} else {
    echo json_encode(["success" => false, "message" => "Database error: " . mysqli_error($db2)]);
}
?>
