<?php
include('conexion.php');
include('nomina_reportes_common.php');
if (function_exists('nlm_ensure_master_schema')) { nlm_ensure_master_schema($conexion); }
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;
$q = trim((string)($_GET['q'] ?? ''));
$cargoFiltro = isset($_GET['cargo_id']) ? (int)$_GET['cargo_id'] : 0;
$origenFiltro = strtoupper(trim((string)($_GET['origen_salario'] ?? '')));
$conNovedades = isset($_GET['con_novedades']) && $_GET['con_novedades'] === '1';
$soloIncompletos = isset($_GET['solo_incompletos']) && $_GET['solo_incompletos'] === '1';
$export = strtolower(trim((string)($_GET['export'] ?? '')));
$flash = function_exists('nomina_flash_get') ? nomina_flash_get() : null;
$stateError = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cambiar_estado'])) {
    $corridaPost = (int)($_POST['corrida_id'] ?? 0);
    $estadoNuevo = strtoupper(trim((string)($_POST['estado_nuevo'] ?? '')));
    $motivo = trim((string)($_POST['motivo'] ?? ''));
    mysqli_begin_transaction($conexion);
    try {
        $resEstado = function_exists('nlm_transition_corrida_estado') ? nlm_transition_corrida_estado($conexion, $corridaPost, $estadoNuevo, $motivo) : ['ok'=>false, 'message'=>'Motor legal master no disponible.'];
        if (!($resEstado['ok'] ?? false)) {
            throw new Exception($resEstado['message'] ?? 'No se pudo cambiar el estado.');
        }
        mysqli_commit($conexion);
        if (function_exists('nomina_flash_set')) { nomina_flash_set('success', $resEstado['message'] ?? 'Estado actualizado.'); }
        header('Location: nomina_corrida_resumen.php?corrida_id=' . $corridaPost);
        exit;
    } catch (Throwable $e) {
        mysqli_rollback($conexion);
        $stateError = $e->getMessage();
    }
}

$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 ? nr_movements_for_corrida($conexion, $corrida_id) : [];
$historialEstados = [];
$ajustesCorrida = [];
if ($corrida_id) {
    $resHist = mysqli_query($conexion, "SELECT * FROM nomina_corrida_estado_historial WHERE corrida_id = {$corrida_id} ORDER BY id ASC");
    if ($resHist) { while ($h = mysqli_fetch_assoc($resHist)) { $historialEstados[] = $h; } }
    if (function_exists('nlm_corrida_ajustes')) { $ajustesCorrida = nlm_corrida_ajustes($conexion, $corrida_id); }
}

$rows = [];
$cargos = [];
foreach ($workers as $wk) {
    $salary = nr_salary_context($wk, $info ?: []);
    $flags = nr_worker_flags($movByPersona[(int)$wk['persona_id']] ?? []);
    $pivot = ['A-001'=>0,'A-002'=>0,'A-003'=>0,'A-004'=>0,'A-005'=>0,'A-007'=>0,'A-008'=>0,'A-009'=>0,'A-010'=>0,'B-001'=>0,'B-002'=>0,'B-003'=>0,'B-004'=>0,'B-005'=>0,'B-006'=>0,'B-007'=>0,'P-001'=>0,'P-002'=>0,'P-003'=>0,'P-004'=>0,'P-005'=>0];
    foreach (($movByPersona[(int)$wk['persona_id']] ?? []) as $m) {
        $code = strtoupper((string)$m['codigo']);
        if (array_key_exists($code, $pivot)) $pivot[$code] += (float)$m['monto'];
    }
    $row = $wk + [
        'salary_source' => $salary['source'],
        'salary_label' => $salary['label'],
        'salary_currency' => $salary['moneda'],
        'salary_amount' => $salary['monto'],
        'salary_bs' => $salary['monto_bs'],
        'has_novedades' => $flags['con_novedades'],
        'has_deducciones' => $flags['con_deducciones'],
    ] + $pivot;

    $cargoId = (int)($wk['id_cargo'] ?? 0);
    if ($cargoId > 0) $cargos[$cargoId] = $wk['cargo'];

    if ($q !== '') {
        $hay = stripos((string)($wk['nombre'].' '.$wk['apellido'].' '.$wk['cedula'].' '.$wk['cargo']), $q) !== false;
        if (!$hay) continue;
    }
    if ($cargoFiltro > 0 && $cargoId !== $cargoFiltro) continue;
    if ($origenFiltro !== '' && $row['salary_source'] !== $origenFiltro) continue;
    if ($conNovedades && !$row['has_novedades']) continue;
    if ($soloIncompletos && $row['salary_source'] !== 'INCOMPLETO') continue;
    $rows[] = $row;
}
asort($cargos);

