<?php
include "../../include/auth.php"; // Ensure session & DB connection
include "../../include/lskfjwfe.php"; // Database connection
header("Content-Type: application/json");
ini_set('log_errors', 1);
ini_set('error_log', '../../php-error.log');

// Get admin username
session_start();
$username = $_SESSION['username'] ?? 'Unknown Admin';

if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["fleet_kteo_id"], $_POST["kteo_cost"])) {
    $fleet_kteo_id = intval($_POST["fleet_kteo_id"]);
    $kteo_cost = floatval($_POST["kteo_cost"]);

    if ($fleet_kteo_id <= 0 || $kteo_cost < 0) {
        error_log("❌ Invalid input: fleet_kteo_id={$fleet_kteo_id}, kteo_cost={$kteo_cost}");
        echo json_encode(["success" => false, "message" => "Invalid input values."]);
        exit;
    }

    // Retrieve the fleet_id linked to this fleet_kteo_id
    $fleet_query = $db2->prepare("SELECT vfleet_id FROM fleet_kteo WHERE fleet_kteo_id = ?");
    $fleet_query->bind_param("i", $fleet_kteo_id);
    $fleet_query->execute();
    $fleet_result = $fleet_query->get_result();
    
    if ($fleet_result->num_rows === 0) {
        error_log("❌ No fleet_id found for fleet_kteo_id={$fleet_kteo_id}");
        echo json_encode(["success" => false, "message" => "Fleet ID not found."]);
        exit;
    }
    
    $fleet_row = $fleet_result->fetch_assoc();
    $fleet_id = $fleet_row['vfleet_id']; // Get fleet_id

    // Update KTEO cost
    $query = $db2->prepare("UPDATE fleet_kteo SET kteo_cost = ? WHERE fleet_kteo_id = ?");
    if (!$query) {
        error_log("❌ SQL Prepare Error: " . $db2->error);
        echo json_encode(["success" => false, "message" => "Database error."]);
        exit;
    }

    $query->bind_param("di", $kteo_cost, $fleet_kteo_id);
    
    if ($query->execute()) {
        // Log action in admin logs
        $log_action = "Updated KTEO cost";
        $log_details = "fleet_id=$fleet_id, KTEO ID: $fleet_kteo_id, New Cost: $kteo_cost €";

        $log_query = $db2->prepare("INSERT INTO action_logs (user, action, details, timestamp) VALUES (?, ?, ?, NOW())");
        if ($log_query) {
            $log_query->bind_param("sss", $username, $log_action, $log_details);
            $log_query->execute();
        }

        echo json_encode(["success" => true]);
    } else {
        error_log("❌ SQL Execution Error: " . $query->error);
        echo json_encode(["success" => false, "message" => "Failed to update database."]);
    }
} else {
    error_log("❌ Invalid request method or missing parameters.");
    echo json_encode(["success" => false, "message" => "Invalid request."]);
}
?>
