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

if(!isset($_GET['month'])){
    die("Month not selected.");
}

$month = $_GET['month']; // Format: YYYY-MM
list($year, $mon) = explode("-", $month);

// Create PDF
$pdf = new FPDF();
$pdf->AddPage();

// Header
$pdf->SetFont('Arial','B',16);
$pdf->Cell(0,10,"Monthly Payment Summary - $month",0,1,'C');
$pdf->Ln(10);

// Table Header
$pdf->SetFont('Arial','B',10);
$pdf->Cell(15,10,'ID',1);
$pdf->Cell(50,10,'Employee Name',1);
$pdf->Cell(40,10,'Position',1);
$pdf->Cell(40,10,'Status',1);
$pdf->Cell(40,10,'Total Paid',1);
$pdf->Ln();

// Query payments grouped by employee
$sql = "SELECT e.id, e.name, e.position, e.status, SUM(p.amount) as total_paid 
        FROM employees e
        LEFT JOIN payments p ON e.id = p.employee_id 
            AND YEAR(p.payment_date)=$year 
            AND MONTH(p.payment_date)=$mon
        GROUP BY e.id
        ORDER BY e.name ASC";
$result = $conn->query($sql);

// Table Rows
$pdf->SetFont('Arial','',10);
$grand_total = 0;
while($row = $result->fetch_assoc()){
    $total = $row['total_paid'] ? $row['total_paid'] : 0;
    $pdf->Cell(15,10,$row['id'],1);
    $pdf->Cell(50,10,$row['name'],1);
    $pdf->Cell(40,10,$row['position'],1);
    $pdf->Cell(40,10,$row['status'],1);
    $pdf->Cell(40,10,number_format($total,2),1);
    $pdf->Ln();
    $grand_total += $total;
}

// Grand Total
$pdf->SetFont('Arial','B',12);
$pdf->Cell(145,10,'Grand Total',1);
$pdf->Cell(40,10,number_format($grand_total,2),1);

$pdf->Output();
?>