<?php
require_once __DIR__ . '/../../config/session.php';
requireAdmin();
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../functions/helper.php';
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../vendor/setasign/fpdf/fpdf.php';

$db = getDB();

$bulan = $_GET['bulan'] ?? '';
$tahun = $_GET['tahun'] ?? '';
$filter_applied = !empty($bulan) && !empty($tahun);

if ($filter_applied) {
    $stmt = $db->prepare(
        "SELECT kp.tanggal_kunjungan, kp.usia_kehamilan_minggu, kp.tekanan_darah,
                kp.berat_badan, kp.tinggi_fundus, kp.letak_janin, kp.denyut_jantung_janin,
                kp.catatan, ih.nama_lengkap, ih.nik, u.nama_lengkap AS nama_bidan
         FROM kunjungan_posyandu kp
         JOIN ibu_hamil ih ON kp.ibu_hamil_id = ih.id
         LEFT JOIN users u ON ih.bidan_id = u.id
         WHERE MONTH(kp.tanggal_kunjungan) = ? AND YEAR(kp.tanggal_kunjungan) = ?
         ORDER BY kp.tanggal_kunjungan DESC"
    );
    $stmt->execute([$bulan, $tahun]);
} else {
    $stmt = $db->query(
        "SELECT kp.tanggal_kunjungan, kp.usia_kehamilan_minggu, kp.tekanan_darah,
                kp.berat_badan, kp.tinggi_fundus, kp.letak_janin, kp.denyut_jantung_janin,
                kp.catatan, ih.nama_lengkap, ih.nik, u.nama_lengkap AS nama_bidan
         FROM kunjungan_posyandu kp
         JOIN ibu_hamil ih ON kp.ibu_hamil_id = ih.id
         LEFT JOIN users u ON ih.bidan_id = u.id
         ORDER BY kp.tanggal_kunjungan DESC"
    );
}
$data = $stmt->fetchAll();

$profil = getProfilPosyandu();
$nama_posyandu = $profil['nama_posyandu'] ?? APP_NAME;
$alamat_posyandu = $profil['alamat'] ?? '';

function u(string $s): string { return iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $s); }
$fmtDec = fn($v) => $v !== null ? rtrim(rtrim(number_format((float)$v, 2, '.', ''), '0'), '.') : '-';

class PDFKunjungan extends FPDF {
    public string $namaPos = '';
    public string $alamatPos = '';

    function Header() {
        $this->SetFont('Arial', 'B', 13);
        $this->Cell(0, 7, u($this->namaPos), 0, 1, 'C');
        $this->SetFont('Arial', '', 9);
        $this->Cell(0, 5, u($this->alamatPos), 0, 1, 'C');
        $this->SetLineWidth(0.5);
        $this->Line(10, $this->GetY() + 2, 200, $this->GetY() + 2);
        $this->Ln(6);
    }

    function Footer() {
        $this->SetY(-13);
        $this->SetLineWidth(0.3);
        $this->Line(10, $this->GetY(), 200, $this->GetY());
        $this->SetFont('Arial', 'I', 8);
        $this->Cell(0, 8, u('Dicetak: ' . date('d/m/Y H:i') . '   |   Halaman ' . $this->PageNo() . '/{nb}'), 0, 0, 'C');
    }
}

$pdf = new PDFKunjungan('L', 'mm', 'A4');
$pdf->namaPos  = $nama_posyandu;
$pdf->alamatPos = $alamat_posyandu;
$pdf->AliasNbPages();
$pdf->SetMargins(10, 20, 10);
$pdf->SetAutoPageBreak(true, 15);
$pdf->AddPage();

// Judul laporan
$pdf->SetFont('Arial', 'B', 11);
$pdf->Cell(0, 7,
    u('LAPORAN KUNJUNGAN POSYANDU' . ($filter_applied ? ' — ' . formatBulan((int)$bulan) . ' ' . $tahun : ' (Semua Data)')),
    0, 1, 'C');
$pdf->Ln(3);

