<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/tarifas_helpers.php';

header('Content-Type: application/json; charset=utf-8');

function dinamicas_float_query(string $key): ?float
{
    if (!isset($_GET[$key])) {
        return null;
    }

    $value = str_replace(',', '.', trim((string) $_GET[$key]));
    return is_numeric($value) ? (float) $value : null;
}

function dinamicas_distancia_km(float $lat1, float $lng1, float $lat2, float $lng2): float
{
    $earthKm = 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 $earthKm * (2 * atan2(sqrt($a), sqrt(max(0.0, 1.0 - $a))));
}

try {
    $lat = dinamicas_float_query('lat') ?? dinamicas_float_query('latitude');
    $lng = dinamicas_float_query('lng') ?? dinamicas_float_query('longitude');
    $raioKm = dinamicas_float_query('raio_km') ?? 35.0;
    $raioKm = max(5.0, min(80.0, $raioKm));

    $celulas = tarifas_dinamicas_ativas(db());
    if ($lat !== null && $lng !== null) {
        $celulas = array_values(array_filter($celulas, static function (array $celula) use ($lat, $lng, $raioKm): bool {
            $centro = $celula['centro'] ?? null;
            if (!is_array($centro) || !isset($centro['lat'], $centro['lng'])) {
                return true;
            }

            return dinamicas_distancia_km(
                $lat,
                $lng,
                (float) $centro['lat'],
                (float) $centro['lng']
            ) <= $raioKm;
        }));
    }

    echo json_encode([
        'success' => true,
        'dinamicas' => $celulas,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Erro ao carregar dinamica.',
    ], JSON_UNESCAPED_UNICODE);
}
