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

$id = intval($_GET['id'] ?? 0);
if ($id <= 0) {
    die("Invalid payroll id");
}

// Fetch payroll + employee
$stmt = $conn->prepare("SELECT p.*, e.name AS employee_name, e.email, e.position, e.id AS employee_id 
                        FROM payrolls p 
                        JOIN employees e ON p.employee_id = e.id 
                        WHERE p.id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$res = $stmt->get_result();
$r = $res->fetch_assoc();
if (!$r) {
    die("Payroll not found");
}

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

class PDF extends FPDF {
    function Header() {
        global $settings;
        if (!empty($settings['company_logo'])) {
            $logoPath = __DIR__ . '/uploads/company/' . $settings['company_logo'];
            if (file_exists($logoPath)) {
                $this->Image($logoPath, 10, 6, 28);
            }
        }
        $this->SetFont('Arial','B',14);
        $this->Cell(0,6, $settings['company_name'] ?? 'Company', 0,1,'C');
        $this->SetFont('Arial','',10);
        if (!empty($settings['company_address'])) {
            $this->Cell(0,5, $settings['company_address'], 0,1,'C');
        }
        if (!empty($settings['company_tel'])) {
            $this->Cell(0,5, 'Tel: '.$settings['company_tel'], 0,1,'C');
        }
        $this->Ln(4);
    }
}

$pdf = new PDF('P','mm','A4');
$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 =====
$earnings = [
    ['desc'=>'Basic Pay','amount'=>floatval($r['basic'] ?? 0)],
    ['desc'=>'Allowance','amount'=>floatval($r['allowances'] ?? 0)],
    ['desc'=>'Overtime','amount'=>floatval($r['ot'] ?? 0)],
];
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'] ?? 'Other'),
                'amount'=> floatval($it['amount'] ?? 0)
            ];
        }
    }
}
$gross = array_sum(array_column($earnings, 'amount'));

// ===== Deductions =====
$deductions = [];

// JSON-based
if (!empty($r['deductions'])) {
    $d = json_decode($r['deductions'], true);
    if (is_array($d)) {
        foreach ($d as $it) {
            $deductions[] = [
                'desc'=> $it['description'] ?? ($it['code'] ?? 'Deduction'),
                'amount'=> floatval($it['amount'] ?? 0)
            ];
        }
    } else {
        $deductions[] = ['desc'=>'General Deduction','amount'=> floatval($r['deductions'])];
    }
}

// Statutory (columns in payrolls table)
$deductions[] = ['desc'=>'EPF Contribution','amount'=> floatval($r['epf'] ?? 0)];
$deductions[] = ['desc'=>'SOCSO Contribution','amount'=> floatval($r['socso'] ?? 0)];
$deductions[] = ['desc'=>'EIS Contribution','amount'=> floatval($r['eis'] ?? 0)];
$deductions[] = ['desc'=>'Income Tax','amount'=> floatval($r['tax'] ?? 0)];
$deductions[] = ['desc'=>'Zakat','amount'=> floatval($r['zakat'] ?? 0)];


// Advances from payments table
$start = ($r['payroll_month'] ?? date('Y-m'))."-01";
$end = date("Y-m-t", strtotime($start));
$payRes = $conn->query("SELECT * FROM payments 
                        WHERE employee_id={$r['employee_id']} 
                          AND payment_date BETWEEN '{$start}' AND '{$end}'");
if ($payRes) {
    while($pr = $payRes->fetch_assoc()) {
        $deductions[] = [
            'desc'=>'Advance ('.$pr['payment_date'].')',
            'amount'=> floatval($pr['amount'])
        ];
    }
}

$total_deductions = array_sum(array_column($deductions,'amount'));
$net_pay = $gross - $total_deductions;

// ===== Print Table =====
$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);

$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);

// Totals
$pdf->SetFont('Arial','B',11);
$pdf->Cell(120,7,'Gross Pay',0,0);
$pdf->Cell(35,7,'RM '.number_format($gross,2),0,1,'R');
$pdf->Cell(120,7,'Total Deductions',0,0);
$pdf->Cell(35,7,'RM '.number_format($total_deductions,2),0,1,'R');
$pdf->Ln(2);
$pdf->SetFont('Arial','B',12);
$pdf->Cell(120,10,'Net Pay',0,0);
$pdf->Cell(35,10,'RM '.number_format($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);

$employee_name_for_file = preg_replace('/[^A-Za-z0-9_\-]/', '_', ($r['employee_name'] ?? 'employee'));
$pdf->Output('I','payslip_'.$employee_name_for_file.'_'.($r['payroll_month'] ?? 'month').'.pdf');
exit;
