<?php
/**
 * PDF Helper using DomPDF.
 *
 * @package PrimeLink
 */

namespace PrimeLink\Helpers;

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

/**
 * PDF Helper class for generating PDF files.
 * Uses DomPDF if available, falls back to error message.
 */
final class PdfHelper {

    /**
     * Check if DomPDF is available.
     *
     * @return bool
     */
    public static function has_dompdf() {
        return class_exists( '\PrimeLink\Vendor\Dompdf\Dompdf' ) ||
               class_exists( '\Dompdf\Dompdf' );
    }

    /**
     * Get DomPDF class.
     *
     * @return string|null
     */
    private static function get_dompdf_class() {
        if ( class_exists( '\PrimeLink\Vendor\Dompdf\Dompdf' ) ) {
            return '\PrimeLink\Vendor\Dompdf\Dompdf';
        } elseif ( class_exists( '\Dompdf\Dompdf' ) ) {
            return '\Dompdf\Dompdf';
        }
        return null;
    }

    /**
     * Get DomPDF Options class.
     *
     * @return string|null
     */
    private static function get_options_class() {
        if ( class_exists( '\PrimeLink\Vendor\Dompdf\Options' ) ) {
            return '\PrimeLink\Vendor\Dompdf\Options';
        } elseif ( class_exists( '\Dompdf\Options' ) ) {
            return '\Dompdf\Options';
        }
        return null;
    }

    /**
     * Generate PDF from HTML.
     *
     * @param string $html      HTML content.
     * @param array  $options   PDF options:
     *                         - 'paper_size' (string): 'A4', 'Letter', etc. (default: 'A4')
     *                         - 'orientation' (string): 'portrait' or 'landscape' (default: 'portrait')
     *                         - 'font' (string): Font family (default: 'DejaVu Sans')
     *                         - 'margin' (array): Top, right, bottom, left margins in mm (default: [10, 10, 10, 10])
     * @return string|WP_Error PDF file path or WP_Error on failure.
     */
    public static function generate_from_html( $html, $options = array() ) {
        if ( ! self::has_dompdf() ) {
            return new \WP_Error(
                'dompdf_not_available',
                __( 'DomPDF library is not available. Please install dompdf/dompdf via Composer.', 'primelink' )
            );
        }

        $defaults = array(
            'paper_size'  => 'A4',
            'orientation' => 'portrait',
            'font'        => 'DejaVu Sans',
            'margin'      => array( 10, 10, 10, 10 ), // Top, Right, Bottom, Left in mm
        );
        $options = wp_parse_args( $options, $defaults );

        try {
            $dompdf_class = self::get_dompdf_class();

            // Create DomPDF instance
            $dompdf = new $dompdf_class();

            // Set options (compatible with both 1.x and 2.x)
            // For version 1.x, use set_option directly
            // For version 2.x, use Options object
            $options_class = self::get_options_class();
            
            if ( $options_class && class_exists( $options_class ) ) {
                // Version 2.x: Use Options object
                try {
                    $dompdf_options = new $options_class();
                    if ( method_exists( $dompdf_options, 'set' ) ) {
                        $dompdf_options->set( 'defaultFont', $options['font'] );
                        $dompdf_options->set( 'isRemoteEnabled', true );
                        $dompdf_options->set( 'isHtml5ParserEnabled', true );
                    }
                    if ( method_exists( $dompdf, 'setOptions' ) ) {
                        $dompdf->setOptions( $dompdf_options );
                    }
                } catch ( \Exception $e ) {
                    // Fallback to direct option setting
                    if ( method_exists( $dompdf, 'set_option' ) ) {
                        $dompdf->set_option( 'defaultFont', $options['font'] );
                        $dompdf->set_option( 'isRemoteEnabled', true );
                        $dompdf->set_option( 'isHtml5ParserEnabled', true );
                    }
                }
            } else {
                // Version 1.x: Use set_option directly
                if ( method_exists( $dompdf, 'set_option' ) ) {
                    $dompdf->set_option( 'defaultFont', $options['font'] );
                    $dompdf->set_option( 'isRemoteEnabled', true );
                    $dompdf->set_option( 'isHtml5ParserEnabled', true );
                }
            }

            // Load HTML
            $dompdf->loadHtml( $html );

            // Set paper size and orientation
            $dompdf->setPaper( $options['paper_size'], $options['orientation'] );

            // Render PDF
            $dompdf->render();

            // Get PDF output
            $output = $dompdf->output();

            return $output;
        } catch ( \Exception $e ) {
            LoggerHelper::error( 'PDF generation failed', array(
                'error' => $e->getMessage(),
            ) );
            return new \WP_Error(
                'pdf_generation_failed',
                sprintf( __( 'PDF generation failed: %s', 'primelink' ), $e->getMessage() )
            );
        }
    }

