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

$inv = $db->prepare("SELECT nombre, appat, apmat, email, telefono FROM inversionista WHERE id_inver = 1459");
$inv->execute();
$inv = $inv->fetch(PDO::FETCH_ASSOC);

$dir = $db->prepare("SELECT * FROM direccionenvio WHERE id = 76");
$dir->execute();
$dir = $dir->fetch(PDO::FETCH_ASSOC);

$nombre = trim(($inv['nombre']??'').' '.($inv['appat']??'').' '.($inv['apmat']??''));
$telefono = preg_replace('/\D/', '', $inv['telefono'] ?? '');
if (strlen($telefono) < 10) $telefono = '3300000000';
$calle = trim(($dir['calle']??'').' '.($dir['noExt']??''));
$entre = trim(($dir['entre1']??'').($dir['entre2'] ? ' y '.$dir['entre2'] : ''));
$referencia = $entre ?: ($dir['referencia'] ?? 'Sin referencias');

$json = [
    'distribuidor' => $inv,
    'direccion' => $dir,
    'address_to_orden' => [
        'address'         => $calle,
        'internal_number' => $dir['noInt'] ?? '',
        'reference'       => $referencia,
        'sector'          => $dir['colonia'] ?? '',
        'city'            => $dir['ciudad'] ?? '',
        'state'           => $dir['estado'] ?? '',
        'postal_code'     => $dir['cp'] ?? '',
        'country'         => 'MX',
        'person_name'     => $nombre ?: 'Cliente',
        'company'         => '',
        'phone'           => $telefono,
        'email'           => $inv['email'] ?? '',
    ],
    'address_to_shipment' => [
        'area_level1'      => $dir['estado'] ?? '',
        'area_level2'      => $dir['ciudad'] ?? '',
        'area_level3'      => $dir['colonia'] ?? '',
        'name'             => $nombre ?: 'Cliente',
        'postal_code'      => $dir['cp'] ?? '',
        'country_code'     => 'MX',
        'street1'          => $calle,
        'company'          => '',
        'phone'            => $telefono,
        'email'            => $inv['email'] ?? '',
        'reference'        => $referencia,
        'address_type'     => 'to',
        'apartment_number' => $dir['noInt'] ?? '',
    ],
];

header('Content-Type: application/json');
echo json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
