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

$project_id = $_GET['id'];
$project = $conn->query("SELECT * FROM projects WHERE id=$project_id")->fetch_assoc();

$expenses = $conn->query("SELECT * FROM project_expenses WHERE project_id=$project_id");

$total_expenses = 0;
while ($row = $expenses->fetch_assoc()) {
    $total_expenses += $row['expense_amount'];
}
$margin = $project['project_po_amount'] - $total_expenses;

$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',14);
$pdf->Cell(190,10,'Project Expense Report',0,1,'C');

$pdf->SetFont('Arial','',12);
$pdf->Cell(190,10,"Project: {$project['name']}",0,1);
$pdf->Cell(190,10,"PO Amount: RM " . number_format($project['project_po_amount'],2),0,1);
$pdf->Cell(190,10,"Total Expenses: RM " . number_format($total_expenses,2),0,1);
$pdf->Cell(190,10,"Margin: RM " . number_format($margin,2),0,1);

$pdf->Ln(10);
$pdf->SetFont('Arial','B',12);
$pdf->Cell(40,10,'Date',1);
$pdf->Cell(100,10,'Expense Name',1);
$pdf->Cell(50,10,'Amount (RM)',1,1);

$pdf->SetFont('Arial','',12);
$expenses = $conn->query("SELECT * FROM project_expenses WHERE project_id=$project_id");
while ($row = $expenses->fetch_assoc()) {
    $pdf->Cell(40,10,$row['expense_date'],1);
    $pdf->Cell(100,10,$row['expense_name'],1);
    $pdf->Cell(50,10,number_format($row['expense_amount'],2),1,1);
}

$pdf->Output('D','project_report.pdf');
?>