<?php
namespace BebasPustaka\Providers;

use Closure;
use SLiMS\Pdf\Contract;
use Dompdf\Dompdf as Core;
use Dompdf\Options; // Tambahkan ini di bagian atas

class Dompdf extends Contract
{
    public static string $name = 'Dompdf';
    
    public function setPdf():void
    {
        // PENGATURAN UTAMA: Buat opsi konfigurasi untuk membuka proteksi gambar
        $options = new Options();
        $options->set('isRemoteEnabled', true);       // Izinkan pembacaan Base64 & Path Gambar Fisik
        $options->set('isHtml5ParserEnabled', true);  // Izinkan parsing elemen HTML5 & SVG murni
        $options->set('chroot', dirname(__DIR__));    // Batasi akses root file hanya di dalam plugin bebas_pustaka
        
        // Masukkan konfigurasi options ke dalam Core Dompdf
        $this->pdf = new Core($options);
    }

    public function setContent(array $data = []):self
    {
        $content = '';
        
        if (count($data)) {
            foreach ($data as $html) {
                if (is_string($html)) {
                    $content .= $html;
                } elseif (is_array($html)) {
                    // Jika array, gabungkan saja
                    $content .= implode('', $html);
                }
                // Page break untuk multiple
                if (count($data) > 1) {
                    $content .= '<div style="page-break-before: always;"></div>';
                }
            }
        }
        
        $this->pdf->loadHtml($content);
        return $this;
    }

    public function download(string $filename):void
    {
        $this->stream($filename, ['Attachment' => true]);
    }
    
    public function stream(?string $filename = null, ?array $options = null):void
    {
        $this->pdf->render();
        $this->pdf->stream(($filename ?? 'surat_bebas_pustaka.pdf'), ($options ?? ['Attachment' => false]));
        exit;
    }
    
    public function saveToFile(string $filepath, ?Closure $callback = null):void
    {
        $this->pdf->render();
        if ($callback !== null) {
            $callback($this->pdf, $filepath);
        } else {
            file_put_contents($filepath, $this->pdf->output());
            exit;
        }
    }
}