<?php
declare(strict_types=1);

function autoCalculateVehicleBaselines(PDO $pdo, int $vehicleId): void
{
    $stmt = $pdo->prepare("
        SELECT
            SUM(COALESCE(quantity_litres, dispensed_litres, fuel_purchase_liters, 0)) AS total_liters,
            SUM(COALESCE(distance_km, mileage_km, monthly_mileage_km, 0)) AS total_km,
            AVG(COALESCE(quantity_litres, dispensed_litres, fuel_purchase_liters, 0)) AS avg_monthly_liters
        FROM vehicle_fuel_entries
        WHERE vehicle_id = ?
          AND month_year >= DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 12 MONTH), '%Y-%m')
    ");
    $stmt->execute([$vehicleId]);
    $data = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$data || !$data['total_km'] || (float)$data['total_km'] <= 0) {
        return;
    }

    $autoEfficiency = round(((float)$data['total_liters'] / (float)$data['total_km']) * 100, 2);
    $autoStandard = round((float)$data['avg_monthly_liters'], 2);

    $check = $pdo->prepare("SELECT id FROM vehicle_fuel_config WHERE vehicle_id = ?");
    $check->execute([$vehicleId]);
    $existingId = $check->fetchColumn();

    if ($existingId) {
        $update = $pdo->prepare("UPDATE vehicle_fuel_config SET efficiency_baseline = ?, standard_consumption = ? WHERE vehicle_id = ?");
        $update->execute([$autoEfficiency, $autoStandard, $vehicleId]);
    } else {
        $insert = $pdo->prepare("INSERT INTO vehicle_fuel_config (vehicle_id, efficiency_baseline, standard_consumption, auto_calculate_baseline, created_at) VALUES (?, ?, ?, 1, NOW())");
        $insert->execute([$vehicleId, $autoEfficiency, $autoStandard]);
    }
}
