<?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 idcat for the vehicle
    $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 = $vehicle['idcat'];

    // Convert categories to an array
    $category_array = explode(';', trim($current_categories, ';'));

    // Check if category is already assigned
    if (in_array($category_id, $category_array)) {
        echo "Vehicle is already in this category.";
        exit;
    }

    // Append new category and update database
    $category_array[] = $category_id;
    $updated_idcat = implode(';', array_filter($category_array)) . ';';

    $update_query = "UPDATE jostj_vikrentcar_cars SET idcat = '$updated_idcat' WHERE id = $vehicle_id";
    if (mysqli_query($db2, $update_query)) {
        // Log the action
        $action = "Add Vehicle to Category";
        $details = "Vehicle ID: $vehicle_id added to 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 added to the category.";
    } else {
        echo "Error updating database.";
    }
} else {
    echo "Invalid request.";
}
?>
