<?php
require __DIR__.'/../../inc/bootstrap.php';

$autoload = __DIR__ . '/../../../vendor/autoload.php';
if (!is_file($autoload)) {
  http_response_code(500);
  echo "No se encontró vendor/autoload.php. Ejecuta:\n".
       "cd C:\\xampp-2\\htdocs\\farmacia && composer require dompdf/dompdf";
  exit;
}
require_once $autoload;

use Dompdf\Dompdf;
use Dompdf\Options;

/* ===== Datos ===== */
$id = (int)($_GET['id'] ?? 0);
if(!$id){ http_response_code(400); echo "ID inválido"; exit; }

$stmt = $pdo->prepare("
  SELECT p.*,
         pa.nombre AS pac, pa.mascota,
         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
  WHERE p.id = ?
");
$stmt->execute([$id]);
$p = $stmt->fetch();
if(!$p){ http_response_code(404); echo "No encontrado"; exit; }

$det = $pdo->prepare("
  SELECT c.nombre AS nombre_componente, cp.unidad_medida, cp.cantidad
  FROM componentes_preparado cp
  JOIN componentes c ON c.id = cp.id_componente
  WHERE cp.id_preparado = ?
  ORDER BY cp.id ASC
");
$det->execute([$id]);
$comps = $det->fetchAll();

/* ===== Helpers ===== */
function fmt_comp($s){
  $s = trim((string)$s);
  if (function_exists('mb_strimwidth')) return mb_strimwidth($s, 0, 10, '');
  return substr($s, 0, 10);
}
function qty3($x){ $q = (string)((int)$x); return substr($q,0,3); }
function fmt_date_local($d){
  if(!$d) return '';
  $t = strtotime($d);
  return date('d-m-Y', $t ?: time());
}
function unidad_total($forma){
  $f = mb_strtolower($forma,'UTF-8');
  if ($f==='cápsulas' || $f==='capsulas') return 'capsulas';
  if (in_array($f, ['jarabe','gotas','locion','loción','laca','shampoo','spray'])) return 'ML';
  if ($f==='supositorios') return 'Supositorios';
  return 'GRS';
}
function normalize($s){
  $s = mb_strtolower($s,'UTF-8');
  $map = ['á'=>'a','é'=>'e','í'=>'i','ó'=>'o','ú'=>'u','ü'=>'u','ñ'=>'n'];
  return strtr($s,$map);
}
$u = unidad_total($p['forma_farmaceutica']);

$ctrl_list = ['clordiazepoxido','clordiazepoxído','diazepam','alprazolam','bromazepam','lorazepam','clonazepam'];
$is_controlado = false;
foreach($comps as $c){
  $n = normalize($c['nombre_componente'] ?? '');
  foreach($ctrl_list as $k){
    if (strpos($n, normalize($k)) !== false) { $is_controlado = true; break 2; }
  }
}

$col1 = array_slice($comps, 0, 6);
$col2 = array_slice($comps, 6);

/* ===== HTML ===== */
ob_start(); ?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<style>
  @page { size: 101mm 34mm; margin: 0; }
  html, body { margin:0; padding:0; font-family: DejaVu Sans, Arial, Helvetica, sans-serif; }

  .label-101x34{
    width:101mm; height:34mm; padding:2mm; box-sizing:border-box;
    font-size:9px; line-height:1.06; overflow:hidden;
  }
  table.layout{ width:97mm; height:30mm; border-collapse:collapse; table-layout:fixed; }
  tr.content{ height:24mm; }
  tr.footer{  height:6mm; }
  td{ padding:0; margin:0; vertical-align:top; }

  td.c1{ width:30mm; padding-right:0.8mm; }
  td.c2{ width:28mm; padding-right:0.8mm; }
  td.c3{ width:36mm; padding-right:1.6mm; }

  .ff{ font-weight:600; }
  .azul{ color:#0b4aa2; font-weight:700; }
  .rojo-small{ color:#b71c1c; font-size:7px; font-weight:700; line-height:1.05; }

  .cline{ white-space:nowrap; font-size:8.6px; line-height:1.02; overflow:hidden; }
  .cline .name{ display:inline-block; width:17mm; overflow:hidden; text-overflow:clip; }
  .cline .sep{ display:inline-block; width:0.7mm; text-align:center; }
  .cline .qty{ display:inline-block; width:5mm; text-align:right; }
  .cline .um{  display:inline-block; margin-left:0; }

  .forma{ margin-bottom:1mm; }
  .footer-azul{ color:#0b4aa2; font-size:6.2px; line-height:1.02; text-align:center; margin:0; }

  /* Estrella 8mm después del Total, pegada a izquierda */
  .star-holder{ margin-top:1mm; text-align:left; }
  .star-green{ width:8mm; height:8mm; display:block; margin-left:0; }
</style>
</head>
<body>
  <div class="label-101x34">
    <table class="layout">
      <tr class="content">
        <!-- Col 1 -->
        <td class="c1">
          <div class="forma ff">F.F.: <?= htmlspecialchars($p['forma_farmaceutica']) ?></div>
          <?php foreach($col1 as $c): ?>
            <div class="cline">
              <span class="name"><?= htmlspecialchars(fmt_comp($c['nombre_componente'])) ?></span>
              <span class="sep">:</span>
              <span class="qty"><?= qty3($c['cantidad']) ?></span>
              <span class="um"><?= htmlspecialchars($c['unidad_medida']) ?></span>
            </div>
          <?php endforeach; ?>
        </td>

        <!-- Col 2 -->
        <td class="c2">
          <?php foreach($col2 as $c): ?>
            <div class="cline">
              <span class="name"><?= htmlspecialchars(fmt_comp($c['nombre_componente'])) ?></span>
              <span class="sep">:</span>
              <span class="qty"><?= qty3($c['cantidad']) ?></span>
              <span class="um"><?= htmlspecialchars($c['unidad_medida']) ?></span>
            </div>
          <?php endforeach; ?>

          <div class="cline ff" style="margin-top:1mm;">
            <span class="name">Total</span><span class="sep">:</span>
            <span class="qty"><?= (int)$p['total'] ?></span><span class="um"><?= $u ?></span>
          </div>

          <?php if($is_controlado): ?>
          <div class="star-holder">
            <svg class="star-green" viewBox="0 0 100 100" aria-hidden="true">
              <polygon fill="#32CD32" points="50,5 61,38 95,38 67,58 78,90 50,70 22,90 33,58 5,38 39,38"/>
            </svg>
          </div>
          <?php endif; ?>
        </td>

        <!-- Col 3 -->
        <td class="c3">
          <div>Doc: <?= htmlspecialchars($p['doc']) ?></div>
          <div>Pac: <?= htmlspecialchars($p['pac']) ?> <?= $p['mascota'] ? "(Mascota: ".htmlspecialchars($p['mascota']).")" : "" ?></div>
          <div>F. Elab.: <?= htmlspecialchars(fmt_date_local($p['fecha_elaboracion'])) ?></div>
          <div>F. Venc.: <?= htmlspecialchars(fmt_date_local($p['fecha_vencimiento'])) ?></div>
          <div class="azul" style="margin-top:1mm;">QF NINOSKA FRANCO</div>
          <div class="rojo-small">DOSIS INDICACION MEDICA</div>
        </td>
      </tr>
      <tr class="footer">
        <td colspan="3" style="vertical-align:middle;">
          <div class="footer-azul">
            Mantener fuera del alcance de los niños. Conservar en lugar fresco y seco. Nota: Eliminar después del vencimiento.
            RESOLUCION RF XIII 05/20 1A,1B y 2C FARMAVIDA, Recoleta 5418
          </div>
        </td>
      </tr>
    </table>
  </div>
</body>
</html>
<?php
$html = ob_get_clean();

/* ===== Dompdf ===== */
$options = new Options();
$options->set('isRemoteEnabled', true);
$options->set('isHtml5ParserEnabled', true);
$options->set('defaultFont', 'DejaVu Sans');

$dompdf = new Dompdf($options);
$dompdf->setPaper([0,0, 101*2.83465, 34*2.83465], 'portrait');
$dompdf->loadHtml($html, 'UTF-8');
$dompdf->render();

$filename = 'etiqueta_'.$id.'.pdf';
$dompdf->stream($filename, ['Attachment' => true]);
exit;

