<?php
include "../../include/auth.php"; // Authentication
include "../../include/lskfjwfe.php"; // Database connection

// Retrieve user from session
$user = isset($_SESSION['username']) && !empty($_SESSION['username']) ? htmlspecialchars($_SESSION['username']) : 'Unknown';

// Logging function
function logAction($db2, $user, $action, $fleet_id, $details) {
    $full_details = "fleet_id=$fleet_id | " . $details;
    $stmt = $db2->prepare("INSERT INTO action_logs (`user`, action, details) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $user, $action, $full_details);
    $stmt->execute();
    $stmt->close();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fleet_id = $_POST['fleet_id'];
    $fleet_active = $_POST['fleet_active'];
    $fleet_sold = $_POST['fleet_sold'];
    $fleet_sold_date = !empty($_POST['fleet_sold_date']) ? strtotime($_POST['fleet_sold_date']) : null;

    $query = "UPDATE fleet SET active = ?, fleet_sold = ?, fleet_sold_date = ? WHERE fleet_id = ?";
    if ($stmt = $db2->prepare($query)) {
        $stmt->bind_param("iiii", $fleet_active, $fleet_sold, $fleet_sold_date, $fleet_id);
        $success = $stmt->execute();
        $stmt->close();

        if ($success) {
            logAction($db2, $user, "Update Vehicle Details", $fleet_id, "Updated Active=$fleet_active, Sold=$fleet_sold, Sold Date=" . ($fleet_sold ? date("d/m/Y", $fleet_sold_date) : "N/A"));

            echo json_encode(["success" => true]);
        } else {
            echo json_encode(["success" => false, "message" => "Database update failed"]);
        }
    }
}
?>
