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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $category_id = intval($_POST['category_id']);
    $vehicle_id = intval($_POST['vehicle_id']);

    // Fetch current categories
    $vehicle_query = "SELECT idcat FROM jostj_vikrentcar_cars WHERE id = $vehicle_id";
    $result = mysqli_query($db2, $vehicle_query);
    $vehicle = mysqli_fetch_assoc($result);
    $current_categories = trim($vehicle['idcat'], ';');

    // Convert to array, remove the category, and rebuild the string
    $category_array = explode(';', $current_categories);
    $updated_categories = array_filter($category_array, function ($cat) use ($category_id) {
        return $cat != $category_id;
    });

    $new_idcat = implode(';', $updated_categories);
    if (!empty($new_idcat)) {
        $new_idcat .= ';';
    }

    // Update database
    $update_query = "UPDATE jostj_vikrentcar_cars SET idcat = '$new_idcat' WHERE id = $vehicle_id";
    if (mysqli_query($db2, $update_query)) {
        // Log the action
        $action = "Remove Vehicle from Category";
        $details = "Vehicle ID: $vehicle_id removed from Category ID: $category_id";
        $log_query = "INSERT INTO action_logs (action, details, user) VALUES ('$action', '$details', '$user')";
        mysqli_query($db2, $log_query);

        echo "Vehicle successfully removed from the category.";
    } else {
        echo "Error updating database.";
    }
} else {
    echo "Invalid request.";
}
?>
