<?php
namespace Dompdf;

if (!defined('ABSPATH')) {
    exit;
}

class Options {
    private $options = array();
    
    public function set($key, $value) {
        $this->options[$key] = $value;
    }
    
    public function get($key) {
        return isset($this->options[$key]) ? $this->options[$key] : null;
    }
}

class Dompdf {
    private $html = '';
    private $options;
    private $paper = 'A4';
    private $orientation = 'portrait';
    
    public function __construct($options = null) {
        $this->options = $options ? $options : new Options();
    }
    
    public function loadHtml($html) {
        $this->html = $html;
    }
    
    public function setPaper($paper, $orientation = 'portrait') {
        $this->paper = $paper;
        $this->orientation = $orientation;
    }
    
    public function render() {
    }
    
    public function output() {
        $text = strip_tags($this->html);
        return $this->generateSimplePDF($text);
    }
    
    private function generateSimplePDF($text) {
        $pdf = "%PDF-1.4\n";
        $pdf .= "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
        $pdf .= "2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n";
        $pdf .= "3 0 obj\n<< /Type /Page /Parent 2 0 R /Resources 4 0 R /MediaBox [0 0 612 792] /Contents 5 0 R >>\nendobj\n";
        $pdf .= "4 0 obj\n<< /Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> >>\nendobj\n";
        
        $content = "BT\n/F1 12 Tf\n50 750 Td\n";
        $lines = explode("\n", wordwrap($text, 80));
        
        foreach ($lines as $line) {
            $content .= "(" . addslashes($line) . ") Tj\n";
            $content .= "0 -15 Td\n";
        }
        
        $content .= "ET\n";
        
        $pdf .= "5 0 obj\n<< /Length " . strlen($content) . " >>\nstream\n";
        $pdf .= $content;
        $pdf .= "\nendstream\nendobj\n";
        
        $pdf .= "xref\n0 6\n";
        $pdf .= "0000000000 65535 f\n";
        $pdf .= "0000000009 00000 n\n";
        $pdf .= "0000000058 00000 n\n";
        $pdf .= "0000000115 00000 n\n";
        $pdf .= "0000000214 00000 n\n";
        $pdf .= "0000000308 00000 n\n";
        
        $pdf .= "trailer\n<< /Size 6 /Root 1 0 R >>\n";
        $pdf .= "startxref\n" . strlen($pdf) . "\n%%EOF";
        
        return $pdf;
    }
}

\add_action('admin_notices', function() {
    if (!\class_exists('Dompdf\Dompdf', false)) {
        echo '<div class="notice notice-warning"><p><strong>Divine Agreement System:</strong> For best PDF quality, install DOMPDF library via Composer: <code>composer require dompdf/dompdf</code></p></div>';
    }
});
