<?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'];
    $kteo_passed_date = strtotime($_POST['kteo_passed_date']);
    $kteo_date = strtotime($_POST['kteo_date']);
    $kteo_center = $_POST['kteo_center'];
    $kteo_cost = floatval($_POST['kteo_cost']);

    if (!$fleet_id || !$kteo_passed_date || !$kteo_date || !$kteo_center || !$kteo_cost) {
        echo json_encode(["success" => false, "message" => "Missing required fields"]);
        exit;
    }

    // Insert the new KTEO record
    $insert_query = "INSERT INTO fleet_kteo (vfleet_id, kteo_passed_date, kteo_date, kteo_center, kteo_cost) VALUES (?, ?, ?, ?, ?)";
    if ($stmt = $db2->prepare($insert_query)) {
        $stmt->bind_param("iiisd", $fleet_id, $kteo_passed_date, $kteo_date, $kteo_center, $kteo_cost);
        $success = $stmt->execute();
        $stmt->close();

        if ($success) {
            // Update fleet table with the latest next KTEO date
            $update_query = "UPDATE fleet SET fleet_kteo = ? WHERE fleet_id = ?";
            if ($stmt2 = $db2->prepare($update_query)) {
                $stmt2->bind_param("ii", $kteo_date, $fleet_id);
                $stmt2->execute();
                $stmt2->close();
            }

            // Log action
            logAction($db2, $user, "Add KTEO", $fleet_id, "Added KTEO: Passed=" . date("d/m/Y", $kteo_passed_date) . ", Next=" . date("d/m/Y", $kteo_date) . ", Center=$kteo_center, Cost=$kteo_cost €");

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