<?php
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../Controllers/ReportsController.php';

use FPDF\FPDF;

class TrialBalancePDF extends FPDF {
    function Header() {
        $this->SetFont('Arial','B',14);
        $this->Cell(0,10,'Trial Balance Report',0,1,'C');
        $this->Ln(5);
        $this->SetFont('Arial','',10);
        $this->Cell(0,8,'SGAccount (Home Renovation Company) - Generated on '.date('d M Y'),0,1,'C');
        $this->Ln(8);
        $this->SetFont('Arial','B',10);
        $this->Cell(40,8,'Account Code',1,0,'C');
        $this->Cell(60,8,'Account Name',1,0,'C');
        $this->Cell(40,8,'Debit (SGD)',1,0,'C');
        $this->Cell(40,8,'Credit (SGD)',1,1,'C');
    }

    function Footer() {
        $this->SetY(-15);
        $this->SetFont('Arial','I',8);
        $this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
    }
}

$controller = new ReportsController();
$data = $controller->trialBalance();

$pdf = new TrialBalancePDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Arial','',10);

$totalDebit = $totalCredit = 0;
foreach ($data as $row) {
    $pdf->Cell(40,8,$row['account_code'],1);
    $pdf->Cell(60,8,$row['account_name'],1);
    $pdf->Cell(40,8,number_format($row['total_debit'],2),1,0,'R');
    $pdf->Cell(40,8,number_format($row['total_credit'],2),1,1,'R');
    $totalDebit += $row['total_debit'];
    $totalCredit += $row['total_credit'];
}

$pdf->SetFont('Arial','B',10);
$pdf->Cell(100,8,'Totals',1);
$pdf->Cell(40,8,number_format($totalDebit,2),1,0,'R');
$pdf->Cell(40,8,number_format($totalCredit,2),1,1,'R');

$pdf->Output('I', 'Trial_Balance_'.date('Ymd').'.pdf');
exit;
