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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    $fleet_id = intval($data['fleet_id']);

    // Validate the vehicle can be deleted
    $validate_query = "SELECT veh_id FROM fleet WHERE fleet_id = $fleet_id";
    $validate_result = mysqli_query($db2, $validate_query);

    if ($validate_row = mysqli_fetch_assoc($validate_result)) {
        $veh_id = $validate_row['veh_id'];

        $contract_check_query = "SELECT COUNT(*) AS contract_count FROM contracts WHERE vehfleet_id = $veh_id";
        $contract_check_result = mysqli_query($db2, $contract_check_query);
        $contract_check_row = mysqli_fetch_assoc($contract_check_result);

        if ($contract_check_row['contract_count'] > 0) {
            echo json_encode(['success' => false, 'message' => 'Vehicle cannot be deleted as it is linked to active contracts.']);
            exit;
        }

        // Proceed to delete
        $delete_query = "DELETE FROM fleet WHERE fleet_id = $fleet_id";
        if (mysqli_query($db2, $delete_query)) {
            // Log the action
            $action = "Delete Vehicle from Fleet";
            $details = "Deleted Vehicle (fleet_id: $fleet_id)";
            $log_query = "INSERT INTO action_logs (action, details, user, timestamp) 
                          VALUES ('$action', '$details', '$user', NOW())";
            mysqli_query($db2, $log_query);

            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Error deleting vehicle: ' . mysqli_error($db2)]);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Vehicle not found.']);
    }
}
?>
