<?php
//ini_set("pcre.backtrack_limit", "10000000");

/** Loads the WordPress Environment and Template */
define('WP_USE_THEMES', false);
if (file_exists('../../../../../../wp-blog-header.php')) {
    require('../../../../../../wp-blog-header.php');
} else if (file_exists('../../../../../wp-blog-header.php')) {
    require('../../../../../wp-blog-header.php');
} else if (file_exists('../../../../wp-blog-header.php')) {
    require('../../../../wp-blog-header.php');
} else if (file_exists('../../../wp-blog-header.php')) {
    require('../../../wp-blog-header.php');
} else {
    echo 'ERROR: Wp Blog Header not found...why?';
    die();
}

use \EAddonsForElementor\Core\Utils;
use \EAddonsPdf\Core\Utils\Pdf as Utils_Pdf;

$template_id = 0;
if (!empty($_GET['post_id'])) {
    $post_id = intval($_GET['post_id']);
} else {
    $post_id = 0;
}
if (!empty($_GET['element_id'])) {
    $element_id = $_GET['element_id'];
} else {
    $element_id = 0;
}

if ($element_id && $post_id) {

    // prevent 404
    status_header(200);
    global $wp_query, $post;
    $wp_query->is_page = $wp_query->is_singular = true;
    $wp_query->is_404 = false;
    
    // set post
    $post = get_post($post_id);
    $wp_query->queried_object = $post;
    $wp_query->queried_object_id = $post_id;

    // elementor data
    $element = Utils::get_element_instance_by_id($element_id, $post_id);
    $settings = $element->get_settings_for_display();

    if ($settings['e_pdf_button_body'] == 'template') {
        $template_id = $settings['e_pdf_button_template'];
    } else {
        //$container = empty($settings['e_pdf_button_container']) ? 'body' : $settings['e_pdf_button_container'];
        $template_id = Utils::get_current_template($post_id);
    }
    //var_dump($template_id); die();

    $styles = $settings['e_pdf_button_styles'];
    $title = Utils_Pdf::get_dynamic_data($settings['e_pdf_button_title'], $post) . '.pdf';    
    //var_dump($title); die();
    if ($template_id) {
        
        if ($template_id) {
            $atts = array(
                'id' => $template_id,
                'post_id' => $post_id,
                //'author_id' => '',
                //'user_id' => $user_id,
                //'term_id' => '',
                'css' => true,
            );
            $pdf_html = \EAddonsForElementor\Core\Managers\Template::e_template($template_id, $atts);
        }

        $pdf_html = Utils::get_dynamic_data($pdf_html);
        //var_dump($pdf_html); die();
        
        $pdf_html = Utils_Pdf::fix_html($pdf_html, $settings);
        
        $css_id = $template_id ? $template_id : $post_id;
        $pdf_html = Utils_Pdf::fix_css($pdf_html, $css_id, $styles, 'pdf');
        if (!$pdf_html) {
            echo 'Content NOT found, please check selector or template';
            die();
        }
        
        $pdf_html = Utils_Pdf::template_unwrap($pdf_html);
        //echo $pdf_html; die();

        switch ($settings['e_pdf_button_converter']) {
            case 'dompdf':           
            case 'mpdf':
                
                $params = Utils_Pdf::get_params(null, $settings);
                if (isset($params['mgt'])) {
                    $pdf_html = Utils_Pdf::add_inline_assets('@page { margin: ' . $params['mgt'] . 'mm ' . $params['mgr'] . 'mm ' . $params['mgb'] . 'mm ' . $params['mgl'] . 'mm; }', 'style', $pdf_html);
                }
                
                /*
                $params['fontDir'] = array_merge($params['fontDir'], [
                    ELEMENTOR_ASSETS_PATH . '/lib/font-awesome/fonts',
                    ELEMENTOR_ASSETS_PATH . '/lib/font-awesome/webfonts',
                ]);
                $params['fontdata'] = $params['fontdata'] + [
                    'fontawesome' => [
                        'R' => 'fontawesome-webfont.ttf',
                        //'I' => 'FrutigerObl-Normal.ttf',
                    ],
                    'Font Awesome 5 Brands' => [
                        'R' => 'fa-brands-400.ttf',
                    ],
                    'Font Awesome 5 Free' => [
                        'R' => 'fa-regular-400.ttf',
                        'B' => 'fa-solid-900.ttf',
                    ],
                ];
                */
                
                try {
                    //var_dump($title); die();
                    $mpdf = new \Mpdf\Mpdf($params);
                    
                    if (WP_DEBUG) {
                        $mpdf->debug = true;
                    }
                    
                    Utils_Pdf::extra_configuration($mpdf, $settings);
                    
                    $pdf_html = Utils_Pdf::SetHTMLHeaderFooter($mpdf, $pdf_html, $settings, null, $params);
                    
                    Utils_Pdf::set_bg($mpdf, $settings);
                    
                    //$mpdf->SetHTMLHeader();
                    //$mpdf->SetHTMLFooter();
                                        
                    Utils_Pdf::WriteHTML($mpdf, $pdf_html);
                    
                    //$mpdf->AddPage();
                    // Output the generated PDF to Browser                
                    
                    //$tempDest = $params['tempDir'].DIRECTORY_SEPARATOR.$title;
                    //var_dump($tempDest); die();
                    
                    header("Content-type:application/pdf");
                    header("Content-Disposition:attachment;filename=" . $title . "");
                    $mpdf->Output($title, 'D');
                                        
                } catch (\Mpdf\MpdfException $e) { 
                    //echo '<pre>';var_dump($e);echo '</pre>';
                    echo $e->getMessage();
                }
                break;

            case 'browser':
                if (isset($settings['e_pdf_margin']['top']) && $settings['e_pdf_margin']['top'] != '') {
                    $pdf_html = Utils_Pdf::add_inline_assets('@page { margin: ' . $settings['e_pdf_margin']['top'] . $settings['e_pdf_margin']['unit'] . ' ' . $settings['e_pdf_margin']['right'] . $settings['e_pdf_margin']['unit'] . ' ' . $settings['e_pdf_margin']['bottom'] . $settings['e_pdf_margin']['unit'] . ' ' . $settings['e_pdf_margin']['left'] . $settings['e_pdf_margin']['unit'] . '; }', 'style', $pdf_html);
                }
            default:
                echo '<!DOCTYPE html' . (empty($settings['e_pdf_rtl']) ? '' : ' dir="rtl"') . '><head><title>' . $title . '</title></head><body>' . $pdf_html . '<script>window.print();</script></body></html>';
                break;
        }
    }
    die();
}

echo 'ERROR';
