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

/* === Recibir IDs seleccionados === */
$ids = $_POST['ids'] ?? $_GET['ids'] ?? [];
if (is_string($ids)) { $ids = [$ids]; }
$ids = array_values(array_filter(array_map('intval',$ids)));

if (empty($ids)) {
  http_response_code(400);
  echo "<!doctype html><meta charset='utf-8'><body style='font-family:system-ui,Arial'>
  <p>No se recibieron IDs. Vuelve al <a href='list.php'>listado</a> y selecciona preparados.</p></body>";
  exit;
}

/* === Cargar datos === */
$sqlP = $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 = ?
");
$sqlC = $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
");

/* Helpers */
function unidad_total($forma){
  $f = mb_strtolower((string)$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 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 fmt_date_local($d){
  if(!$d) return '';
  $t = strtotime($d);
  return date('d-m-Y', $t ?: time());
}
function normalize_txt($s){
  $s = mb_strtolower((string)$s,'UTF-8');
  $map = ['á'=>'a','é'=>'e','í'=>'i','ó'=>'o','ú'=>'u','ü'=>'u','ñ'=>'n'];
  return strtr($s,$map);
}

/* Lógica estrella (controlado) */
$ctrl_list = ['clordiazepoxido','diazepam','alprazolam','bromazepam','lorazepam','clonazepam'];

function etiqueta_html($p, $comps, $ctrl_list) {
  // ¿Controlado?
  $is_controlado = false;
  foreach($comps as $c){
    $n = normalize_txt($c['nombre_componente'] ?? '');
    foreach($ctrl_list as $k){
      if (strpos($n, $k) !== false) { $is_controlado = true; break 2; }
    }
  }

  $u = unidad_total($p['forma_farmaceutica']);
  $col1 = array_slice($comps, 0, 6);
  $col2 = array_slice($comps, 6);

  ob_start(); ?>
  <div class="print-area label-101x34 labelBox">
    <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>

    <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; ?>

      <!-- Total en una sola línea, con espacios mínimos -->
      <div class="comp ff g-total" 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): ?>
      <!-- Estrella verde (≈8mm, 80%) después del Total, pegada a la izquierda -->
      <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>

    <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_local($p['fecha_elaboracion']))?></div>
      <div>F. Venc.: <?=h(fmt_date_local($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>
  <?php
  return ob_get_clean();
}

/* Arreglo de etiquetas */
$labels = [];
foreach ($ids as $id) {
  $sqlP->execute([$id]); $p = $sqlP->fetch();
  if(!$p) continue;
  $sqlC->execute([$id]); $comps = $sqlC->fetchAll();
  $labels[] = ['id'=>$id, 'html'=>etiqueta_html($p, $comps, $ctrl_list)];
}
?>
<!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>Hoja múltiple · Avery 5162 (2×7)</title>
<style>
:root{
  /* 101×34 ajustado a Avery 5162 (101.6 × 33.9 mm) */
  --label-w: 101.6mm;
  --label-h: 33.9mm;
  --pad: 2mm;
  --col-gap: 2mm;
  --col1: 30mm; --col2: 28mm; --col3: 35.6mm;
}

/* Etiqueta individual (mismo look de label_preview) */
.print-area.label-101x34{
  display: grid;
  grid-template-columns: var(--col1) var(--col2) var(--col3);
  column-gap: var(--col-gap);
  align-items: start;
  font-size: 9px;
  width: var(--label-w); height: var(--label-h);
  box-sizing: border-box;
  padding: var(--pad);
  background: #fff;        /* FONDO BLANCO explícito */
  overflow: hidden;
  border: none;
}
.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:7.8px}
.rojo-small{color:#b71c1c;font-size:9px;font-weight:700}
.footer-azul{color:#0b4aa2;font-size:8px;margin-top:2px;text-align:center}
.azul{color:#0b4aa2;font-weight:700}

/* Estrella controlado (8mm) */
.star-holder{ margin-top:1mm; text-align:left; }
.star-green{ width:8mm; height:8mm; display:block; margin-left:0; }

/* Vista previa (vertical). Sin sombras en PDF, solo en pantalla */
.container{max-width:940px;margin:16px auto}
.toolbar{display:flex;gap:8px;margin-bottom:12px;flex-wrap:wrap}
.hint{color:#333;font-size:13px}
.preview-list .labelBox{margin:8px 0; box-shadow:0 0 0 1px #e5e7eb inset;}
</style>
</head>
<body>
<div class="container">
  <div class="no-print toolbar">
    <a class="btn" href="list.php">← Volver</a>
    <button class="btn" id="btnDownload">📄 Descargar PDF (Avery 5162 2×7)</button>
    <span class="hint">Se colocan 14 por hoja (2×7). Si hay más, se crean múltiples páginas.</span>
  </div>

  <!-- Vista previa simple (vertical) -->
  <div class="preview-list" id="previewList">
    <?php foreach($labels as $L): ?>
      <?= $L['html'] ?>
    <?php endforeach; ?>
  </div>
</div>

<!-- Cargador robusto con fallbacks -->
<script>
function loadScriptOnce(urls, globalCheck){
  return new Promise(async (resolve, reject) => {
    try { if (globalCheck()) return resolve(); } catch(e){}
    for (const src of urls) {
      try {
        await new Promise((res, rej) => {
          const s = document.createElement('script');
          s.src = src; s.async = true;
          s.onload = () => res();
          s.onerror = () => rej(new Error('No cargó: '+src));
          document.head.appendChild(s);
        });
        if (globalCheck()) return resolve();
      } catch(e) {}
    }
    reject(new Error('No fue posible cargar: ' + urls.join(' | ')));
  });
}
const H2C_SRCS = [
  '../../assets/js/html2canvas.min.js',
  'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js',
  'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js',
  'https://unpkg.com/html2canvas@1.4.1/dist/html2canvas.min.js'
];
const JSPDF_SRCS = [
  '../../assets/js/jspdf.umd.min.js',
  'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js',
  'https://cdn.jsdelivr.net/npm/jspdf@2.5.1/dist/jspdf.umd.min.js',
  'https://unpkg.com/jspdf@2.5.1/dist/jspdf.umd.min.js'
];
function ensureLibs(){
  return Promise.all([
    loadScriptOnce(H2C_SRCS, () => !!window.html2canvas),
    loadScriptOnce(JSPDF_SRCS, () => !!(window.jspdf && window.jspdf.jsPDF))
  ]);
}
</script>

<script>
(async function(){
  const btn = document.getElementById('btnDownload');
  btn.addEventListener('click', async function(e){
    e.preventDefault();
    try { await ensureLibs(); } catch(err){
      console.error(err);
      alert('No se pudieron cargar html2canvas/jsPDF.');
      return;
    }

    const nodes = Array.from(document.querySelectorAll('.labelBox'));
    if (!nodes.length){ alert('No hay etiquetas para generar.'); return; }

    // Contenedor offscreen para clones limpios (sin sombra)
    const wrapper = document.createElement('div');
    wrapper.style.position = 'fixed';
    wrapper.style.left = '-10000px';
    wrapper.style.top = '0';
    document.body.appendChild(wrapper);

    const images = [];
    for (const el of nodes) {
      // ---- CLON LIMPIO: fondo blanco y sin sombra ----
      const clone = el.cloneNode(true);
      clone.style.background = '#ffffff';
      clone.style.boxShadow = 'none';
      clone.style.filter = 'none';
      clone.style.transform = 'none';
      wrapper.appendChild(clone);

      const canvas = await window.html2canvas(clone, {
        scale: 3,
        backgroundColor: '#ffffff',
        useCORS: false,
        allowTaint: true,
        scrollX: 0,
        scrollY: 0
      });

      images.push(canvas.toDataURL('image/jpeg', 0.98));
      wrapper.removeChild(clone);
    }
    try { document.body.removeChild(wrapper); } catch(e){}

    const { jsPDF } = window.jspdf;
    const pdf = new jsPDF({ unit: 'mm', format: 'letter', orientation: 'portrait' });

    /* ===== Avery 5162 =====
       2 columnas × 7 filas
       Tamaño etiqueta: 101.6 × 33.9 mm
       Pitch H: 107.95 mm, Pitch V: 38.1 mm
       Márgenes: izquierda 4.2 mm, superior 12.7 mm
    */
    const LABEL_W = 101.6;
    const LABEL_H = 33.9;
    const H_PITCH = 107.95;
    const V_PITCH = 38.1;
    const MARGIN_LEFT = 4.2;
    const MARGIN_TOP  = 12.7;
    const COLS = 2, ROWS = 7, PER_PAGE = COLS * ROWS;

    for (let i = 0; i < images.length; i++) {
      if (i > 0 && i % PER_PAGE === 0) pdf.addPage('letter', 'portrait');

      const idxInPage = i % PER_PAGE;
      const r = Math.floor(idxInPage / COLS);
      const c = idxInPage % COLS;
      const x = MARGIN_LEFT + c * H_PITCH;
      const y = MARGIN_TOP  + r * V_PITCH;

      // Fondo blanco “debajo” (por seguridad)
      pdf.setFillColor(255,255,255);
      pdf.rect(x, y, LABEL_W, LABEL_H, 'F');

      pdf.addImage(images[i], 'JPEG', x, y, LABEL_W, LABEL_H);
    }

    pdf.save('etiquetas_avery_5162.pdf');
  });
})();
</script>
</body>
</html>