    /**
     * Generate PDF from HTML and save to file.
     *
     * @param string $file_path File path to save PDF.
     * @param string $html      HTML content.
     * @param array  $options   PDF options.
     * @return bool|WP_Error True on success, WP_Error on failure.
     */
    public static function save_pdf( $file_path, $html, $options = array() ) {
        $pdf_output = self::generate_from_html( $html, $options );
        
        if ( is_wp_error( $pdf_output ) ) {
            return $pdf_output;
        }

        // Ensure directory exists
        $dir = dirname( $file_path );
        if ( ! \PrimeLink\Helpers\FilesystemHelper::directory_exists( $dir ) ) {
            \PrimeLink\Helpers\FilesystemHelper::create_directory( $dir );
        }

        // Write PDF to file
        $result = \PrimeLink\Helpers\FilesystemHelper::write_file( $file_path, $pdf_output );
        
        if ( false === $result ) {
            return new \WP_Error(
                'pdf_save_failed',
                __( 'Failed to save PDF file.', 'primelink' )
            );
        }

        return true;
    }

    /**
     * Generate PDF table from headers and rows.
     *
     * @param array  $headers   Table headers.
     * @param array  $rows      Table rows.
     * @param array  $options   PDF options.
     * @param string $title     PDF title (optional).
     * @return string|WP_Error PDF file path or WP_Error on failure.
     */
    public static function generate_table_pdf( $headers, $rows, $options = array(), $title = '' ) {
        // Build HTML table
        $html = '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body {
            font-family: DejaVu Sans, Arial, sans-serif;
            font-size: 10pt;
            margin: 0;
            padding: 20px;
        }
        h1 {
            font-size: 18pt;
            margin-bottom: 20px;
            color: #333;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        th {
            background-color: #f5f5f5;
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
            font-weight: bold;
        }
        td {
            border: 1px solid #ddd;
            padding: 6px;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .footer {
            margin-top: 20px;
            font-size: 8pt;
            color: #666;
            text-align: center;
        }
    </style>
</head>
<body>';

        if ( ! empty( $title ) ) {
            $html .= '<h1>' . esc_html( $title ) . '</h1>';
        }

        $html .= '<table>';
        
        // Headers
        $html .= '<thead><tr>';
        foreach ( $headers as $header ) {
            $html .= '<th>' . esc_html( $header ) . '</th>';
        }
        $html .= '</tr></thead>';
        
        // Rows
        $html .= '<tbody>';
        foreach ( $rows as $row ) {
            $html .= '<tr>';
            foreach ( $row as $cell ) {
                // Escape HTML but preserve line breaks
                $cell_value = esc_html( $cell );
                $cell_value = str_replace( "\n", '<br>', $cell_value );
                $html .= '<td>' . $cell_value . '</td>';
            }
            $html .= '</tr>';
        }
        $html .= '</tbody>';
        
        $html .= '</table>';
        
        // Footer
        $html .= '<div class="footer">';
        $html .= sprintf(
            __( 'Generated on %s', 'primelink' ),
            date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) )
        );
        $html .= '</div>';
        
        $html .= '</body></html>';

        return self::generate_from_html( $html, $options );
    }

    /**
     * Generate PDF table and save to file.
     *
     * @param string $file_path File path to save PDF.
     * @param array  $headers   Table headers.
     * @param array  $rows      Table rows.
     * @param array  $options   PDF options.
     * @param string $title     PDF title (optional).
     * @return bool|WP_Error True on success, WP_Error on failure.
     */
    public static function save_table_pdf( $file_path, $headers, $rows, $options = array(), $title = '' ) {
        $pdf_output = self::generate_table_pdf( $headers, $rows, $options, $title );
        
        if ( is_wp_error( $pdf_output ) ) {
            return $pdf_output;
        }

        // Ensure directory exists
        $dir = dirname( $file_path );
        if ( ! \PrimeLink\Helpers\FilesystemHelper::directory_exists( $dir ) ) {
            \PrimeLink\Helpers\FilesystemHelper::create_directory( $dir );
        }

        // Write PDF to file
        $result = \PrimeLink\Helpers\FilesystemHelper::write_file( $file_path, $pdf_output );
        
        if ( false === $result ) {
            return new \WP_Error(
                'pdf_save_failed',
                __( 'Failed to save PDF file.', 'primelink' )
            );
        }

        return true;
    }
}

