<?php
include('conexion.php');
include('nomina_reportes_common.php');
if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); }
if (!isset($_SESSION['usuario'])) { header('Location: login.php'); exit; }

$corrida_id = isset($_GET['corrida_id']) ? (int)$_GET['corrida_id'] : 0;
$autoPrint = isset($_GET['print']) ? (int)$_GET['print'] === 1 : false;
$info = $corrida_id ? nr_corrida_info($conexion, $corrida_id) : null;
$workers = $corrida_id ? nr_workers_for_corrida($conexion, $corrida_id) : [];
$movByPersona = $corrida_id ? nr_movements_for_corrida($conexion, $corrida_id) : [];
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>Impresión masiva de recibos</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
:root{--primary:#1a3c8b;--bg:#f5f7fa;--card:#fff;--border:#e5e7eb;--text:#24364b;--muted:#6b7280;--shadow:0 8px 24px rgba(16,24,40,.08);--radius:16px;}*{box-sizing:border-box}body{margin:0;font-family:'Inter',sans-serif;background:var(--bg);color:var(--text)}.container{max-width:1200px;margin:24px auto;padding:0 16px}.topbar,.receipt{background:var(--card);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow)}.topbar{padding:16px;display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap}.title{font-size:18px;font-weight:800}.subtitle,.muted{font-size:12px;color:var(--muted)}.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;padding:10px 14px;border-radius:12px;border:1px solid transparent;background:var(--primary);color:#fff;font-weight:700;cursor:pointer;text-decoration:none}.btn.secondary{background:#fff;color:var(--primary);border-color:rgba(26,60,139,.25)}.receipt{margin-top:16px;overflow:hidden}.receipt-header{padding:18px 20px;background:linear-gradient(135deg,#1a3c8b,#15326f);color:#fff}.receipt-body{padding:18px}.info-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px;margin-bottom:14px}.info-box{background:#f8fafc;border:1px solid #e5e7eb;border-radius:12px;padding:10px}.info-box .lbl{font-size:11px;color:#6b7280}.info-box .val{font-size:14px;font-weight:800;margin-top:4px}.receipt-grid{display:grid;grid-template-columns:minmax(220px,2fr) minmax(80px,.6fr) minmax(220px,1.2fr) minmax(110px,.8fr);border:1px solid var(--border);border-radius:12px;overflow:hidden}.receipt-grid>div{padding:8px 10px;border-bottom:1px solid #eef2f7;font-size:12px}.receipt-grid>div.header{background:#fafafa;font-weight:800}.receipt-grid>div:nth-child(4n+2),.receipt-grid>div:nth-child(4n+4){text-align:right}.section-title{font-weight:800;margin:14px 0 8px}.totals{margin-top:14px;display:grid;grid-template-columns:repeat(4,1fr);gap:10px}.total-box{background:#f8fafc;border:1px solid #e5e7eb;border-radius:12px;padding:10px}.total-box .label{font-size:11px;color:#6b7280}.total-box .value{font-size:18px;font-weight:800;margin-top:4px}.page-break{page-break-after:always}.ref{font-size:11px;color:#64748b}@media print {.topbar{display:none!important}.container{margin:0;max-width:none;padding:0}.receipt{box-shadow:none;border:none;margin:0 0 16px 0;border-radius:0}.receipt-header{background:#fff!important;color:#111;border-bottom:2px solid #111}.receipt-grid>div.header{background:#f0f0f0!important;color:#111}.info-box,.total-box{background:#fff!important}body{background:#fff}}
</style>
<?php if ($autoPrint): ?><script>window.addEventListener('load',()=>window.print());</script><?php endif; ?>
</head>
<body>
<div class="container">
  <div class="topbar">
    <div>
      <div class="title">Impresión masiva de recibos</div>
      <div class="subtitle">Corrida #<?php echo (int)$corrida_id; ?> · <?php echo $info ? nr_h($info['periodo_codigo']) : 'Sin corrida'; ?></div>
    </div>
    <div style="display:flex;gap:8px;flex-wrap:wrap;">
      <?php if ($corrida_id): ?><a class="btn secondary" href="nomina_corrida_resumen.php?corrida_id=<?php echo (int)$corrida_id; ?>">Resumen</a><?php endif; ?>
      <?php if ($corrida_id): ?><a class="btn secondary" href="nomina_recibo.php?corrida_id=<?php echo (int)$corrida_id; ?>">Recibos</a><?php endif; ?>
      <a class="btn" href="nomina_recibos_lote.php?corrida_id=<?php echo (int)$corrida_id; ?>&print=1">Imprimir todos</a>
    </div>
  </div>
  <?php if (!$info): ?>
    <div class="receipt"><div class="receipt-body">No se encontró la corrida indicada.</div></div>
  <?php else: ?>
    <?php $index = 0; foreach($workers as $wk): $index++; $salary = nr_salary_context($wk, $info); list($asig, $ded, $pat) = nr_receipt_group($movByPersona[(int)$wk['persona_id']] ?? []); ?>
      <div class="receipt <?php echo $index < count($workers) ? 'page-break' : ''; ?>">
        <div class="receipt-header">
          <div style="display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;align-items:flex-start;">
            <div>
              <div style="font-size:18px;font-weight:800;">RECIBO DE PAGO</div>
              <div style="font-size:12px;opacity:.92;">Período: <?php echo nr_h($info['periodo_codigo']); ?></div>
            </div>
            <div style="text-align:right;">
              <div style="font-size:12px;opacity:.92;">Trabajador</div>
              <div style="font-size:17px;font-weight:800;"><?php echo nr_h(trim($wk['nombre'].' '.$wk['apellido'])); ?></div>
              <div style="font-size:12px;opacity:.92;">C.I.: <?php echo nr_h($wk['cedula']); ?></div>
            </div>
          </div>
        </div>
        <div class="receipt-body">
          <div class="info-grid">
            <div class="info-box"><div class="lbl">Fecha de pago</div><div class="val"><?php echo nr_h($info['fecha_pago']); ?></div></div>
            <div class="info-box"><div class="lbl">BCV</div><div class="val"><?php echo number_format((float)$info['tasa_bcv_usd'], 4, '.', ''); ?></div></div>
            <div class="info-box"><div class="lbl">Cargo</div><div class="val"><?php echo nr_h($wk['cargo'] ?: 'Sin cargo'); ?></div></div>
            <div class="info-box"><div class="lbl">Salario ref.</div><div class="val"><?php echo nr_h($salary['moneda']); ?> <?php echo nr_money($salary['monto']); ?></div><div class="muted"><?php echo nr_h($salary['label']); ?></div></div>
          </div>
          <div class="section-title">Asignaciones</div>
          <div class="receipt-grid">
            <div class="header">Concepto</div><div class="header">Cantidad</div><div class="header">Referencia</div><div class="header">Monto</div>
            <?php if ($asig): foreach($asig as $m): ?>
              <div><strong><?php echo nr_h($m['codigo'].' - '.$m['nombre']); ?></strong></div>
              <div><?php echo $m['cantidad'] === null ? '—' : nr_h(number_format((float)$m['cantidad'], 4, '.', '')); ?></div>
              <div class="ref"><?php echo nr_h(nr_reference_text($m)); ?></div>
              <div><?php echo nr_money($m['monto']); ?></div>
            <?php endforeach; else: ?><div>Sin asignaciones</div><div>—</div><div>—</div><div>0,00</div><?php endif; ?>
          </div>
          <div class="section-title">Deducciones</div>
          <div class="receipt-grid">
            <div class="header">Concepto</div><div class="header">Cantidad</div><div class="header">Referencia</div><div class="header">Monto</div>
            <?php if ($ded): foreach($ded as $m): ?>
              <div><strong><?php echo nr_h($m['codigo'].' - '.$m['nombre']); ?></strong></div>
              <div><?php echo $m['cantidad'] === null ? '—' : nr_h(number_format((float)$m['cantidad'], 4, '.', '')); ?></div>
              <div class="ref"><?php echo nr_h(nr_reference_text($m)); ?></div>
              <div><?php echo nr_money($m['monto']); ?></div>
            <?php endforeach; else: ?><div>Sin deducciones</div><div>—</div><div>—</div><div>0,00</div><?php endif; ?>
          </div>
          <div class="totals">
            <div class="total-box"><div class="label">Total asignaciones</div><div class="value"><?php echo nr_money($wk['total_asignaciones']); ?></div></div>
            <div class="total-box"><div class="label">Total deducciones</div><div class="value"><?php echo nr_money($wk['total_deducciones']); ?></div></div>
            <div class="total-box"><div class="label">Neto a pagar</div><div class="value"><?php echo nr_money($wk['neto_pagar']); ?></div></div>
            <div class="total-box"><div class="label">Patronal informativo</div><div class="value"><?php echo nr_money($wk['total_patronal'] ?? 0); ?></div></div>
          </div>
        </div>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</div>
</body>
</html>