<?php
/**
 * compra-envio-cotizar.php
 * POST → cotiza envío con Skydropx PRO
 * Body: { cp_destino, peso_gramos }
 * Devuelve: { ok, cotizacion_id, tarifas: [{id, provider, servicio, total, dias}] }
 *
 * Ruta: public_html/app-api/admin/api/
 * config.php: public_html/app-api/config.php  → ../../config.php
 */
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

require_once __DIR__ . '/../../config.php';
$db = getDB();

// ── Validar token ─────────────────────────────────────────────────────────────
$headers    = getallheaders();
$authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
if (!preg_match('/Bearer\s+(.+)/i', $authHeader, $m)) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Token requerido']);
    exit;
}
$token = trim($m[1]);
$stmtTok = $db->prepare("SELECT idusuarios_sist FROM admin_sessions WHERE token = ? AND expira > NOW()");
$stmtTok->execute([$token]);
if (!$stmtTok->fetch()) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Sesion invalida o expirada']);
    exit;
}

$b           = json_decode(file_get_contents('php://input'), true) ?? [];
$cp_destino  = trim($b['cp_destino']  ?? '');
$peso_gramos = (float)($b['peso_gramos'] ?? 0);

if (!$cp_destino) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'cp_destino es requerido']);
    exit;
}
if ($peso_gramos <= 0) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'peso_gramos debe ser mayor a 0']);
    exit;
}

// Credenciales Skydropx PRO — cotizaciones
define('SKY_CLIENT_ID',     '0ErQV1SYQIFLt9XY8HOyC7AyW81ggP1AUs1CpVzA7bY');
define('SKY_CLIENT_SECRET', 'eC3okv6-hIqBbyg9jKA8V_RiZwQ_3624ZQSjEEC-N5o');
define('SKY_API_URL',       'https://pro.skydropx.com');

// Paqueterías permitidas
$PAQUETERIAS = ['ampm', 'estafeta', 'fedex', 'paqueteexpress', 'paquete express'];

// ── Helper cURL ───────────────────────────────────────────────────────────────
function skyReq(string $method, string $path, ?array $body = null, string $tok = ''): array {
    $ch = curl_init(SKY_API_URL . $path);
    $hdrs = ['Content-Type: application/json'];
    if ($tok) $hdrs[] = 'Authorization: Bearer ' . $tok;
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 25,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_HTTPHEADER     => $hdrs,
    ]);
    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)];
}

try {
    // Paso 1: Obtener Bearer token
    $tokResp = skyReq('POST', '/api/v1/oauth/token', [
        'grant_type'    => 'client_credentials',
        'client_id'     => SKY_CLIENT_ID,
        'client_secret' => SKY_CLIENT_SECRET,
    ]);
    if ($tokResp['code'] !== 200 || empty($tokResp['body']['access_token'])) {
        echo json_encode(['ok' => false, 'error' => 'No se pudo autenticar con Skydropx']);
        exit;
    }
    $skyToken = $tokResp['body']['access_token'];

    // Paso 2: Obtener datos del CP destino (Sepomex)
    $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;
    }

    // Paso 3: Crear cotización
    $pesoKg = max(round($peso_gramos / 1000, 3), 0.1);
    $quoteResp = skyReq('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',
            ],
            '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',
            ],
            'parcels' => [[
                'length' => 30,
                'width'  => 25,
                'height' => 20,
                'weight' => $pesoKg,
            ]],
        ],
    ], $skyToken);

    if (!in_array($quoteResp['code'], [200, 201])) {
        echo json_encode(['ok' => false, 'error' => 'Error al cotizar con Skydropx: ' . ($quoteResp['body']['message'] ?? 'Error desconocido')]);
        exit;
    }

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

    // Paso 4: Polling para obtener tarifas completas (hasta 4 intentos × 1.5s)
    $rates = [];
    for ($i = 0; $i < 4; $i++) {
        usleep(1500000);
        $pollResp = skyReq('GET', "/api/v1/quotations/{$quotationId}", null, $skyToken);
        if ($pollResp['code'] === 200) {
            $rates = $pollResp['body']['rates'] ?? [];
            if (!empty($pollResp['body']['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;
        $provName  = strtolower($rate['provider_display_name'] ?? $rate['provider_name'] ?? '');
        $permitida = false;
        foreach ($PAQUETERIAS as $p) {
            if (str_contains($provName, $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)round($rate['total'] ?? $rate['amount']),
            'dias'     => (int)($rate['days'] ?? 0),
        ];
    }
    usort($tarifas, fn($a, $b) => $a['total'] <=> $b['total']);

    echo json_encode([
        'ok'           => true,
        'cotizacion_id' => $quotationId,
        'peso_kg'      => $pesoKg,
        'area_destino' => "{$area2}, {$area1}",
        'tarifas'      => $tarifas,
    ], JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
