<?php
$lpc_orders_table        = (isset($args['table'])) ? $args['table'] : array();
$get_args                = (isset($args['get'])) ? $args['get'] : array();
$thermalLabelPrintAction = $args['thermalLabelPrintAction'];
wp_nonce_field('wc_colissimo_view');
$errorMsgPrintThermal = __('Print thermal error on some orders. Please check browser console for more information',
	'wc_colissimo');
?>
<div class="wrap">
	<?php
	$lpc_orders_table->prepare_items($get_args);
	$lpc_orders_table->displayHeaders();
	?>
	<iframe type="application/pdf" src=""
			width="100%" style="display:none;" height="100%" id="lpcPrintIframe">
	</iframe>
	<form method="post">
		<?php
		if (isset($_REQUEST['page'])) {
			?>
			<input type="hidden" name="page"
				   value="<?php echo esc_attr(sanitize_text_field(wp_unslash($_REQUEST['page']))); ?>"/>
			<?php
		}
		$lpc_orders_table->search_box('search', 'search_id');
		$lpc_orders_table->display();
		?>
	</form>
	<script type="text/Javascript">
        jQuery(function ($) {
            $('.lpc__orders_listing__tracking-number > .lpc_download_label').off('click').on('click', function () {
                let specificAction = $(this).attr('data-link');
                if (specificAction !== undefined && specificAction !== '') {
                    location.href = specificAction;
                }
            });

            $('.lpc__orders_listing__tracking-number > .lpc_print_label').off('click').on('click', function () {
                let specificAction = $(this).attr('data-link');
                let labelType = $(this).attr('data-label-type');
                let trackingNumber = $(this).closest('.lpc__orders_listing__tracking-number').attr('data-tracking-number');
                switch ($(this).attr('data-format')) {
                    case 'ZPL':
                    case 'DPL':
                        let lpc_thermal_labels_infos = [
                            {
                                lpc_tracking_number: trackingNumber,
                            }
                        ];

                        printThermal(lpc_thermal_labels_infos);
                    //We don't break here because we want to print in PDF the invoice and maybe the CN23

                    case 'PDF':
                        printPDF(specificAction);
                        break;
                }
            });

            $('.lpc__orders_listing__tracking-number > .lpc_send_email').off('click').on('click', function () {
                let specificAction = $(this).attr('data-link');
                if (specificAction !== undefined && specificAction !== '') {
                    location.href = specificAction;
                }
            });

            $('.lpc__orders_listing__tracking-number > .lpc_delete_label').off('click').on('click', function () {
                let specificAction = $(this).attr('data-link');
                let trackingNumber = $(this).closest('.lpc__orders_listing__tracking-number').attr('data-tracking-number');
                let labelType = $(this).closest('.lpc__orders_listing__tracking-number').attr('data-label-type');

                let confirmText = labelType == 'outward'
                    ?
                    "<?php echo __('Do you confirm the deletion of label? All related inwards label will be deleted too',
						'wc_colissimo'); ?>"
                    :
                    "<?php echo __('Do you confirm the deletion of label?', 'wc_colissimo'); ?>"
                ;

                if (specificAction !== undefined && specificAction !== '') {
                    if (window.confirm(trackingNumber + " : " + confirmText)) {
                        location.href = specificAction;
                    }
                }
            });

            function printThermal(thermalLabelsInfos) {
                let urlThermal = '<?php echo $thermalLabelPrintAction->getThermalPrintActionUrl(); ?>';

                $.ajax({
                    type: 'POST',
                    url: urlThermal,
                    data: {lpc_thermal_labels_infos: thermalLabelsInfos},
                    dataType: 'json'
                }).success(function (response) {
                    let urlsForOrdersdId = $.parseJSON(response);

                    Object.keys(urlsForOrdersdId).forEach(trackingNumber => {
                        urlsForOrdersdId[trackingNumber].forEach(url => {
                            if (url.length !== 0) {
                                $.ajax({
                                    type: 'GET', url: url, dataType: 'html'
                                }).error(function () {
                                    console.error('error on label ' + trackingNumber);
                                    if ($('#lpc_thermal_print_error_message').length === 0) {
                                        displayErrors("<?php echo $errorMsgPrintThermal; ?>");
                                    }
                                });
                            }
                        });
                    });
                }).error(function (error) {
                    console.error(error);
                });
            }

            function printPDF(specificAction) {
                let ePdf = document.getElementById('lpcPrintIframe');
                if (ePdf && ePdf.tagName === 'IFRAME') {
                    ePdf.src = specificAction;
                    ePdf.onload = function () {
                        if ($(ePdf).contents().find('body').html() != 'null') {
                            ePdf.contentWindow.focus();
                            ePdf.contentWindow.print();
                        }
                    }
                }
            }

            function lpc_print_labels(infos) {
                let url = infos.pdfUrl;
                let trackingNumbers = infos.trackingNumbers;
                let type = infos.labelType;

                let splittedTrackingNumbers = trackingNumbers.split(',');

                let thermalPrintInfo = [];

                splittedTrackingNumbers.forEach(function (trackingNumber) {
                    thermalPrintInfo.push({
                        lpc_tracking_number: trackingNumber,
                    })
                });

                printThermal(thermalPrintInfo);
                printPDF(url);
            }

            function displayErrors(errorMessage) {
                let $wpHeaderEnd = $('.wp-header-end');

                if ($wpHeaderEnd.length) {
                    $wpHeaderEnd.after('<div class="error" id="lpc_thermal_print_error_message"><p>' + errorMessage + '</p></div>');
                } else {
                    alert(errorMessage);
                }
            }

            window.lpc_print_labels = lpc_print_labels;

        });


	</script>
</div>
