<?php
require('fpdf/fpdf.php');
include 'db.php';

$month = $_GET['month'] ?? date('Y-m');

// Load settings
$settings = $conn->query("SELECT * FROM payroll_settings LIMIT 1")->fetch_assoc();

// Get payrolls + employee info
$sql = "SELECT p.*, e.name AS employee_name, e.position 
        FROM payrolls p 
        JOIN employees e ON p.employee_id=e.id
        WHERE p.payroll_month='{$month}'
        ORDER BY e.name";
$res = $conn->query($sql);

if (!$res || !$res->num_rows) {
    die("No payroll records found for $month");
}

class PDF extends FPDF {
    function Header() {
        global $settings;
        $this->SetFont('Arial','B',14);
        $this->Cell(0,6, $settings['company_name'] ?? 'Company', 0,1,'C');
        $this->SetFont('Arial','',10);
        $this->Cell(0,5, $settings['company_address'] ?? '', 0,1,'C');
        $this->Ln(4);
    }
}

$pdf = new PDF('P','mm','A4');

while($r = $res->fetch_assoc()) {
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',12);
    $pdf->Cell(0,6,'PAYSLIP',0,1,'C');
    $pdf->Ln(4);

    // Employee info
    $pdf->SetFont('Arial','',10);
    $pdf->Cell(100,6,"Employee: " . $r['employee_name'],0,0);
    $pdf->Cell(0,6,"Month: " . $r['payroll_month'],0,1);
    $pdf->Cell(100,6,"Position: " . ($r['position'] ?? ''),0,0);
    $pdf->Cell(0,6,"Payslip ID: " . $r['id'],0,1);
    $pdf->Ln(4);

    // Earnings & deductions
    $pdf->SetFont('Arial','B',10);
    $pdf->Cell(95,7,'EARNINGS',1,0,'C');
    $pdf->Cell(95,7,'DEDUCTIONS',1,1,'C');
    $pdf->SetFont('Arial','',10);

    $earnings = [
        ['desc'=>'Basic Pay','amount'=>$r['basic']],
        ['desc'=>'Allowance','amount'=>$r['allowances']],
        ['desc'=>'Overtime','amount'=>$r['ot']]
    ];
    if (!empty($r['other_earnings'])) {
        $extra = json_decode($r['other_earnings'], true);
        if (is_array($extra)) {
            foreach($extra as $it) $earnings[] = ['desc'=>$it['description'] ?? $it['code'], 'amount'=>$it['amount']];
        }
    }

    $deductions = [];
    if (!empty($r['deductions'])) {
        $d = json_decode($r['deductions'], true);
        if (is_array($d)) {
            foreach($d as $it) $deductions[] = ['desc'=>$it['description'] ?? $it['code'], 'amount'=>$it['amount']];
        }
    }

    $rows = max(count($earnings), count($deductions));
    for ($i=0; $i<$rows; $i++) {
        $e = $earnings[$i] ?? ['desc'=>'','amount'=>0];
        $d = $deductions[$i] ?? ['desc'=>'','amount'=>0];
        $pdf->Cell(60,7,$e['desc'],1,0);
        $pdf->Cell(35,7,number_format($e['amount'],2),1,0,'R');
        $pdf->Cell(60,7,$d['desc'],1,0);
        $pdf->Cell(35,7,number_format($d['amount'],2),1,1,'R');
    }

    $pdf->Ln(3);
    $pdf->Cell(120,7,'Gross Pay',0,0);
    $pdf->Cell(35,7,'RM '.number_format($r['gross'],2),0,1,'R');

    $pdf->Cell(120,7,'Total Deductions',0,0);
    $pdf->Cell(35,7,'RM '.number_format($r['total_deductions'],2),0,1,'R');

    $pdf->Ln(4);
    $pdf->SetFont('Arial','B',12);
    $pdf->Cell(120,10,'Net Pay',0,0);
    $pdf->Cell(35,10,'RM '.number_format($r['net_pay'],2),0,1,'R');

    $pdf->Ln(8);
    $pdf->SetFont('Arial','',10);
    $pdf->Cell(90,6,'Prepared By: ____________________',0,0);
    $pdf->Cell(90,6,'Received By: ____________________',0,1);
}

$pdf->Output('I','payslips_'.$month.'.pdf');
