<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, 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 expirada o inválida']);
    exit;
}

// ── Parámetros ────────────────────────────────────────────────────────────
$q = trim($_GET['q'] ?? '');
if (strlen($q) < 1) {
    echo json_encode(['ok' => false, 'error' => 'Parámetro q requerido']);
    exit;
}

$like = '%' . $q . '%';

$stmt = $db->prepare("
    SELECT
        i.id_inver   AS id_inv,
        i.referencia,
        i.nombre,
        i.appat,
        i.apmat,
        i.rfc,
        i.email,
        i.tel1,
        i.tel2,
        i.wa
    FROM inversionista i
    WHERE i.referencia LIKE ?
       OR i.rfc        LIKE ?
       OR i.nombre     LIKE ?
       OR i.appat      LIKE ?
       OR i.apmat      LIKE ?
       OR CONCAT(COALESCE(i.nombre,''), ' ', COALESCE(i.appat,''), ' ', COALESCE(i.apmat,'')) LIKE ?
    ORDER BY i.referencia ASC
    LIMIT 50
");
$stmt->execute([$like, $like, $like, $like, $like, $like]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode(['ok' => true, 'distribuidores' => $rows]);
