<?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'];
    $ins_company = $_POST['ins_company'];
    $ins_from = strtotime($_POST['ins_from']);
    $ins_until = strtotime($_POST['ins_until']);
    $ins_cost = floatval($_POST['ins_cost']);

    if (!$fleet_id || !$ins_company || !$ins_from || !$ins_until || $_POST['ins_cost'] === '') {
        echo json_encode(["success" => false, "message" => "Missing required fields"]);
        exit;
    }

    // Insert the new insurance record
    $insert_query = "INSERT INTO fleet_insurance (vfleet_id, ins_company, ins_from, ins_until, ins_cost) VALUES (?, ?, ?, ?, ?)";
    if ($stmt = $db2->prepare($insert_query)) {
        $stmt->bind_param("isssd", $fleet_id, $ins_company, $ins_from, $ins_until, $ins_cost);
        $success = $stmt->execute();
        $stmt->close();

        if ($success) {
            // Update fleet table with latest insurance period
            $update_query = "UPDATE fleet SET fleet_insurance_from = ?, fleet_insurance_until = ? WHERE fleet_id = ?";
            if ($stmt2 = $db2->prepare($update_query)) {
                $stmt2->bind_param("iii", $ins_from, $ins_until, $fleet_id);
                $stmt2->execute();
                $stmt2->close();
            }

            // Log action
            logAction($db2, $user, "Add Insurance", $fleet_id, "Added Insurance: Company=$ins_company, From=" . date("d/m/Y", $ins_from) . ", Until=" . date("d/m/Y", $ins_until) . ", Cost=$ins_cost €");

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