$totals = ['asig'=>0,'ded'=>0,'neto'=>0,'pat'=>0,'trab'=>count($rows),'incompletos'=>0];
foreach ($rows as $r) {
    $totals['asig'] += (float)$r['total_asignaciones'];
    $totals['ded'] += (float)$r['total_deducciones'];
    $totals['neto'] += (float)$r['neto_pagar'];
    $totals['pat'] += (float)($r['total_patronal'] ?? 0);
    if ($r['salary_source'] === 'INCOMPLETO') $totals['incompletos']++;
}
$totalConNovedades = 0;
foreach ($rows as $rowTemp) {
    if (!empty($rowTemp['has_novedades'])) {
        $totalConNovedades++;
    }
}

if ($export === 'csv' && $info) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="resumen_corrida_'.$corrida_id.'.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Trabajador','Cedula','Cargo','Origen salario','Moneda','Salario ref','Salario ref Bs','A-001','A-002','A-005','A-009','B-001','B-002','B-003','P-001 IVSS Patr','P-002 RPE Patr','P-003 FAOV Patr','P-004 INCES Patr','P-005 Pensiones','Asignaciones','Deducciones','Neto','Total patronal'], ';');
    foreach ($rows as $r) {
        fputcsv($out, [trim($r['apellido'].' '.$r['nombre']), $r['cedula'], $r['cargo'], $r['salary_source'], $r['salary_currency'], $r['salary_amount'], $r['salary_bs'], $r['A-001'], $r['A-002'], $r['A-005'], $r['A-009'], $r['B-001'], $r['B-002'], $r['B-003'], $r['P-001'], $r['P-002'], $r['P-003'], $r['P-004'], $r['P-005'], $r['total_asignaciones'], $r['total_deducciones'], $r['neto_pagar'], ($r['total_patronal'] ?? 0)], ';');
    }
    fclose($out);
    exit;
}
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>Resumen de Corrida</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;--ok:#166534;--warn:#b45309;--danger:#be123c;}*{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:1450px;margin:24px auto;padding:0 16px}.topbar,.card{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:20px;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:14px}.col-3{grid-column:span 3}.col-4{grid-column:span 4}.col-6{grid-column:span 6}.col-12{grid-column:span 12}@media(max-width:1100px){.col-3,.col-4,.col-6{grid-column:span 12}}label{display:block;font-size:12px;font-weight:700;margin:0 0 6px 2px;color:#334155}select,input{width:100%;padding:10px 12px;border:1px solid var(--border);border-radius:12px;background:#fff;font:inherit}.stats{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px;margin-top:14px}@media(max-width:960px){.stats{grid-template-columns:repeat(2,minmax(0,1fr))}}.stat{padding:14px;border:1px solid var(--border);border-radius:14px;background:#fff}.stat b{display:block;font-size:24px;margin-bottom:4px}.summary-line{padding:12px;border:1px dashed rgba(26,60,139,.25);background:#fbfdff;border-radius:12px;margin-top:12px}.table-wrap{overflow:auto;border:1px solid var(--border);border-radius:14px;margin-top:14px}.table{width:100%;border-collapse:collapse;min-width:1650px}.table th,.table td{padding:10px 12px;border-bottom:1px solid #eef2f7;font-size:13px;vertical-align:top;text-align:left}.table th{background:#fafafa;font-weight:800;position:sticky;top:0}.table td.num,.table th.num{text-align:right}.chip{display:inline-flex;align-items:center;gap:6px;padding:4px 8px;border-radius:999px;font-size:11px;font-weight:800}.chip.ok{background:rgba(22,101,52,.10);color:var(--ok)}.chip.warn{background:rgba(180,83,9,.10);color:var(--warn)}.chip.danger{background:rgba(190,18,60,.10);color:var(--danger)}.helper{border-left:4px solid #1a3c8b;background:rgba(26,60,139,.06);padding:14px;border-radius:14px;font-size:13px}.alert{padding:12px 14px;border-radius:12px;margin-top:12px;border:1px solid}.alert.success{background:rgba(22,101,52,.08);border-color:rgba(22,101,52,.22);color:var(--ok)}.alert.error{background:rgba(190,18,60,.08);border-color:rgba(190,18,60,.22);color:var(--danger)}.small{font-size:11px;color:#64748b}.actions{display:flex;gap:8px;flex-wrap:wrap}.toolbar{display:flex;justify-content:space-between;gap:12px;align-items:center;flex-wrap:wrap}@media print {.topbar,.no-print,.filters{display:none!important}.container{margin:0;max-width:none;padding:0}.card{box-shadow:none;border:none}.table th{position:static}}
</style>
</head>
<body>
<div class="container">
  <div class="topbar no-print">
    <div>
      <div class="title">Resumen de Corrida</div>
      <div class="subtitle">Revisa la nómina calculada antes de imprimir recibos o pagar.</div>
    </div>
    <div class="actions">
      <?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; ?>
      <?php if ($corrida_id && $info): ?><a class="btn secondary" href="nomina_recibo.php?corrida_id=<?php echo (int)$corrida_id; ?>">Recibos</a><?php endif; ?>
      <a class="btn secondary" href="nomina_calcular_actualizado.php<?php echo $info ? '?periodo_id='.(int)$info['periodo_id'] : ''; ?>">Volver</a>
      <a class="btn secondary" href="index.php">Inicio</a>
      <?php if ($corrida_id && $info): ?><button class="btn" type="button" onclick="window.print()">Imprimir resumen</button><?php endif; ?>
    </div>
  </div>
  <?php if ($flash): ?><div class="alert <?php echo nr_h($flash['type']); ?>"><?php echo nr_h($flash['message']); ?></div><?php endif; ?>
  <?php if ($stateError): ?><div class="alert error"><strong>No se pudo cambiar el estado:</strong> <?php echo nr_h($stateError); ?></div><?php endif; ?>

  <?php if (!$corrida_id): ?>
    <div class="card">
      <div class="title" style="font-size:16px;">Últimas corridas</div>
      <div class="subtitle" style="margin-bottom:12px;">Abre una corrida para revisar resultados, imprimir recibos o exportar 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 foreach($corridas as $c): ?>
            <tr>
              <td>#<?php echo (int)$c['id']; ?></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><a class="btn" href="nomina_corrida_resumen.php?corrida_id=<?php echo (int)$c['id']; ?>">Abrir resumen</a></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  <?php elseif (!$info): ?>
    <div class="card">La corrida indicada no existe o no pudo cargarse.</div>
  <?php else: ?>
    <div class="card">
      <div class="toolbar">
        <div>
          <div class="title" style="font-size:18px;">Corrida #<?php echo (int)$info['id']; ?> · <?php echo nr_h($info['estado']); ?></div>
          <div class="subtitle">Período <?php echo nr_h($info['periodo_codigo']); ?> · <?php echo nr_h($info['fecha_desde']); ?> a <?php echo nr_h($info['fecha_hasta']); ?> · Pago <?php echo nr_h($info['fecha_pago']); ?></div>
        </div>
        <div class="actions no-print">
          <a class="btn secondary" href="nomina_auditoria_corrida.php?corrida_id=<?php echo (int)$corrida_id; ?>">Hoja auditoría</a>
          <a class="btn secondary" href="nomina_reversos_ajustes.php?corrida_id=<?php echo (int)$corrida_id; ?>">Reversos/Ajustes</a>
          <a class="btn secondary" href="nomina_corrida_resumen.php?corrida_id=<?php echo (int)$corrida_id; ?>&export=csv">Exportar CSV</a>
          <a class="btn ghost" href="nomina_recibos_lote.php?corrida_id=<?php echo (int)$corrida_id; ?>">Vista de impresión masiva</a>
        </div>
      </div>
      <div class="summary-line">
        <strong>BCV de la corrida:</strong> <?php echo number_format((float)$info['tasa_bcv_usd'], 4, '.', ''); ?> ·
        <strong>Cestaticket mensual:</strong> USD <?php echo nr_money($info['cestaticket_usd_mensual']); ?> ·
        <strong>Última quincena:</strong> <?php echo ((int)$info['es_ultima_quincena'] === 1) ? 'Sí' : 'No'; ?>
      </div>
      <div class="stats">
        <div class="stat"><b><?php echo $totals['trab']; ?></b><div class="muted">Trabajadores en la vista</div></div>
        <div class="stat"><b><?php echo nr_money($totals['asig']); ?></b><div class="muted">Asignaciones</div></div>
        <div class="stat"><b><?php echo nr_money($totals['ded']); ?></b><div class="muted">Deducciones</div></div>
        <div class="stat"><b><?php echo nr_money($totals['neto']); ?></b><div class="muted">Neto total</div></div>
        <div class="stat"><b><?php echo nr_money($totals['pat']); ?></b><div class="muted">Aportes patronales</div></div>
      </div>
      <div class="stats" style="grid-template-columns:repeat(2,minmax(0,1fr));">
        <div class="stat"><b><?php echo $totals['incompletos']; ?></b><div class="muted">Con salario incompleto</div></div>
        <div class="stat"><b><?php echo (int)$totalConNovedades; ?></b><div class="muted">Con novedades o ajustes</div></div>
      </div>
    </div>

    <div class="card no-print">
      <div class="toolbar">
        <div>
          <div class="title" style="font-size:16px;">Flujo de cierre y auditoría laboral</div>
          <div class="subtitle">Secuencia recomendada: CALCULADA → REVISADA → APROBADA → PAGADA → CERRADA. Al cerrar, el período queda bloqueado. Desde esta versión el motivo es obligatorio en todos los pasos.</div>
        </div>
        <div><span class="chip warn">Estado actual: <?php echo nr_h($info['estado']); ?></span></div>
      </div>
      <?php $nextEstado = function_exists('nlm_estado_siguiente') ? nlm_estado_siguiente($info['estado']) : null; ?>
      <?php if ($nextEstado): ?>
        <form method="post" class="grid" style="margin-top:12px;align-items:end;">
          <input type="hidden" name="corrida_id" value="<?php echo (int)$corrida_id; ?>">
          <input type="hidden" name="estado_nuevo" value="<?php echo nr_h($nextEstado); ?>">
          <div class="col-6">
            <label>Observación / motivo de avance</label>
            <input type="text" name="motivo" minlength="10" required placeholder="Ej: Revisado por RRHH con soporte de novedades. Aprobado por gerencia. Pago ejecutado. Cierre definitivo...">
            <div class="small">Obligatorio desde REVISADA: deja evidencia mínima de quién revisó, autorizó o ejecutó el paso.</div>
          </div>
          <div class="col-3">
            <label>Siguiente estado</label>
            <input type="text" value="<?php echo nr_h($nextEstado); ?>" readonly>
          </div>
          <div class="col-3">
            <label>&nbsp;</label>
            <button class="btn" name="cambiar_estado" value="1" type="submit" onclick="return confirm('¿Confirmas avanzar esta corrida a <?php echo nr_h($nextEstado); ?>?');"><?php echo nr_h(nlm_estado_accion_label($info['estado'])); ?></button>
          </div>
        </form>
      <?php else: ?>
        <div class="summary-line"><strong>Flujo finalizado:</strong> esta corrida no tiene un siguiente estado automático. Si está CERRADA, no debe recalcularse ni editarse sin procedimiento de reverso.</div>
      <?php endif; ?>
      <?php if ($historialEstados): ?>
        <div class="table-wrap" style="margin-top:12px;">
          <table class="table" style="min-width:900px;">
            <thead><tr><th>Fecha</th><th>De</th><th>A</th><th>Usuario</th><th>Motivo</th></tr></thead>
            <tbody><?php foreach($historialEstados as $h): ?><tr><td><?php echo nr_h($h['created_at']); ?></td><td><?php echo nr_h($h['estado_anterior']); ?></td><td><?php echo nr_h($h['estado_nuevo']); ?></td><td><?php echo nr_h($h['usuario']); ?></td><td><?php echo trim((string)($h['motivo'] ?? '')) !== '' ? nr_h($h['motivo']) : '<span class="chip danger">Sin motivo registrado</span>'; ?></td></tr><?php endforeach; ?></tbody>
          </table>
        </div>
      <?php endif; ?>
    </div>

    <?php if (!empty($ajustesCorrida)): ?>
    <div class="card no-print">
      <div class="toolbar">
        <div>
          <div class="title" style="font-size:16px;">Ajustes y reversos registrados</div>
          <div class="subtitle">Incidencias posteriores registradas sin alterar movimientos originales.</div>
        </div>
        <a class="btn secondary" href="nomina_reversos_ajustes.php?corrida_id=<?php echo (int)$corrida_id; ?>">Abrir bitácora</a>
      </div>
      <div class="table-wrap" style="margin-top:12px;">
        <table class="table" style="min-width:1000px;">
          <thead><tr><th>Fecha</th><th>Tipo</th><th>Trabajador</th><th>Concepto</th><th class="num">Monto Bs</th><th>Motivo</th><th>Usuario</th></tr></thead>
          <tbody>
            <?php foreach($ajustesCorrida as $aj): ?>
            <tr>
              <td><?php echo nr_h($aj['created_at']); ?></td>
              <td><?php echo nr_h($aj['tipo']); ?></td>
              <td><?php echo nr_h(trim(($aj['apellido'] ?? '').' '.($aj['nombre'] ?? '')).' '.($aj['cedula'] ?? '')); ?></td>
              <td><?php echo nr_h(trim(($aj['codigo'] ?? '').' '.($aj['concepto_nombre'] ?? ''))); ?></td>
              <td class="num"><?php echo nr_money($aj['monto']); ?></td>
              <td><?php echo nr_h($aj['motivo']); ?></td>
              <td><?php echo nr_h($aj['usuario']); ?></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
    <?php endif; ?>

    <div class="card filters no-print">
      <div class="helper"><strong>Cómo revisar esta corrida</strong><br>Filtra por trabajador, cargo o fuente salarial. Las columnas P-001…P-005 son aportes patronales informativos y no disminuyen el neto del trabajador.</div>
      <form method="get" class="grid" style="margin-top:12px;align-items:end;">
        <input type="hidden" name="corrida_id" value="<?php echo (int)$corrida_id; ?>">
        <div class="col-4">
          <label>Buscar trabajador</label>
          <input type="text" name="q" value="<?php echo nr_h($q); ?>" placeholder="Nombre, cédula o cargo">
        </div>
        <div class="col-3">
          <label>Cargo</label>
          <select name="cargo_id">
            <option value="0">Todos</option>
            <?php foreach($cargos as $cid => $cname): ?>
              <option value="<?php echo (int)$cid; ?>" <?php echo ($cargoFiltro === (int)$cid ? 'selected' : ''); ?>><?php echo nr_h($cname); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-3">
          <label>Origen salarial</label>
          <select name="origen_salario">
            <option value="">Todos</option>
            <option value="FICHA" <?php echo ($origenFiltro==='FICHA'?'selected':''); ?>>Definido en ficha</option>
            <option value="CARGO" <?php echo ($origenFiltro==='CARGO'?'selected':''); ?>>Heredado del cargo</option>
            <option value="INCOMPLETO" <?php echo ($origenFiltro==='INCOMPLETO'?'selected':''); ?>>Incompleto</option>
          </select>
        </div>
        <div class="col-2">
          <label>&nbsp;</label>
          <div class="actions"><button class="btn" type="submit">Filtrar</button><a class="btn secondary" href="nomina_corrida_resumen.php?corrida_id=<?php echo (int)$corrida_id; ?>">Limpiar</a></div>
        </div>
        <div class="col-12 actions">
          <label style="display:flex;align-items:center;gap:8px;font-weight:600;"><input type="checkbox" name="solo_incompletos" value="1" <?php echo $soloIncompletos ? 'checked' : ''; ?> style="width:auto;">Solo salario incompleto</label>
          <label style="display:flex;align-items:center;gap:8px;font-weight:600;"><input type="checkbox" name="con_novedades" value="1" <?php echo $conNovedades ? 'checked' : ''; ?> style="width:auto;">Solo con novedades / ajustes</label>
        </div>
      </form>
    </div>

    <div class="card">
      <div class="table-wrap">
        <table class="table">
          <thead>
            <tr>
              <th>Trabajador</th>
              <th>Cargo</th>
              <th>Origen</th>
              <th class="num">Salario ref.</th>
              <th class="num">Salario ref. Bs</th>
              <th class="num">A-001</th>
              <th class="num">A-002</th>
              <th class="num">A-005</th>
              <th class="num">A-009</th>
              <th class="num">B-001</th>
              <th class="num">B-002</th>
              <th class="num">B-003</th>
              <th class="num">P-001</th>
              <th class="num">P-002</th>
              <th class="num">P-003</th>
              <th class="num">P-004</th>
              <th class="num">P-005</th>
              <th class="num">Patronal</th>
              <th class="num">Asign.</th>
              <th class="num">Ded.</th>
              <th class="num">Neto</th>
              <th>Acciones</th>
            </tr>
          </thead>
          <tbody>
          <?php if ($rows): foreach($rows as $r): ?>
            <tr>
              <td>
                <strong><?php echo nr_h(trim($r['apellido'].' '.$r['nombre'])); ?></strong>
                <div class="small">C.I. <?php echo nr_h($r['cedula']); ?></div>
                <?php if ($r['has_novedades']): ?><div class="small"><span class="chip warn">Con novedades</span></div><?php endif; ?>
              </td>
              <td><?php echo nr_h($r['cargo'] ?: 'Sin cargo'); ?></td>
              <td>
                <?php if ($r['salary_source'] === 'FICHA'): ?><span class="chip ok">Ficha</span>
                <?php elseif ($r['salary_source'] === 'CARGO'): ?><span class="chip warn">Cargo</span>
                <?php else: ?><span class="chip danger">Incompleto</span><?php endif; ?>
              </td>
              <td class="num"><?php echo nr_h($r['salary_currency']); ?> <?php echo nr_money($r['salary_amount']); ?></td>
              <td class="num"><?php echo nr_money($r['salary_bs']); ?></td>
              <td class="num"><?php echo nr_money($r['A-001']); ?></td>
              <td class="num"><?php echo nr_money($r['A-002']); ?></td>
              <td class="num"><?php echo nr_money($r['A-005']); ?></td>
              <td class="num"><?php echo nr_money($r['A-009']); ?></td>
              <td class="num"><?php echo nr_money($r['B-001']); ?></td>
              <td class="num"><?php echo nr_money($r['B-002']); ?></td>
              <td class="num"><?php echo nr_money($r['B-003']); ?></td>
              <td class="num"><?php echo nr_money($r['P-001']); ?></td>
              <td class="num"><?php echo nr_money($r['P-002']); ?></td>
              <td class="num"><?php echo nr_money($r['P-003']); ?></td>
              <td class="num"><?php echo nr_money($r['P-004']); ?></td>
              <td class="num"><?php echo nr_money($r['P-005']); ?></td>
              <td class="num"><strong><?php echo nr_money($r['total_patronal'] ?? 0); ?></strong></td>
              <td class="num"><?php echo nr_money($r['total_asignaciones']); ?></td>
              <td class="num"><?php echo nr_money($r['total_deducciones']); ?></td>
              <td class="num"><strong><?php echo nr_money($r['neto_pagar']); ?></strong></td>
              <td>
                <div class="actions">
                  <a class="btn secondary" href="nomina_recibo.php?corrida_id=<?php echo (int)$corrida_id; ?>&persona_id=<?php echo (int)$r['persona_id']; ?>">Recibo</a>
                </div>
              </td>
            </tr>
          <?php endforeach; else: ?>
            <tr><td colspan="22">No hay resultados con los filtros aplicados.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  <?php endif; ?>
</div>
</body>
</html>