<?php

namespace EAddonsPdf\Modules\Pdf\Actions;

use EAddonsForElementor\Base\Base_Action;
use Elementor\Controls_Manager;
use EAddonsForElementor\Core\Utils;
use EAddonsForElementor\Core\Utils\Form;
use EAddonsPdf\Core\Utils\Pdf as Utils_Pdf;

if (!defined('ABSPATH'))
    exit; // Exit if accessed directly

class Pdf extends Base_Action {
    
    use \EAddonsPdf\Modules\Pdf\Traits\Pdf;

    public static $attachment;

    /**
     * Get Name
     *
     * Return the action name
     *
     * @access public
     * @return string
     */
    public function get_name() {
        return 'pdf';
    }

    public function get_icon() {
        return 'eadd-el-form-pro-act-pdf-generator';
    }

    /**
     * Get Label
     *
     * Returns the action label
     *
     * @access public
     * @return string
     */
    public function get_label() {
        return esc_html__('PDF', 'e-addons');
    }

    public function get_pid() {
        return 3651;
    }

    /**
     * Register Settings Section
     *
     * Registers the Action controls
     *
     * @access public
     * @param \Elementor\Widget_Base $widget
     */
    public function register_settings_section($widget) {

        $this->start_controls_section($widget);

        $widget->add_control(
                'e_form_pdf_name', [
            'label' => esc_html__('File name', 'e-addons'),
            'label_block' => true,
            'type' => Controls_Manager::TEXT,
            'default' => '[U]',
            'description' => esc_html__('Write here the PDF file title without extension. The [U] generate current time as name.', 'e-addons'),
            
                ]
        );

        $widget->add_control(
                'e_form_pdf_folder', [
            'label' => esc_html__('Directory', 'e-addons'),
            'label_block' => true,
            'type' => Controls_Manager::TEXT,
            'default' => 'elementor/pdf/[Y]/[m]',
            'description' => esc_html__('Select here the path inside the "wp-content/uploads/" folder where store the PDF file.', 'e-addons'),
            
                ]
        );

        $widget->add_control(
                'e_form_pdf_h_header',
                [
                    'label' => esc_html__('Header', 'e-addons'),
                    'type' => Controls_Manager::HEADING,
                    'separator' => 'before',
                ]
        );
        $widget->add_control(
                'e_form_pdf_header',
                [
                    'label' => esc_html__('Add Header', 'e-addons'),
                    'type' => Controls_Manager::SWITCHER,
                    'description' => 'Set an HTML page header.',
                ]
        );
        $widget->add_control(
                'e_form_pdf_header_txt',
                [
                    //'label' => esc_html__('Header', 'e-addons'),
                    'type' => Controls_Manager::WYSIWYG,
                    'condition' => [
                        'e_form_pdf_header!' => '',
                    ],
                ]
        );
        $widget->add_control(
                'e_form_pdf_header_aliases',
                [
                    'label' => '<b>' . esc_html__('Replaceable Aliases', 'e-addons') . '</b>',
                    'type' => Controls_Manager::RAW_HTML,
                    'raw' => 'There are several placemarkers you can include, which will be replaced when the PDF file is ouput: <b>{nb}</b> for total pages number, and <b>{PAGENO}</b> for current page number.' .
                    '<br><a href="https://mpdf.github.io/what-else-can-i-do/replaceable-aliases.html" target="_blank">Read more</a>',
                    'condition' => [
                        'e_form_pdf_header!' => '',
                    ],
                ]
        );
        $widget->add_control(
                'e_pdf_header_margin', [
            'label' => esc_html__('Header Margin', 'e-addons'),
            'type' => Controls_Manager::NUMBER,
                'condition' => [
                        'e_form_pdf_header!' => '',
                    ],
                ]
        );

        $widget->add_control(
                'e_form_pdf_h_body',
                [
                    'label' => esc_html__('Body', 'e-addons'),
                    'type' => Controls_Manager::HEADING,
                    'separator' => 'before',
                ]
        );

        $widget->add_control(
                'e_form_pdf_body',
                [
                    'label' => esc_html__('Type', 'e-addons'),
                    'type' => Controls_Manager::CHOOSE,
                    'options' => [
                        'text' => [
                            'title' => esc_html__('Html', 'e-addons'),
                            'icon' => 'eicon-text-area',
                        ],
                        'template' => [
                            'title' => esc_html__('Template', 'e-addons'),
                            'icon' => 'eicon-inner-section',
                        ]
                    ],
                    'toggle' => false,
                    'default' => 'text',
                ]
        );
        $widget->add_control(
                'e_form_pdf_text',
                [
                    'label' => esc_html__('Html', 'e-addons'),
                    'type' => Controls_Manager::WYSIWYG,
                    'default' => '[all-fields]',
                    'description' => 'Write here the content for this PDF.',
                    'condition' => [
                        'e_form_pdf_body' => 'text',
                    ],
                ]
        );
        $widget->add_control(
                'e_form_pdf_template',
                [
                    'label' => esc_html__('Template', 'e-addons'),
                    'type' => 'e-query',
                    'placeholder' => esc_html__('Template Name', 'e-addons'),
                    'label_block' => true,
                    'query_type' => 'posts',
                    'object_type' => 'elementor_library',
                    'description' => esc_html__('Use a Elementor Template as body fo this PDF', 'e-addons'),
                    'condition' => [
                        'e_form_pdf_body' => 'template',
                    ],
                ]
        );

        $widget->add_control(
                'e_form_pdf_h_footer',
                [
                    'label' => esc_html__('Footer', 'e-addons'),
                    'type' => Controls_Manager::HEADING,
                    'separator' => 'before',
                ]
        );
        $widget->add_control(
                'e_form_pdf_footer',
                [
                    'label' => esc_html__('Add Footer', 'e-addons'),
                    'type' => Controls_Manager::SWITCHER,
                    'description' => 'Set an HTML page footer.',
                ]
        );
        $widget->add_control(
                'e_form_pdf_footer_txt',
                [
                    //'label' => esc_html__('Footer', 'e-addons'),
                    'type' => Controls_Manager::WYSIWYG,
                    'condition' => [
                        'e_form_pdf_footer!' => '',
                    ],
                ]
        );
        $widget->add_control(
                'e_form_pdf_footer_aliases',
                [
                    'label' => '<b>' . esc_html__('Replaceable Aliases', 'e-addons') . '</b>',
                    'type' => Controls_Manager::RAW_HTML,
                    'raw' => 'There are several placemarkers you can include, which will be replaced when the PDF file is ouput: <b>{nb}</b> for total pages number, and <b>{PAGENO}</b> for current page number.' .
                    '<br><a href="https://mpdf.github.io/what-else-can-i-do/replaceable-aliases.html" target="_blank">Read more</a>',
                    'condition' => [
                        'e_form_pdf_footer!' => '',
                    ],
                ]
        );
        $widget->add_control(
                'e_pdf_footer_margin', [
            'label' => esc_html__('Footer Margin', 'e-addons'),
            'type' => Controls_Manager::NUMBER,
                'condition' => [
                        'e_form_pdf_footer!' => '',
                    ],
                ]
        );

        $widget->add_control(
                'e_form_pdf_page',
                [
                    'label' => esc_html__('Page', 'e-addons'),
                    'type' => Controls_Manager::HEADING,
                    'separator' => 'before',
                ]
        );

        $widget->add_control(
                'e_form_pdf_size',
                [
                    'label' => esc_html__('Size', 'e-addons'),
                    'type' => Controls_Manager::SELECT,
                    'default' => 'a4',
                    'options' => \EAddonsPdf\Modules\Pdf\Pdf::get_paper_sizes(),
                ]
        );
        
        $this->add_common_pdf_controls($widget);
        
        $widget->add_control(
                'e_pdf_dpi',
                [
                    'label' => esc_html__('DPI', 'e-addons'),
                    'type' => Controls_Manager::SELECT,
                    'options' => [
                        '' => esc_html__('Default', 'e-addons'),
                        '72' => esc_html__('72', 'e-addons'),
                        '150' => esc_html__('150', 'e-addons'),
                        '300' => esc_html__('300', 'e-addons'),
                    ],
                ]
        );
        
        $widget->add_control(
                'e_pdf_section_page', [
            'label' => esc_html__('Sections as Pages', 'e-addons'),
            'type' => Controls_Manager::SWITCHER,
            'description' => esc_html__('Force every Template Section as a new page', 'e-addons'),
            'condition' => [
                'e_form_pdf_body' => 'template',
            ]
                ]
        );

        $this->add_bg_controls($widget);

        $widget->add_control(
                'e_pdf_attachment',
                [
                    'label' => esc_html__('Media', 'e-addons'),
                    'type' => Controls_Manager::HEADING,
                    'separator' => 'before',
                ]
        );
        $widget->add_control(
                'e_form_pdf_save', [
            'label' => esc_html__('Save', 'e-addons'),
            'type' => Controls_Manager::SWITCHER,
            'description' => esc_html__('Save the generated PDF file as Media', 'e-addons'),
                ]
        );
        $widget->add_control(
                'e_form_pdf_title', [
            'label' => esc_html__('Title', 'e-addons'),
            'type' => Controls_Manager::TEXT,
            'default' => 'Form data by [field id="name"] in [date|Y-m-d H:i:s]',
            'description' => esc_html__('The PDF file Title', 'e-addons'),
            'label_block' => true,
            'condition' => [
                'e_form_pdf_save!' => '',
            ],
                ]
        );
        $widget->add_control(
                'e_form_pdf_content', [
            'label' => esc_html__('Description', 'e-addons'),
            'type' => Controls_Manager::TEXT,
            'default' => '[field id="message"]',
            'description' => esc_html__('The PDF file Description', 'e-addons'),
            'label_block' => true,
            'condition' => [
                'e_form_pdf_save!' => '',
            ],
                ]
        );

        //if (Utils::is_plugin_active('e-addons-pro-form-actions')) {
        $widget->add_control(
                'e_form_pdf_email_heading',
                [
                    'label' => esc_html__('Email', 'e-addons'),
                    'type' => Controls_Manager::HEADING,
                    'separator' => 'before',
                /* 'condition' => [
                  'submit_actions' => 'e-email',
                  ], */
                ]
        );
        $widget->add_control(
                'e_form_pdf_email', [
            'label' => esc_html__('Add PDF as email attachment', 'e-addons'),
            'type' => \Elementor\Controls_Manager::SWITCHER,
            'description' => esc_html__('Send the generated PDF as an Email attachment', 'e-addons'),
                /* 'condition' => [
                  'submit_actions' => ['email', 'e-email'],
                  ], */

                /* 'conditions' => [
                  'relation' => 'or',
                  'terms' => [
                  [
                  'name' => 'submit_actions',
                  'operator' => 'contain',
                  'value' => 'email'
                  ],
                  [
                  'name' => 'submit_actions',
                  'operator' => 'contain',
                  'value' => 'e-email'
                  ]
                  ]
                  ] */
                ]
        );
        
        $widget->add_control(
                'e_form_pdf_redirect', [
            'label' => esc_html__('Redirect to', 'e-addons'),
            'type' => Controls_Manager::SWITCHER,
            'description' => esc_html__('Goto new PDF file after generate it', 'e-addons'),
                    'separator' => 'before',
                ]
        );
        //}

        Utils::add_help_control($this, $widget);

        $widget->end_controls_section();
    }

