<?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();
$ibu_hamil_id = $_SESSION['ibu_hamil_id'] ?? 0;

if (!$ibu_hamil_id) {
    $stmt = $db->prepare("SELECT ibu_hamil_id FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $ibu_hamil_id = (int)($stmt->fetchColumn() ?: 0);
}

if (!$ibu_hamil_id) {
    die('Data profil tidak ditemukan.');
}

$stmt = $db->prepare("SELECT ih.*, u.nama_lengkap as nama_bidan FROM ibu_hamil ih LEFT JOIN users u ON ih.bidan_id = u.id WHERE ih.id = ?");
$stmt->execute([$ibu_hamil_id]);
$ih = $stmt->fetch();

if (!$ih) {
    die('Data profil tidak ditemukan.');
}

$dob       = new DateTime($ih['tanggal_lahir']);
$umur      = (new DateTime())->diff($dob)->y;
$diff      = (new DateTime($ih['hpht']))->diff(new DateTime())->days;
$minggu    = intdiv($diff, 7);
$trimester = getTrimester($minggu);

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

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

// ── Kelas PDF kustom dengan header/footer ─────────────────────
class ProfilPDF extends FPDF
{
    public string $namaPos = '';
    public string $namaIbu = '';

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

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

        // Sub-judul
        $this->SetFont('Helvetica', '', 9);
        $this->SetTextColor(80, 80, 80);
        $this->Cell(0, 5, u('Rekam Medis Ibu Hamil  —  ' . $this->namaIbu), 0, 1, 'C');

        // Garis bawah header
        $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');
    }

    // Baris section header (background biru)
    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);
    }

    // Baris label + value
    function DataRow(string $label, string $value)
    {
        $lw = 65; // lebar kolom label
        $vw = 0;  // sisa lebar

        $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($vw, 6, u($value), 'RB', 1, 'L', false);
    }
}

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

// ── Section: Identitas Pribadi ────────────────────────────────
$pdf->SectionHeader('IDENTITAS PRIBADI');
$pdf->DataRow('NIK',                $ih['nik']);
$pdf->DataRow('Nama Lengkap',       $ih['nama_lengkap']);
$pdf->DataRow('Tanggal Lahir',      formatDate($ih['tanggal_lahir']) . ' (' . $umur . ' Tahun)');
$pdf->DataRow('Golongan Darah',     $ih['golongan_darah']);
$pdf->DataRow('Alamat',             $ih['alamat']);
$pdf->DataRow('No. HP / WA Ibu',    $ih['no_hp']);
$pdf->DataRow('Nama Suami',         $ih['nama_suami']);
$pdf->DataRow('No. HP Suami',       $ih['no_hp_suami'] ?: '-');

$pdf->Ln(4);

// ── Section: Data Kehamilan ───────────────────────────────────
$pdf->SectionHeader('DATA KEHAMILAN');
$pdf->DataRow('Kehamilan Ke-',          (string)(int)$ih['kehamilan_ke']);
$pdf->DataRow('HPHT',                   formatDate($ih['hpht']));
$pdf->DataRow('Perkiraan Lahir (HPL)',  formatDate($ih['hpl']));
$pdf->DataRow('Usia Kehamilan',         $minggu . ' Minggu');
$pdf->DataRow('Trimester',              'Trimester ' . $trimester);
$pdf->DataRow('Status',                 $ih['status']);
$pdf->DataRow('Bidan Penanggungjawab',  $ih['nama_bidan'] ?? '-');
$pdf->DataRow('Terdaftar Sejak',        formatDate($ih['tanggal_daftar']));

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

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