<?php
// views/pages/generar_qr.php — Interfaz + API en uno (SGO)
// GET  -> Renderiza la interfaz (con sidebar/topbar/footer).
// POST -> Recibe JSON: { "chasis": ["AAA","BBB", ...] } y responde: { success, items:[{id,chasis,color,marca,modelo}] }

declare(strict_types=1);
session_start();

date_default_timezone_set('America/Guayaquil');

// ====== CORS / Preflight para fetch() ======
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
  header('Access-Control-Allow-Origin: *');
  header('Access-Control-Allow-Headers: Content-Type, Authorization');
  header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
  http_response_code(204);
  exit;
}

// ====== Conexión ======
require_once __DIR__ . '/conex.php';
if (!isset($conn) || !$conn instanceof mysqli) {
  http_response_code(500);
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode(['success'=>false,'message'=>'Error de conexión a BD']);
  exit;
}
mysqli_set_charset($conn, 'utf8mb4');
if (function_exists('mysqli_report')) { mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); }

// ====== Si es POST con JSON, actúa como API y NO renderiza HTML ======
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  header('Access-Control-Allow-Origin: *');
  header('Content-Type: application/json; charset=utf-8');

  $raw = file_get_contents('php://input');
  $payload = json_decode($raw, true);
  if (!is_array($payload)) {
    echo json_encode(['success'=>false,'message'=>'JSON inválido o vacío']); exit;
  }

  $lista = $payload['chasis'] ?? [];
  if (!is_array($lista) || count($lista) === 0) {
    echo json_encode(['success'=>false,'message'=>'Lista de chasis vacía']); exit;
  }

  // Normaliza y quita duplicados
  $norm = [];
  foreach ($lista as $c) {
    $x = strtoupper(trim((string)$c));
    if ($x !== '' && strlen($x) >= 4) $norm[$x] = true;
  }
  $keys = array_keys($norm);
  if (count($keys) === 0) {
    echo json_encode(['success'=>false,'message'=>'Sin chasis válidos']); exit;
  }

  $ph = implode(',', array_fill(0, count($keys), '?'));

  // Ajusta a tu esquema si cambian nombres de tabla/campos
  $sql = "
    SELECT 
      d.iddatadai AS id,
      d.chasis    AS chasis,
      d.color     AS color,
      d.marca     AS marca,
      d.modelo    AS modelo
    FROM tb_datadai d
    WHERE UPPER(d.chasis) IN ($ph)
  ";

  try {
    $stmt  = $conn->prepare($sql);
    $types = str_repeat('s', count($keys));
    $stmt->bind_param($types, ...$keys);
    $stmt->execute();
    $res = $stmt->get_result();

    $items = [];
    while ($row = $res->fetch_assoc()) {
      $items[] = [
        'id'     => (string)$row['id'],
        'chasis' => (string)$row['chasis'],
        'color'  => $row['color']  !== null ? (string)$row['color']  : '',
        'marca'  => $row['marca']  !== null ? (string)$row['marca']  : '',
        'modelo' => $row['modelo'] !== null ? (string)$row['modelo'] : '',
      ];
    }

    echo json_encode(['success'=>true, 'items'=>$items], JSON_UNESCAPED_UNICODE);
  } catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success'=>false,'message'=>'Error en consulta','error'=>$e->getMessage()]);
  }
  exit;
}

// ====== GET normal: Render de la interfaz ======
if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES') {
  header("Location: ../../views/index.php");
  exit();
}
$usuario = $_SESSION['usuario'] ?? '';
$permiso = (int)($_SESSION['permiso'] ?? 0);
?>
<?php include __DIR__ . '/partials/header.php'; ?>

