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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fleet_id = intval($_POST['api_fleet_id']);
    $partner_id = intval($_POST['api_fleet_partner']);
    $vehicle_id = intval($_POST['api_fleet_idcar']);
    $acriss = mysqli_real_escape_string($db2, $_POST['api_fleet_acriss']);
    $excess = mysqli_real_escape_string($db2, $_POST['api_fleet_excess']);

    // Validate unique ACRISS per partner
    $check_query = "SELECT COUNT(*) AS count FROM api_fleet 
                    WHERE api_fleet_partner = $partner_id AND api_fleet_acriss = '$acriss' AND api_fleet_id != $fleet_id";
    $check_result = mysqli_query($db2, $check_query);
    $check_row = mysqli_fetch_assoc($check_result);

    if ($check_row['count'] > 0) {
        echo json_encode(['success' => false, 'message' => 'This ACRISS code is already assigned to this partner.']);
        exit;
    }

    // Update the partner fleet
    $update_query = "UPDATE api_fleet 
                     SET api_fleet_partner = $partner_id, api_fleet_idcar = $vehicle_id, 
                         api_fleet_acriss = '$acriss', api_fleet_excess = '$excess' 
                     WHERE api_fleet_id = $fleet_id";

    if (mysqli_query($db2, $update_query)) {
        // Log the action
        $action = "Edit Partner Fleet";
        $details = "Edited Partner Fleet Vehicle (ID: $fleet_id, Partner ID: $partner_id, ACRISS: $acriss)";
        $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 updating partner fleet: ' . mysqli_error($db2)]);
    }
}
?>
