<?php
/**
 * admin/download-pdf.php
 * Export register as PDF using FPDF.
 */

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

requireLogin();

if (!file_exists(__DIR__ . '/../includes/fpdf.php')) {
    die('FPDF library not found. Please download fpdf.php from http://www.fpdf.org/ and place it in includes/');
}
require_once __DIR__ . '/../includes/fpdf.php';

$stmt = $pdo->query("SELECT membership_id, full_name, gender, phone, kindred, DATE_FORMAT(date_joined, '%Y-%m-%d') as registered
                      FROM members ORDER BY created_at DESC");
$rows = $stmt->fetchAll();

$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial', 'B', 14);
$pdf->Cell(0, 10, 'Emehama Village Community Register', 0, 1, 'C');
$pdf->Ln(6);
$pdf->SetFont('Arial', 'B', 10);
$w = [30, 50, 25, 40, 40, 30];
$pdf->Cell($w[0], 8, 'Membership ID', 1);
$pdf->Cell($w[1], 8, 'Full Name', 1);
$pdf->Cell($w[2], 8, 'Gender', 1);
$pdf->Cell($w[3], 8, 'Phone', 1);
$pdf->Cell($w[4], 8, 'Kindred', 1);
$pdf->Cell($w[5], 8, 'Date Joined', 1);
$pdf->Ln();

$pdf->SetFont('Arial', '', 10);
foreach ($rows as $r) {
    $pdf->Cell($w[0], 7, $r['membership_id'], 1);
    $pdf->Cell($w[1], 7, $r['full_name'], 1);
    $pdf->Cell($w[2], 7, $r['gender'], 1);
    $pdf->Cell($w[3], 7, $r['phone'], 1);
    $pdf->Cell($w[4], 7, $r['kindred'] ?: '—', 1);
    $pdf->Cell($w[5], 7, $r['registered'], 1);
    $pdf->Ln();
}

$pdf->Output('D', 'register_' . date('Y-m-d') . '.pdf');
exit;