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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $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'";
    $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;
    }

    // Insert the new partner fleet
    $insert_query = "INSERT INTO api_fleet (api_fleet_partner, api_fleet_idcar, api_fleet_acriss, api_fleet_excess) 
                     VALUES ($partner_id, $vehicle_id, '$acriss', '$excess')";

    if (mysqli_query($db2, $insert_query)) {
        // Log the action
        $action = "Add Partner Fleet";
        $details = "Added Partner Fleet Vehicle (Partner ID: $partner_id, Vehicle ID: $vehicle_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 adding partner fleet: ' . mysqli_error($db2)]);
    }
}
?>
