<?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,
    pi.advances,
    pi.extras,
    pi.discounts,
    pi.net_pay
FROM payroll_items pi
JOIN employees e ON e.id = pi.employee_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;