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

if (!isset($_GET['id'])) {
    die("Quotation ID is required.");
}
$id = intval($_GET['id']);

// Get quotation
$qry = $conn->prepare("SELECT * FROM quotations WHERE id=?");
$qry->bind_param("i", $id);
$qry->execute();
$quotation = $qry->get_result()->fetch_assoc();

if (!$quotation) {
    die("Quotation not found!");
}

// Get quotation items
$items = $conn->query("SELECT * FROM quotation_items WHERE quotation_id=$id");

// Calculate totals
$subtotal = 0;
while($row = $items->fetch_assoc()){
    $subtotal += $row['total'];
    $quotation_items[] = $row;
}
$sst = $quotation['sst_enabled'] ? $subtotal * 0.08 : 0;
$grand_total = $subtotal + $sst;

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

// Company Header
$pdf->Cell(0,10,"VSONIC ENGINEERING",0,1,'C');
$pdf->SetFont('Arial','',12);
$pdf->Cell(0,6,"Professional Quotation",0,1,'C');
$pdf->Ln(10);

// Partner Info
$pdf->SetFont('Arial','B',12);
$pdf->Cell(100,6,"To: ".$quotation['partner_name'],0,1);
$pdf->SetFont('Arial','',11);
$pdf->MultiCell(100,6,$quotation['partner_address']);
$pdf->Ln(5);

// Quotation Info
$pdf->SetFont('Arial','',11);
$pdf->Cell(100,6,"Quotation No: ".$quotation['id'],0,0);
$pdf->Cell(0,6,"Date: ".$quotation['date_created'],0,1);
$pdf->Ln(8);

// Table Header
$pdf->SetFont('Arial','B',11);
$pdf->Cell(80,8,"Description",1);
$pdf->Cell(30,8,"Quantity",1);
$pdf->Cell(40,8,"Unit Price",1);
$pdf->Cell(40,8,"Total",1);
$pdf->Ln();

// Table Body
$pdf->SetFont('Arial','',11);
foreach($quotation_items as $item){
    $pdf->Cell(80,8,$item['description'],1);
    $pdf->Cell(30,8,$item['quantity'],1,0,'C');
    $pdf->Cell(40,8,number_format($item['unit_price'],2),1,0,'R');
    $pdf->Cell(40,8,number_format($item['total'],2),1,0,'R');
    $pdf->Ln();
}

// Totals
$pdf->Ln(5);
$pdf->Cell(150,8,"Subtotal",0,0,'R');
$pdf->Cell(40,8,number_format($subtotal,2),0,1,'R');

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

$pdf->SetFont('Arial','B',12);
$pdf->Cell(150,8,"Grand Total",0,0,'R');
$pdf->Cell(40,8,number_format($grand_total,2),0,1,'R');

// Footer
$pdf->Ln(15);
$pdf->SetFont('Arial','I',10);
$pdf->MultiCell(0,6,"This is a system generated quotation from VSONIC ENGINEERING.\nThank you for your business.");

$pdf->Output("D","quotation_".$id.".pdf");
?>
