<?php
ini_set('max_execution_time', 300);
ini_set('memory_limit', '512M');
set_time_limit(300);

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

require_once __DIR__ . '/../vendor/dompdf/vendor/autoload.php';

use Dompdf\Dompdf;
use Dompdf\Options;

/* ================= MODE PDF ================= */
define('MODE_PDF', true);

/* ================= AMBIL HTML ASLI ================= */
ob_start();
include 'laporan_balita.php';
$html = ob_get_clean();


/* =====================================================
   SUNTIK CSS AGAR MUAT 1 HALAMAN (ANTI KE POTONG)
   ===================================================== */

$inject_css = '
<style>
@page { margin: 6mm 6mm; }

body{
    font-family: DejaVu Sans, sans-serif;
    font-size:7px;
}

/* tabel utama */
table{
    border-collapse:collapse;
    width:100%;
    table-layout:fixed;
}

th,td{
    border:1px solid #000;
    padding:1px;
    text-align:center;
    vertical-align:middle;
    overflow:hidden;
    white-space:nowrap;
}

/* teks kiri */
.text-left{
    text-align:left;
    padding-left:2px;
}

/* HEADER */
thead th{
    background:#eaeaea;
    font-weight:bold;
}
@page { margin: 6mm 6mm; }

body{
    font-family: DejaVu Sans, sans-serif;
    font-size:7px;
}

/* tabel utama */
table{
    border-collapse:collapse;
    width:100%;
    table-layout:fixed;
}

th,td{
    border:1px solid #000;
    padding:1px;
    text-align:center;
    vertical-align:middle;
    overflow:hidden;
    white-space:nowrap;
}

/* teks kiri */
.text-left{
    text-align:left;
    padding-left:2px;
}

/* HEADER */
thead th{
    background:#eaeaea;
    font-weight:bold;
}
</style>
';

/* masukkan CSS sebelum </head> */
$html = str_replace('</head>', $inject_css . '</head>', $html);

/* bungkus seluruh body agar diskalakan */
$html = str_replace('<body>', '<body><div class="wrapper">', $html);
$html = str_replace('</body>', '</div></body>', $html);


/* ================= DOMPDF CONFIG ================= */
$options = new Options();
$options->set('isHtml5ParserEnabled', false); // lebih cepat
$options->set('isRemoteEnabled', false);
$options->set('isFontSubsettingEnabled', true);
$options->set('defaultFont', 'DejaVu Sans');

$dompdf = new Dompdf($options);
$dompdf->setPaper([0,0,936,612]); // A3 paling lebar
$dompdf->loadHtml($html);
$dompdf->render();

/* tampilkan di browser */
$dompdf->stream("Laporan_Posyandu.pdf", ["Attachment"=>false]);
exit;
