<?php
/**
 * distribuidores-actualizar.php — Actualiza datos editables de un distribuidor
 * PUT /admin/api/distribuidores-actualizar.php
 * Body JSON: { id, rfc, email, tel1, tel2, wa, domicilio, colonia, ciudad, cp, estados_idestado }
 */
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: PUT, POST, OPTIONS');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
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' => 'Sesión inválida o expirada']);
    exit;
}

// ── Leer body JSON ───────────────────────────────────────────────────────────
$body = json_decode(file_get_contents('php://input'), true);
if (!$body) {
    echo json_encode(['ok' => false, 'error' => 'Body inválido']);
    exit;
}

$id = (int)($body['id'] ?? 0);
if (!$id) {
    echo json_encode(['ok' => false, 'error' => 'ID requerido']);
    exit;
}

// ── Campos editables (patrocinador, id_inver y referencia NO se pueden cambiar)
$rfc       = trim($body['rfc']       ?? '');
$email     = trim($body['email']     ?? '');
$tel1      = trim($body['tel1']      ?? '');
$tel2      = trim($body['tel2']      ?? '');
$wa        = trim($body['wa']        ?? '');
$domicilio = trim($body['domicilio'] ?? '');
$colonia   = trim($body['colonia']   ?? '');
$ciudad    = trim($body['ciudad']    ?? '');
$cp        = (int)($body['cp']       ?? 0);
$idEstado  = (int)($body['estados_idestado'] ?? 0);

// ── Actualizar ───────────────────────────────────────────────────────────────
$stmt = $db->prepare("
    UPDATE inversionista SET
        rfc                = ?,
        email              = ?,
        tel1               = ?,
        tel2               = ?,
        wa                 = ?,
        domicilio          = ?,
        colonia            = ?,
        ciudad             = ?,
        cp                 = ?,
        estados_idestado   = ?
    WHERE id_inver = ?
");
$stmt->execute([
    $rfc, $email, $tel1, $tel2, $wa,
    $domicilio, $colonia, $ciudad, $cp, $idEstado,
    $id
]);

echo json_encode(['ok' => true, 'updated' => $stmt->rowCount()]);