    /**
     * Run
     *
     * Runs the action after submit
     *
     * @access public
     * @param \ElementorPro\Modules\Forms\Classes\Form_Record $record
     * @param \ElementorPro\Modules\Forms\Classes\Ajax_Handler $ajax_handler
     */
    public function run($record, $ajax_handler) {
        $fields = Form::get_form_data($record);
        $settings = $this->get_settings(true, $fields);
        global $e_form, $epdf, $post, $wp_query;

        $epdf = array();

        //setup_postdata($post);
        $post_id = $_POST['queried_id'];
        $post = get_post($post_id);
        $wp_query->queried_object = $post;
        $wp_query->queried_object_id = $post_id;

        $pdf_name = Utils_Pdf::get_dynamic_data($settings['e_form_pdf_name']);
        $pdf_folder = Utils_Pdf::get_dynamic_data($settings['e_form_pdf_folder']);

        $pdf_folder = '/' . $pdf_folder . '/';
        $upload = wp_upload_dir();
        $pdf_dir = $upload['basedir'] . $pdf_folder;
        $pdf_url = $upload['baseurl'] . $pdf_folder;
        $pdf_name = $pdf_name . '.pdf';
        $e_form['pdf']['path'] = $pdf_dir . $pdf_name;
        $epdf['path'] = $pdf_dir . $pdf_name;
        $e_form['pdf']['url'] = $pdf_url . $pdf_name;
        $epdf['url'] = $pdf_url . $pdf_name;
        //var_dump($e_form); die();

        $template_id = empty($settings['e_form_pdf_template']) ? false : $settings['e_form_pdf_template'];
        
        if ($settings['e_form_pdf_body'] == 'template') {            
            if (!$template_id) {
                $ajax_handler->add_error_message(__('Error: PDF Template not found or not set', 'e-addons'));
                return;
            }
            // verify Template
            $template = get_post($template_id);
            if (!$template || $template->post_type != 'elementor_library') {
                $ajax_handler->add_error_message(__('Error: PDF Template is not correctly set', 'e-addons'));
                return;
            }
            $pdf_html = \EAddonsForElementor\Core\Managers\Template::e_template($template_id);

            //var_dump($pdf_html); die();
        } else {
            $pdf_html = $settings['e_form_pdf_text'];
        }
        
        

        $pdf_html = Form::replace_content_shortcodes($pdf_html, $fields);
        $pdf_html = Form::do_setting_shortcodes($pdf_html, $fields);
        $pdf_html = Utils::get_dynamic_data($pdf_html, $fields, 'form');

        // link image from url to path
        //$pdf_html = str_replace('src="'.site_url(), 'src="'.$upload['basedir'], $pdf_html);

        $pdf_html = Utils_Pdf::fix_html($pdf_html, $settings);
        
        //var_dump($pdf_html); die();
        if ($template_id) {
            $pdf_html = Utils_Pdf::fix_css($pdf_html, $template_id, 'all', 'pdf');
            $pdf_html = Utils_Pdf::template_unwrap($pdf_html);
        }
        
        if (!is_dir($pdf_dir)) {
            // create dir
            mkdir($pdf_dir, 0755, true);
        }
        
        $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);
            //var_dump($pdf_html); die();
        }
        
        /*
        if ($settings['e_form_pdf_header'] && isset($settings['e_pdf_header_margin']) && $settings['e_pdf_header_margin'] != '') {
            $params['margin_header'] = intval($settings['e_pdf_header_margin']); 
        }
        if ($settings['e_form_pdf_footer'] && isset($settings['e_pdf_footer_margin']) && $settings['e_pdf_footer_margin'] != '') {
            $params['margin_footer'] = intval($settings['e_pdf_footer_margin']); 
        }
        */

        try {
            $mpdf = new \Mpdf\Mpdf($params);

            if (WP_DEBUG) {
                $mpdf->debug = true;
            }
            
            Utils_Pdf::extra_configuration($mpdf, $settings);

            //$mpdf->SetHTMLHeader();
            $pdf_html = Utils_Pdf::SetHTMLHeaderFooter($mpdf, $pdf_html, $settings, $fields, $params);

            Utils_Pdf::set_bg($mpdf, $settings);

            //$mpdf->WriteHTML($pdf_html);
            Utils_Pdf::WriteHTML($mpdf, $pdf_html);
            // You can write parts of HTML elements by using the initialise and close parameters:
            //$mpdf->WriteHTML('This is the beginning...', \Mpdf\HTMLParserMode::HTML_BODY, true, false);
            //$mpdf->WriteHTML('...this is the middle...', \Mpdf\HTMLParserMode::HTML_BODY, false, false);
            //$mpdf->WriteHTML('...and this is the end', \Mpdf\HTMLParserMode::HTML_BODY, false, true);
            
            //var_dump($pdf_dir . $pdf_name); die();
            $mpdf->Output($pdf_dir . $pdf_name, 'F');
            
        } catch (\Mpdf\MpdfException $e) { 
            echo $e->getMessage();
        }

        if (!empty($settings['e_form_pdf_email'])) {
            //$pdf_name = $pdf_name . '.pdf';
            self::$attachment = $pdf_dir . $pdf_name;
            add_filter('wp_mail', function ($atts) {
                //var_dump(self::$attachment); die();
                if (self::$attachment && file_exists(self::$attachment)) {
                    $atts['attachments']['pdf'] = self::$attachment;
                }
                return $atts;
            });

            if (!empty($settings['e_form_email_repeater'])) {
                foreach ($settings['e_form_email_repeater'] as $email) {
                    if (!empty($email['e_form_attachments_delete'])) {
                        add_action('elementor_pro/forms/new_record', function ($record, $ajax_handler) {
                            if (self::$attachment && file_exists(self::$attachment)) {
                                unlink(self::$attachment);
                            }
                        }, 10, 2);
                    }
                }
            }
        }
        $guid = $pdf_url . $pdf_name; //end($tmp);$guid
        if ($settings['e_form_pdf_save']) {
            // Insert the post into the database
            // https://codex.wordpress.org/Function_Reference/wp_insert_attachment
            // $filename should be the path to a file in the upload directory.
            $filename = $pdf_dir . $pdf_name;

            // The ID of the post this attachment is for.
            $parent_post_id = !empty($_POST['queried_id']) ? $_POST['queried_id'] : $_POST['post_id'];
            // Check the type of file. We'll use this as the 'post_mime_type'.
            $filetype = wp_check_filetype(basename($filename), null);
            // Get the path to the upload directory.
            //$tmp = explode('/wp-content/uploads/', $filename);
            
            // Prepare an array of post data for the attachment.
            $attachment = array(
                'guid' => $guid,
                'post_mime_type' => $filetype['type'],
                'post_status' => 'inherit',
                'post_title' => $settings['e_form_pdf_title'],
                'post_content' => $settings['e_form_pdf_content'],
            );
            // Insert the attachment.
            $attach_id = wp_insert_attachment($attachment, $filename, $parent_post_id);
            if ($attach_id) {

                // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
                require_once( ABSPATH . 'wp-admin/includes/image.php' );
                // Generate the metadata for the attachment, and update the database record.
                $attach_data = wp_generate_attachment_metadata($attach_id, $filename);
                wp_update_attachment_metadata($attach_id, $attach_data);

                if (!empty($fields) && is_array($fields)) {
                    foreach ($fields as $akey => $adata) {
                        update_post_meta($attach_id, $akey, $adata);
                    }
                }
                $e_form['pdf']['ID'] = $attach_id;
                $epdf['ID'] = $attach_id;
            } else {
                $ajax_handler->add_error_message(__('Error during save PDF as Media', 'e-addons'));
            }
        }
        
        if ($settings['e_form_pdf_redirect']) {
            $url = urlencode($guid);
            // http%3A%2F%2Flocalhost%2Fwp-content%2Fuploads%2Felementor%2Fpdf%2F2021%2F11%2F1636401059.pdf
            $url = str_replace('%3A', ':', $url);
            $url = str_replace('%2F', '/', $url);
            //var_dump($url); die();
            if (!empty($guid) && filter_var($url, FILTER_VALIDATE_URL)) {
                //var_dump($guid); die();
                $ajax_handler->add_response_data('redirect_url', $url);
            }
        }
    }

}
