<?php
require_once __DIR__ . '/../config/session.php';
requireLogin();
if (($_SESSION['role'] ?? '') !== 'user') {
    header('Location: ' . BASE_URL . '/admin/dashboard');
    exit;
}
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();
$id           = (int)($_GET['id'] ?? 0);
$ibu_hamil_id = $_SESSION['ibu_hamil_id'] ?? 0;

if (!$id || !$ibu_hamil_id) { die('Parameter tidak valid.'); }

// Pastikan kunjungan milik user yang login
$stmt = $db->prepare(
    "SELECT kp.*, 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 kp.id = ? AND kp.ibu_hamil_id = ?"
);
$stmt->execute([$id, $ibu_hamil_id]);
$kj = $stmt->fetch();
if (!$kj) { die('Data tidak ditemukan.'); }

$profil_web    = getProfilPosyandu();
$nama_posyandu = $profil_web['nama_posyandu'] ?? APP_NAME;

$fmtDec = fn($v) => $v !== null ? rtrim(rtrim(number_format((float)$v, 2, '.', ''), '0'), '.') : '-';

function u(string $str): string {
    return iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $str);
}

// ── PDF Class ─────────────────────────────────────────────────
class KunjunganPDF extends FPDF
{
    public string $namaPos  = '';
    public string $namaIbu  = '';
    public string $tanggal  = '';

    function Header()
    {
        $this->SetDrawColor(30, 64, 175);
        $this->SetLineWidth(0.8);
        $this->Line(10, 8, 200, 8);
        $this->Ln(3);

        $this->SetFont('Helvetica', 'B', 13);
        $this->SetTextColor(30, 64, 175);
        $this->Cell(0, 7, u($this->namaPos), 0, 1, 'C');

        $this->SetFont('Helvetica', '', 9);
        $this->SetTextColor(80, 80, 80);
        $this->Cell(0, 5, u('Rekam Kunjungan: ' . $this->namaIbu . '  |  Tanggal: ' . $this->tanggal), 0, 1, 'C');

        $this->SetDrawColor(200, 200, 200);
        $this->SetLineWidth(0.3);
        $this->Line(10, $this->GetY() + 2, 200, $this->GetY() + 2);
        $this->Ln(5);
        $this->SetTextColor(0, 0, 0);
    }

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

    function SectionHeader(string $title)
    {
        $this->SetFillColor(30, 64, 175);
        $this->SetTextColor(255, 255, 255);
        $this->SetFont('Helvetica', 'B', 10);
        $this->Cell(0, 7, u($title), 0, 1, 'L', true);
        $this->SetTextColor(0, 0, 0);
        $this->Ln(1);
    }

    function DataRow(string $label, string $value)
    {
        $lw = 65;
        $this->SetFont('Helvetica', 'B', 9);
        $this->SetFillColor(239, 246, 255);
        $this->Cell($lw, 6, u($label), 'LRB', 0, 'L', true);
        $this->SetFont('Helvetica', '', 9);
        $this->SetFillColor(255, 255, 255);
        $this->Cell(0, 6, u($value), 'RB', 1, 'L', false);
    }
}

// ── Build PDF ─────────────────────────────────────────────────
$pdf = new KunjunganPDF('P', 'mm', 'A4');
$pdf->namaPos = $nama_posyandu;
$pdf->namaIbu = $kj['nama_lengkap'];
$pdf->tanggal = formatDate($kj['tanggal_kunjungan']);
$pdf->SetMargins(10, 28, 10);
$pdf->SetAutoPageBreak(true, 15);
$pdf->AddPage();

$pdf->SectionHeader('DATA KUNJUNGAN');
$pdf->DataRow('Tanggal Kunjungan',      formatDate($kj['tanggal_kunjungan']));
$pdf->DataRow('Nama Ibu Hamil',         $kj['nama_lengkap']);
$pdf->DataRow('NIK',                    $kj['nik']);
$pdf->DataRow('Bidan Penanggungjawab',  $kj['nama_bidan'] ?? '-');

$pdf->Ln(4);
$pdf->SectionHeader('HASIL PEMERIKSAAN');
$pdf->DataRow('Usia Kehamilan',         $kj['usia_kehamilan_minggu'] !== null ? $kj['usia_kehamilan_minggu'] . ' Minggu' : '-');
$pdf->DataRow('Tekanan Darah',          $kj['tekanan_darah'] ?: '-');
$pdf->DataRow('Berat Badan',            $kj['berat_badan'] !== null ? $fmtDec($kj['berat_badan']) . ' kg' : '-');
$pdf->DataRow('Tinggi Fundus (TFU)',    $kj['tinggi_fundus'] !== null ? $fmtDec($kj['tinggi_fundus']) . ' cm' : '-');
$pdf->DataRow('Letak Janin',            $kj['letak_janin'] ?: '-');
$pdf->DataRow('DJJ',                    $kj['denyut_jantung_janin'] !== null ? $kj['denyut_jantung_janin'] . ' /menit' : '-');

if (!empty($kj['catatan'])) {
    $pdf->Ln(4);
    $pdf->SectionHeader('CATATAN BIDAN');
    $pdf->SetFont('Helvetica', '', 9);
    $pdf->SetFillColor(255, 251, 235);
    $pdf->MultiCell(0, 5, u($kj['catatan']), 'LRB', 'L', true);
}

$filename = 'kunjungan_' . date('Ymd', strtotime($kj['tanggal_kunjungan'])) . '_' . preg_replace('/[^a-z0-9]/i', '_', $kj['nama_lengkap']) . '.pdf';
$pdf->Output('D', $filename);
exit;
