<?php
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}


include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
require_once( ABSPATH .'wp-content/plugins/wpcargo-frontend-manager/admin/includes/dompdf/lib/html5lib/Parser.php' );
require_once( ABSPATH .'wp-content/plugins/wpcargo-frontend-manager/admin/includes/dompdf/lib/php-font-lib/src/FontLib/Autoloader.php' );
require_once( ABSPATH .'wp-content/plugins/wpcargo-frontend-manager/admin/includes/dompdf/src/Options.php' );
require_once( ABSPATH .'wp-content/plugins/wpcargo-frontend-manager/admin/includes/dompdf/src/Autoloader.php' );

Dompdf\WPCFE_Autoloader::register();
use Dompdf\Dompdf;
use Dompdf\WPCFE_Options;

// Print Shipment Barcode
function wpcstl_barcode_template( $shipment_id, $waybill_title, $pallet = 0 ){
    global $WPCCF_Fields, $wpcargo, $wpcargo_print_admin;
    ob_start();
    $mp_settings            = get_option('wpc_mp_settings');
    $setting_options        = get_option('wpcargo_option_settings');
    $origin                 = get_post_meta( $shipment_id, '__wpcsr_origin', true );
    $orig_postcode          = get_post_meta( $shipment_id, '__wpcsr_origin_postcode', true );
    $destination            = get_post_meta( $shipment_id, '__wpcsr_destination', true );
    $dest_postcode          = get_post_meta( $shipment_id, '__wpcsr_destination_postcode',true );
    $packages               = maybe_unserialize( get_post_meta( $shipment_id,'wpc-multiple-package', TRUE) );
    $package_count          = count($packages);
    $counter                = 1;
    $print_fonts 		    = wpcargo_print_fonts();
    $ffamily 			    = get_option('wpcargo_print_ffamily');
    $fsize 				    = get_option('wpcargo_print_fsize') ? get_option('wpcargo_print_fsize') : 12 ;
    $logo                   = '';
    $shipment_number        = get_the_title( $shipment_id );
    if( !empty( $setting_options['settings_shipment_ship_logo'] ) ){
        $logo 		= $setting_options['settings_shipment_ship_logo'];
    }
    $barcode        = WPCARGO_PLUGIN_URL."includes/barcode.php?orientation=horizontal&codetype=code128&size=120&text=".$shipment_number;
    ?>
    <!DOCTYPE html>
    <html <?php language_attributes(); ?> <?php echo is_rtl() ? 'dir="rtl"' : '' ; ?>>
        <head>
        <title><?php echo $waybill_title; ?></title>
        <meta charset="<?php bloginfo( 'charset' ); ?>">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <style type="text/css">         
            @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
            *{
                font-family: Calibri, Candara, Segoe, "Segoe UI", Optima, Arial, sans-serif;
            }
            html, body{ margin:0px; padding:0px; }
            h1, h2, h3, h4, h5, h6{ font-weight: normal !important; }
            h6, h5{ font-size: 1.1rem!important; }
            h4, h3{ font-size: 1.2rem!important; }
            h2{ font-size: 1.4rem!important; }
            h1{ font-size: 1.6rem!important; }
            /* table{
                border-collapse: collapse;
            }
            table td{
                border:1px solid #000;
            } */
            .page_break { page-break-before: always; }
            @media screen, print{ .page_break { page-break-before: always; } }
        </style>
        </head>
        <body style="padding:0;margin:0;">
            <?php if( $pallet ): ?>
                <?php $counter = $pallet; ?>
                <?php require WPCSTL_PATH.'templates/print-pallet.php'; ?>
            <?php else: ?>
                <?php foreach ( $packages as $packages) : ?>
                    <?php require WPCSTL_PATH.'templates/print-pallet.php'; ?>
                    <?php echo $package_count != $counter ? '<div class="page_break"></div>' : '' ; ?>
                <?php $counter++; endforeach; ?>
            <?php endif; ?>
        </body>
    </html>
    <?php
    $output = ob_get_clean();
	return $output;
}
function wpcstl_print_barcode_callback(){
    global $wpdb, $WPCCF_Fields, $wpcargo;
    $directory    = WPCSTL_PATH .'download-files/';
    // Clean directory before adding new file
    foreach( glob($directory.'*.pdf') as $pdf_file){
        unlink($pdf_file);
    }
    $wpcfe_pdf_dpi  = apply_filters( 'wpcfe_pdf_dpi', 160 );
    $shipment_id    = $_POST['shipmentID'];
    $waybill_title 	= get_the_title($shipment_id).'-'.time();	
    // instantiate and use the dompdf class
    $options 		= new WPCFE_Options();
    $options->setDpi( $wpcfe_pdf_dpi );
    $dompdf 		= new Dompdf( $options );
    $dompdf->set_option('isRemoteEnabled', true);
    $dompdf->loadHtml( wpcstl_barcode_template( $shipment_id, $waybill_title  ) );
    $dompdf->setPaper( 'A6', 'landscape' );
    // Render the HTML as PDF
    $dompdf->render();
    // Output the generated PDF to Browser
    $output = $dompdf->output();
    $data_info = array();
    if( file_put_contents( $directory.$waybill_title.'.pdf', $output) ){
        $data_info = array(
            'file_url' => WPCSTL_URL .'download-files/'.$waybill_title.'.pdf',
            'file_name' => $waybill_title
        );  
    }
    echo json_encode( $data_info );
    wp_die();
}
add_action( 'wp_ajax_wpcstl_print_barcode', 'wpcstl_print_barcode_callback' );
function wpcstl_print_pallet_callback(){
    global $wpdb, $WPCCF_Fields, $wpcargo;
    $directory    = WPCSTL_PATH .'download-files/';
    // Clean directory before adding new file
    foreach( glob($directory.'*.pdf') as $pdf_file){
        unlink($pdf_file);
    }
    $wpcfe_pdf_dpi  = apply_filters( 'wpcfe_pdf_dpi', 160 );
    $pallet         = $_POST['pallet'];
    $shipment_id    = $_POST['shipmentID'];
    $waybill_title 	= get_the_title($shipment_id).'-'.time();
    // instantiate and use the dompdf class
    $options 		= new WPCFE_Options();
    $options->setDpi( $wpcfe_pdf_dpi );
    $dompdf 		= new Dompdf( $options );
    $dompdf->set_option('isRemoteEnabled', true);
    $dompdf->loadHtml( wpcstl_barcode_template( $shipment_id, $waybill_title, $pallet ) );
    $dompdf->setPaper( 'A6', 'landscape' );
    // Render the HTML as PDF
    $dompdf->render();
    // Output the generated PDF to Browser
    $output = $dompdf->output();
    $data_info = array();
    if( file_put_contents( $directory.$waybill_title.'.pdf', $output) ){
        $data_info = array(
            'file_url' => WPCSTL_URL .'download-files/'.$waybill_title.'.pdf',
            'file_name' => $waybill_title
        );  
    }
    echo json_encode( $data_info );
    wp_die();
}
add_action( 'wp_ajax_wpcstl_print_pallet', 'wpcstl_print_pallet_callback' );
