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

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

$db = getDB();

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

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

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"
    );
}
$laporan_data = $stmt->fetchAll();
$fmtDec = fn($v) => $v !== null ? rtrim(rtrim(number_format((float)$v, 2, '.', ''), '0'), '.') : '-';

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

// Judul
$sheet->mergeCells('A1:L1');
$sheet->setCellValue('A1', 'LAPORAN KUNJUNGAN POSYANDU');
$sheet->mergeCells('A2:L2');
$sheet->setCellValue('A2', strtoupper($nama_posyandu));
$sheet->mergeCells('A3:L3');
$sheet->setCellValue('A3', $filter_applied ? 'Bulan: ' . formatBulan((int)$bulan) . ' ' . $tahun : 'Semua Data');

$styleJudul = ['font' => ['bold' => true, 'size' => 14], 'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER]];
$sheet->getStyle('A1:A2')->applyFromArray($styleJudul);
$sheet->getStyle('A3')->applyFromArray(['font' => ['bold' => true, 'size' => 12], 'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER]]);

// Header tabel
$headerRow = 5;
$headers = ['No', 'Tanggal Kunjungan', 'Nama Ibu Hamil', 'NIK', 'Usia (mgg)', 'Tekanan Darah', 'Berat Badan (kg)', 'TFU (cm)', 'Letak Janin', 'DJJ (/mnt)', 'Bidan PJ', 'Catatan'];
$cols = ['A','B','C','D','E','F','G','H','I','J','K','L'];
foreach ($headers as $i => $h) {
    $sheet->setCellValue($cols[$i] . $headerRow, $h);
}

$headerStyle = [
    'font'      => ['bold' => true],
    'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER, 'wrapText' => true],
    'borders'   => ['allBorders' => ['borderStyle' => Border::BORDER_THIN]],
    'fill'      => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['argb' => 'FF1E40AF']],
];
$sheet->getStyle("A{$headerRow}:L{$headerRow}")->applyFromArray($headerStyle);
$sheet->getStyle("A{$headerRow}:L{$headerRow}")->getFont()->getColor()->setARGB('FFFFFFFF');
$sheet->getRowDimension($headerRow)->setRowHeight(22);

// Lebar kolom
$widths = [5, 18, 30, 20, 12, 16, 18, 12, 15, 12, 28, 35];
foreach ($cols as $i => $c) {
    $sheet->getColumnDimension($c)->setWidth($widths[$i]);
}

// Data
$rowNum = $headerRow + 1;
$no = 1;
$dataStyle = ['borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN]]];

if (count($laporan_data) > 0) {
    foreach ($laporan_data as $row) {
        $sheet->setCellValue("A{$rowNum}", $no++);
        $sheet->setCellValue("B{$rowNum}", date('d-m-Y', strtotime($row['tanggal_kunjungan'])));
        $sheet->setCellValue("C{$rowNum}", $row['nama_lengkap']);
        $sheet->setCellValueExplicit("D{$rowNum}", $row['nik'], \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
        $sheet->setCellValue("E{$rowNum}", $row['usia_kehamilan_minggu'] !== null ? (int)$row['usia_kehamilan_minggu'] : '-');
        $sheet->setCellValue("F{$rowNum}", $row['tekanan_darah'] ?: '-');
        $sheet->setCellValue("G{$rowNum}", $row['berat_badan'] !== null ? $fmtDec($row['berat_badan']) : '-');
        $sheet->setCellValue("H{$rowNum}", $row['tinggi_fundus'] !== null ? $fmtDec($row['tinggi_fundus']) : '-');
        $sheet->setCellValue("I{$rowNum}", $row['letak_janin'] ?: '-');
        $sheet->setCellValue("J{$rowNum}", $row['denyut_jantung_janin'] !== null ? (int)$row['denyut_jantung_janin'] : '-');
        $sheet->setCellValue("K{$rowNum}", $row['nama_bidan'] ?? '-');
        $sheet->setCellValue("L{$rowNum}", $row['catatan'] ?: '-');

        // Center alignment untuk kolom numerik/tanggal
        foreach (['A','B','D','E','F','G','H','I','J'] as $c) {
            $sheet->getStyle("{$c}{$rowNum}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        }
        $sheet->getStyle("A{$rowNum}:L{$rowNum}")->applyFromArray($dataStyle);
        $sheet->getRowDimension($rowNum)->setRowHeight(15);

        // Alternating row color
        if ($no % 2 === 0) {
            $sheet->getStyle("A{$rowNum}:L{$rowNum}")->getFill()
                ->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FFF8FAFC');
        }
        $rowNum++;
    }
} else {
    $sheet->setCellValue("A{$rowNum}", 'Tidak ada data kunjungan.');
    $sheet->mergeCells("A{$rowNum}:L{$rowNum}");
    $sheet->getStyle("A{$rowNum}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
    $sheet->getStyle("A{$rowNum}:L{$rowNum}")->applyFromArray($dataStyle);
    $rowNum++;
}

// ── Output ────────────────────────────────────────────────────
$filename = 'Laporan_Kunjungan_' . ($filter_applied ? formatBulan((int)$bulan) . '_' . $tahun : 'Semua') . '.xlsx';

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;
