<?php

if ( ! defined( 'ABSPATH' ) ) exit;

add_action('admin_init', 'dvs_analytics_download_report');
function dvs_analytics_download_report() {

	$first_date = new DateTime('now');
	$first_date->modify('first day of this month');
	$first_date = $first_date->format('Y-m-d');

	$last_date = new DateTime('now');
	$last_date->modify('last day of this month');
	$last_date = $last_date->format('Y-m-d');

	$pre_hxs_date = $first_date . ' - ' . $last_date;

    $hxs_date = $_POST['hxs_date'] ?? $pre_hxs_date;
    $hxs_courier = $_POST['hxs_courier'] ?? $_GET['hxs_courier'] ?? 'All';
    $hxs_city = $_POST['hxs_city'] ?? 'All';
 
	$created_at_min = substr($hxs_date, 0, 10) . ' 00:00:00';
	$created_at_max = substr($hxs_date, -10) . ' 23:59:59';

    $parameters[] = [
        'key' => 'courier_datetime',
        'value' => "'{$created_at_min}' AND '{$created_at_max}'",
        'operator' => 'BETWEEN',
    ];

	if($hxs_city && $hxs_city != "All") {
		$parameters[] = [
		    'key' => 'courier_destination',
		    'value' => $hxs_city,
		    'operator' => 'LIKE',
		];
	}

	if($hxs_courier && $hxs_courier != "All") {
		$parameters[] = [
		    'key' => 'courier_name',
		    'value' => $hxs_courier,
		    'operator' => 'LIKE',
		];
	}	

    $bookings = new CourierBooking([
        'shop_url' => get_home_url(),
    ]);
    $bookings->paginate_by = 10000000;
    $parcels = $bookings->get($parameters);


	// DOWNLOAD REPORT
	if(isset($_POST['hxs_download_analytics'])) {
		if (count($parcels) > 0) {
			$rows = [];
			$rows[] = [
				'Booked',
				'Shipped',
				'Received',
				'Days',
				'Order Number',
				'Name', 
				'Phone',
				'Email',
				'Address',
				"City",
				"Order Total",
				"Courier COD",
				"Products",
				"Courier Name",
				"Courier Tracking",
				"Courier Status",
			];
			foreach ($parcels as $parcel){

				$dvs_courier_datetime = !empty($parcel->courier_datetime) ? date('d/m/Y', strtotime($parcel->courier_datetime)) : '';
				$dvs_shipped_datetime = !empty($parcel->shipped_datetime) ? date('d/m/Y', strtotime($parcel->shipped_datetime)) : '';
				$dvs_received_datetime = !empty($parcel->received_datetime) ? date('d/m/Y', strtotime($parcel->received_datetime)) : '';		
				$dvs_parcel_days = get_post_meta($parcel->order_id, '_dvs_parcel_days', true);

				$rows[] = [
		        	$dvs_courier_datetime,
		        	$dvs_shipped_datetime,
		        	$dvs_received_datetime,
		            $dvs_parcel_days,
					$parcel->order_name,
					$parcel->consignee_name,
					$parcel->consignee_phone,
					$parcel->consignee_email,
					$parcel->consignee_address,
					$parcel->courier_destination,
					$parcel->order_total,
					$parcel->order_amount,
					$parcel->order_products,
					$parcel->courier_name,
					$parcel->courier_tracking,
					$parcel->courier_status,
				];
			}
			header('Content-Type: text/csv');
			header('Content-Disposition: attachment; filename="ucp-report.csv";');
			header('Pragma: no-cache');
			header("Expires: 0");        
			$f = fopen('php://output', 'w'); 
			foreach ($rows as $line) { 
				fputcsv($f, $line); 
			}
			die();
		}
		else{
			$error = true;
		}
	}

}

