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

use Dompdf\Dompdf;
use Dompdf\Options;

/**
 * Pdf_maker
 *
 * Wrapper Dompdf untuk:
 *  - Simpan HTML ke file PDF di disk (save_html_to_pdf)  -> dipakai invoice/email
 *  - Langsung kirim PDF ke browser (generate)
 *  - Render PDF dari view CodeIgniter (generate_view)
 */
class Pdf_maker
{
    /** @var \Dompdf\Dompdf */
    private $dompdf;

    public function __construct(array $config = [])
    {
        // --- 1. Pastikan Dompdf ke-load dulu ---
        if (!class_exists('\Dompdf\Dompdf')) {
            $candidates = [
                APPPATH . 'libraries/dompdf/autoload.inc.php',
                APPPATH . 'third_party/dompdf/autoload.inc.php',
                FCPATH   . 'vendor/autoload.php',
            ];

            foreach ($candidates as $file) {
                if (is_file($file)) {
                    require_once $file;
                    break;
                }
            }
        }

        if (!class_exists('\Dompdf\Dompdf')) {
            // Biar error-nya jelas
            throw new RuntimeException('Dompdf belum terpasang/terload.');
        }

        // --- 2. Set options Dompdf ---
        $options = new Options();
        // allow load asset external (logo, css, dll)
        $options->set('isRemoteEnabled', $config['isRemoteEnabled'] ?? true);
        // batasi root path supaya aman
        $options->set('chroot', $config['chroot'] ?? FCPATH);

        $this->dompdf = new Dompdf($options);
    }

    /**
     * Helper internal buat render HTML ke dompdf.
     *
     * @param string $html
     * @param string $paper        'A4', 'Letter', dll.
     * @param string $orientation  'portrait' | 'landscape'
     */
    private function render_html(string $html, string $paper = 'A4', string $orientation = 'portrait'): void
    {
        $this->dompdf->setPaper($paper, $orientation);
        $this->dompdf->loadHtml($html, 'UTF-8');
        $this->dompdf->render();
    }

    /**
     * === FUNGSI LAMA (dipakai invoice) ===
     * Render HTML ke PDF dan simpan ke path di disk.
     *
     * @param string $html
     * @param string $save_path absolute path (mis. FCPATH."uploads/tmp/file.pdf")
     * @param string $paper
     * @param string $orientation
     * @return string path yang disimpan
     */
    public function save_html_to_pdf($html, $save_path, $paper = 'A4', $orientation = 'portrait')
    {
        $this->render_html($html, $paper, $orientation);

        $output = $this->dompdf->output();
        $dir = dirname($save_path);
        if (!is_dir($dir)) {
            @mkdir($dir, 0755, true);
        }
        file_put_contents($save_path, $output);

        return $save_path;
    }

    /**
     * Ambil hasil PDF dalam bentuk string (kalau mau di-handle manual).
     *
     * @param string $html
     * @param string $paper
     * @param string $orientation
     * @return string
     */
    public function output($html, $paper = 'A4', $orientation = 'portrait')
    {
        $this->render_html($html, $paper, $orientation);
        return $this->dompdf->output();
    }

    /**
     * === FUNGSI BARU ===
     * Generate PDF dari HTML dan langsung kirim ke browser.
     *
     * @param string $html
     * @param string $filename    tanpa .pdf
     * @param string $paper
     * @param string $orientation
     * @param bool   $download    true = force download, false = inline
     */
    public function generate(
        $html,
        $filename = 'document',
        $paper = 'A4',
        $orientation = 'portrait',
        $download = true
    ) {
        $this->render_html($html, $paper, $orientation);

        $this->dompdf->stream($filename . '.pdf', [
            'Attachment' => $download ? 1 : 0
        ]);
    }

    /**
     * Generate PDF langsung dari view CodeIgniter.
     *
     * @param string $view        path view (mis. 'laporan_keuangan/pdf')
     * @param array  $data        data untuk view
     * @param string $filename    tanpa .pdf
     * @param string $paper
     * @param string $orientation
     * @param bool   $download
     */
    public function generate_view(
        $view,
        array $data = [],
        $filename = 'document',
        $paper = 'A4',
        $orientation = 'portrait',
        $download = true
    ) {
        $CI =& get_instance();
        $html = $CI->load->view($view, $data, true);

        $this->generate($html, $filename, $paper, $orientation, $download);
    }
}
