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

// Logging function
function logAction($db2, $user, $action, $fleet_id, $details) {
    $full_details = "fleet_id=$fleet_id | " . $details; // Ensure fleet_id is included properly
    $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'];
    $road_tax_year = intval($_POST['road_tax_year']);
    $road_tax_date = strtotime($_POST['road_tax_date']); // Convert to epoch timestamp
    $fleet_rtax_cost = floatval($_POST['fleet_rtax_cost']);

    // Validate inputs
    if (!$fleet_id || !$road_tax_year || !$road_tax_date || !$fleet_rtax_cost) {
        echo json_encode(["success" => false, "message" => "Missing required fields"]);
        exit;
    }

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


    // Calculate the last day of the given tax year (31st December, 23:59:59)
    $end_of_year_timestamp = strtotime("31 December $road_tax_year 23:59:59");

    // Insert the new road tax record
    $insert_query = "INSERT INTO fleet_rtax (vfleet_id, road_tax, road_tax_date, fleet_rtax_cost) VALUES (?, ?, ?, ?)";
    if ($stmt = $db2->prepare($insert_query)) {
        $stmt->bind_param("iiid", $fleet_id, $road_tax_year, $road_tax_date, $fleet_rtax_cost);
        $success = $stmt->execute();
        $stmt->close();

        if ($success) {
            // Update the fleet table with the last day of the given tax year
            $update_query = "UPDATE fleet SET road_tax = ? WHERE fleet_id = ?";
            if ($stmt2 = $db2->prepare($update_query)) {
                $stmt2->bind_param("ii", $end_of_year_timestamp, $fleet_id);
                $stmt2->execute();
                $stmt2->close();
            }

            // Log the update action
            $log_details = "Added Road Tax: Year=$road_tax_year, Date Paid=" . date("d/m/Y", $road_tax_date) . ", Cost=$fleet_rtax_cost €";
            logAction($db2, $user, "Add Road Tax", $fleet_id, "Added Road Tax: Year=$road_tax_year, Date Paid=" . date("d/m/Y", $road_tax_date) . ", Cost=$fleet_rtax_cost €");


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