// Header tabel (landscape A4 = 277mm usable)
$col = [8, 22, 52, 30, 20, 22, 20, 20, 20, 43];
// No | Tanggal | Nama Ibu / NIK | Usia | Tek.Darah | Berat | TFU | Letak | DJJ | Bidan PJ

$pdf->SetFont('Arial', 'B', 8);
$pdf->SetFillColor(226, 232, 240);
$pdf->Cell($col[0],  7, 'No',        1, 0, 'C', true);
$pdf->Cell($col[1],  7, 'Tanggal',   1, 0, 'C', true);
$pdf->Cell($col[2],  7, 'Nama / NIK',1, 0, 'C', true);
$pdf->Cell($col[3],  7, 'Usia (mgg)',1, 0, 'C', true);
$pdf->Cell($col[4],  7, 'Tek.Darah', 1, 0, 'C', true);
$pdf->Cell($col[5],  7, 'BB (kg)',   1, 0, 'C', true);
$pdf->Cell($col[6],  7, 'TFU (cm)',  1, 0, 'C', true);
$pdf->Cell($col[7],  7, 'Letak',     1, 0, 'C', true);
$pdf->Cell($col[8],  7, 'DJJ',       1, 0, 'C', true);
$pdf->Cell($col[9],  7, 'Bidan PJ',  1, 1, 'C', true);

// Isi data
$pdf->SetFont('Arial', '', 8);
$no = 1;
if (count($data) > 0) {
    foreach ($data as $row) {
        $nama = u(mb_strimwidth($row['nama_lengkap'], 0, 22, '..'));
        $nik  = u($row['nik']);
        $bidan = u(mb_strimwidth($row['nama_bidan'] ?? '-', 0, 25, '..'));

        $pdf->Cell($col[0], 6, $no++,                                           1, 0, 'C');
        $pdf->Cell($col[1], 6, date('d-m-Y', strtotime($row['tanggal_kunjungan'])), 1, 0, 'C');
        $pdf->Cell($col[2], 6, $nama . ' / ' . $nik,                            1, 0, 'L');
        $pdf->Cell($col[3], 6, $row['usia_kehamilan_minggu'] !== null ? $row['usia_kehamilan_minggu'] . ' mgg' : '-', 1, 0, 'C');
        $pdf->Cell($col[4], 6, u($row['tekanan_darah'] ?: '-'),                 1, 0, 'C');
        $pdf->Cell($col[5], 6, $fmtDec($row['berat_badan']),                    1, 0, 'C');
        $pdf->Cell($col[6], 6, $fmtDec($row['tinggi_fundus']),                  1, 0, 'C');
        $pdf->Cell($col[7], 6, u($row['letak_janin'] ?: '-'),                   1, 0, 'C');
        $pdf->Cell($col[8], 6, $row['denyut_jantung_janin'] !== null ? $row['denyut_jantung_janin'] : '-', 1, 0, 'C');
        $pdf->Cell($col[9], 6, $bidan,                                           1, 1, 'L');
    }
} else {
    $pdf->Cell(array_sum($col), 8, u('Tidak ada data kunjungan.'), 1, 1, 'C');
}

// Tanda tangan
$pdf->Ln(12);
$pdf->SetFont('Arial', '', 9);
$pdf->Cell(190);
$pdf->Cell(80, 5, u('Mentawak Ulu, ' . date('d ') . formatBulan((int)date('m')) . ' ' . date('Y')), 0, 1, 'C');
$pdf->Cell(190);
$pdf->Cell(80, 5, u('Bidan Penanggung Jawab'), 0, 1, 'C');
$pdf->Ln(16);
$pdf->Cell(190);
$pdf->SetFont('Arial', 'B', 9);
$pdf->Cell(80, 5, u($_SESSION['nama'] ?? ''), 0, 1, 'C');
$pdf->SetFont('Arial', '', 9);
$pdf->Cell(190);
$pdf->Cell(80, 5, 'NIP. .............................', 0, 1, 'C');

$fname = 'Laporan_Kunjungan_' . ($filter_applied ? formatBulan((int)$bulan) . '_' . $tahun : 'Semua') . '.pdf';
$pdf->Output('D', $fname);
exit;
