<?php
/**
 * dist-buscar.php — Buscador de distribuidores
 * GET /admin/api/dist-buscar.php?q={texto}
 *
 * Busca por: referencia, rfc, nombre, appat, apmat
 * Devuelve hasta 30 resultados
 */
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(['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(['error' => 'Sesión expirada o inválida']);
    exit;
}

// ── Parámetro de búsqueda ─────────────────────────────────────────────────
$q = trim($_GET['q'] ?? '');
if (strlen($q) < 2) {
    echo json_encode(['success' => true, 'distribuidores' => [], 'total' => 0]);
    exit;
}

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

$stmt = $db->prepare("
    SELECT
        i.id_inver,
        i.referencia,
        i.rfc,
        i.nombre,
        i.appat,
        i.apmat,
        i.email,
        i.tel1,
        i.tel2,
        i.wa,
        i.estado,
        i.ciudad,
        i.cp,
        i.calle,
        i.noExt,
        i.noInt,
        i.activo
    FROM inversionista i
    WHERE
        i.referencia LIKE ?
        OR i.rfc      LIKE ?
        OR i.nombre   LIKE ?
        OR i.appat    LIKE ?
        OR i.apmat    LIKE ?
    ORDER BY i.appat, i.nombre
    LIMIT 30
");
$stmt->execute([$like, $like, $like, $like, $like]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$distribuidores = [];
foreach ($rows as $r) {
    $distribuidores[] = [
        'id_inver'   => (int)$r['id_inver'],
        'referencia' => $r['referencia'] ?? '',
        'rfc'        => $r['rfc']        ?? '',
        'nombre'     => trim(($r['nombre'] ?? '') . ' ' . ($r['appat'] ?? '') . ' ' . ($r['apmat'] ?? '')),
        'nombre_raw' => $r['nombre'] ?? '',
        'appat'      => $r['appat']  ?? '',
        'apmat'      => $r['apmat']  ?? '',
        'email'      => $r['email']  ?? '',
        'tel1'       => $r['tel1']   ?? '',
        'tel2'       => $r['tel2']   ?? '',
        'wa'         => $r['wa']     ?? '',
        'estado'     => $r['estado'] ?? '',
        'ciudad'     => $r['ciudad'] ?? '',
        'cp'         => $r['cp']     ?? '',
        'calle'      => $r['calle']  ?? '',
        'noExt'      => $r['noExt']  ?? '',
        'noInt'      => $r['noInt']  ?? '',
        'activo'     => (int)($r['activo'] ?? 0),
    ];
}

echo json_encode([
    'success'        => true,
    'distribuidores' => $distribuidores,
    'total'          => count($distribuidores),
    'query'          => $q,
], JSON_UNESCAPED_UNICODE);
