<?php
session_start();
include 'config.php';

$month = $_GET['month'] ?? date('n');
$year = $_GET['year'] ?? date('Y');

require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Payroll ' . date('F Y', mktime(0,0,0,$month,1,$year)));

$result = $conn->query("SELECT * FROM payroll_belief WHERE month=$month AND year=$year ORDER BY employee_name");

$row = 1;
$sheet->setCellValue("A$row", 'Employee ID');
$sheet->setCellValue("B$row", 'Name');
$sheet->setCellValue("C$row", 'Gross Salary');
$sheet->setCellValue("D$row", 'Basic');
$sheet->setCellValue("E$row", 'HRA');
$sheet->setCellValue("F$row", 'Net Pay');
$sheet->setCellValue("G$row", 'PF');
$sheet->setCellValue("H$row", 'ESI');
$sheet->setCellValue("I$row", 'Tax');
$sheet->setCellValue("J$row", 'Total Deductions');
$row++;

while ($r = $result->fetch_assoc()) {
    $sheet->setCellValue("A$row", $r['employee_id']);
    $sheet->setCellValue("B$row", $r['employee_name']);
    $sheet->setCellValue("C$row", $r['gross_salary']);
    $sheet->setCellValue("D$row", $r['basic']);
    $sheet->setCellValue("E$row", $r['hra']);
    $sheet->setCellValue("F$row", $r['net_pay']);
    $sheet->setCellValue("G$row", $r['pf']);
    $sheet->setCellValue("H$row", $r['esi']);
    $sheet->setCellValue("I$row", $r['tax']);
    $sheet->setCellValue("J$row", $r['total_ded']);
    $row++;
}

$writer = new Xlsx($spreadsheet);
$filename = "payroll_{$month}_{$year}.xlsx";
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '"');
$writer->save('php://output');
exit();
?>