<?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;
$persona_id = isset($_GET['persona_id']) ? (int)$_GET['persona_id'] : 0;

$corridas = !$corrida_id ? nr_latest_corridas($conexion, 30) : [];
$info = $corrida_id ? nr_corrida_info($conexion, $corrida_id) : null;
$workers = $corrida_id ? nr_workers_for_corrida($conexion, $corrida_id) : [];
$movByPersona = ($corrida_id && $persona_id) ? nr_movements_for_corrida($conexion, $corrida_id) : [];
$persona = $persona_id && isset($workers[$persona_id]) ? $workers[$persona_id] : null;
$detalle = $persona;
$asig = [];
$ded = [];
$pat = [];
if ($persona) {
    list($asig, $ded, $pat) = nr_receipt_group($movByPersona[$persona_id] ?? []);
}
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>Recibos de Nómina</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;--primary2:#15326f;--bg:#f5f7fa;--card:#fff;--border:#e1e5eb;--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)}a{color:var(--primary);text-decoration:none}.container{max-width:1200px;margin:24px auto;padding:0 16px}.topbar,.card,.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}.card{padding:16px;margin-top:16px}.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}.btn.secondary{background:#fff;color:var(--primary);border-color:rgba(26,60,139,.25)}.btn.ghost{background:#eef4ff;color:var(--primary)}.grid{display:grid;grid-template-columns:repeat(12,1fr);gap:12px}.col-4{grid-column:span 4}.col-6{grid-column:span 6}.col-12{grid-column:span 12}@media (max-width:960px){.col-4,.col-6{grid-column:span 12}}label{display:block;font-size:12px;color:#374151;margin:0 0 6px 2px;font-weight:600}select{width:100%;padding:10px 12px;border:1px solid var(--border);border-radius:12px;background:#fff;outline:none}.table{width:100%;border-collapse:collapse;border:1px solid var(--border);border-radius:12px;overflow:hidden}.table th,.table td{padding:10px 12px;border-bottom:1px solid #eef2f7;font-size:12px;text-align:left;vertical-align:top}.table th{background:#fafafa;font-weight:800}.table tr:last-child td{border-bottom:none}.badge{display:inline-flex;align-items:center;gap:6px;font-size:12px;padding:6px 10px;border-radius:999px;background:rgba(26,60,139,.10);color:var(--primary);border:1px solid rgba(26,60,139,.18)}.receipt{margin-top:16px;overflow:hidden}.receipt-header{padding:20px;background:linear-gradient(135deg,var(--primary),var(--primary2));color:#fff}.receipt-body{padding:20px}.info-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin-bottom:18px}@media(max-width:960px){.info-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:620px){.info-grid{grid-template-columns:1fr}}.info-box{background:#f8fafc;border:1px solid #e5e7eb;border-radius:12px;padding:12px}.info-box .lbl{font-size:11px;color:var(--muted)}.info-box .val{font-size:16px;font-weight:800;margin-top:4px}.section-title{font-weight:800;margin:18px 0 8px}.receipt-grid{display:grid;grid-template-columns:minmax(260px,2fr) minmax(90px,.6fr) minmax(220px,1.2fr) minmax(120px,.8fr);gap:0;border:1px solid var(--border);border-radius:12px;overflow:hidden}.receipt-grid>div{padding:10px 12px;border-bottom:1px solid #eef2f7;font-size:13px}.receipt-grid>div:nth-child(4n+2),.receipt-grid>div:nth-child(4n+4){text-align:right}.receipt-grid>div.header{background:#fafafa;font-weight:800}.receipt-grid .ref{font-size:11px;color:#64748b}.totals{margin-top:18px;padding-top:14px;border-top:1px dashed #cbd5e1;display:grid;grid-template-columns:repeat(3,1fr);gap:12px}.total-box{background:#f8fafc;border:1px solid #e5e7eb;border-radius:12px;padding:12px}.total-box .label{font-size:12px;color:var(--muted)}.total-box .value{font-size:20px;font-weight:800;margin-top:4px}.helper-list{margin-top:16px}.helper-list .row{display:flex;justify-content:space-between;gap:12px;padding:8px 0;border-bottom:1px dashed #e5e7eb;font-size:12px}.helper-list .row:last-child{border-bottom:none}.selector-card{display:flex;align-items:flex-end;gap:10px;flex-wrap:wrap}.worker-list td:last-child{text-align:right}@media print {.topbar,.selector,.no-print{display:none!important}.container{margin:0;max-width:none;padding:0}.receipt{box-shadow:none;border:none}.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}}
</style>
</head>
<body>
<div class="container">
  <div class="topbar no-print">
    <div>
      <div class="title">Recibos de Nómina</div>
      <div class="subtitle">Consulta recibos por corrida y trabajador.</div>
    </div>
    <div style="display:flex;gap:8px;flex-wrap:wrap;">
      <?php if ($corrida_id && $info): ?><a class="btn secondary" href="nomina_corrida_resumen.php?corrida_id=<?php echo (int)$corrida_id; ?>">Resumen corrida</a><?php endif; ?>
      <?php if ($corrida_id && $info): ?><a class="btn ghost" href="nomina_recibos_lote.php?corrida_id=<?php echo (int)$corrida_id; ?>">Imprimir todos</a><?php endif; ?>
      <a class="btn secondary" href="<?php echo $corrida_id && $info ? 'nomina_corrida_resumen.php?corrida_id='.(int)$corrida_id : 'nomina_calcular_actualizado.php'; ?>">Volver</a>
      <a class="btn secondary" href="index.php">Inicio</a>
      <?php if ($corrida_id && $persona_id && $detalle): ?><button class="btn" type="button" onclick="window.print()">Imprimir</button><?php endif; ?>
    </div>
  </div>

  <?php if (!$corrida_id): ?>
    <div class="card">
      <div class="title" style="font-size:16px;">Últimas corridas</div>
      <div class="subtitle" style="margin-bottom:12px;">Selecciona una corrida para abrir sus recibos o revisar el resumen.</div>
      <table class="table">
        <thead><tr><th>Corrida</th><th>Período</th><th>Estado</th><th>Fecha cálculo</th><th>Trabajadores</th><th>Neto total</th><th></th></tr></thead>
        <tbody>
        <?php if ($corridas): foreach($corridas as $c): ?>
          <tr>
            <td><span class="badge">#<?php echo (int)$c['id']; ?></span></td>
            <td><?php echo nr_h($c['periodo_codigo']); ?></td>
            <td><?php echo nr_h($c['estado']); ?></td>
            <td><?php echo nr_h($c['fecha_calculo']); ?></td>
            <td><?php echo (int)$c['total_trabajadores']; ?></td>
            <td><?php echo nr_money($c['total_neto']); ?></td>
            <td style="white-space:nowrap; text-align:right;">
              <a class="btn secondary" href="nomina_corrida_resumen.php?corrida_id=<?php echo (int)$c['id']; ?>">Resumen</a>
              <a class="btn" href="nomina_recibo.php?corrida_id=<?php echo (int)$c['id']; ?>">Recibos</a>
            </td>
          </tr>
        <?php endforeach; else: ?>
            <tr><td colspan="7">No hay corridas registradas todavía.</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  <?php else: ?>
    <?php if (!$info): ?>
      <div class="card">La corrida indicada no existe o no pudo cargarse.</div>
    <?php else: ?>
      <div class="grid selector">
        <div class="card col-6">
          <div class="muted">Corrida</div>
          <div style="font-size:18px;font-weight:800;">#<?php echo (int)$corrida_id; ?> · <?php echo nr_h($info['estado']); ?></div>
          <div class="muted" style="margin-top:6px;">Período: <?php echo nr_h($info['periodo_codigo']); ?> · <?php echo nr_h($info['fecha_desde']); ?> a <?php echo nr_h($info['fecha_hasta']); ?></div>
        </div>
        <div class="card col-6">
          <form method="get">
            <input type="hidden" name="corrida_id" value="<?php echo (int)$corrida_id; ?>">
            <div class="selector-card">
              <div style="flex:1 1 360px;min-width:260px;">
                <label>Seleccionar trabajador</label>
                <select name="persona_id" onchange="this.form.submit()">
                  <option value="">-- Seleccionar --</option>
                  <?php foreach($workers as $wk): ?>
                    <option value="<?php echo (int)$wk['persona_id']; ?>" <?php echo ($persona_id === (int)$wk['persona_id'] ? 'selected' : ''); ?>>
                      <?php echo nr_h(trim($wk['apellido'].' '.$wk['nombre']).' - '.$wk['cedula']); ?>
                    </option>
                  <?php endforeach; ?>
                </select>
              </div>
            </div>
          </form>
        </div>
      </div>

      <?php if ($persona_id && $persona && $detalle): ?>
        <?php $salary = nr_salary_context($persona, $info); ?>
        <div class="receipt">
          <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:20px;font-weight:800;">RECIBO DE PAGO</div>
                <div style="font-size:13px;opacity:.92;">Período: <?php echo nr_h($info['periodo_codigo']); ?></div>
              </div>
              <div style="text-align:right;">
                <div style="font-size:13px;opacity:.92;">Trabajador</div>
                <div style="font-size:18px;font-weight:800;"><?php echo nr_h(trim($persona['nombre'].' '.$persona['apellido'])); ?></div>
                <div style="font-size:13px;opacity:.92;">C.I.: <?php echo nr_h($persona['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">Tasa BCV utilizada</div><div class="val"><?php echo number_format((float)$info['tasa_bcv_usd'], 4, '.', ''); ?></div></div>
              <div class="info-box"><div class="lbl">Salario referencia</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 class="info-box"><div class="lbl">Cargo</div><div class="val"><?php echo nr_h($persona['cargo'] ?: 'Sin cargo'); ?></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($detalle['total_asignaciones']); ?></div></div>
              <div class="total-box"><div class="label">Total deducciones</div><div class="value"><?php echo nr_money($detalle['total_deducciones']); ?></div></div>
              <div class="total-box"><div class="label">Neto a pagar</div><div class="value"><?php echo nr_money($detalle['neto_pagar']); ?></div></div>
            </div>


            <?php if ($pat): ?>
            <div class="section-title">Aportes patronales informativos</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 foreach($pat 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; ?>
            </div>
            <div class="muted" style="margin-top:8px;">Estos montos son costo patronal/parafiscal y no forman parte de las deducciones del trabajador.</div>
            <?php endif; ?>

            <div class="helper-list">
              <div class="row"><span>Origen salarial</span><strong><?php echo nr_h($salary['label']); ?></strong></div>
              <div class="row"><span>Equivalente referencial en Bs</span><strong><?php echo nr_money($salary['monto_bs']); ?></strong></div>
              <div class="row"><span>Cestaticket mensual de la corrida</span><strong>USD <?php echo nr_money($info['cestaticket_usd_mensual']); ?></strong></div>
              <div class="row"><span>Total patronal informativo</span><strong><?php echo nr_money($detalle['total_patronal'] ?? 0); ?> Bs</strong></div>
            </div>
          </div>
        </div>
      <?php elseif ($persona_id): ?>
        <div class="card">No se encontró detalle de nómina para el trabajador seleccionado en esta corrida.</div>
      <?php else: ?>
        <div class="card">
          <div class="title" style="font-size:16px;">Trabajadores incluidos en la corrida</div>
          <div class="subtitle" style="margin-bottom:12px;">Selecciona un trabajador arriba o abre un recibo desde la tabla.</div>
          <table class="table worker-list">
            <thead><tr><th>Trabajador</th><th>Cargo</th><th>Asignaciones</th><th>Deducciones</th><th>Neto</th><th>Patronal</th><th></th></tr></thead>
            <tbody>
            <?php foreach($workers as $wk): ?>
              <tr>
                <td><?php echo nr_h(trim($wk['apellido'].' '.$wk['nombre'])); ?><div class="muted"><?php echo nr_h($wk['cedula']); ?></div></td>
                <td><?php echo nr_h($wk['cargo'] ?: 'Sin cargo'); ?></td>
                <td><?php echo nr_money($wk['total_asignaciones']); ?></td>
                <td><?php echo nr_money($wk['total_deducciones']); ?></td>
                <td><?php echo nr_money($wk['neto_pagar']); ?></td>
                <td><?php echo nr_money($wk['total_patronal'] ?? 0); ?></td>
                <td><a class="btn secondary" href="nomina_recibo.php?corrida_id=<?php echo (int)$corrida_id; ?>&persona_id=<?php echo (int)$wk['persona_id']; ?>">Abrir recibo</a></td>
              </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    <?php endif; ?>
  <?php endif; ?>
</div>
</body>
</html>