<?php
require __DIR__.'/../../inc/bootstrap.php'; use Dompdf\Dompdf; use Dompdf\Options;

$where = []; $params = [];
if(!empty($_GET['comp'])){ $where[] = "EXISTS (SELECT 1 FROM componentes_preparado cp WHERE cp.id_preparado=p.id AND cp.nombre_componente LIKE ?)"; $params[] = "%".$_GET['comp']."%"; }
if(!empty($_GET['dr'])){ $where[] = "d.nombre LIKE ?"; $params[] = "%".$_GET['dr']."%"; }
if(!empty($_GET['pa'])){ $where[] = "pa.nombre LIKE ?"; $params[] = "%".$_GET['pa']."%"; }
if(!empty($_GET['d1'])){ $where[] = "p.fecha_elaboracion >= ?"; $params[] = $_GET['d1']; }
if(!empty($_GET['d2'])){ $where[] = "p.fecha_elaboracion <= ?"; $params[] = $_GET['d2']; }

$order = "p.fecha_elaboracion DESC";
if(($_GET['o'] ?? '')==='doctor') $order = "d.nombre ASC, p.fecha_elaboracion DESC";
if(($_GET['o'] ?? '')==='paciente') $order = "pa.nombre ASC, p.fecha_elaboracion DESC";

$sql = "SELECT p.*, pa.nombre AS pac, d.nombre AS doc FROM preparados p
        JOIN pacientes pa ON pa.id=p.id_paciente
        JOIN doctores d ON d.id=p.id_doctor".(count($where)?" WHERE ".implode(" AND ",$where):"")."
        ORDER BY $order LIMIT 1000";
$stmt=$pdo->prepare($sql); $stmt->execute($params); $rows = $stmt->fetchAll();

ob_start(); ?>
<!doctype html><html><head><meta charset="utf-8"><style>
table{width:100%;border-collapse:collapse;font-size:12px}
th,td{border:1px solid #ccc;padding:6px;text-align:left}
</style></head><body>
<h3>Listado de preparados</h3>
<table><thead><tr><th>Fecha</th><th>N° externo</th><th>Forma</th><th>Paciente</th><th>Doctor</th><th>Valor</th></tr></thead><tbody>
<?php foreach($rows as $r): ?>
<tr>
  <td><?=h($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>$<?=number_format($r['valor_calculado'],0,',','.')?></td>
</tr>
<?php endforeach; ?>
</tbody></table>
</body></html>
<?php
$html = ob_get_clean();
if (!class_exists(Dompdf::class)) { header('Content-Type: text/html; charset=utf-8'); echo $html; exit; }
$options = new Options(); $options->set('isRemoteEnabled', true);
$dompdf = new Dompdf($options); $dompdf->loadHtml($html, 'UTF-8'); $dompdf->setPaper('A4','portrait'); $dompdf->render(); $dompdf->stream('preparados.pdf',['Attachment'=>false]);
