<?php

global $wpdb;
global $globKurier;

$globKurier->isUserLoggedIn(true);

if (isset($_GET[ 'getPdfLabels' ])) {
	ob_clean();
	
	$pdf = $globKurier->documents()->getOrderLabelPdf($_GET[ 'hashes' ] ?? []);
	
	if(strpos($pdf, '%PDF') === false){
		echo $pdf;
		die;
	}
	
	header('Content-type: application/pdf');
	header('Content-Disposition: inline; filename="label.pdf"');
	header('Content-Transfer-Encoding: binary');
	header('Accept-Ranges: bytes');
	
	die($pdf);
}

if (isset($_GET[ 'getPdfProtocols' ])) {
	$pdf = $globKurier->documents()->getOrderProtocolPdf($_GET[ 'hashes' ] ?? []);
	
	if(strpos($pdf, '%PDF') === false){
		echo $pdf;
		die;
	}
	
	ob_clean();
	header('Content-type: application/pdf');
	header('Content-Disposition: inline; filename="protocol.pdf"');
	header('Content-Transfer-Encoding: binary');
	header('Accept-Ranges: bytes');
	
	die($pdf);
}

$mataName = apply_filters('globkurier_wc_order_meta_name', 'globkurier_orders');

$s_orders = $wpdb->get_results("SELECT `meta_value`, `post_id` FROM `{$wpdb->postmeta}` WHERE meta_key = '{$mataName}'", ARRAY_A);

$orders = [];
foreach ($s_orders as $order) {
	$data = maybe_unserialize(maybe_unserialize($order[ 'meta_value' ]));
	
	$data[ 'wcOrderId' ] = $order[ 'post_id' ];
	
	$orders[] = $data;
}

usort($orders, function ($item1, $item2){
	return $item2[ 'date' ] <=> $item1[ 'date' ];
});

?>

<h1><?php
	echo __('Lista zamówień GlobKurier', 'globkurier') ?></h1>

<div class="globkurier-old-orders-table-wrapper">
	<table class="globkurier-old-orders-table stripe udi-is-ajax-datatable">
		<thead>
		<tr>
			<th></th>
			<th style="min-width: 150px"><?php
				echo __('Nr zamówienia GK', 'globkurier') ?></th>
			<th style="min-width: 100px"><?php
				echo __('Data nadania', 'globkurier') ?></th>
			<th style="min-width: 100px"><?php
				echo __('Odbiorca', 'globkurier') ?></th>
			<th style="min-width: 100px"><?php
				echo __('Zawartość', 'globkurier') ?></th>
			<th style="min-width: 100px"><?php
				echo __('Waga [kg]', 'globkurier') ?></th>
			<th style="min-width: 150px"><?php
				echo __('Przewoźnik', 'globkurier') ?></th>
			<th style="min-width: 100px"><?php
				echo __('Pobranie [zł]', 'globkurier') ?></th>
			<th style="min-width: 150px"><?php
				echo __('Płatność', 'globkurier') ?></th>
			<th style="min-width: 100px"><?php
				echo __('Cena [zł]', 'globkurier') ?></th>
			<th style="min-width: 100px"><?php
				echo __('Status', 'globkurier') ?></th>
			<th style="min-width: 100px"><?php
				echo __('Nr Zamówienia <br> Woocommerce', 'globkurier') ?></th>
			<th style="min-width: 50px"><?php
				echo __('Opcja', 'globkurier') ?></th>
		</tr>
		</thead>
		<tbody></tbody>
		<tfoot>
		<tr>
			<td colspan="13">

				<input id="udi-check-all" type="checkbox">
				<label for="udi-check-all"><?php
					echo __('Zaznacz wszystkie', 'globkurier') ?></label>
				<br>
				<div class="glogburier-orders-bulk-actions-container">

					<p class="glogburier-orders-bulk-actions-header"><?php
						echo __('Masowe działania dla', 'globkurier') ?>
						<span id="bulk-actions-counter">0</span> <?php
						echo __('zaznaczonych pozycji', 'globkurier') ?>
					</p>

					<div class="globkurier-orders-bulk-actions">
						<select id="bulk-print-format">
							<option value="A4"><?php
								echo __('Generuj list zbiorczy (format A4)', 'globkurier') ?></option>
							<option value="ZEBRA_PRINTER"><?php
								echo __('Generuj list zbiorczy (format ZEBRA)', 'globkurier') ?></option>
						</select>

						<button type="button" class="button globkurier-bulk-action"><?php
							echo __('Wykonaj', 'globkurier') ?></button>
					</div>

				</div>

			</td>
		</tr>
		</tfoot>
	</table>
</div>

