<?php
declare(strict_types=1);
// ============================================================
// shipping/track.php — Consultar estado de rastreo de un pedido
// ============================================================
require_once __DIR__ . '/../config.php';

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

$payload = auth();
$idtransacciones = (int)($_GET['id'] ?? 0);

if (!$idtransacciones) {
    jsonErr(400, 'id de transacción requerido.');
}

$db = getDB();

// Verificar que la transacción pertenece al usuario y obtener datos de envío
$stmt = $db->prepare(
    "SELECT t.idtransacciones, t.skydropx_shipment_id, t.tracking_number,
            t.label_url, t.carrier, t.statusentrega
     FROM transacciones t
     JOIN inventario i ON i.id_inv = t.inversionista_id_inver
     WHERE t.idtransacciones = ? AND i.ci = ?"
);
$stmt->execute([$idtransacciones, $payload['ci']]);
$tx = $stmt->fetch();

if (!$tx) {
    jsonErr(403, 'Transacción no encontrada o sin permisos.');
}

if (empty($tx['skydropx_shipment_id'])) {
    jsonOk([
        'tiene_envio'    => false,
        'tracking_number'=> null,
        'carrier'        => null,
        'label_url'      => null,
        'status'         => $tx['statusentrega'] ?? 'PENDIENTE',
        'eventos'        => [],
    ]);
}

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

function skyGet(string $path, string $token): array {
    $ch = curl_init(SKYDROPX_API_URL . $path);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_HTTPHEADER     => ['Authorization: Bearer ' . $token],
    ]);
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ['code' => $code, 'body' => json_decode($resp ?: '{}', true)];
}

// Obtener token
$tokenResp = (function() {
    $ch = curl_init(SKYDROPX_API_URL . '/api/v1/oauth/token');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
        CURLOPT_POSTFIELDS     => json_encode([
            'grant_type'    => 'client_credentials',
            'client_id'     => SKYDROPX_CLIENT_ID,
            'client_secret' => SKYDROPX_CLIENT_SECRET,
        ]),
    ]);
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ['code' => $code, 'body' => json_decode($resp ?: '{}', true)];
})();

if ($tokenResp['code'] !== 200 || empty($tokenResp['body']['access_token'])) {
    // Si no podemos conectar a Skydropx, devolver los datos guardados en DB
    jsonOk([
        'tiene_envio'    => true,
        'tracking_number'=> $tx['tracking_number'],
        'carrier'        => $tx['carrier'],
        'label_url'      => $tx['label_url'],
        'status'         => $tx['statusentrega'] ?? 'EN_TRANSITO',
        'eventos'        => [],
        'fuente'         => 'cache',
    ]);
}

$skyToken = $tokenResp['body']['access_token'];

// Consultar el shipment en Skydropx
$shipResp = skyGet('/api/v1/shipments/' . $tx['skydropx_shipment_id'], $skyToken);

if ($shipResp['code'] !== 200) {
    // Devolver datos guardados si falla la consulta
    jsonOk([
        'tiene_envio'    => true,
        'tracking_number'=> $tx['tracking_number'],
        'carrier'        => $tx['carrier'],
        'label_url'      => $tx['label_url'],
        'status'         => $tx['statusentrega'] ?? 'EN_TRANSITO',
        'eventos'        => [],
        'fuente'         => 'cache',
    ]);
}

$ship = $shipResp['body'];
$status   = strtoupper($ship['status'] ?? 'PENDIENTE');
$eventos  = $ship['tracking_events'] ?? $ship['events'] ?? [];

// Mapear status de Skydropx a texto amigable
$statusMap = [
    'PENDING'     => 'PENDIENTE',
    'TRANSIT'     => 'EN_TRANSITO',
    'IN_TRANSIT'  => 'EN_TRANSITO',
    'DELIVERED'   => 'ENTREGADO',
    'RETURNED'    => 'DEVUELTO',
    'EXCEPTION'   => 'EXCEPCION',
    'CANCELLED'   => 'CANCELADO',
    'OUT_FOR_DELIVERY' => 'EN_CAMINO',
];
$statusAmigable = $statusMap[$status] ?? $status;

// Actualizar status en DB si cambió
if ($statusAmigable !== ($tx['statusentrega'] ?? '')) {
    $db->prepare("UPDATE transacciones SET statusentrega = ? WHERE idtransacciones = ?")
       ->execute([$statusAmigable, $idtransacciones]);
}

// Formatear eventos de rastreo
$eventosFormateados = array_map(function($ev) {
    return [
        'fecha'       => $ev['occurred_at'] ?? $ev['date'] ?? '',
        'descripcion' => $ev['description'] ?? $ev['message'] ?? '',
        'ubicacion'   => $ev['location'] ?? '',
    ];
}, array_slice($eventos, 0, 10));

jsonOk([
    'tiene_envio'    => true,
    'tracking_number'=> $tx['tracking_number'],
    'carrier'        => $tx['carrier'],
    'label_url'      => $tx['label_url'],
    'status'         => $statusAmigable,
    'status_raw'     => $status,
    'eventos'        => $eventosFormateados,
    'fuente'         => 'live',
]);
