<?php require_once __DIR__ . '/../includes/bootstrap.php'; require_login(); $id = (int)($_GET['id'] ?? 0); $stmt = db()->prepare("SELECT * FROM payroll_periods WHERE id = ?"); $stmt->execute([$id]); $period = $stmt->fetch(); if (!$period) { die('Período no encontrado.'); } header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename=nomina_' . $period['year'] . '_' . $period['month'] . '.csv'); $out = fopen('php://output', 'w'); fputs($out, chr(0xEF) . chr(0xBB) . chr(0xBF)); fputcsv($out, ['Empleado','Cédula','Salario base','Adelantos del mes','Extras','Descuentos','Neto']); $sql = "SELECT e.full_name, e.document_number, pi.base_salary, (SELECT COALESCE(SUM(sa.amount),0) FROM salary_advances sa WHERE sa.employee_id = e.id AND YEAR(sa.advance_date)=p.year AND MONTH(sa.advance_date)=p.month AND sa.status='Activo') advance_total, pi.extras, pi.discounts, pi.net_pay FROM payroll_items pi JOIN employees e ON e.id = pi.employee_id JOIN payroll_periods p ON p.id = pi.period_id WHERE pi.period_id = ? ORDER BY e.full_name"; $stmt = db()->prepare($sql); $stmt->execute([$id]); foreach ($stmt as $row) { fputcsv($out, $row); } fclose($out); exit;
