<?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");

$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(190,10,"Project Report: {$project['project_name']}",0,1,'C');
$pdf->Ln(5);

$pdf->SetFont('Arial','',12);
$pdf->Cell(95,10,"Client: {$project['client_name']}",0,0);
$pdf->Cell(95,10,"PO Value: {$project['project_po']}",0,1);

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

$total = 0;
$pdf->SetFont('Arial','',12);
while($row = $expenses->fetch_assoc()){
    $pdf->Cell(90,10,$row['expense_name'],1);
    $pdf->Cell(50,10,$row['amount'],1);
    $pdf->Cell(50,10,$row['expense_date'],1,1);
    $total += $row['amount'];
}

$margin = $project['project_po'] - $total;
$pdf->Ln(10);
$pdf->Cell(95,10,"Total Expenses: $total",0,1);
$pdf->Cell(95,10,"Margin: $margin",0,1);

$pdf->Output('D', "project_report_{$project_id}.pdf");
?>