<?php
session_start();
require('../fpdf/fpdf.php');
include '../config/database.php';
$db = new Database(); $conn = $db->getConnection();

$role = $_SESSION['role'];
$where = $role=='gembala' ? "WHERE g.id=".$_SESSION['gereja_id'] : "";

$stmt = $conn->prepare("SELECT g.*, u.nama as nama_gembala FROM gereja g LEFT JOIN users u ON g.gembala_id=u.id $where ORDER BY g.nama_gereja ASC");
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

class PDF extends FPDF {
    function Header(){
        $this->Image('../assets/img/logo_gbi.png',60,8,20);
        $this->SetFont('Arial','B',14);
        $this->Cell(0,6,'LAPORAN DATA GEREJA',0,1,'C');
        $this->SetFont('Arial','B',12);
        $this->Cell(0,6,'DEWAN PENGURUS WILAYAH GBI KABUPATEN KEEROM',0,1,'C');
        $this->Ln(8);
        
        // Lebar tabel: 8+55+60+30+40+15+20 = 228
        // Center: (297-228)/2 = 34.5
        $this->SetX(34.5);
        $this->SetFont('Arial','B',9);
        $this->Cell(8,7,'No',1,0,'C');
        $this->Cell(55,7,'Nama Gereja',1,0,'C');
        $this->Cell(60,7,'Alamat',1,0,'C');
        $this->Cell(30,7,'Distrik',1,0,'C');
        $this->Cell(40,7,'Gembala',1,0,'C');
        $this->Cell(15,7,'Tahun',1,0,'C');
        $this->Cell(20,7,'Status',1,1,'C');
    }
    function Footer(){
        $this->SetY(-15);
        $this->SetFont('Arial','I',8);
        $this->Cell(0,10,'Halaman '.$this->PageNo().'/{nb}',0,0,'C');
    }
}

$pdf = new PDF();
$pdf->AliasNbPages();
$pdf->AddPage('L','A4');
$pdf->SetFont('Arial','',9);

$no=1;
foreach($data as $d){
    $pdf->SetX(34.5);
    $pdf->Cell(8,6,$no++,1,0,'C');
    $pdf->Cell(55,6,substr($d['nama_gereja'],0,32),1,0);
    $pdf->Cell(60,6,substr($d['alamat'],0,35),1,0);
    $pdf->Cell(30,6,$d['distrik'],1,0);
    $pdf->Cell(40,6,substr($d['nama_gembala'],0,23),1,0);
    $pdf->Cell(15,6,$d['tahun_berdiri'],1,0,'C');
    $pdf->Cell(20,6,$d['status'],1,1,'C');
}

$pdf->Ln(10);
$pdf->SetFont('Arial','',11);
$pdf->Cell(190);
$pdf->Cell(68,6,'Keerom, '.date('d F Y'),0,1,'C');
$pdf->Cell(190);
if($role=='gembala'){
    $pdf->Cell(68,6,'Gembala,',0,1,'C');
    $pdf->Ln(20);
    $pdf->Cell(190);
    $pdf->SetFont('Arial','BU',11);
    $pdf->Cell(68,6,$_SESSION['nama'],0,1,'C');
} else {
    $pdf->Cell(68,6,'Ketua DPW GBI Kab. Keerom,',0,1,'C');
    $pdf->Ln(20);
    $pdf->Cell(190);
    $pdf->SetFont('Arial','BU',11);
    $pdf->Cell(68,6,'Pdt. [Nama Ketua DPW]',0,1,'C');
}

$pdf->Output('I','Laporan_Gereja.pdf');
?>