<?php include __DIR__ . '/../includes/header.php'; ensure_can_manage_payroll(); ?>
<div class="table-wrap"><div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2"><div><h4 class="mb-0">Nómina</h4><div class="text-muted small">Períodos, generación masiva, cierre y aplicación de adelantos al momento del cierre.</div></div><div class="d-flex gap-2"><a class="btn btn-outline-primary" href="<?= e(base_url('advances/index.php')) ?>">Ver adelantos</a><a class="btn btn-primary" href="<?= e(base_url('payroll/create.php')) ?>">Nuevo período</a></div></div><div class="table-responsive"><table class="table table-bordered table-hover align-middle"><thead><tr><th>Año</th><th>Mes</th><th>Desde</th><th>Hasta</th><th>Estado</th><th>Total empleados</th><th>Total adelantos</th><th>Total neto</th><th width="420">Acciones</th></tr></thead><tbody><?php foreach (db()->query("SELECT p.*, (SELECT COUNT(*) FROM payroll_items pi WHERE pi.period_id=p.id) total_items, (SELECT COALESCE(SUM(sa.amount),0) FROM salary_advances sa WHERE YEAR(sa.advance_date)=p.year AND MONTH(sa.advance_date)=p.month AND sa.status='Activo') total_advances, (SELECT COALESCE(SUM(net_pay),0) FROM payroll_items pi WHERE pi.period_id=p.id) total_net FROM payroll_periods p ORDER BY p.id DESC") as $row): ?><tr><td><?= e($row['year']) ?></td><td><?= e(month_name_es($row['month'])) ?></td><td><?= e($row['start_date']) ?></td><td><?= e($row['end_date']) ?></td><td><span class="badge text-bg-<?= e(status_badge_class($row['status'])) ?>"><?= e($row['status']) ?></span></td><td><?= e($row['total_items']) ?></td><td><?= money_gs($row['total_advances']) ?></td><td><?= money_gs($row['total_net']) ?></td><td><a class="btn btn-sm btn-success" href="<?= e(base_url('payroll/generate.php?id=' . $row['id'])) ?>" onclick="return confirm('¿Generar o regenerar la nómina con los adelantos cargados hasta ahora?')">Generar</a> <?php if ($row['status'] !== 'Cerrado'): ?><a class="btn btn-sm btn-dark" href="<?= e(base_url('payroll/close.php?id=' . $row['id'])) ?>" onclick="return confirm('¿Cerrar nómina y recalcular descuentos por adelantos del período?')">Cerrar</a><?php endif; ?> <a class="btn btn-sm btn-info" href="<?= e(base_url('payroll/view.php?id=' . $row['id'])) ?>">Ver</a> <a class="btn btn-sm btn-outline-dark" href="<?= e(base_url('reports/payroll_summary.php?id=' . $row['id'])) ?>" target="_blank">Imprimir</a> <a class="btn btn-sm btn-outline-primary" href="<?= e(base_url('payroll/export.php?id=' . $row['id'])) ?>">CSV</a> <a class="btn btn-sm btn-danger" href="<?= e(base_url('payroll/delete.php?id=' . $row['id'])) ?>" onclick="return confirm('¿Eliminar período?')">Eliminar</a></td></tr><?php endforeach; ?></tbody></table></div></div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
