<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
ob_start();

require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/config/app.php';
require_once __DIR__ . '/modules/analisis_kunjungan/functions.php';

$vendorAutoload = __DIR__ . '/vendor/autoload.php';
if (file_exists($vendorAutoload)) {
    require_once $vendorAutoload;
}

if (function_exists('checkAuth')) {
    checkAuth();
}

if (!ak_docx_writer_available()) {
    http_response_code(500);
    exit('Library PhpWord belum terpasang atau vendor/autoload.php tidak ditemukan.');
}

$conn = getConnection();
$analysisYear = (int)($_GET['year'] ?? date('Y'));

$exportData = ak_build_export_data($conn, $analysisYear);

$phpWord = new \PhpOffice\PhpWord\PhpWord();
$phpWord->setDefaultFontName('Times New Roman');
$phpWord->setDefaultFontSize(12);

$section = $phpWord->addSection([
    'marginTop'    => 1000,
    'marginBottom' => 1000,
    'marginLeft'   => 1200,
    'marginRight'  => 1000,
]);

$titleStyle   = ['bold' => true, 'size' => 14];
$headingStyle = ['bold' => true, 'size' => 12];
$normalStyle  = ['size' => 12];
$centerStyle  = ['align' => 'center'];
$justifyStyle = ['align' => 'both'];
$tableStyleName = 'MainTable';

$phpWord->addTableStyle($tableStyleName, [
    'borderSize' => 6,
    'borderColor' => '666666',
    'cellMargin' => 60,
], [
    'bgColor' => 'D9EAF7',
]);

$section->addText('LAPORAN ANALISIS REKAM MEDIS TERKAIT JUMLAH KUNJUNGAN PASIEN PER UNIT DI DIV. KEPERAWATAN', $titleStyle, $centerStyle);
$section->addText('TAHUN ' . $analysisYear, $titleStyle, $centerStyle);
$section->addTextBreak(1);

$section->addText('BAB I', $headingStyle, $centerStyle);
$section->addText('PENDAHULUAN', $headingStyle, $centerStyle);
$section->addTextBreak(1);

$pendahuluan = "Mengingat pentingnya data dan informasi sebagai dasar pengambilan keputusan dan pelaksanaan fungsi manajemen, rumah sakit perlu memanfaatkan data pelayanan secara optimal. Salah satu pendekatan yang digunakan adalah analisis kunjungan pasien per unit pelayanan keperawatan dan rasio pasien terhadap jumlah perawat. Analisis ini membantu memetakan beban kerja, kecenderungan kunjungan, dan kebutuhan penyesuaian SDM keperawatan.";
$section->addText($pendahuluan, $normalStyle, $justifyStyle);
$section->addTextBreak(1);

$section->addText('BAB II', $headingStyle, $centerStyle);
$section->addText('PEMBAHASAN', $headingStyle, $centerStyle);
$section->addTextBreak(1);

$section->addText('Ringkasan Umum', ['bold' => true], ['align' => 'left']);
$section->addText($exportData['summary_text'], $normalStyle, $justifyStyle);
$section->addTextBreak(1);

$section->addText('Tabel 1. Rekap Kunjungan dan Rasio Per Unit', ['bold' => true], ['align' => 'left']);
$table = $section->addTable($tableStyleName);
$table->addRow();
$table->addCell(800)->addText('No', ['bold' => true]);
$table->addCell(2800)->addText('Unit', ['bold' => true]);
$table->addCell(1800)->addText('Total Kunjungan', ['bold' => true]);
$table->addCell(1800)->addText('Jumlah Perawat', ['bold' => true]);
$table->addCell(2200)->addText('Rata-rata Kunjungan / Perawat', ['bold' => true]);

foreach ($exportData['dashboard_rows'] as $i => $row) {
    $table->addRow();
    $table->addCell(800)->addText((string)($i + 1));
    $table->addCell(2800)->addText($row['unit_name']);
    $table->addCell(1800)->addText(number_format((int)$row['total_visits'], 0, ',', '.'));
    $table->addCell(1800)->addText(number_format((int)$row['nurse_count'], 0, ',', '.'));
    $table->addCell(2200)->addText(number_format((float)$row['ratio'], 2, ',', '.'));
}

$section->addTextBreak(1);

foreach ($exportData['unit_analysis'] as $unitItem) {
    $section->addText('Analisis Unit: ' . $unitItem['unit_name'], ['bold' => true], ['align' => 'left']);
    $section->addText($unitItem['note'], $normalStyle, $justifyStyle);

    $detailTable = $section->addTable($tableStyleName);
    $detailTable->addRow();
    $detailTable->addCell(900)->addText('No', ['bold' => true]);
    $detailTable->addCell(2200)->addText('Periode', ['bold' => true]);
    $detailTable->addCell(1800)->addText('Kunjungan', ['bold' => true]);
    $detailTable->addCell(1800)->addText('Perawat', ['bold' => true]);
    $detailTable->addCell(2200)->addText('Rasio', ['bold' => true]);

    foreach ($unitItem['detail'] as $i => $detail) {
        $detailTable->addRow();
        $detailTable->addCell(900)->addText((string)($i + 1));
        $detailTable->addCell(2200)->addText($detail['period_label']);
        $detailTable->addCell(1800)->addText(number_format((int)$detail['visit_total'], 0, ',', '.'));
        $detailTable->addCell(1800)->addText(number_format((int)$detail['nurse_count'], 0, ',', '.'));
        $detailTable->addCell(2200)->addText(number_format((float)$detail['ratio'], 2, ',', '.'));
    }

    $section->addTextBreak(1);
}

$section->addText('BAB III', $headingStyle, $centerStyle);
$section->addText('ANALISIS RASIO PERAWAT', $headingStyle, $centerStyle);
$section->addTextBreak(1);

$bab3 = "Rasio pasien terhadap perawat menjadi indikator penting untuk menggambarkan beban kerja pelayanan. Total jumlah perawat yang digunakan dalam analisis ini adalah " .
    number_format((int)$exportData['total_nurses'], 0, ',', '.') .
    " orang. Unit dengan rasio rata-rata tertinggi adalah {$exportData['highest_ratio_unit']} dengan nilai " .
    number_format((float)$exportData['highest_ratio_value'], 2, ',', '.') .
    ". Data ini perlu menjadi dasar evaluasi distribusi SDM dan penjadwalan layanan.";
$section->addText($bab3, $normalStyle, $justifyStyle);
$section->addTextBreak(1);

$section->addText('BAB IV', $headingStyle, $centerStyle);
$section->addText('KESIMPULAN DAN REKOMENDASI', $headingStyle, $centerStyle);
$section->addTextBreak(1);

$section->addText($exportData['conclusion'], $normalStyle, $justifyStyle);
$section->addTextBreak(2);

$day   = date('d');
$month = ak_month_name_id((int)date('n'));
$year  = date('Y');

$section->addText('Denpasar, ' . $day . ' ' . $month . ' ' . $year, $normalStyle, ['align' => 'right']);
$section->addText('Kepala Divisi Keperawatan', $normalStyle, ['align' => 'right']);
$section->addTextBreak(3);
$section->addText('Ns. Gusti Ngurah Agung, S.Kep', ['bold' => true], ['align' => 'right']);

$filename = 'Laporan_Analisis_Kunjungan_Keperawatan_' . $analysisYear . '.docx';
$tempFile = tempnam(sys_get_temp_dir(), 'ak_docx_');

$writer = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$writer->save($tempFile);

if (ob_get_length()) {
    ob_end_clean();
}

header('Content-Description: File Transfer');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($tempFile));

readfile($tempFile);
@unlink($tempFile);
exit;