<?php
require_once __DIR__ . '/../../config/session.php';
requireAdmin();
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../functions/helper.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'] ?? '';

// Ambil profil posyandu
$profil = getProfilPosyandu();
$nama_posyandu = $profil['nama_posyandu'] ?? 'Posyandu Tunas Bangsa';

// Check if filter is applied
$filter_applied = !empty($bulan) && !empty($tahun);

// Ambil data laporan
if ($filter_applied) {
    $stmt = $db->prepare("SELECT ih.nik, ih.nama_lengkap, ih.hpl, ih.status, u.nama_lengkap as nama_bidan, ih.hpht, ih.tanggal_daftar FROM ibu_hamil ih LEFT JOIN users u ON ih.bidan_id = u.id WHERE MONTH(ih.tanggal_daftar) = ? AND YEAR(ih.tanggal_daftar) = ? ORDER BY ih.tanggal_daftar DESC");
    $stmt->execute([$bulan, $tahun]);
} else {
    $stmt = $db->query("SELECT ih.nik, ih.nama_lengkap, ih.hpl, ih.status, u.nama_lengkap as nama_bidan, ih.hpht, ih.tanggal_daftar FROM ibu_hamil ih LEFT JOIN users u ON ih.bidan_id = u.id ORDER BY ih.tanggal_daftar DESC");
}
$laporan_data = $stmt->fetchAll();

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Laporan Ibu Hamil');

// Judul Laporan
$sheet->setCellValue('A1', 'LAPORAN PENDAFTARAN IBU HAMIL');
$sheet->setCellValue('A2', strtoupper($nama_posyandu));
$sheet->setCellValue('A3', $filter_applied ? 'Bulan: ' . formatBulan($bulan) . ' ' . $tahun : 'Semua Data');

// Merge dan Styling Judul
$sheet->mergeCells('A1:H1');
$sheet->mergeCells('A2:H2');
$sheet->mergeCells('A3:H3');

$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 Daftar', 'NIK', 'Nama Ibu Hamil', 'Usia Kandungan (Minggu)', 'HPL', 'Bidan Penanggung Jawab', 'Status'];
$col = 'A';
foreach ($headers as $header) {
    $sheet->setCellValue($col . $headerRow, $header);
    $col++;
}

// Styling Header Tabel
$lastCol = 'H';
$headerStyle = [
    'font' => ['bold' => true],
    'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER],
    'borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN]],
    'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['argb' => 'FFE2E8F0']]
];
$sheet->getStyle('A'.$headerRow.':'.$lastCol.$headerRow)->applyFromArray($headerStyle);

// Lebar Kolom
$sheet->getColumnDimension('A')->setWidth(5);
$sheet->getColumnDimension('B')->setWidth(15);
$sheet->getColumnDimension('C')->setWidth(20);
$sheet->getColumnDimension('D')->setWidth(30);
$sheet->getColumnDimension('E')->setWidth(25);
$sheet->getColumnDimension('F')->setWidth(15);
$sheet->getColumnDimension('G')->setWidth(30);
$sheet->getColumnDimension('H')->setWidth(15);

// Isi Data
$rowNum = $headerRow + 1;
$no = 1;

if (count($laporan_data) > 0) {
    foreach ($laporan_data as $row) {
        $diff = (new DateTime($row['hpht']))->diff(new DateTime())->days;
        $minggu = intdiv($diff, 7);
        
        $sheet->setCellValue('A'.$rowNum, $no++);
        $sheet->setCellValue('B'.$rowNum, date('d-m-Y', strtotime($row['tanggal_daftar'])));
        $sheet->setCellValueExplicit('C'.$rowNum, $row['nik'], \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
        $sheet->setCellValue('D'.$rowNum, $row['nama_lengkap']);
        $sheet->setCellValue('E'.$rowNum, $minggu);
        $sheet->setCellValue('F'.$rowNum, date('d-m-Y', strtotime($row['hpl'])));
        $sheet->setCellValue('G'.$rowNum, $row['nama_bidan']);
        $sheet->setCellValue('H'.$rowNum, $row['status']);
        
        // Alignment
        $sheet->getStyle('A'.$rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle('B'.$rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle('C'.$rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle('E'.$rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle('F'.$rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle('H'.$rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        
        $rowNum++;
    }
} else {
    $sheet->setCellValue('A'.$rowNum, 'Tidak ada data pendaftaran di bulan ini.');
    $sheet->mergeCells('A'.$rowNum.':H'.$rowNum);
    $sheet->getStyle('A'.$rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
    $rowNum++;
}

// Styling Data Borders
$dataStyle = [
    'borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN]]
];
$sheet->getStyle('A'.$headerRow.':'.$lastCol.($rowNum-1))->applyFromArray($dataStyle);

// Output HTTP headers
$filename = 'Laporan_Ibu_Hamil_' . ($filter_applied ? formatBulan($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');
header('Cache-Control: max-age=1'); // If you're serving to IE 9, then the following may be needed
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0

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