<?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;
use PhpOffice\PhpSpreadsheet\Style\Font;

$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;
$filename      = 'profil_' . preg_replace('/[^a-z0-9]/i', '_', $ih['nama_lengkap']) . '_' . date('Ymd') . '.xlsx';

// ── Buat Spreadsheet ──────────────────────────────────────────
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Profil Ibu Hamil');

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

// ── Baris 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 Medis Ibu Hamil — Dicetak: ' . date('d/m/Y H:i'));
$sheet->getStyle('A2')->applyFromArray([
    'font'      => ['size' => 9, 'color' => ['argb' => 'FF555555']],
    'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
]);

// Gaya section header
$sectionStyle = [
    'font'      => ['bold' => true, 'size' => 10, 'color' => ['argb' => 'FFFFFFFF']],
    'fill'      => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['argb' => 'FF1E40AF']],
    'alignment' => ['horizontal' => Alignment::HORIZONTAL_LEFT],
];

// Gaya label
$labelStyle = [
    'font' => ['bold' => true, 'size' => 10],
    'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['argb' => 'FFEFF6FF']],
    'alignment' => ['horizontal' => Alignment::HORIZONTAL_LEFT, 'vertical' => Alignment::VERTICAL_TOP, 'wrapText' => true],
    'borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN, 'color' => ['argb' => 'FFCBD5E1']]],
];

// Gaya value
$valueStyle = [
    'font'      => ['size' => 10],
    'alignment' => ['horizontal' => Alignment::HORIZONTAL_LEFT, 'vertical' => Alignment::VERTICAL_TOP, 'wrapText' => true],
    'borders'   => ['allBorders' => ['borderStyle' => Border::BORDER_THIN, 'color' => ['argb' => 'FFCBD5E1']]],
];

// Helper: tulis baris data
$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++;
};

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

$row++; // spasi antar section

// ── Data Kehamilan ────────────────────────────────────────────
$addSection('DATA KEHAMILAN');
$addRow('Kehamilan Ke-',        (int)$ih['kehamilan_ke']);
$addRow('HPHT',                 formatDate($ih['hpht']));
$addRow('Perkiraan Lahir (HPL)',formatDate($ih['hpl']));
$addRow('Usia Kehamilan',       $minggu . ' Minggu');
$addRow('Trimester',            'Trimester ' . $trimester);
$addRow('Status',               $ih['status']);
$addRow('Bidan Penanggungjawab',$ih['nama_bidan'] ?? '-');
$addRow('Terdaftar Sejak',      formatDate($ih['tanggal_daftar']));
if (!empty($ih['catatan'])) {
    $addRow('Catatan Khusus',   $ih['catatan']);
}

// ── Output file ───────────────────────────────────────────────
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;
