<?php
/**
 * shipping/create.php  — v3
 * Crea una orden en Skydropx PRO.
 *
 * Campos que recibe del app:
 *   idtransacciones      int     ID de la transacción
 *   cotizacion_id        string  ID de la cotización Skydropx
 *   rate_id              string  ID de la tarifa seleccionada
 *   generar_guia         bool    true = guía inmediata (tarjeta), false = solo orden
 *   idinv                int     ID del distribuidor
 *   contacto_tel         string  Teléfono del destinatario
 *   contacto_email       string  Correo del destinatario
 *   peso_gramos          int     Peso total del pedido en gramos
 *   carrier              string  Proveedor de paquetería
 *   service_level_code   string  Código de servicio
 *   direccion            object  {calle, noExt, noInt, colonia, ciudad, estado, cp, pais}
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// ─── Configuración ────────────────────────────────────────────────────────────
define('SKYDROPX_BASE',          'https://pro.skydropx.com');
define('SKYDROPX_CLIENT_ID',     'QsgcphLaKKrD3G-qKyMLvIG7EJD1mcJBL5J0o_jX_Cs');
define('SKYDROPX_CLIENT_SECRET', 'DpY8SEx925sqxt78DCIqrYpwhBtiqBDRdk0bNSKRD1M');
define('LOG_FILE', __DIR__ . '/create_log.txt');

// Dirección del remitente (almacén RRB México)
define('SHIPPER_ADDRESS',    'Mexico Independiente 499');
define('SHIPPER_NUMBER',     '');
define('SHIPPER_REFERENCIA', 'En esquina');
define('SHIPPER_COLONIA',    'Plaza Patria');
define('SHIPPER_CIUDAD',     'Zapopan');
define('SHIPPER_ESTADO',     'Jalisco');
define('SHIPPER_CP',         '45160');
define('SHIPPER_NOMBRE',     'Enrique Zaragoza');
define('SHIPPER_EMPRESA',    'RRB Mexico');
define('SHIPPER_TELEFONO',   '3336244770');
define('SHIPPER_EMAIL',      'contacto@rrbmexico.com');

// ─── Log ──────────────────────────────────────────────────────────────────────
function logMsg($msg) {
    $line = '[' . date('Y-m-d H:i:s') . '] ' . $msg . "\n";
    file_put_contents(LOG_FILE, $line, FILE_APPEND);
}

// ─── cURL helper ─────────────────────────────────────────────────────────────
function skydropxRequest($method, $url, $data, $token = null) {
    $headers = ['Content-Type: application/json'];
    if ($token) {
        $headers[] = 'Authorization: Bearer ' . $token;
    }
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_POSTFIELDS     => ($data !== null) ? json_encode($data) : null,
        CURLOPT_HTTPHEADER     => $headers,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    $resp     = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err      = curl_error($ch);
    curl_close($ch);
    return ['code' => $httpCode, 'body' => $resp, 'error' => $err];
}

// ─── Incluir config BD ────────────────────────────────────────────────────────
$configPath = __DIR__ . '/../config.php';
if (!file_exists($configPath)) {
    logMsg("ERROR: config.php no encontrado en $configPath");
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'config.php not found']);
    exit;
}
require_once $configPath;

// ─── Leer input JSON ──────────────────────────────────────────────────────────
$raw   = file_get_contents('php://input');
$input = json_decode($raw, true);

if (!$input) {
    logMsg("ERROR: JSON inválido. Raw: $raw");
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Invalid JSON']);
    exit;
}

logMsg("=== Nueva solicitud ===");
logMsg("Input: " . json_encode($input));

// ─── Extraer campos ───────────────────────────────────────────────────────────
$idtransacciones = isset($input['idtransacciones']) ? intval($input['idtransacciones']) : 0;
$cotizacion_id   = $input['cotizacion_id']          ?? null;
$rate_id         = $input['rate_id']                ?? null;
$generar_guia    = isset($input['generar_guia'])    ? (bool)$input['generar_guia'] : false;
$idinv           = isset($input['idinv'])           ? intval($input['idinv'])       : 0;
$contacto_tel    = $input['contacto_tel']           ?? '';
$contacto_email  = $input['contacto_email']         ?? '';
$peso_gramos     = isset($input['peso_gramos'])     ? intval($input['peso_gramos']) : 500;
$carrier         = $input['carrier']                ?? '';
$dir             = $input['direccion']              ?? [];

if ($idtransacciones <= 0) {
    logMsg("ERROR: idtransacciones inválido: $idtransacciones");
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'idtransacciones requerido y debe ser > 0']);
    exit;
}

// ─── Conectar BD ──────────────────────────────────────────────────────────────
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) {
    logMsg("ERROR BD: " . $conn->connect_error);
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'DB error: ' . $conn->connect_error]);
    exit;
}
$conn->set_charset('utf8');
logMsg("BD OK");

// ─── Obtener nombre del distribuidor ─────────────────────────────────────────
$nombreDestinatario = '';
if ($idinv > 0) {
    $r = $conn->query("SELECT nombre, appat, apmat FROM inversionista WHERE id_inver = $idinv LIMIT 1");
    if ($r && $r->num_rows > 0) {
        $row = $r->fetch_assoc();
        $nombreDestinatario = trim(
            ($row['nombre'] ?? '') . ' ' .
            ($row['appat']  ?? '') . ' ' .
            ($row['apmat']  ?? '')
        );
    }
    logMsg("Distribuidor idinv=$idinv nombre='$nombreDestinatario'");
}

// ─── Obtener token Skydropx ───────────────────────────────────────────────────
function getToken($conn) {
    // Buscar token válido en BD
    $r = $conn->query("SELECT valor FROM configuracion WHERE clave = 'skydropx_token' ORDER BY actualizado DESC LIMIT 1");
    if ($r && $r->num_rows > 0) {
        $row  = $r->fetch_assoc();
        $data = json_decode($row['valor'], true);
        if ($data && isset($data['access_token'], $data['expires_at'])) {
            if ($data['expires_at'] - time() > 300) {
                logMsg("Token en BD válido, expira en " . ($data['expires_at'] - time()) . "s");
                return $data['access_token'];
            }
        }
    }
    logMsg("Generando nuevo token OAuth...");

    $result = skydropxRequest('POST', SKYDROPX_BASE . '/api/v1/oauth/token', [
        'client_id'     => SKYDROPX_CLIENT_ID,
        'client_secret' => SKYDROPX_CLIENT_SECRET,
        'grant_type'    => 'client_credentials',
        'redirect_uri'  => 'urn:ietf:wg:oauth:2.0:oob',
        'scope'         => 'default orders.create',
    ]);

    logMsg("OAuth HTTP " . $result['code'] . ": " . $result['body']);

    if ($result['error']) {
        logMsg("OAuth cURL error: " . $result['error']);
        return null;
    }
    if ($result['code'] !== 200) {
        logMsg("OAuth falló HTTP " . $result['code']);
        return null;
    }

    $tokenData = json_decode($result['body'], true);
    if (!isset($tokenData['access_token'])) {
        logMsg("OAuth sin access_token en respuesta");
        return null;
    }

    $accessToken = $tokenData['access_token'];
    $expiresIn   = intval($tokenData['expires_in'] ?? 7200);
    $expiresAt   = time() + $expiresIn;

    // Guardar en BD
    $val = $conn->real_escape_string(json_encode([
        'access_token' => $accessToken,
        'expires_at'   => $expiresAt,
    ]));
    $conn->query("INSERT INTO configuracion (clave, valor, actualizado)
                  VALUES ('skydropx_token', '$val', NOW())
                  ON DUPLICATE KEY UPDATE valor = '$val', actualizado = NOW()");

    if ($conn->error) {
        logMsg("Error guardando token en BD: " . $conn->error);
    } else {
        logMsg("Token guardado en BD. Expira en {$expiresIn}s");
    }

    return $accessToken;
}

$token = getToken($conn);
if (!$token) {
    logMsg("ERROR: No se pudo obtener token");
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'No se pudo obtener token de Skydropx']);
    exit;
}

// ─── Construir payload de la orden ───────────────────────────────────────────
// Peso en kg (mínimo 0.1 kg)
$pesoKg = max(round($peso_gramos / 1000, 2), 0.1);

// Normalizar país
$pais = isset($dir['pais']) ? strtoupper(trim($dir['pais'])) : 'MX';
if (strlen($pais) > 2 || in_array($pais, ['MÉXICO', 'MEXICO', 'MÉX', 'MEX'])) {
    $pais = 'MX';
}

// Nombre del destinatario
$personName = $nombreDestinatario ?: ($contacto_tel ?: 'Cliente RRB');

$orderPayload = [
    'order' => [
        'reference'        => $idtransacciones,
        'reference_number' => 'RRB-' . $idtransacciones,
        'payment_status'   => $generar_guia ? 'paid' : 'pending',
        'total_price'      => '0.00',
		 'consignment_note' => 31231400,
        'parcels'          => [
            [
                'weight'         => $pesoKg,
                'length'         => 20,
                'width'          => 20,
                'height'         => 20,
                'quantity'         => 1,
                'dimension_unit'   => 'CM',
                'mass_unit'        => 'KG',
               
            ]
        ],
        'shipper_address'  => [
            'address'         => SHIPPER_ADDRESS,
            'internal_number' => SHIPPER_NUMBER,
            'reference'       => SHIPPER_REFERENCIA,
            'sector'          => SHIPPER_COLONIA,
            'city'            => SHIPPER_CIUDAD,
            'state'           => SHIPPER_ESTADO,
            'postal_code'     => SHIPPER_CP,
            'country'         => 'MX',
            'person_name'     => SHIPPER_NOMBRE,
            'company'         => SHIPPER_EMPRESA,
            'phone'           => SHIPPER_TELEFONO,
            'email'           => SHIPPER_EMAIL,
        ],
        'recipient_address' => [
            'address'         => trim(($dir['calle'] ?? '') . ' ' . ($dir['noExt'] ?? '')),
            'internal_number' => $dir['noInt']      ?? '',
            'reference'       => $dir['referencia'] ?? '',
            'sector'          => $dir['colonia']    ?? '',
            'city'            => $dir['ciudad']     ?? '',
            'state'           => $dir['estado']     ?? '',
            'postal_code'     => $dir['cp']         ?? '',
            'country'         => $pais,
            'person_name'     => $personName,
            'company'         => '',
            'phone'           => $contacto_tel,
            'email'           => $contacto_email,
        ],
    ]
];

// Incluir rate_id si viene de cotización previa
if ($rate_id) {
    $orderPayload['order']['rate_id'] = $rate_id;
}

logMsg("Payload orden: " . json_encode($orderPayload));

// ─── Crear orden en Skydropx ──────────────────────────────────────────────────
$result = skydropxRequest('POST', SKYDROPX_BASE . '/api/v1/orders', $orderPayload, $token);
logMsg("Orden HTTP " . $result['code'] . ": " . $result['body']);

if ($result['error']) {
    logMsg("Orden cURL error: " . $result['error']);
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'cURL: ' . $result['error']]);
    exit;
}

$orderData = json_decode($result['body'], true);

if ($result['code'] !== 200 && $result['code'] !== 201) {
    logMsg("Orden falló HTTP " . $result['code']);
    echo json_encode([
        'success'   => false,
        'error'     => 'Skydropx error HTTP ' . $result['code'],
        'response'  => $orderData,
    ]);
    exit;
}

$skydropxOrderId = $orderData['id'] ?? null;
logMsg("Orden creada OK. Skydropx ID: $skydropxOrderId");

// ─── Guardar IDs en transacciones ─────────────────────────────────────────────
if ($skydropxOrderId) {
    $safeId = $conn->real_escape_string($skydropxOrderId);

    // skydropx_order_id
    $colCheck = $conn->query("SHOW COLUMNS FROM transacciones LIKE 'skydropx_order_id'");
    if ($colCheck && $colCheck->num_rows > 0) {
        $conn->query("UPDATE transacciones SET skydropx_order_id = '$safeId' WHERE idtransacciones = $idtransacciones");
        if ($conn->error) {
            logMsg("Error UPDATE skydropx_order_id: " . $conn->error);
        } else {
            logMsg("skydropx_order_id guardado (affected: " . $conn->affected_rows . ")");
        }
    } else {
        logMsg("Columna skydropx_order_id no existe, omitiendo");
    }

    // cotizacion_id y rate_id
    if ($cotizacion_id || $rate_id) {
        $safeCot  = $conn->real_escape_string($cotizacion_id ?? '');
        $safeRate = $conn->real_escape_string($rate_id ?? '');
        $colCot   = $conn->query("SHOW COLUMNS FROM transacciones LIKE 'skydropx_cotizacion_id'");
        if ($colCot && $colCot->num_rows > 0) {
            $conn->query("UPDATE transacciones SET skydropx_cotizacion_id = '$safeCot', skydropx_rate_id = '$safeRate' WHERE idtransacciones = $idtransacciones");
            logMsg("cotizacion_id y rate_id guardados");
        }
    }
}

// ─── Si generar_guia=true, obtener shipment con guía ─────────────────────────
$trackingNumber = null;
$labelUrl       = null;
$carrierName    = null;
$shipmentData   = null;

if ($generar_guia && $skydropxOrderId) {
    logMsg("Obteniendo shipments para orden $skydropxOrderId...");
    $shipResult = skydropxRequest('GET', SKYDROPX_BASE . '/api/v1/orders/' . $skydropxOrderId . '/shipments', null, $token);
    logMsg("Shipments HTTP " . $shipResult['code'] . ": " . $shipResult['body']);

    if ($shipResult['code'] === 200) {
        $ships = json_decode($shipResult['body'], true);
        if (!empty($ships)) {
            $shipmentData   = is_array($ships) ? $ships[0] : $ships;
            $trackingNumber = $shipmentData['tracking_number'] ?? null;
            $labelUrl       = $shipmentData['label_url'] ?? ($shipmentData['labels'][0]['url'] ?? null);
            $carrierName    = $shipmentData['carrier'] ?? $carrier;
            logMsg("Guía: tracking=$trackingNumber label=$labelUrl");
        }
    }
}

// ─── Respuesta ────────────────────────────────────────────────────────────────
$response = [
    'success'           => true,
    'skydropx_order_id' => $skydropxOrderId,
    'generar_guia'      => $generar_guia,
];

if ($trackingNumber) $response['tracking_number'] = $trackingNumber;
if ($labelUrl)       $response['label_url']        = $labelUrl;
if ($carrierName)    $response['carrier']           = $carrierName;
if ($shipmentData)   $response['shipment']          = $shipmentData;

logMsg("Respuesta: " . json_encode($response));
logMsg("=== Fin ===\n");

echo json_encode($response);
$conn->close();