<body>
<div class="container-fluid">
  <div class="row">

    <!-- Sidebar -->
    <?php include __DIR__ . '/partials/menu.php'; ?>

    <!-- Contenido principal -->
    <main class="col-md-9 ms-sm-auto col-lg-10 px-0">

      <!-- Topbar -->
      <?php include __DIR__ . '/partials/topbar.php'; ?>

      <!-- Contenido específico de la página -->
      <section class="p-3">

        <div class="d-flex justify-content-between align-items-center mb-3">
          <h5 class="m-0">QR · Búsqueda múltiple de chasis</h5>
          <button id="btnImprimir" class="btn btn-primary btn-sm" disabled>
            <i class="bi bi-printer"></i> Imprimir seleccionados
          </button>
        </div>

        <div class="card mb-3">
          <div class="card-body">
            <label for="txtChasis" class="form-label fw-semibold mb-1">Pega o escribe múltiples chasis</label>
            <textarea id="txtChasis" class="form-control form-control-sm" rows="4" placeholder="Ejemplos:
8AJKB3CD3T1717945
93HBC2AA2S1234567, MR0HA3CD0R7654321"></textarea>

            <div class="d-flex justify-content-between align-items-center mt-2">
              <small class="text-muted">Separadores aceptados: coma, espacio o saltos de línea. Se eliminan duplicados.</small>
              <div class="d-flex gap-2">
                <button id="btnLimpiar" class="btn btn-outline-secondary btn-sm">Limpiar</button>
                <button id="btnBuscar" class="btn btn-success btn-sm">Buscar</button>
              </div>
            </div>
          </div>
        </div>

        <div class="card">
          <div class="card-header py-2 d-flex align-items-center gap-3">
            <div class="form-check m-0">
              <input class="form-check-input" type="checkbox" id="chkAll">
              <label class="form-check-label" for="chkAll">Seleccionar todo</label>
            </div>
            <small id="selCount" class="text-muted">0 seleccionados</small>
          </div>
          <div class="card-body p-0">
            <div class="table-responsive">
              <table class="table table-sm table-striped table-hover align-middle m-0">
                <thead class="table-light">
                  <tr>
                    <th style="width:48px;"></th>
                    <th>Chasis</th>
                    <th>Marca</th>
                    <th>Modelo</th>
                    <th>Color</th>
                    <th style="width:120px;">QR</th>
                  </tr>
                </thead>
                <tbody id="tbody">
                  <!-- filas dinámicas -->
                </tbody>
              </table>
            </div>
          </div>
        </div>

      </section>
      <!-- /contenido específico -->
    </main>
  </div>
</div>

<?php include __DIR__ . '/partials/footer.php'; ?>

<!-- QRious (genera QR en <canvas>) -->
<script src="https://cdn.jsdelivr.net/npm/qrious@4.0.2/dist/qrious.min.js"></script>

<script>
// ====== Config rutas ======
// Como este mismo archivo responde al POST JSON, podemos apuntar a sí mismo:
const API_URL      = 'generar_qr.php';
const URL_IMPRIMIR = './qr/imprimir_multiple.php'; // Ajusta si tu ruta es distinta

// ====== Helpers ======
function parseListaChasis(raw) {
  if (!raw) return [];
  return [...new Set(
    raw.split(/[\s,;]+/g)
       .map(s => s.trim().toUpperCase())
       .filter(Boolean)
  )];
}

function buildRow(item) {
  // item esperado: {id, chasis, color, marca, modelo}
  const tr = document.createElement('tr');
  tr.dataset.id     = String(item.id ?? '');
  tr.dataset.chasis = item.chasis ?? '';
  tr.dataset.color  = item.color  ?? '';
  tr.dataset.marca  = item.marca  ?? '';
  tr.dataset.modelo = item.modelo ?? '';

  // Col 1: checkbox
  const tdChk = document.createElement('td');
  const chk = document.createElement('input');
  chk.type = 'checkbox';
  chk.className = 'form-check-input row-chk';
  chk.addEventListener('change', updateSelectionCount);
  tdChk.appendChild(chk);

  // Col 2: chasis
  const tdChasis = document.createElement('td');
  tdChasis.textContent = item.chasis ?? '';

  // Col 3: marca
  const tdMarca = document.createElement('td');
  tdMarca.textContent = item.marca ?? '';

  // Col 4: modelo
  const tdModelo = document.createElement('td');
  tdModelo.textContent = item.modelo ?? '';

  // Col 5: color
  const tdColor = document.createElement('td');
  tdColor.textContent = item.color ?? '';

  // Col 6: QR (canvas)
  const tdQR = document.createElement('td');
  const canvas = document.createElement('canvas');
  canvas.width = 96; canvas.height = 96; canvas.className = 'd-block';
  tdQR.appendChild(canvas);

  // Contenido del QR (puedes usar JSON si prefieres)
  new QRious({ element: canvas, value: item.chasis ?? '', size: 96, level: 'H' });

  tr.appendChild(tdChk);
  tr.appendChild(tdChasis);
  tr.appendChild(tdMarca);
  tr.appendChild(tdModelo);
  tr.appendChild(tdColor);
  tr.appendChild(tdQR);
  return tr;
}