<script>
	
	( function ( $ ) {
		$( function () {
			
			function checkItem( data, type, full ) {
				let isActive = full.hasLabel || false;
				let hash = full.hash;
				if ( isActive ) {
					return '<input type="checkbox" class="globkurier-order-bulk-check" value="' + hash + '" title="<?php echo __('Zaznacz', 'globkurier') ?>">';
				} else {
					return '';
				}
			}
			
			function getStatus( data, type, full ) {
				let orderNumer = full.number;
				let html = '';
				
				html += '<div style=" display: flex; flex-direction: column; max-width: 100px; text-align: center;">';
				html += '<div class="udi-loader"></div>\n<span class="udi-status-value"></span><button type="button" data-number="' + orderNumer + '" title="<?php echo __('Pobierz status zamówienia',
					'globkurier') ?>" class="udi-get-current-status"><?php echo __('Pobierz', 'globkurier') ?></button>';
				html += '</div>';
				
				return html;
				
			}
			
			function getOrderLink( data, type, full ) {
				let orderLink = full.wc_order_link;
				let wcOrderId = full.wc_order_id;
				
				if ( orderLink ) {
					return '<a style="text-decoration: none" href="' + orderLink + '" target="_blank">#' + wcOrderId + '</a>'
				}
				
				return '-';
			}
			
			function actionLinks( data, type, full ) {
				let hasLabel = full.hasLabel || false;
				
				let orderLabelUrl = full.order_label_url || '#';
				let orderTrackUrl = full.order_track_url || '#';
				
				let getLabelStyle = 'text-decoration: none;';
				let getLabelIconStyle = '';
				let getLabelIconTitle = '<?php echo __('Pobierz list przewozowy', 'globkurier') ?>';
				
				let getTrackStyle = 'text-decoration: none;';
				
				if ( !hasLabel ) {
					getLabelIconStyle += 'opacity: .2;';
					getLabelStyle += 'pointer-events: none; cursor: default;';
					getLabelIconTitle = '<?php echo __('List przewozowy jest niedostępny', 'globkurier') ?>';
					orderLabelUrl = '#';
				}
				let html = '<td>';
				html += '<div style="display: flex">';
				
				html += '<div title="' + getLabelIconTitle + '"><a style="' + getLabelStyle + '" href="' + orderLabelUrl + '" target="_blank" >\n\t\t<span class="dashicons dashicons-media-document" style="' + getLabelIconStyle + '"></span>\n\t</a></div>'
				html += '<div title="<?php echo __('Śledź przesyłkę',
					'globkurier') ?>"><a style="' + getTrackStyle + '" href="' + orderTrackUrl + '" target="_blank" >\n\t\t<span class="dashicons dashicons-search"></span>\n\t</a></div>'
				
				html += '</div>';
				html += '</td>';
				
				return html;
			}
			
			$( '.udi-is-ajax-datatable' )
				.DataTable( {
					'language': {
						'url': '//cdn.datatables.net/plug-ins/1.10.20/i18n/Polish.json'
					},
					'stateSave': true,
					'processing': true,
					'serverSide': true,
					'ajax': ajaxurl + "?action=globkurierGetOrders",
					
					'bSort': false,
					
					'columns': [
						{ "render": checkItem },
						{ 'data': "number" },
						{ 'data': "date" },
						{ 'data': "receiver_address_name" },
						{ 'data': "content" },
						{ 'data': "shipment_weight" },
						{ 'data': "carrier_name" },
						{ 'data': "cod_value" },
						{ 'data': "payment_name" },
						{ 'data': "price_net" },
						{ 'render': getStatus },
						{ 'render': getOrderLink },
						{ 'render': actionLinks },
					],
					
				} )
				.on( 'page.dt', function () {
					$( '.globkurier-order-bulk-check' ).prop( 'checked', false ).change();
				} );
			
			$( '#udi-check-all' ).change( function () {
				if ( $( this ).is( ':checked' ) ) {
					$( '.globkurier-order-bulk-check' ).prop( 'checked', true ).change();
				}
			} );
			
			$( document ).on( 'change', '.globkurier-order-bulk-check', function () {
				let counter = $( '.globkurier-order-bulk-check:checked' ).length;
				$( '#bulk-actions-counter' ).html( counter );
			} );
			
			$( '.globkurier-bulk-action' ).click( function () {
				let counter = $( '.globkurier-order-bulk-check:checked' ).length;
				
				if ( counter == 0 ) {
					return;
				}
				let button = $( this );
				button.attr( 'disabled', true );
				
				let orderHashes = $( '.globkurier-order-bulk-check:checked' ).map( function ( idx, elem ) {
					return $( this ).val();
				} ).get();
				
				let format = $( '#bulk-print-format' ).val();
				
				window.open( '?page=globkurier_all_orders&getPdfLabels&hashes=' + orderHashes, '_blank' );
				return;
				
				let ajaxData = {
					action: 'globkurierGetLabels',
					data: {
						orderHashes: orderHashes,
						format: format
					}
				};
				
				let loader = $( this ).parent().find( '.udi-loader' );
				
				loader.show();
				
				let statusText = $( this ).parent().find( '.udi-status-value' );
				statusText.text( '' );
				
				$.post( data[ 'ajaxUrl' ], ajaxData, function ( response ) {
					
					let url = $.parseJSON( response );
					window.open( url, '_blank' );
					
					button.attr( 'disabled', false );
					
				} );
				
			} );
			
			
		} );
	} )( jQuery );

</script>
