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

$id = intval($_GET['id']);
$invoice = $conn->query("SELECT * FROM invoices WHERE id=$id")->fetch_assoc();
$items = $conn->query("SELECT * FROM invoice_items WHERE invoice_id=$id");

$total = 0;
while ($row = $items->fetch_assoc()) {
    $total += $row['total'];
    $invoice_items[] = $row;
}
$sst = $invoice['sst_enabled'] ? $total * 0.08 : 0;
$grandTotal = $total + $sst;

$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',14);

$pdf->Cell(0,10,"VSONIC ENGINEERING - Invoice #{$invoice['id']}",0,1,'C');
$pdf->Ln(5);

$pdf->SetFont('Arial','',12);
$pdf->Cell(0,10,"Partner: {$invoice['partner_name']}",0,1);
$pdf->MultiCell(0,8,"Address:\n{$invoice['partner_address']}");
$pdf->Cell(0,10,"Date: {$invoice['created_at']}",0,1);
$pdf->Ln(5);

$pdf->SetFont('Arial','B',12);
$pdf->Cell(90,10,'Description',1);
$pdf->Cell(25,10,'Qty',1,0,'C');
$pdf->Cell(35,10,'Unit Price',1,0,'C');
$pdf->Cell(40,10,'Total',1,1,'C');

$pdf->SetFont('Arial','',12);
foreach($invoice_items as $item){
    $pdf->Cell(90,10,$item['description'],1);
    $pdf->Cell(25,10,$item['quantity'],1,0,'C');
    $pdf->Cell(35,10,number_format($item['unit_price'],2),1,0,'R');
    $pdf->Cell(40,10,number_format($item['total'],2),1,1,'R');
}

$pdf->Ln(5);
$pdf->Cell(150,10,'Subtotal',1);
$pdf->Cell(40,10,number_format($total,2),1,1,'R');

if ($invoice['sst_enabled']) {
    $pdf->Cell(150,10,'SST (8%)',1);
    $pdf->Cell(40,10,number_format($sst,2),1,1,'R');
}

$pdf->SetFont('Arial','B',12);
$pdf->Cell(150,10,'Grand Total',1);
$pdf->Cell(40,10,number_format($grandTotal,2),1,1,'R');

$pdf->Output('D',"invoice_{$invoice['id']}.pdf");
?>
