<?php
declare(strict_types=1);
// ============================================================
// shipping/quote.php — Cotización de envío con Skydropx PRO
// ============================================================
require_once __DIR__ . '/../config.php';

// Solo POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonErr(405, 'Método no permitido.');
}

// Validar token del usuario
$payload = auth();

$data = body();
$cp_destino  = trim($data['cp_destino']  ?? '');
$cp_origen   = trim($data['cp_origen']   ?? '45160'); // CP de Zapopan (sede principal RRB)
$peso_gramos = (float)($data['peso_gramos'] ?? 0);

if (!$cp_destino) {
    jsonErr(400, 'cp_destino es requerido.');
}
if ($peso_gramos <= 0) {
    jsonErr(400, 'peso_gramos debe ser mayor a 0.');
}

// Convertir gramos a KG (mínimo 0.1 KG para Skydropx)
$peso_kg = max(round($peso_gramos / 1000, 3), 0.1);

// Credenciales Skydropx PRO (client_credentials para cotizaciones)
define('SKYDROPX_CLIENT_ID',     '0ErQV1SYQIFLt9XY8HOyC7AyW81ggP1AUs1CpVzA7bY');
define('SKYDROPX_CLIENT_SECRET', 'eC3okv6-hIqBbyg9jKA8V_RiZwQ_3624ZQSjEEC-N5o');
define('SKYDROPX_API_URL',       'https://pro.skydropx.com');

// Paqueterías permitidas (filtro)
$PAQUETERIAS_PERMITIDAS = ['ampm', 'estafeta', 'fedex', 'paqueteexpress', 'paquete express'];

// ─── Helpers cURL ────────────────────────────────────────────────────────────
function skyRequest(string $method, string $path, ?array $body = null, string $token = ''): array {
    $ch = curl_init(SKYDROPX_API_URL . $path);
    $headers = ['Content-Type: application/json'];
    if ($token) {
        $headers[] = 'Authorization: Bearer ' . $token;
    }
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 20,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_HTTPHEADER     => $headers,
    ]);
    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    }
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ['code' => $code, 'body' => json_decode($resp ?: '{}', true)];
}

// ─── Paso 1: Obtener Bearer token de Skydropx ────────────────────────────────
$tokenResp = skyRequest('POST', '/api/v1/oauth/token', [
    'grant_type'    => 'client_credentials',
    'client_id'     => SKYDROPX_CLIENT_ID,
    'client_secret' => SKYDROPX_CLIENT_SECRET,
]);

if ($tokenResp['code'] !== 200 || empty($tokenResp['body']['access_token'])) {
    jsonErr(502, 'No se pudo autenticar con Skydropx.');
}
$skyToken = $tokenResp['body']['access_token'];

// ─── Paso 2: Obtener datos del CP destino ────────────────────────────────────
// Usar la API pública de Sepomex para obtener estado/municipio/colonia
$cpUrl = "https://sepomex.icalialabs.com/api/v1/zip_codes?zip_code=" . urlencode($cp_destino);
$cpResp = @file_get_contents($cpUrl);
$cpData = $cpResp ? json_decode($cpResp, true) : null;

$area1 = 'México';
$area2 = 'México';
$area3 = 'Centro';

if (!empty($cpData['zip_codes'][0])) {
    $cp = $cpData['zip_codes'][0];
    $area1 = $cp['d_estado']  ?? $area1;
    $area2 = $cp['d_mnpio']   ?? $area2;
    $area3 = $cp['d_asenta']  ?? $area3;
}

// Datos del CP de origen (Zapopan - sede principal RRB)
$origenArea1 = 'Jalisco';
$origenArea2 = 'Zapopan';
$origenArea3 = 'Plaza Patria';

// ─── Paso 3: Crear cotización ────────────────────────────────────────────────
$quoteResp = skyRequest('POST', '/api/v1/quotations', [
    'quotation' => [
        'address_from' => [
            'area_level1'      => 'Jalisco',
            'area_level2'      => 'Zapopan',
            'area_level3'      => 'Plaza Patria',
            'name'             => 'Enrique Zaragoza',
            'postal_code'      => '45160',
            'country_code'     => 'MX',
            'street1'          => 'Mexico Independiente 499',
            'company'          => 'RRB Mexico',
            'phone'            => '3336244770',
            'email'            => 'contacto@rrbmexico.com',
            'reference'        => 'En esquina',
            'address_type'     => 'from',
            'apartment_number' => '',
        ],
        'address_to' => [
            'area_level1'      => $area1,
            'area_level2'      => $area2,
            'area_level3'      => $area3,
            'name'             => 'Cliente',
            'postal_code'      => $cp_destino,
            'country_code'     => 'MX',
            'street1'          => 'Calle destino',
            'company'          => 'Cliente',
            'phone'            => '3300000000',
            'email'            => 'cliente@sistemarrb.com',
            'reference'        => 'Destino',
            'address_type'     => 'to',
            'apartment_number' => '',
        ],
        'parcels' => [[
            'length' => 30,
            'width'  => 25,
            'height' => 20,
            'weight' => $peso_kg,
        ]],
    ],
], $skyToken);

if (!in_array($quoteResp['code'], [200, 201])) {
    jsonErr(502, 'Error al cotizar: ' . ($quoteResp['body']['message'] ?? 'Error desconocido'));
}

$quotationId = $quoteResp['body']['id'];

// ─── Paso 4: Polling para obtener tarifas completas ──────────────────────────
$rates = [];
for ($i = 0; $i < 4; $i++) {
    usleep(1500000); // 1.5 segundos
    $pollResp = skyRequest('GET', "/api/v1/quotations/{$quotationId}", null, $skyToken);

    if ($pollResp['code'] === 200) {
        $pollData = $pollResp['body'];
        $rates = $pollData['rates'] ?? [];
        if (!empty($pollData['is_completed'])) {
            break;
        }
    }
}

// ─── Paso 5: Filtrar y formatear tarifas ─────────────────────────────────────
$tarifas = [];
foreach ($rates as $rate) {
    if (empty($rate['success']) || empty($rate['amount']) || floatval($rate['amount']) <= 0) {
        continue;
    }

    // Filtrar solo las paqueterías permitidas
    $providerName = strtolower($rate['provider_display_name'] ?? $rate['provider_name'] ?? '');
    $permitida = false;
    foreach ($PAQUETERIAS_PERMITIDAS as $p) {
        if (str_contains($providerName, $p)) {
            $permitida = true;
            break;
        }
    }
    if (!$permitida) continue;

    $tarifas[] = [
        'id'       => $rate['id']                    ?? '',
        'provider' => $rate['provider_display_name'] ?? $rate['provider_name'] ?? '',
        'servicio' => $rate['provider_service_name'] ?? '',
        'total'    => (int)($rate['total']         ?? $rate['amount']),
        'dias'     => (int)($rate['days']            ?? 0),
        'moneda'   => $rate['currency_code']         ?? 'MXN',
    ];
}

// Ordenar por precio
usort($tarifas, fn($a, $b) => $a['total'] <=> $b['total']);

jsonOk([
    'cotizacion_id' => $quotationId,
    'peso_kg'       => $peso_kg,
    'cp_origen'     => $cp_origen,
    'cp_destino'    => $cp_destino,
    'area_destino'  => "{$area2}, {$area1}",
    'tarifas'       => $tarifas,
]);
