<?php
defined('BASEPATH') OR exit('No direct script access allowed');

require_once APPPATH . 'libraries/dompdf/autoload.inc.php';

use Dompdf\Dompdf;
use Dompdf\Options;

class Pdf
{
    protected $dompdf;

    public function __construct()
    {
        // Setup options Dompdf
        $options = new Options();
        $options->set('isHtml5ParserEnabled', true);
        $options->set('isRemoteEnabled', true); // bisa load img/logo dari base_url
        $options->set('defaultFont', 'DejaVu Sans'); // support UTF-8

        $this->dompdf = new Dompdf($options);
        $this->dompdf->setPaper('A4', 'portrait');
    }

    /**
     * Load view ke Dompdf
     */
    public function load_view($view, $data = [], $paper = 'A4', $orientation = 'portrait')
    {
        $CI = &get_instance();
        $html = $CI->load->view($view, $data, TRUE);

        $this->dompdf->setPaper($paper, $orientation);
        $this->dompdf->loadHtml($html);
        $this->dompdf->render();
    }

    /**
     * Output PDF ke browser
     * @param string $filename Nama file PDF
     * @param array $options ['Attachment' => 1] -> 1 = download, 0 = preview
     */
    public function stream($filename = "document.pdf", $options = ["Attachment" => 1])
    {
        // 🔥 Fix auto-download
        $this->dompdf->stream($filename, $options);
        exit;
    }

    /**
     * Simpan PDF ke server (opsional)
     */
    public function save($path)
    {
        $output = $this->dompdf->output();
        file_put_contents($path, $output);
        return $path;
    }
}
