<?php

namespace App\Support;

class DeliveryPricing
{
    public const BASE_FARE = 50.0;        // MT, fixed base
    public const PER_KM = 12.0;           // MT per km
    public const WEIGHT_PER_KG = 5.0;     // MT per kg

    public const SIZE_MULTIPLIER = [
        'pequeno' => 1.0,
        'medio' => 1.5,
        'grande' => 2.0,
    ];

    /** Great-circle distance between two coordinates, in km. */
    public static function distanceKm(float $lat1, float $lng1, float $lat2, float $lng2): float
    {
        $earthRadius = 6371.0;
        $dLat = deg2rad($lat2 - $lat1);
        $dLng = deg2rad($lng2 - $lng1);
        $a = sin($dLat / 2) ** 2
            + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLng / 2) ** 2;

        return $earthRadius * 2 * atan2(sqrt($a), sqrt(1 - $a));
    }

    /** Estimated price (MT) from distance, package size and optional weight. */
    public static function estimate(float $distanceKm, string $tamanho, ?float $peso): float
    {
        $multiplier = self::SIZE_MULTIPLIER[$tamanho] ?? 1.0;
        $price = (self::BASE_FARE + $distanceKm * self::PER_KM) * $multiplier;
        $price += ($peso ?? 0.0) * self::WEIGHT_PER_KG;

        return round($price);
    }
}
