<?php include __DIR__ . '/../includes/header.php'; ensure_can_manage_payroll();
$year = (int)($_GET['year'] ?? 0);
$month = (int)($_GET['month'] ?? 0);
$where = [];
$params = [];
if ($year > 0) { $where[] = 'YEAR(sa.advance_date) = ?'; $params[] = $year; }
if ($month > 0) { $where[] = 'MONTH(sa.advance_date) = ?'; $params[] = $month; }
$whereSql = $where ? (' WHERE ' . implode(' AND ', $where)) : '';
$sql = "SELECT sa.*, e.full_name, e.document_number FROM salary_advances sa JOIN employees e ON e.id = sa.employee_id {$whereSql} ORDER BY sa.advance_date DESC, sa.id DESC";
$stmt = db()->prepare($sql); $stmt->execute($params);
?>
<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">Adelantos de salario</h4><div class="text-muted small">Podés cargar adelantos en cualquier momento. Se descuentan al generar o cerrar la nómina del mes correspondiente.</div></div><div class="d-flex gap-2"><a class="btn btn-outline-secondary" href="<?= e(base_url('payroll/index.php')) ?>">Ir a Nómina</a><a class="btn btn-primary" href="<?= e(base_url('advances/create.php')) ?>">Nuevo adelanto</a></div></div><form class="row g-2 mb-3" method="get"><div class="col-md-2"><input type="number" name="year" class="form-control" placeholder="Año" value="<?= $year ?: '' ?>"></div><div class="col-md-2"><select name="month" class="form-select"><option value="">Todos los meses</option><?php for ($i=1; $i<=12; $i++): ?><option value="<?= $i ?>" <?= $month===$i ? 'selected' : '' ?>><?= e(month_name_es($i)) ?></option><?php endfor; ?></select></div><div class="col-auto"><button class="btn btn-outline-primary">Filtrar</button></div><div class="col-auto"><a class="btn btn-outline-secondary" href="<?= e(base_url('advances/index.php')) ?>">Limpiar</a></div></form><div class="table-responsive"><table class="table table-bordered table-hover align-middle"><thead><tr><th>Fecha</th><th>Empleado</th><th>Cédula</th><th>Monto</th><th>Estado</th><th>Observación</th><th width="180">Acciones</th></tr></thead><tbody><?php foreach ($stmt as $row): ?><tr><td><?= e($row['advance_date']) ?></td><td><?= e($row['full_name']) ?></td><td><?= e($row['document_number']) ?></td><td><?= money_gs($row['amount']) ?></td><td><span class="badge text-bg-<?= e(status_badge_class($row['status'])) ?>"><?= e($row['status']) ?></span></td><td><?= e($row['notes']) ?></td><td><a class="btn btn-sm btn-warning" href="<?= e(base_url('advances/edit.php?id=' . $row['id'])) ?>">Editar</a> <a class="btn btn-sm btn-danger" href="<?= e(base_url('advances/delete.php?id=' . $row['id'])) ?>" onclick="return confirm('¿Eliminar adelanto?')">Eliminar</a></td></tr><?php endforeach; ?></tbody></table></div></div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
