<?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; }
if (function_exists('nlm_ensure_master_schema')) { nlm_ensure_master_schema($conexion); }

$corridaId = isset($_GET['corrida_id']) ? (int)$_GET['corrida_id'] : 0;
$corridas = nr_latest_corridas($conexion, 50);
if (!$corridaId && $corridas) { $corridaId = (int)$corridas[0]['id']; }
$info = $corridaId ? nr_corrida_info($conexion, $corridaId) : null;
$rows = [];
$totalesConcepto = [];
$totalGeneral = 0;
if ($corridaId) {
    $sql = "SELECT p.cedula, p.nombre, p.apellido, c.codigo, c.nombre AS concepto, m.base, m.tasa, m.monto, m.meta
            FROM nomina_movimientos m
            INNER JOIN conceptos_nomina c ON c.id = m.concepto_id
            INNER JOIN personas p ON p.id = m.persona_id
            WHERE m.corrida_id = {$corridaId} AND c.tipo = 'PATR'
            ORDER BY c.codigo, p.apellido, p.nombre";
    $res = mysqli_query($conexion, $sql);
    if ($res) {
        while($r = mysqli_fetch_assoc($res)) {
            $rows[] = $r;
            $code = $r['codigo'];
            if (!isset($totalesConcepto[$code])) { $totalesConcepto[$code] = ['nombre'=>$r['concepto'], 'monto'=>0]; }
            $totalesConcepto[$code]['monto'] += (float)$r['monto'];
            $totalGeneral += (float)$r['monto'];
        }
    }
}
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8"><title>Aportes Patronales</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;--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:#24364b}.container{max-width:1350px;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{display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;padding:16px}.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;padding:10px 14px;border-radius:12px;border:1px solid transparent;background:var(--primary);color:#fff;font-weight:700;text-decoration:none}.btn.secondary{background:#fff;color:var(--primary);border-color:rgba(26,60,139,.25)}select{padding:10px 12px;border:1px solid var(--border);border-radius:12px;background:#fff}.stats{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:12px;margin-top:12px}@media(max-width:980px){.stats{grid-template-columns:repeat(2,minmax(0,1fr))}}.stat{border:1px solid var(--border);border-radius:14px;padding:14px;background:#fff}.stat b{display:block;font-size:22px}.table-wrap{overflow:auto;border:1px solid var(--border);border-radius:14px;margin-top:14px}.table{width:100%;border-collapse:collapse;min-width:1100px}.table th,.table td{padding:10px 12px;border-bottom:1px solid #eef2f7;font-size:13px;text-align:left;vertical-align:top}.table th{background:#fafafa;font-weight:800}.num{text-align:right!important}.chip{display:inline-flex;padding:4px 8px;border-radius:999px;background:rgba(26,60,139,.09);color:var(--primary);font-size:11px;font-weight:800}.actions{display:flex;gap:8px;flex-wrap:wrap}.helper{border-left:4px solid var(--primary);background:rgba(26,60,139,.06);padding:14px;border-radius:14px;font-size:13px}@media print{.topbar,.no-print{display:none!important}.container{margin:0;max-width:none;padding:0}.card{box-shadow:none;border:none}}
</style>
</head>
<body>
<div class="container">
 <div class="topbar no-print">
  <div><div class="title">Aportes Patronales y Parafiscales</div><div class="subtitle">IVSS patronal, RPE patronal, FAOV patronal, INCES y Protección de Pensiones por corrida.</div></div>
  <div class="actions"><a class="btn secondary" href="nomina_corrida_resumen.php<?php echo $corridaId ? '?corrida_id='.$corridaId : ''; ?>">Resumen</a><a class="btn secondary" href="index.php">Inicio</a><button class="btn" onclick="window.print()">Imprimir</button></div>
 </div>
 <div class="card no-print">
  <form method="get"><label class="muted">Corrida</label><br><select name="corrida_id" onchange="this.form.submit()">
   <?php foreach($corridas as $c): ?><option value="<?php echo (int)$c['id']; ?>" <?php echo (int)$c['id']===$corridaId?'selected':''; ?>>#<?php echo (int)$c['id']; ?> · <?php echo nr_h($c['periodo_codigo']); ?> · <?php echo nr_h($c['estado']); ?></option><?php endforeach; ?>
  </select></form>
 </div>
 <?php if (!$info): ?><div class="card">No hay corrida seleccionada.</div><?php else: ?>
 <div class="card">
  <div class="helper"><strong>Uso auditor:</strong> estos importes no afectan el neto del trabajador. Son costos/obligaciones patronales calculados con los parámetros legales vigentes congelados en la corrida.</div>
  <div class="stats">
   <?php foreach($totalesConcepto as $code=>$t): ?><div class="stat"><span class="chip"><?php echo nr_h($code); ?></span><b><?php echo nr_money($t['monto']); ?></b><div class="muted"><?php echo nr_h($t['nombre']); ?></div></div><?php endforeach; ?>
   <div class="stat"><span class="chip">TOTAL</span><b><?php echo nr_money($totalGeneral); ?></b><div class="muted">Total patronal</div></div>
  </div>
  <div class="table-wrap"><table class="table"><thead><tr><th>Concepto</th><th>Trabajador</th><th>Cédula</th><th class="num">Base</th><th class="num">Tasa</th><th>Referencia</th><th class="num">Monto</th></tr></thead><tbody>
   <?php if($rows): foreach($rows as $r): ?><tr><td><strong><?php echo nr_h($r['codigo'].' - '.$r['concepto']); ?></strong></td><td><?php echo nr_h(trim($r['apellido'].' '.$r['nombre'])); ?></td><td><?php echo nr_h($r['cedula']); ?></td><td class="num"><?php echo nr_money($r['base']); ?></td><td class="num"><?php echo number_format(((float)$r['tasa'])*100,2,',','.'); ?>%</td><td class="muted"><?php echo nr_h(nr_reference_text($r)); ?></td><td class="num"><strong><?php echo nr_money($r['monto']); ?></strong></td></tr><?php endforeach; else: ?><tr><td colspan="7">No hay aportes patronales en esta corrida.</td></tr><?php endif; ?>
  </tbody></table></div>
 </div>
 <?php endif; ?>
</div>
</body>
</html>
