<?php
session_start();
require 'config.php';
require 'vendor/autoload.php';
use FPDF;

class PDF extends FPDF {
    function Header() {
        $this->SetFont('Arial','B',16);
        $this->Cell(0,10,'PAYSLIP',0,1,'C');
        $this->Ln(5);
    }
}

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

if (!isset($_SESSION['user_id'])) die("Access denied.");

$result = $conn->query("SELECT * FROM payroll_belief WHERE month=$month AND year=$year ORDER BY employee_name");
if (!$result || $result->num_rows == 0) die("No data.");

$zip = new ZipArchive();
$zipFile = "payslips/payroll_{$month}_{$year}.zip";
if ($zip->open($zipFile, ZipArchive::CREATE) !== TRUE) die("ZIP error");

while ($r = $result->fetch_assoc()) {
    $pdf = new PDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','',12);

    $html = "<h3 style='text-align:center;'>".date('F Y', mktime(0,0,0,$month,1,$year))."</h3>
    <table border='1' cellpadding='6' width='100%'>
        <tr><td width='50%'><b>ID:</b> {$r['employee_id']}</td><td><b>Name:</b> {$r['employee_name']}</td></tr>
        <tr><td><b>Gross:</b> ₹".number_format($r['gross_salary'],2)."</td><td><b>Net:</b> <span style='color:green;'>₹".number_format($r['net_pay'],2)."</span></td></tr>
    </table><br>
    <table border='1' cellpadding='5' width='100%'>
        <tr style='background:#2c3e50;color:white;'><th colspan='2'>EARNINGS</th><th colspan='2'>DEDUCTIONS</th></tr>
        <tr><td>Basic</td><td>₹".number_format($r['basic'],2)."</td><td>PF</td><td>₹".number_format($r['pf'],2)."</td></tr>
        <tr><td>HRA</td><td>₹".number_format($r['hra'],2)."</td><td>ESI</td><td>₹".number_format($r['esi'],2)."</td></tr>
        <tr><td>Conv</td><td>₹".number_format($r['conv'],2)."</td><td>Tax</td><td>₹".number_format($r['tax'],2)."</td></tr>
        <tr style='background:#f0f0f0;font-weight:bold;'>
            <td>Total Earnings</td><td>₹".number_format($r['gross_earnings'],2)."</td>
            <td>Total Deductions</td><td>₹".number_format($r['total_ded'],2)."</td>
        </tr>
    </table>
    <br><p style='text-align:center;font-size:13pt;'><strong>Net Pay: ₹".number_format($r['net_pay'],2)."</strong></p>";

    $pdf->writeHTML($html, true, false, true, false, '');
    $file = "payslip_{$r['employee_id']}_{$month}_{$year}.pdf";
    $pdf->Output('F', $file);
    $zip->addFile($file, $file);
    unlink($file);
}

$zip->close();
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($zipFile).'"');
readfile($zipFile);
unlink($zipFile);
exit;
?>