function dvs_courier_analytics_page() {

	// calculate percentage function
	function dvs_cal_percentage($num_amount, $num_total) {
		if($num_amount && $num_total) {
			$count1 = $num_amount / $num_total;
			$count2 = $count1 * 100;
			$count = number_format($count2, 0);
			return $count . '%';
		}
	}	
    
    global $couriers;

	$first_date = new DateTime('now');
	$first_date->modify('first day of this month');
	$first_date = $first_date->format('Y-m-d');

	$last_date = new DateTime('now');
	$last_date->modify('last day of this month');
	$last_date = $last_date->format('Y-m-d');

	$pre_hxs_date = $first_date . ' - ' . $last_date;

    $hxs_date = $_POST['hxs_date'] ?? $pre_hxs_date;
    $hxs_courier = $_POST['hxs_courier'] ?? $_GET['hxs_courier'] ?? 'All';
    $hxs_city = $_POST['hxs_city'] ?? 'All';
 
	$created_at_min = substr($hxs_date, 0, 10) . ' 00:00:00';
	$created_at_max = substr($hxs_date, -10) . ' 23:59:59';

    $parameters[] = [
        'key' => 'courier_datetime',
        'value' => "'{$created_at_min}' AND '{$created_at_max}'",
        'operator' => 'BETWEEN',
    ];

	if($hxs_city && $hxs_city != "All") {
		$parameters[] = [
		    'key' => 'courier_destination',
		    'value' => $hxs_city,
		    'operator' => 'LIKE',
		];
	}

	if($hxs_courier && $hxs_courier != "All") {
		$parameters[] = [
		    'key' => 'courier_name',
		    'value' => $hxs_courier,
		    'operator' => 'LIKE',
		];
	}	

    $bookings = new CourierBooking([
        'shop_url' => get_home_url(),
    ]);
    $bookings->paginate_by = 10000000;
    $parcels = $bookings->get($parameters);

	?>

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
    <style>
    	input[type=text] {
    		font-size: 13px;
    	}
        .select2-selection {
            height: 40px !important;
            border-color: #8c8f94 !important;
        }
        .select2-container--default .select2-selection--single {
            border-radius: 0px !important;
        }
        .select2-container .select2-selection--single .select2-selection__rendered {
            line-height: 37px !important;
            font-size: 13px;
        }
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            color: #595c5e !important;
        }
        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 37px !important;
        }
		.select2-results__option {
			font-size: 12px !important;
			padding: 5px 10px !important;
    		margin-bottom: 0px !important;
		}        
        tbody td {
        	color: #333333 !important;
        }
		.td-bold {
			font-weight: bold;
		}           
        .dvs-ucp-table-head td {
        	background-color: #f1f1f1;
        	font-size: 12px;
        }        
		.dvs-ucp-analytics {
			font-size: 13px;
			box-shadow: 0 1px 1px rgba(0,0,0,.04)
		}
		.dvs-ucp-analytics th {
		    padding-left: 15px;
		    background-color: #f1f1f1;
		    font-weight: 500;
		}
		.hxs-stats-city {
			font-size: 14px;
		}
		.hxs-stats-parcel {
			text-align: center;
		}
		.hxs-stats-parcel a {
			color: inherit;
			text-decoration: none;
		}
		.hxs-stats-parcel a:hover {
			text-decoration: underline;
		}
		.hxs-stats-cod {
			text-align: center;
		}
		.hxs-stats-percentage {
			text-align: center;
			font-weight: bold;
		}		
    </style>
</head>

