<?php
require_once __DIR__ . '/../../inc/bootstrap.php';
require_once __DIR__ . '/../../inc/auth.php';
require_login();
?>

<!doctype html><html lang="es"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../../assets/styles.css">
<link rel="stylesheet" href="../../assets/theme.css">
<title>Preparados</title>
<style>
  /* Minimal y compacto */
  .card.theme-prep { padding:14px }
  .mini * { font-size: 12px; }
  .mini h2 { font-size:16px; margin:6px 0 10px }
  .mini .input, .mini .btn { font-size:12px; padding:6px 8px }
  .table.table-sm { font-size:12px; }
  .table.table-sm th, .table.table-sm td { padding:6px 8px; vertical-align:middle }
  .btn-icon { padding:4px 6px; line-height:1; border:1px solid #cbd5e1; background:#f8fafc; border-radius:6px }
  .btn-icon:hover { background:#eef2ff; }
  .actions { display:flex; gap:6px; justify-content:center }
  .comp-col { max-width:340px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; color:#475569 }
  .filters { display:grid; grid-template-columns: repeat(6,1fr); gap:8px; align-items:end; }
  @media (max-width: 980px){ .filters { grid-template-columns: repeat(3,1fr); } }
  @media (max-width: 620px){ .filters { grid-template-columns: 1fr; } }
</style>
</head><body>
<div class="container mini">
  <div class="card theme-prep">
    <div style="display:flex;gap:8px;align-items:center;justify-content:space-between">
      <a class="btn" href="../../index.php">← Inicio</a>
      <div style="display:flex;gap:8px;flex-wrap:wrap">
        <a class="btn" href="create.php">➕ Nuevo</a>
        <a class="btn" href="reporte_margen.php">📊 Margen</a>
      </div>
    </div>

    <h2>Preparados</h2>

    <?php
    // Parámetros filtro
    $f_doc   = trim($_GET['doc']   ?? '');
    $f_pac   = trim($_GET['pac']   ?? '');
    $f_desde = trim($_GET['desde'] ?? '');
    $f_hasta = trim($_GET['hasta'] ?? '');

    // WHERE dinámico
    $where = []; $params = [];
    if ($f_doc   !== '') { $where[] = "d.nombre LIKE ?";          $params[] = "%$f_doc%"; }
    if ($f_pac   !== '') { $where[] = "pa.nombre LIKE ?";         $params[] = "%$f_pac%"; }
    if ($f_desde !== '') { $where[] = "p.fecha_elaboracion >= ?"; $params[] = $f_desde; }
    if ($f_hasta !== '') { $where[] = "p.fecha_elaboracion <= ?"; $params[] = $f_hasta; }
    $sqlWhere = $where ? ("WHERE ".implode(" AND ", $where)) : "";

    // Importante si hay muchos componentes largos
    $pdo->query("SET SESSION group_concat_max_len = 8192");

    // Consulta con componentes agregados
    $sql = "
      SELECT
        p.id, p.fecha_elaboracion, p.numero_externo, p.forma_farmaceutica,
        pa.nombre AS pac, d.nombre AS doc,
        COALESCE(GROUP_CONCAT(DISTINCT c.nombre ORDER BY c.nombre SEPARATOR ', '), '') AS comps
      FROM preparados p
      JOIN pacientes pa ON pa.id = p.id_paciente
      JOIN doctores  d  ON d.id  = p.id_doctor
      LEFT JOIN componentes_preparado cp ON cp.id_preparado = p.id
      LEFT JOIN componentes c           ON c.id = cp.id_componente
      $sqlWhere
      GROUP BY p.id
      ORDER BY p.fecha_elaboracion DESC, p.id DESC
      LIMIT 500
    ";
    $stmt = $pdo->prepare($sql); $stmt->execute($params);
    $rows = $stmt->fetchAll();
    ?>

    <!-- Filtros (compactos) -->
    <form class="filters" style="margin-top:10px">
      <div><div class="label">Doctor</div><input class="input" name="doc" value="<?=h($f_doc)?>" placeholder="Nombre"></div>
      <div><div class="label">Paciente</div><input class="input" name="pac" value="<?=h($f_pac)?>" placeholder="Nombre"></div>
      <div><div class="label">Desde</div><input class="input" type="date" name="desde" value="<?=h($f_desde)?>"></div>
      <div><div class="label">Hasta</div><input class="input" type="date" name="hasta" value="<?=h($f_hasta)?>"></div>
      <div><button class="btn" type="submit">🔎 Filtrar</button></div>
      <div><a class="btn" href="list.php">❌ Limpiar</a></div>
    </form>

    <!-- Selección múltiple para imprimir -->
    <form method="post" action="sheet_multi.php" style="margin-top:10px">
      <div class="label">Selecciona y luego “Imprimir hoja carta”.</div>
      <div style="margin:6px 0"><button class="btn" type="submit">🖨️ Imprimir hoja carta</button></div>

      <table class="table table-sm">
        <thead>
          <tr>
            <th style="width:28px">
              <input type="checkbox" onclick="document.querySelectorAll('.chk').forEach(c=>c.checked=this.checked)">
            </th>
            <th>Fecha</th>
            <th>N°</th>
            <th>Forma</th>
            <th>Paciente</th>
            <th>Doc</th>
            <th>Comp.</th>
            <th style="width:120px; text-align:center">Acc.</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach($rows as $r): ?>
          <tr>
            <td><input class="chk" type="checkbox" name="ids[]" value="<?= (int)$r['id'] ?>"></td>
            <td><?=h(fmt_date($r['fecha_elaboracion']))?></td>
            <td><?=h($r['numero_externo'])?></td>
            <td><?=h($r['forma_farmaceutica'])?></td>
            <td><?=h($r['pac'])?></td>
            <td><?=h($r['doc'])?></td>
            <td class="comp-col" title="<?=h($r['comps'])?>"><?=h($r['comps'])?></td>
            <td>
              <div class="actions">
                <a class="btn-icon" href="label_preview.php?id=<?= (int)$r['id'] ?>" title="Vista etiqueta">🏷️</a>
                <a class="btn-icon" href="edit.php?id=<?= (int)$r['id'] ?>" title="Editar">✏️</a>
                <a class="btn-icon" href="delete.php?id=<?= (int)$r['id'] ?>" title="Eliminar">🗑️</a>
              </div>
            </td>
          </tr>
        <?php endforeach; ?>
        <?php if (!$rows): ?>
          <tr><td colspan="8" style="text-align:center;color:#64748b">Sin resultados</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </form>
  </div>
</div>
</body></html>
