<?php
/**
 * compra-direcciones.php
 * GET ?id_inver=X → devuelve las direcciones de entrega del distribuidor (direccionenvio WHERE id_inver=X AND status=1)
 */
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
header('Access-Control-Allow-Methods: GET, OPTIONS');
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;
}

$id_inver = intval($_GET['id_inver'] ?? 0);
if (!$id_inver) {
    echo json_encode(['ok' => false, 'error' => 'id_inver requerido']);
    exit;
}

try {
    $stmt = $db->prepare("
        SELECT id, calle, noInt, noExt, entre1, entre2, referencia, colonia, ciudad, estado, cp, pais
        FROM direccionenvio
        WHERE id_inver = ? AND status = 1
        ORDER BY id DESC
    ");
    $stmt->execute([$id_inver]);
    $dirs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['ok' => true, 'direcciones' => $dirs], JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Error: ' . $e->getMessage()]);
}
