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

if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $vehicle_id = intval($_GET['id']);

    // Check if the vehicle is in any reservation
    $reservation_check_query = "SELECT COUNT(*) AS reservation_count FROM jostj_vikrentcar_orders WHERE idcar = $vehicle_id";
    $reservation_check_result = mysqli_query($db2, $reservation_check_query);
    $reservation_check_row = mysqli_fetch_assoc($reservation_check_result);

    if ($reservation_check_row['reservation_count'] > 0) {
        echo "<script>
            alert('Cannot delete vehicle. It is part of a reservation.');
            window.location.href = '../fleet.php';
        </script>";
        exit;
    }

    // Log the vehicle details before deletion
    $vehicle_query = "SELECT * FROM jostj_vikrentcar_cars WHERE id = $vehicle_id";
    $vehicle_result = mysqli_query($db2, $vehicle_query);
    $vehicle = mysqli_fetch_assoc($vehicle_result);
    $vehicle_name = $vehicle['name'];

    // Delete the vehicle
    $delete_query = "DELETE FROM jostj_vikrentcar_cars WHERE id = $vehicle_id";
    if (mysqli_query($db2, $delete_query)) {
        // Log the action
        $action = "Delete Vehicle";
        $details = "Deleted vehicle: $vehicle_name (ID: $vehicle_id)";
        $log_query = "INSERT INTO action_logs (action, details, user, timestamp) VALUES ('$action', '$details', '$user', NOW())";
        mysqli_query($db2, $log_query);

        echo "<script>
            alert('Vehicle deleted successfully.');
            window.location.href = '../fleet.php';
        </script>";
    } else {
        echo "<script>
            alert('Error deleting vehicle: " . mysqli_error($db2) . "');
            window.history.back();
        </script>";
    }
} else {
    echo "<script>
        alert('Invalid request.');
        window.history.back();
    </script>";
}
?>
