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

$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 qty3($x){ $q = (string)((int)$x); return substr($q,0,3); }
function comp10($s){
  $s = trim((string)$s);
  if (function_exists('mb_strimwidth')) return mb_strimwidth($s, 0, 10, '');
  return substr($s, 0, 10);
}
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';
}
$u = unidad_total($p['forma_farmaceutica']);

/* Controlados → estrella */
function normalize($s){
  $s = mb_strtolower($s,'UTF-8');
  $map = ['á'=>'a','é'=>'e','í'=>'i','ó'=>'o','ú'=>'u','ü'=>'u','ñ'=>'n'];
  return strtr($s,$map);
}
$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; }
  }
}

/* Columnas */
$col1 = array_slice($comps, 0, 6);
$col2 = array_slice($comps, 6);
?>
<!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">
<title>Etiqueta</title>
<style>
.print-area.label-101x34{
  display:grid; grid-template-columns:30mm 28mm 36mm; column-gap:2mm;
  align-items:start; font-size:9px; width:101mm; height:34mm;
  padding:2mm; box-sizing:border-box; background:#fff; overflow:hidden;
}
.comp{display:flex;align-items:center;gap:3px;white-space:nowrap}
.comp .comp-name{display:inline-block;min-width:58px;max-width:58px;font-size:9px}
.comp .comp-name.total{min-width:auto;max-width:none}
.comp .sep{margin:0 1px}
.comp .qty{display:inline-block;min-width:16px;text-align:right}
.ff{font-weight:600}
.forma{font-size:8.0px}
.rojo-small{color:#b71c1c;font-size:8px;font-weight:700}
.footer-azul{color:#0b4aa2;font-size:8px;margin-top:2px;text-align:center}
.azul{color:#0b4aa2;font-weight:700}

/* Estrella controlado (20% menor → 8mm), pegada a la izquierda, DESPUÉS del Total */
.star-holder{ margin-top:1mm; text-align:left; }
.star-green{ width:8mm; height:8mm; display:block; margin-left:0; }

.container{max-width:900px;margin:16px auto}
.no-print{display:flex;gap:8px;margin-bottom:12px;flex-wrap:wrap}
@media print{ .no-print{display:none!important} @page{size:101mm 34mm; margin:0} }
</style>
</head>
<body>
<div class="container">
  <div class="no-print">
    <a class="btn" href="list.php">← Volver</a>
    <?php
      $base = rtrim(str_replace('\\','/', dirname($_SERVER['SCRIPT_NAME'])), '/');
      $pdfUrl = $base . '/label_pdf.php?id=' . (int)$id;
    ?>
    <a class="btn" href="<?= h($pdfUrl) ?>" target="_blank" rel="noopener">📄 Descargar PDF</a>
    <button class="btn" onclick="window.print()">🖨️ Imprimir</button>
  </div>

  <div class="print-area label-101x34">
    <!-- Columna 1 -->
    <div>
      <div class="ff forma">F.F: <?=h($p['forma_farmaceutica'])?></div>
      <?php foreach($col1 as $c): ?>
        <div class="comp">
          <span class="comp-name"><?=h(comp10($c['nombre_componente']))?></span><span class="sep">:</span>
          <span class="qty"><?=qty3($c['cantidad'])?></span>
          <span><?=h($c['unidad_medida'])?></span>
        </div>
      <?php endforeach; ?>
    </div>

    <!-- Columna 2 -->
    <div>
      <?php foreach($col2 as $c): ?>
        <div class="comp">
          <span class="comp-name"><?=h(comp10($c['nombre_componente']))?></span><span class="sep">:</span>
          <span class="qty"><?=qty3($c['cantidad'])?></span>
          <span><?=h($c['unidad_medida'])?></span>
        </div>
      <?php endforeach; ?>

      <div class="comp ff" style="margin-top:4px">
        <span class="comp-name total">Total :</span><span class="qty"><?= (int)$p['total'] ?></span><span><?=$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; ?>
    </div>

    <!-- Columna 3 -->
    <div>
      <div>Doc: <?=h($p['doc'])?></div>
      <div>Pac: <?=h($p['pac'])?> <?= $p['mascota'] ? "(Mascota: ".h($p['mascota']).")" : "" ?></div>
      <div>F. Elab.: <?=h(fmt_date($p['fecha_elaboracion']))?></div>
      <div>F. Venc.: <?=h(fmt_date($p['fecha_vencimiento']))?></div>
      <div class="azul" style="margin-top:4px">QF NINOSKA FRANCO</div>
      <div class="rojo-small">DOSIS INDICACION MEDICA</div>
    </div>

    <div class="footer-azul" style="grid-column:1 / span 3;">
      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>
  </div>
</div>
</body>
</html>

