<?php
/**
 * compra-guardar-direccion.php
 * POST → Guarda una nueva dirección de envío en la tabla direccionenvio
 *        para el distribuidor indicado.
 */
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; }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'Método no permitido']);
    exit;
}

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

// ── Validar token admin ───────────────────────────────────────────────────────
$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' => 'Sesión inválida o expirada']);
    exit;
}

// ── Leer payload ──────────────────────────────────────────────────────────────
$b = json_decode(file_get_contents('php://input'), true) ?? [];

$id_inver   = (int)($b['id_inver']   ?? 0);
$calle      = trim($b['calle']       ?? '');
$noExt      = trim($b['noExt']       ?? '');
$noInt      = trim($b['noInt']       ?? '');
$entre1     = trim($b['entre1']      ?? '');
$entre2     = trim($b['entre2']      ?? '');
$referencia = trim($b['referencia']  ?? '');
$colonia    = trim($b['colonia']     ?? '');
$ciudad     = trim($b['ciudad']      ?? '');
$estado     = trim($b['estado']      ?? '');
$cp         = trim($b['cp']          ?? '');
$pais       = trim($b['pais']        ?? 'México');

if (!$id_inver || !$calle || !$cp) {
    echo json_encode(['ok' => false, 'error' => 'Faltan campos requeridos (id_inver, calle, cp)']);
    exit;
}

try {
    $stmt = $db->prepare("
        INSERT INTO direccionenvio
            (id_inver, calle, noExt, noInt, entre1, entre2, referencia, colonia, ciudad, estado, cp, pais, status)
        VALUES
            (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
    ");
    $stmt->execute([$id_inver, $calle, $noExt, $noInt, $entre1, $entre2, $referencia, $colonia, $ciudad, $estado, $cp, $pais]);
    $newId = (int)$db->lastInsertId();
    echo json_encode(['ok' => true, 'id' => $newId]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
