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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fleet_id = intval($_POST['fleet_id']);
    $fleet_kteo = empty($_POST['fleet_kteo']) ? 'NULL' : strtotime($_POST['fleet_kteo']);
    $insurance_from = empty($_POST['fleet_insurance_from']) ? 'NULL' : strtotime($_POST['fleet_insurance_from']);
    $insurance_until = empty($_POST['fleet_insurance_until']) ? 'NULL' : strtotime($_POST['fleet_insurance_until']);
    $ins_company = mysqli_real_escape_string($db2, $_POST['fleet_ins_company']);
    $fleet_sold = intval($_POST['fleet_sold']);
    $sold_date = empty($_POST['fleet_sold_date']) ? 'NULL' : strtotime($_POST['fleet_sold_date']);
    $road_tax = empty($_POST['road_tax']) ? 'NULL' : strtotime($_POST['road_tax']);

    $update_query = "UPDATE fleet 
                     SET fleet_kteo = $fleet_kteo, 
                         fleet_insurance_from = $insurance_from, 
                         fleet_insurance_until = $insurance_until, 
                         fleet_ins_company = '$ins_company', 
                         fleet_sold = $fleet_sold, 
                         fleet_sold_date = $sold_date, 
                         road_tax = $road_tax 
                     WHERE fleet_id = $fleet_id";

    if (mysqli_query($db2, $update_query)) {
        // Log the action
        $action = "Update Vehicle Details";
        $details = "Updated details for 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 updating details: ' . mysqli_error($db2)]);
    }
}
?>