<body>
    <div class="container-fluid mt-4 mb-4">
        <div class="row">
            <div class="col-2">
            </div>
            <div id="hxs-stats-filters" class="col-8">
                <h4 class="text-center pb-2">Courier Analytics</h4>
                <form class="input-group" method="post" action="" id="hxs-stats-form">

                    <input class="form-control" type="text" name="hxs_date" value="<?= $hxs_date ?>" autocomplete="off" placeholder="Date Range">

                    <select id="hxs_courier" name="hxs_courier" class="form-control">
                        <?php
                        	unset($couriers["all"]);
                        	echo '<option value="All">All Couriers</option>';
                            foreach ($couriers as $courier) {
								$selected = ($hxs_courier == $courier) ? 'selected' : '';
								echo '<option ' . $selected . '>' . $courier . '</option>';                                 
                            }
                        ?>
                    </select>

                    <select id="hxs_city" name="hxs_city" class="form-control">
                        <?php
                            include_once('dvs-ucp-cities.php');
                            echo '<option value="All">All Citites</option>';
                            foreach ($cities as $city) {
								$selected = ($hxs_city == $city) ? 'selected' : '';
								echo '<option ' . $selected . '>' . $city . '</option>';                    	
                            }
                            if(empty($selected) && $hxs_city != "All") {
                            	echo '<option selected>' . $hxs_city . '</option>';
                            }
                        ?>
                    </select>

                    <input class="form-control" type="hidden" name="hxs_analytics_search" value="true">
                    <button class="btn btn-success" name="hxs_stats_btn" type="submit">Search</button>
					<?php
					if (count($parcels) > 0) { ?>
						<button class="btn btn-outline-success" id="hxs_download_analytics" name="hxs_download_analytics" type="submit" style="margin-left: 15px;border-radius: 5px;">Download Report</button>
					<?php
					}
					?>                    
                </form>
            </div>       
        </div>    
    </div>    

	<div class="container-fluid">
		<?php
		if(count($parcels) == 0) {
			echo '<div class="row"><div class="col-2"></div><div class="col-8"><div class="alert alert-warning" role="alert">Sorry: No shipment found</div></div></div>';
		}
		else {
			?>
			<div class="row">
				<?php

				$total_couriers = 0;

				$all_total = 0;
				$all_delivered = 0;
				$all_returned = 0;
				$all_shipped = 0;
				$all_cancelled = 0;
				$all_refused = 0;
				$all_active = 0;
				$all_cod_total = 0;
				$all_cod_delivered = 0;
				$all_cod_returned = 0;
				$all_cod_shipped = 0;
				$all_cod_cancelled = 0;
				$all_cod_refused = 0;
				$all_cod_active = 0;

				$all_delivered_trackings = '';
				$all_returned_trackings = '';
				$all_shipped_trackings = '';
				$all_refused_trackings = '';
				$all_cancelled_trackings = '';
				$all_active_trackings = '';

				foreach($couriers as $key => $courier) {

					$total = 0;
					$delivered = 0;
					$returned = 0;
					$shipped = 0;
					$cancelled = 0;
					$refused = 0;
					$active = 0;

					$cod_total = 0;
					$cod_delivered = 0;
					$cod_returned = 0;
					$cod_shipped = 0;
					$cod_cancelled = 0;
					$cod_refused = 0;
					$cod_active = 0;

					$delivered_trackings = '';
					$returned_trackings = '';
					$shipped_trackings = '';
					$refused_trackings = '';
					$cancelled_trackings = '';
					$active_trackings = '';

					$tcs = 0;
				    $lcs = 0;
				    $trax = 0;
				    $mnp = 0;
				    $ccs = 0;
				    $blx = 0;
				    $swyft = 0;
				    $daewoo = 0;
				    $postex = 0;
				    $ccx = 0;
				    $movex = 0;
				    $rider = 0;
					$rocket = 0;
					$rgs = 0;
					$insta = 0;
					$dodeliver = 0;
					$covered = 0;
					$oshi = 0;
					$zaaf = 0;
					$falcomail = 0;
					$noc = 0;
					$csn = 0;
				    $acs = 0;					
			
					foreach($parcels as $parcel) {

						// COURIER WISE
						if(strpos($parcel->courier_name, 'TCS') !== false){
							$tcs++;
						}
						else if(strpos($parcel->courier_name, 'Leopards Courier') !== false){
							$lcs++;
						}
						else if(strpos($parcel->courier_name, 'Trax') !== false){
							$trax++;
						}
						else if(strpos($parcel->courier_name, 'MNP') !== false){
							$mnp++;
						}
						else if(strpos($parcel->courier_name, 'Call Courier') !== false){
							$ccs++;
						}
						else if(strpos($parcel->courier_name, 'BlueEx') !== false){
							$blx++;
						}
						else if(strpos($parcel->courier_name, 'Daewoo Courier') !== false){
							$daewoo++;
						}
						else if(strpos($parcel->courier_name, 'PostEx') !== false){
							$postex++;
						}
						else if(strpos($parcel->courier_name, 'Insta World') !== false){
							$insta++;
						}
						else if(strpos($parcel->courier_name, 'Do Deliver') !== false){
							$dodeliver++;
						}												
						else if(strpos($parcel->courier_name, 'Rider') !== false){
							$rider++;
						}
						else if(strpos($parcel->courier_name, 'Falcomail') !== false){
							$falcomail++;
						}							
						else if(strpos($parcel->courier_name, 'Ship NOC') !== false){
							$noc++;
						}											
						else if(strpos($parcel->courier_name, 'Oshi Courier') !== false){
							$oshi++;
						}	
						else if(strpos($parcel->courier_name, 'Zaaf Courier') !== false){
							$zaaf++;
						}												
						else if(strpos($parcel->courier_name, 'Rocket Courier') !== false){
							$rocket++;
						}
						else if(strpos($parcel->courier_name, 'Couriers Next') !== false){
							$csn++;
						}
						else if(strpos($parcel->courier_name, 'RGS Logistics') !== false){
							$rgs++;
						}							
						else if(strpos($parcel->courier_name, 'Covered Logistics') !== false){
							$covered++;
						}																					
						else if(strpos($parcel->courier_name, 'Active Courier') !== false){
							$acs++;
						}
						else {

						}

						if($parcel->courier_name !== $courier)
							continue;

						// STATUS WISE
						if(strpos($parcel->courier_status, 'delivered') !== false){
							$delivered++;
							$cod_delivered += $parcel->order_total;
							// $delivered_trackings .= $parcel->courier_tracking . ',';
						}
						else if(strpos($parcel->courier_status, 'returned') !== false){
							$returned++;
							$cod_returned += $parcel->order_total;
							$returned_trackings .= $parcel->courier_tracking . ',';
						}
						else if(strpos($parcel->courier_status, 'shipped') !== false){
							$shipped++;
							$cod_shipped += $parcel->order_total;
							$shipped_trackings .= $parcel->courier_tracking . ',';
						}
						else if(strpos($parcel->courier_status, 'refused') !== false){
							$refused++;
							$cod_refused += $parcel->order_total;
							$refused_trackings .= $parcel->courier_tracking . ',';
						}					
						else if(strpos($parcel->courier_status, 'cancel') !== false){
							$cancelled++;
							$cod_cancelled += $parcel->order_total;
							$cancelled_trackings .= $parcel->courier_tracking . ',';
						}
						else if(strpos($parcel->courier_status, 'active') !== false){
							$active++;
							$cod_active += $parcel->order_total;
							$active_trackings .= $parcel->courier_tracking . ',';
						}
						else {

						}

						$total++;
						$cod_total += $parcel->order_total;
					}
					
					$updated_total = $total - $cancelled - $active;
					
					if($total > 0) {
						$total_couriers++;
						?>
			    		<div class="col-3 mb-2">
							<table class="table table-sm table-bordered table-hover dvs-ucp-analytics">
								<thead class="dvs-ucp-table-head text-center">
									<td class="td-bold"><center><img src="<?php echo plugin_dir_url( __DIR__ ) . "images/{$key}-label-logo.png"; ?>" alt="Universal Courier" height="20"></center></td>
									<td>Parcel</td>
									<td>Amount</td>
									<td>Result</td>
								</thead>
								<tbody>
									<tr>
										<th scope="col">Total</th>
										<td class="hxs-stats-parcel"><?= $total ?></td>
										<td class="hxs-stats-cod"><?= (int)$cod_total ?></td>
										<td></td>										
									</tr>
									<tr>
										<th scope="col">Delivered</th>
										<td class="hxs-stats-parcel"><a href="#" class="tracking-link" data-tracking="<?= $delivered_trackings ?>" data-status="delivered" data-courier="<?= $key ?>"><?= $delivered ?></a></td>
										<td class="hxs-stats-cod"><?= (int)$cod_delivered ?></td>
										<td class="hxs-stats-percentage"><?= dvs_cal_percentage($delivered, $updated_total) ?></td>
									</tr>
									<tr>
										<th scope="col">Returned</th>
										<td class="hxs-stats-parcel"><a href="#" class="tracking-link" data-tracking="<?= $returned_trackings ?>" data-status="returned" data-courier="<?= $key ?>"><?= $returned ?></a></td>
										<td class="hxs-stats-cod"><?= (int)$cod_returned ?></td>										
										<td class="hxs-stats-percentage"><?= dvs_cal_percentage($returned, $updated_total) ?></td>
									</tr>
									<tr>
										<th scope="col">Shipped</th>
										<td class="hxs-stats-parcel"><a href="#" class="tracking-link" data-tracking="<?= $shipped_trackings ?>" data-status="shipped" data-courier="<?= $key ?>"><?= $shipped ?></a></td>
										<td class="hxs-stats-cod"><?= (int)$cod_shipped ?></td>
										<td class="hxs-stats-percentage"><?= dvs_cal_percentage($shipped, $updated_total) ?></td>
									</tr>
									<tr>
										<th scope="col">Refused</th>
										<td class="hxs-stats-parcel"><a href="#" class="tracking-link" data-tracking="<?= $refused_trackings ?>" data-status="refused" data-courier="<?= $key ?>"><?= $refused ?></a></td>
										<td class="hxs-stats-cod"><?= (int)$cod_refused ?></td>
										<td class="hxs-stats-percentage"><?= dvs_cal_percentage($refused, $updated_total) ?></td>
									</tr>									
									<tr>	
										<th scope="col">Cancelled</th>
										<td class="hxs-stats-parcel"><a href="#" class="tracking-link" data-tracking="<?= $cancelled_trackings ?>" data-status="cancelled" data-courier="<?= $key ?>"><?= $cancelled ?></a></td>
										<td class="hxs-stats-cod"><?= (int)$cod_cancelled ?></td>
										<td></td>										
									</tr>
									<tr>
										<th scope="col">Booked</th>
										<td class="hxs-stats-parcel"><a href="#" class="tracking-link" data-tracking="<?= $active_trackings ?>" data-status="active" data-courier="<?= $key ?>"><?= $active ?></a></td>
										<td class="hxs-stats-cod"><?= (int)$cod_active ?></td>
										<td></td>										
									</tr>
								</tbody>
							</table>
			    		</div>
					<?php		
					}

					$all_total += $total;
					$all_delivered += $delivered;
					$all_returned += $returned;
					$all_shipped += $shipped;
					$all_cancelled += $cancelled;
					$all_refused  += $refused;
					$all_active += $active;
					$all_cod_total += $cod_total;
					$all_cod_delivered += $cod_delivered;
					$all_cod_returned += $cod_returned;
					$all_cod_shipped += $cod_shipped;
					$all_cod_cancelled += $cod_cancelled;
					$all_cod_refused += $cod_refused;
					$all_cod_active += $cod_active;

					$all_delivered_trackings .= $delivered_trackings;
					$all_returned_trackings .= $returned_trackings;
					$all_shipped_trackings .= $shipped_trackings;
					$all_refused_trackings .= $refused_trackings;
					$all_cancelled_trackings .= $cancelled_trackings;
					$all_active_trackings .= $active_trackings;

				}
				$all_updated_total = $all_total - $all_cancelled - $all_active;
			    $chart_data = array($all_total,$all_delivered,$all_returned,$all_shipped,$all_refused,$all_cancelled,$all_active);
			    $chart_data = implode(', ', $chart_data);				
				?>
			</div>

			<?php
			if($all_total > 0 && $total_couriers > 1) {
			?>	<h5 class="text-center mb-4">Search Summary</h5>
				<div class="row justify-content-center">
		    		<div class="col-5">
						<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
						<canvas id="myChart" width="400" height="225"></canvas>
						<script>
						const ctx = document.getElementById('myChart').getContext('2d');
						const myChart = new Chart(ctx, {
						    type: 'bar',
						    data: {
						        labels: ['Total', 'Delivered', 'Returned', 'Shipped', 'Refused', 'Cancelled', 'Booked'],
						        datasets: [{
						            label: 'All Courier',
						            data: [<?php echo $chart_data ?>],
						            backgroundColor: [
						                '#8395a7',
						                '#10ac84',
						                '#ee5253',
						               	'#54a0ff',
						                '#ff9f43',
						                '#686de0',
						                '#feca57'
						            ],
						        }]
						    },
						    options: {
						        scales: {
						            y: {
						                beginAtZero: true
						            }
						        }
						    }
						});
						</script>
		    		</div>
		    		<div class="col-3">
						<table class="table table-sm table-bordered table-hover dvs-ucp-analytics">
							<thead class="dvs-ucp-table-head text-center">
								<td class="td-bold">All Couriers</td>
								<td>Parcel</td>
								<td>Amount</td>
								<td>Result</td>
							</thead>
							<tbody>
								<tr>
									<th scope="col">Total</th>
									<td class="hxs-stats-parcel"><?= $all_total ?></td>
									<td class="hxs-stats-cod"><?= (int)$all_cod_total ?></td>
									<td></td>										
								</tr>
								<tr>
									<th scope="col">Delivered</th>
									<td class="hxs-stats-parcel"><a href="#" class="tracking-link" data-tracking="<?= $all_delivered_trackings ?>" data-status="delivered" data-courier="all"><?= $all_delivered ?></a></td>
									<td class="hxs-stats-cod"><?= (int)$all_cod_delivered ?></td>										
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($all_delivered, $all_updated_total) ?></td>
								</tr>
								<tr>
									<th scope="col">Returned</th>
									<td class="hxs-stats-parcel"><a href="#" class="tracking-link" data-tracking="<?= $all_returned_trackings ?>" data-status="returned" data-courier="all"><?= $all_returned ?></a></td>
									<td class="hxs-stats-cod"><?= (int)$all_cod_returned ?></td>										
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($all_returned, $all_updated_total) ?></td>
								</tr>
								<tr>
									<th scope="col">Shipped</th>
									<td class="hxs-stats-parcel"><a href="#" class="tracking-link" data-tracking="<?= $all_shipped_trackings ?>" data-status="shipped" data-courier="all"><?= $all_shipped ?></a></td>
									<td class="hxs-stats-cod"><?= (int)$all_cod_shipped ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($all_shipped, $all_updated_total) ?></td>
								</tr>
								<tr>	
									<th scope="col">Refused</th>
									<td class="hxs-stats-parcel"><a href="#" class="tracking-link" data-tracking="<?= $all_refused_trackings ?>" data-status="refused" data-courier="all"><?= $all_refused ?></a></td>
									<td class="hxs-stats-cod"><?= (int)$all_cod_refused ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($all_refused, $all_updated_total) ?></td>
								</tr>									
								<tr>	
									<th scope="col">Cancelled</th>
									<td class="hxs-stats-parcel"><a href="#" class="tracking-link" data-tracking="<?= $all_cancelled_trackings ?>" data-status="cancelled" data-courier="all"><?= $all_cancelled ?></a></td>
									<td class="hxs-stats-cod"><?= (int)$all_cod_cancelled ?></td>
									<td></td>										
								</tr>
								<tr>	
									<th scope="col">Booked</th>
									<td class="hxs-stats-parcel"><a href="#" class="tracking-link" data-tracking="<?= $all_active_trackings ?>" data-status="active" data-courier="all"><?= $all_active ?></a></td>
									<td class="hxs-stats-cod"><?= (int)$all_cod_active ?></td>
									<td></td>										
								</tr>
							</tbody>
						</table>
		    		</div>
		    		<div class="col-3">
						<table class="table table-sm table-bordered dvs-ucp-analytics table-hover text-center">
							<thead class="dvs-ucp-table-head">
								<td class="td-bold">Couriers</td>
								<td>Parcel</td>
								<td>Result</td>
							</thead>
							<tbody>
								<?php if($tcs > 0) { ?>
									<tr>
										<th scope="col" class="text-start">TCS</th>
										<td><?= $tcs ?></td>
										<td class="hxs-stats-percentage"><?= dvs_cal_percentage($tcs, $all_total) ?></td>
									</tr>
								<?php }
								if($lcs > 0) { ?>
								<tr>
									<th scope="col" class="text-start">Leopards Courier</th>
									<td><?= $lcs ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($lcs, $all_total)?></td>
								</tr>
								<?php }
								if($trax > 0) { ?>								
								<tr>
									<th scope="col" class="text-start">Trax</th>
									<td><?= $trax ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($trax, $all_total) ?></td>
								</tr>
								<?php }
								if($mnp > 0) { ?>								
								<tr>
									<th scope="col" class="text-start">MNP</th>
									<td><?= $mnp ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($mnp, $all_total) ?></td>
								</tr>
								<?php }
								if($ccs > 0) { ?>								
								<tr>
									<th scope="col" class="text-start">Call Courier</th>
									<td><?= $ccs ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($ccs, $all_total) ?></td>
								</tr>
								<?php }
								if($blx > 0) { ?>								
								<tr>
									<th scope="col" class="text-start">BlueEx</th>
									<td><?= $blx ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($blx, $all_total) ?></td>
								</tr>
								<?php }
								if($oshi > 0) { ?>														
								<tr>
									<th scope="col" class="text-start">Oshi Courier</th>
									<td><?= $oshi ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($oshi, $all_total) ?></td>
								</tr>
								<?php }
								if($zaaf > 0) { ?>														
								<tr>
									<th scope="col" class="text-start">Zaaf Courier</th>
									<td><?= $zaaf ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($zaaf, $all_total) ?></td>
								</tr>																
								<?php }
								if($postex > 0) { ?>								
								<tr>
									<th scope="col" class="text-start">PostEx</th>
									<td><?= $postex ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($postex, $all_total) ?></td>
								</tr>
								<?php }
								if($insta > 0) { ?>								
								<tr>
									<th scope="col" class="text-start">Insta World</th>
									<td><?= $insta ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($insta, $all_total) ?></td>
								</tr>
								<?php }
								if($dodeliver > 0) { ?>								
								<tr>
									<th scope="col" class="text-start">Do Deliver</th>
									<td><?= $dodeliver ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($dodeliver, $all_total) ?></td>
								</tr>								
								<?php }								
								if($rider > 0) { ?>								
								<tr>
									<th scope="col" class="text-start">Rider</th>
									<td><?= $rider ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($rider, $all_total) ?></td>
								</tr>
								<?php }
								if($daewoo > 0) { ?>																		
								<tr>
									<th scope="col" class="text-start">Daewoo</th>
									<td><?= $daewoo ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($daewoo, $all_total) ?></td>
								</tr>
								<?php }
								if($rocket > 0) { ?>								
								<tr>
									<th scope="col" class="text-start">Rocket Courier</th>
									<td><?= $rocket ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($rocket, $all_total) ?></td>
								</tr>
								<?php }
								if($falcomail > 0) { ?>								
								<tr>
									<th scope="col" class="text-start">Falcomail</th>
									<td><?= $falcomail ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($falcomail, $all_total) ?></td>
								</tr>
								<?php }									
								if($noc > 0) { ?>								
								<tr>
									<th scope="col" class="text-start">Ship NOC</th>
									<td><?= $noc ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($noc, $all_total) ?></td>
								</tr>
								<?php }								
								if($rgs > 0) { ?>								
								<tr>
									<th scope="col" class="text-start">RGS Logistics</th>
									<td><?= $rgs ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($rgs, $all_total) ?></td>
								</tr>
								<?php }

								if($covered > 0) { ?>								
								<tr>
									<th scope="col" class="text-start">Covered Logistics</th>
									<td><?= $covered ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($covered, $all_total) ?></td>
								</tr>
								<?php }
								if($csn > 0) { ?>								
								<tr>
									<th scope="col" class="text-start">Couriers Next</th>
									<td><?= $csn ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($csn, $all_total) ?></td>
								</tr>															
								<?php }
								if($acs > 0) { ?>								
								<tr>
									<th scope="col" class="text-start">Active Courier</th>
									<td><?= $acs ?></td>
									<td class="hxs-stats-percentage"><?= dvs_cal_percentage($acs, $all_total) ?></td>
								</tr>
								<?php } ?>																		
							</tbody>				
						</table>	
		    		</div>
		    	</div>				
			<?php
			}
		}
		?>
	</div>

	<script type="text/javascript">
	    $(function() {
	        // Define your custom date ranges
	        var customRanges = {
	            'Today': [moment(), moment()],
	            'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
	            'This Month': [moment().startOf('month'), moment().endOf('month')],
	            'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
	            'This Year': [moment().startOf('year'), moment().endOf('year')],
	            'Last Year': [moment().subtract(1, 'year').startOf('year'), moment().subtract(1, 'year').endOf('year')]
	        };

	        $('input[name="hxs_date"]').daterangepicker({
	            autoUpdateInput: <?php echo empty($hxs_date) ? 'false' : 'true' ?>,
	            alwaysShowCalendars: true, // Keep the calendars visible
	            locale: {
	                cancelLabel: 'Clear',
	                format: "YYYY-MM-DD",
	            },
	            ranges: customRanges,
				dateLimit: {
                	months: 12 // Limit the date selection to a maximum of 12 months
            	}	            	            
	        });

	        $('input[name="hxs_date"]').on('apply.daterangepicker', function(ev, picker) {
	            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
	        });

	        $('input[name="hxs_date"]').on('cancel.daterangepicker', function(ev, picker) {
	            $(this).val('');
	        });
	    });
	</script>


    <script type="text/javascript">
        $(document).ready(function() {
            $('#hxs_courier').select2({
            });
        });
    </script>

    <script type="text/javascript">
        $(document).ready(function() {
            $('#hxs_city').select2({
                tags: true
            });
        });
    </script> 

	<script>
	  // Function to handle link click
	  function handleLinkClick(event) {
	    // Prevent the default link behavior
	    event.preventDefault();

	    // Get the tracking numbers from the data attribute
	    var trackingNumbers = $(this).data('tracking').split(',');

	    // Get the tracking status from the data attribute
	    var trackingStatus = $(this).data('status');

		// Get the tracking status from the data attribute
	    var trackingCourier = $(this).data('courier');        

	    // Check if trackingNumbers has a valid value
	    if (trackingNumbers !== undefined && trackingNumbers !== null && trackingNumbers.toString().trim() !== '') {

		    // Remove the last character from the entire string
		    trackingNumbers = trackingNumbers.slice(0, -1);

		    // Create a form dynamically
		    var form = $('<form>', {
				'action': '<?= get_admin_url(null, 'admin.php?page=dvs_ucp_') ?>' + trackingCourier + '_logs&hxs_status=' + trackingStatus,
				'method': 'POST',
				'target': '_blank' // Open in a new tab
		    });

		    // Add an input field for each tracking number
		    trackingNumbers.forEach(function(trackingNumber) {
		      $('<input>', {
		        'type': 'hidden',
		        'name': 'tracking_numbers[]',
		        'value': trackingNumber.trim()
		      }).appendTo(form);
		    });

		    // Append the form to the body and submit it
		    form.appendTo('body').submit();
		}
	  }

	  // Attach the click event handler to all elements with the class 'tracking-link'
	  $('.tracking-link').on('click', handleLinkClick);
	</script>

</body>

<br>
<a href="https://www.youtube.com/watch?v=UP_3CZmyl4k&t=907s" target="blank" class="woocommerce-Button button">Video: How to use Courier Analytics</a>
<br>
<br>
<a href="https://wa.me/9203038518000" target="blank" class="woocommerce-Button button">Get Support</a>
<br>

<?php
}