function updateSelectionCount() {
  const total = document.querySelectorAll('.row-chk').length;
  const sel   = document.querySelectorAll('.row-chk:checked').length;
  document.getElementById('selCount').textContent = `${sel} seleccionados`;
  document.getElementById('btnImprimir').disabled = sel === 0 || total === 0;

  const chkAll = document.getElementById('chkAll');
  if (sel === 0) { chkAll.indeterminate = false; chkAll.checked = false; }
  else if (sel < total) { chkAll.indeterminate = true; }
  else { chkAll.indeterminate = false; chkAll.checked = true; }
}

function getSeleccionados() {
  const out = [];
  document.querySelectorAll('#tbody tr').forEach(tr => {
    const chk = tr.querySelector('.row-chk');
    if (chk && chk.checked) {
      out.push({
        id:     tr.dataset.id,
        chasis: tr.dataset.chasis,
        color:  tr.dataset.color,
        marca:  tr.dataset.marca,
        modelo: tr.dataset.modelo
      });
    }
  });
  return out;
}

// ====== Eventos ======
document.getElementById('btnLimpiar').addEventListener('click', () => {
  document.getElementById('txtChasis').value = '';
  document.getElementById('tbody').innerHTML = '';
  const chkAll = document.getElementById('chkAll');
  chkAll.checked = false; chkAll.indeterminate = false;
  updateSelectionCount();
});

document.getElementById('chkAll').addEventListener('change', e => {
  document.querySelectorAll('.row-chk').forEach(c => c.checked = e.currentTarget.checked);
  updateSelectionCount();
});

document.getElementById('btnBuscar').addEventListener('click', async () => {
  const lista = parseListaChasis(document.getElementById('txtChasis').value);
  const tbody = document.getElementById('tbody');
  tbody.innerHTML = '';
  const chkAll = document.getElementById('chkAll');
  chkAll.checked = false; chkAll.indeterminate = false;
  updateSelectionCount();

  if (lista.length === 0) { alert('Ingrese al menos un chasis.'); return; }

  try {
    const res = await fetch(API_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json; charset=utf-8' },
      body: JSON.stringify({ chasis: lista })
    });
    if (!res.ok) throw new Error('Error de servidor');
    const data = await res.json(); // {success, items:[...]}
    if (!data.success) { alert(data.message || 'Sin resultados'); return; }

    const items = Array.isArray(data.items) ? data.items : [];
    if (items.length === 0) { alert('No se encontraron chasis.'); return; }

    const frag = document.createDocumentFragment();
    items.forEach(it => frag.appendChild(buildRow(it)));
    tbody.appendChild(frag);
    updateSelectionCount();
  } catch (err) {
    console.error(err);
    alert('No se pudo completar la búsqueda.');
  }
});

document.getElementById('btnImprimir').addEventListener('click', () => {
  const sel = getSeleccionados();
  if (sel.length === 0) { alert('Seleccione al menos un registro.'); return; }
  // Construye: ./api/imprimir_multiple.php?data=[{...}]
  const q = encodeURIComponent(JSON.stringify(sel));
  const url = `${URL_IMPRIMIR}?data=${q}`;
  window.open(url, '_blank', 'noopener');
});
</script>

<!-- Iconos Bootstrap -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
</body>
</html>
