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

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

    // Parse the current idcat and update only the second part
    $idcat_parts = explode(';', $current_idcat);
    $idcat_parts[1] = $new_subcategory_id; // Replace the subcategory ID
    $updated_idcat = implode(';', $idcat_parts); // Rebuild the idcat string

    $update_query = "UPDATE jostj_vikrentcar_cars SET idcat = '$updated_idcat;' WHERE id = $vehicle_id";

    if (mysqli_query($db2, $update_query)) {
        // Log the action
        $action = "Edit Vehicle Subcategory";
        $details = "Updated idcat for vehicle $vehicle_id to $updated_idcat";
        $log_query = "INSERT INTO action_logs (action, details, user) VALUES ('$action', '$details', '$user')";
        mysqli_query($db2, $log_query);

        echo "<script>
            alert('Vehicle subcategory updated successfully.');
            window.location.href = '../category_vehicles.php?category_id={$idcat_parts[0]}';
        </script>";
    } else {
        echo "<script>
            alert('Error updating vehicle subcategory: " . mysqli_error($db2) . "');
            window.location.href = '../category_vehicles.php?category_id={$idcat_parts[0]}';
        </script>";
    }
}
?>
