<?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/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;

$db           = getDB();
$id           = (int)($_GET['id'] ?? 0);
$ibu_hamil_id = $_SESSION['ibu_hamil_id'] ?? 0;

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

$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'), '.') : '-';

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

// ── Spreadsheet ───────────────────────────────────────────────
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Kunjungan');

$sheet->getColumnDimension('A')->setWidth(28);
$sheet->getColumnDimension('B')->setWidth(45);

// Judul
$sheet->mergeCells('A1:B1');
$sheet->setCellValue('A1', $nama_posyandu);
$sheet->getStyle('A1')->applyFromArray([
    'font'      => ['bold' => true, 'size' => 14],
    'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
]);

$sheet->mergeCells('A2:B2');
$sheet->setCellValue('A2', 'Rekam Kunjungan — Dicetak: ' . date('d/m/Y H:i'));
$sheet->getStyle('A2')->applyFromArray([
    'font'      => ['size' => 9, 'color' => ['argb' => 'FF555555']],
    'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
]);

$sectionStyle = [
    'font' => ['bold' => true, 'size' => 10, 'color' => ['argb' => 'FFFFFFFF']],
    'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['argb' => 'FF1E40AF']],
];
$labelStyle = [
    'font'      => ['bold' => true, 'size' => 10],
    'fill'      => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['argb' => 'FFEFF6FF']],
    'alignment' => ['horizontal' => Alignment::HORIZONTAL_LEFT, 'wrapText' => true],
    'borders'   => ['allBorders' => ['borderStyle' => Border::BORDER_THIN, 'color' => ['argb' => 'FFCBD5E1']]],
];
$valueStyle = [
    'font'      => ['size' => 10],
    'alignment' => ['horizontal' => Alignment::HORIZONTAL_LEFT, 'wrapText' => true],
    'borders'   => ['allBorders' => ['borderStyle' => Border::BORDER_THIN, 'color' => ['argb' => 'FFCBD5E1']]],
];

$row = 4;
$addSection = function (string $title) use ($sheet, $sectionStyle, &$row) {
    $sheet->mergeCells("A{$row}:B{$row}");
    $sheet->setCellValue("A{$row}", $title);
    $sheet->getStyle("A{$row}:B{$row}")->applyFromArray($sectionStyle);
    $sheet->getRowDimension($row)->setRowHeight(18);
    $row++;
};
$addRow = function (string $label, $value) use ($sheet, $labelStyle, $valueStyle, &$row) {
    $sheet->setCellValue("A{$row}", $label);
    $sheet->setCellValue("B{$row}", $value);
    $sheet->getStyle("A{$row}")->applyFromArray($labelStyle);
    $sheet->getStyle("B{$row}")->applyFromArray($valueStyle);
    $sheet->getRowDimension($row)->setRowHeight(16);
    $row++;
};

// ── Data Kunjungan ────────────────────────────────────────────
$addSection('DATA KUNJUNGAN');
$addRow('Tanggal Kunjungan',    formatDate($kj['tanggal_kunjungan']));
$addRow('Nama Ibu Hamil',       $kj['nama_lengkap']);
$addRow('NIK',                  $kj['nik']);
$addRow('Bidan Penanggungjawab',$kj['nama_bidan'] ?? '-');

$row++;

// ── Hasil Pemeriksaan ─────────────────────────────────────────
$addSection('HASIL PEMERIKSAAN');
$addRow('Usia Kehamilan',       $kj['usia_kehamilan_minggu'] !== null ? $kj['usia_kehamilan_minggu'] . ' Minggu' : '-');
$addRow('Tekanan Darah',        $kj['tekanan_darah'] ?: '-');
$addRow('Berat Badan',          $kj['berat_badan'] !== null ? $fmtDec($kj['berat_badan']) . ' kg' : '-');
$addRow('Tinggi Fundus (TFU)',  $kj['tinggi_fundus'] !== null ? $fmtDec($kj['tinggi_fundus']) . ' cm' : '-');
$addRow('Letak Janin',          $kj['letak_janin'] ?: '-');
$addRow('DJJ',                  $kj['denyut_jantung_janin'] !== null ? $kj['denyut_jantung_janin'] . ' /menit' : '-');

if (!empty($kj['catatan'])) {
    $row++;
    $addSection('CATATAN BIDAN');
    $sheet->setCellValue("A{$row}", $kj['catatan']);
    $sheet->mergeCells("A{$row}:B{$row}");
    $sheet->getStyle("A{$row}")->applyFromArray([
        'font'      => ['size' => 10],
        'fill'      => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['argb' => 'FFFFFBEB']],
        'alignment' => ['wrapText' => true],
        'borders'   => ['allBorders' => ['borderStyle' => Border::BORDER_THIN, 'color' => ['argb' => 'FFCBD5E1']]],
    ]);
    $sheet->getRowDimension($row)->setRowHeight(-1);
}

// ── Output ────────────────────────────────────────────────────
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: max-age=0');

$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
exit;
