<?php
/**
 * @package Divine_Agreement_System
 * @author Aditya Singh
 */


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

use Dompdf\Dompdf;
use Dompdf\Options;

class Divine_PDF_Generator {

    private static function divine_get_filesystem() {
        require_once ABSPATH . 'wp-admin/includes/file.php';
        WP_Filesystem();

        global $wp_filesystem;

        return $wp_filesystem;
    }
    
    
    public static function divine_generate_pdf($agreement_id) {
        $agreement = get_post($agreement_id);
        
        if (!$agreement) {
            return false;
        }
        
        
        $data = Divine_Placeholder_Engine::divine_get_agreement_data($agreement_id);
        $content = Divine_Placeholder_Engine::divine_get_rendered_content($agreement_id);
        
        
        $signature_path = $data['signature_image'];
        $signature_base64 = '';
        
        if ($signature_path && file_exists($signature_path)) {
            $wp_filesystem = self::divine_get_filesystem();

            if ($wp_filesystem) {
                $signature_data = $wp_filesystem->get_contents($signature_path);

                if (false !== $signature_data) {
                    $signature_base64 = base64_encode($signature_data);
                }
            }
        }
        
        
        $html = self::divine_build_pdf_html($agreement, $data, $content, $signature_base64);
        
        
        try {
            $options = new Options();
            $options->set('isHtml5ParserEnabled', true);
            $options->set('isPhpEnabled', false);
            $options->set('isRemoteEnabled', false);
            $options->set('defaultFont', 'DejaVu Sans');
            
            $dompdf = new Dompdf($options);
            $dompdf->loadHtml($html);
            $dompdf->setPaper('A4', 'portrait');
            $dompdf->render();
            
            
            $upload_dir = DIVINE_AGREEMENT_UPLOAD_DIR;
            if (!file_exists($upload_dir)) {
                wp_mkdir_p($upload_dir);
            }
            
            $filename = 'divine-agreement-system-' . $agreement_id . '.pdf';
            $filepath = $upload_dir . $filename;
            
            $output = $dompdf->output();
            $wp_filesystem = self::divine_get_filesystem();
            $bytes_written = false;

            if ($wp_filesystem) {
                $bytes_written = $wp_filesystem->put_contents($filepath, $output, FS_CHMOD_FILE);
            }

            if (false === $bytes_written) {
                return false;
            }
            
            return $filepath;
            
        } catch (Exception $e) {
            return false;
        }
    }
    
    
    private static function divine_build_pdf_html($agreement, $data, $content, $signature_base64) {
        ob_start();
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title><?php echo esc_html($agreement->post_title); ?></title>
            <style>
                body {
                    font-family: DejaVu Sans, Arial, sans-serif;
                    font-size: 12pt;
                    line-height: 1.6;
                    color: #333;
                    margin: 40px;
                }
                h1 {
                    text-align: center;
                    color: #2c3e50;
                    border-bottom: 3px solid #3498db;
                    padding-bottom: 10px;
                    margin-bottom: 30px;
                }
                .agreement-header {
                    background: #f8f9fa;
                    padding: 20px;
                    border-left: 4px solid #3498db;
                    margin-bottom: 30px;
                }
                .agreement-header p {
                    margin: 5px 0;
                }
                .agreement-content {
                    margin: 30px 0;
                    text-align: justify;
                }
                .signature-section {
                    margin-top: 50px;
                    border-top: 2px solid #ddd;
                    padding-top: 30px;
                }
                .signature-box {
                    margin-top: 20px;
                }
                .signature-image {
                    border: 1px solid #ddd;
                    padding: 10px;
                    background: #fff;
                    display: inline-block;
                }
                .signature-details {
                    margin-top: 20px;
                    background: #f8f9fa;
                    padding: 15px;
                }
                .signature-details p {
                    margin: 5px 0;
                }
                .footer {
                    margin-top: 50px;
                    text-align: center;
                    font-size: 10pt;
                    color: #7f8c8d;
                    border-top: 1px solid #ddd;
                    padding-top: 20px;
                }
            </style>
        </head>
        <body>
            <h1><?php echo esc_html($agreement->post_title); ?></h1>
            
            <div class="agreement-header">
                <p><strong>Agreement ID:</strong> <?php echo esc_html($agreement->ID); ?></p>
                <p><strong>Collaborator:</strong> <?php echo esc_html($data['collaborator_name']); ?></p>
                <p><strong>Email:</strong> <?php echo esc_html($data['collaborator_email']); ?></p>
                <?php if ($data['collaborator_address']) : ?>
                <p><strong>Address:</strong> <?php echo nl2br(esc_html($data['collaborator_address'])); ?></p>
                <?php endif; ?>
                <p><strong>Date Created:</strong> <?php echo esc_html(date_i18n(get_option('date_format'), strtotime($agreement->post_date))); ?></p>
            </div>
            
            <div class="agreement-content">
                <?php echo wp_kses_post($content); ?>
            </div>
            
            <div class="signature-section">
                <h3>Digital Signature</h3>
                
                <?php if ($signature_base64) : ?>
                <div class="signature-box">
                    <p><strong>Signature:</strong></p>
                    <div class="signature-image">
                        <img src="data:image/png;base64,<?php echo esc_attr($signature_base64); ?>" 
                             alt="Signature" style="max-width: 300px; height: auto;">
                    </div>
                </div>
                <?php endif; ?>
                
                <div class="signature-details">
                    <p><strong>Signed by:</strong> <?php echo esc_html($data['collaborator_name']); ?></p>
                    <p><strong>Email:</strong> <?php echo esc_html($data['collaborator_email']); ?></p>
                    <p><strong>Date Signed:</strong> <?php echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($data['signed_date']))); ?></p>
                    <p><strong>IP Address:</strong> <?php echo esc_html($data['signed_ip']); ?></p>
                </div>
            </div>
            
            <div class="footer">
                <p>This is a digitally signed agreement generated by <?php echo esc_html(get_bloginfo('name')); ?></p>
                <p>Generated on: <?php echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'))); ?></p>
            </div>
        </body>
        </html>
        <?php
        return ob_get_clean();
    }
    
    
    public static function divine_download_pdf($agreement_id) {
        
        if (!current_user_can('edit_post', $agreement_id)) {
            wp_die(esc_html__('You do not have permission to access this file.', 'divine-agreement-system'));
        }
        
        $pdf_path = get_post_meta($agreement_id, '_divine_pdf_path', true);
        
        if (!$pdf_path || !file_exists($pdf_path)) {
            wp_die(esc_html__('PDF file not found.', 'divine-agreement-system'));
        }
        
        $filename = basename($pdf_path);
        $wp_filesystem = self::divine_get_filesystem();

        if (!$wp_filesystem) {
            wp_die(esc_html__('PDF file not found.', 'divine-agreement-system'));
        }

        $pdf_contents = $wp_filesystem->get_contents($pdf_path);

        if (false === $pdf_contents) {
            wp_die(esc_html__('PDF file not found.', 'divine-agreement-system'));
        }
        
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
        header('Content-Length: ' . strlen($pdf_contents));
        header('Cache-Control: private, max-age=0, must-revalidate');
        header('Pragma: public');
        
        echo $pdf_contents; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        exit;
    }
}
