<?php
if (!defined('ABSPATH')) {
    exit;
}

class BMTQB_PDF_Service {
    public static function generate(BMTQB_Industry_Interface $industry, array $data, array $results, $post_id, array $photos = []) {
        $autoload = BMTQB_PATH . 'lib/dompdf/vendor/autoload.php';

        if (!file_exists($autoload)) {
            throw new Exception('DOMPDF autoload file not found at: ' . $autoload);
        }

        require_once $autoload;

        $options = new \Dompdf\Options();
        $options->set('isRemoteEnabled', true);

        $dompdf = new \Dompdf\Dompdf($options);
        $html = $industry->render_pdf($data, $results, $photos, $post_id);

        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        $upload_dir = wp_upload_dir();
        if (!empty($upload_dir['error'])) {
            throw new Exception('Unable to access uploads directory: ' . $upload_dir['error']);
        }

        $file_path = trailingslashit($upload_dir['basedir']) . $industry->key() . "-quote-{$post_id}.pdf";

        $bytes_written = file_put_contents($file_path, $dompdf->output());
        if ($bytes_written === false) {
            throw new Exception('Unable to write PDF file at: ' . $file_path);
        }

        return $file_path;
    }
}
