<?php
// Start output buffering to prevent any premature output
ob_start();

require('fpdf.php');
require_once __DIR__ . '/../model/users.php';

try {
    // Create User object to access its methods
    $userModel = new User();

    $users = $userModel->getPDFUsers();

    // PDF Generation Code
    $pdf = new FPDF();
    
    $pdf->AddPage();
    $pdf->Header();
    $pdf->SetFont('Arial', 'B', 12);
    if (!empty($users)) {
        // Add table headers
        $pdf->SetFont('Arial', 'B', 12);
        $pdf->Cell(15, 10, 'ID', 1, 0, 'C');
        $pdf->Cell(50, 10, 'Name', 1);
        $pdf->Cell(60, 10, 'Email', 1);
        $pdf->Cell(30, 10, 'Gender', 1, 0, 'C');
        $pdf->Cell(30, 10, 'Status', 1, 0, 'C');
        $pdf->Ln();
        
        // Reset font for data
        $pdf->SetFont('Arial', '', 10);
        
        // Add table data - fixed array keys by trimming whitespace
        foreach ($users as $row) {
            // Clean array keys by trimming whitespace
            $cleanedRow = array();
            foreach ($row as $key => $value) {
                $cleanedRow[trim($key)] = $value;
            }
            
            $pdf->Cell(15, 10, $cleanedRow['ID'], 1, 0, 'C');
            $pdf->Cell(50, 10, $cleanedRow['Name'], 1);
            $pdf->Cell(60, 10, $cleanedRow['Email'], 1);
            $pdf->Cell(30, 10, $cleanedRow['Gender'], 1, 0, 'C');
            $pdf->Cell(30, 10, $cleanedRow['Status'], 1, 0, 'C');
            $pdf->Ln();
        }
        $pdf->Cell(0, 10, '----------------------Nothing Follows----------------------', 0, 1, 'C');
    } else {
        $pdf->Cell(0, 10, 'No user records found', 0, 1, 'C');
    }

    // Clear the buffer and output the PDF
    ob_end_clean();
    $pdf->Output('I', 'User_Records_' . date('Y-m-d') . '.pdf');

} catch (Exception $e) {
    // Clean any output if error occurs
    ob_end_clean();
    die('Error generating PDF: ' . $e->getMessage());
}
?>