<?php
require_once __DIR__ . '/fpdf/fpdf.php';
include 'koneksi.php';

$pdf = new FPDF('P','mm','A4');
$pdf->AddPage();
$pdf->SetMargins(10,10,10);

/* ================= JUDUL ================= */
$pdf->SetFont('Arial','B',16);
$pdf->Cell(0,10,'LAPORAN PENGEMBALIAN BUKU',0,1,'C');
$pdf->Ln(5);

/* ================= QUERY ================= */
$query = mysqli_query($koneksi, "
    SELECT 
        p.nama_peminjam,
        b.judul,
        p.tanggal_pinjam,
        p.tanggal_kembali,
        DATEDIFF(p.tanggal_kembali, p.tanggal_jatuh_tempo) AS terlambat
    FROM peminjaman p
    JOIN buku b ON p.id_buku = b.id
    WHERE p.status = 'Dikembalikan'
");

/* ================= SET TABEL CENTER ================= */
$tableWidth = 190;
$pageWidth  = $pdf->GetPageWidth();
$xStart = ($pageWidth - $tableWidth) / 2;

/* ================= HEADER TABEL (SATU KALI) ================= */
$pdf->SetFont('Arial','B',10);
$pdf->SetX($xStart);

$pdf->Cell(10,7,'No',1,0,'C');
$pdf->Cell(40,7,'Nama',1,0,'C');
$pdf->Cell(55,7,'Judul Buku',1,0,'C');
$pdf->Cell(30,7,'Tgl Pinjam',1,0,'C');
$pdf->Cell(30,7,'Tgl Kembali',1,0,'C');
$pdf->Cell(25,7,'Terlambat',1,1,'C');

/* ================= ISI DATA ================= */
$pdf->SetFont('Arial','',10);
$no = 1;

while ($row = mysqli_fetch_assoc($query)) {

    $judul = $row['judul'];
    $cellHeight = 6;
    $judulLines = ceil(strlen($judul) / 30);
    $rowHeight = $cellHeight * $judulLines;

    $terlambat = ($row['terlambat'] > 0)
        ? $row['terlambat'].' hari'
        : 'Tidak';

    $pdf->SetX($xStart);
    $x = $pdf->GetX();
    $y = $pdf->GetY();

    /* FRAME BARIS */
    $pdf->Rect($x, $y, 10, $rowHeight);
    $pdf->Rect($x+10, $y, 40, $rowHeight);
    $pdf->Rect($x+50, $y, 55, $rowHeight);
    $pdf->Rect($x+105, $y, 30, $rowHeight);
    $pdf->Rect($x+135, $y, 30, $rowHeight);
    $pdf->Rect($x+165, $y, 25, $rowHeight);

    /* ISI KOLOM */
    $pdf->SetXY($x, $y);
    $pdf->Cell(10, $rowHeight, $no++, 0, 0, 'C');

    $pdf->SetXY($x+10, $y);
    $pdf->Cell(40, $rowHeight, $row['nama_peminjam'], 0);

    $pdf->SetXY($x+50, $y);
    $pdf->MultiCell(55, $cellHeight, $judul, 0);

    $pdf->SetXY($x+105, $y);
    $pdf->Cell(30, $rowHeight, $row['tanggal_pinjam'], 0, 0, 'C');

    $pdf->SetXY($x+135, $y);
    $pdf->Cell(30, $rowHeight, $row['tanggal_kembali'], 0, 0, 'C');

    $pdf->SetXY($x+165, $y);
    $pdf->Cell(25, $rowHeight, $terlambat, 0, 0, 'C');

    /* PINDAH KE BARIS BERIKUTNYA */
    $pdf->SetY($y + $rowHeight);
}

$pdf->Output();
