<?php

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

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

	if (isset($_GET['dvs_trackings'])) {
	    $trackings_db = $_GET['dvs_trackings'] ?? null;

	    $bookings = new CourierBooking([
	        'shop_url' =>get_home_url(),
	    ]);
		$bookings->paginate_by = (int)get_option('dvs_ucp_courier_pagination');

	    $parcels = [];

        $trackings_db = explode(',', $trackings_db);

		function add_quotes($x)
		{
		  return "'{$x}'";
		}

		$trackings_db = array_map("add_quotes", $trackings_db);
	    
	    if ($trackings_db){
	        $parameters[] = [
	            'key' => 'courier_tracking',
	            'value' => '(' . join(',', $trackings_db) . ')',
	            'operator' => 'IN',
	        ];
	        $parcels = $bookings->get($parameters);
	    }

        if($parcels){
            $key = get_courier_key($parcels[0]->courier_name);
    	    $courier_logo = plugin_dir_url( __DIR__ ) . "images/{$key}-label-logo.png";
        }

        $dvs_label_size = get_option('dvs_label_shipper_size');

		if($dvs_label_size == '2') {
	    	include_once('dvs-label-template-2.php');
		}		
		else if($dvs_label_size == '3') {
	    	include_once('dvs-label-template-3.php');
		}
		else if($dvs_label_size == '4') {
	    	include_once('dvs-label-template-4.php');
		}
		else if($dvs_label_size == '5') {
	    	include_once('dvs-label-template-5.php');
		}										
		else {
			include_once('dvs-label-template-1.php');
		}
	    die();
	}

}

add_action('admin_init', 'dvs_print_label');
function dvs_print_label() {
	if (isset($_POST['hxs_print_btn'])) {
	    $orders = $_POST['order'] ?? null;
	    $trackings = [];
	    $trackings_db = [];
	    foreach ($orders as $order) {
	        if (isset($order['check'])) {
	            $trackings[] = $order['tracking'];
	            $trackings_db[] = "'{$order['id']}'";
	        }
	    }
	    $bookings = new CourierBooking([
	        'shop_url' =>get_home_url(),
	    ]);
		$bookings->paginate_by = (int)get_option('dvs_ucp_courier_pagination');

	    $parcels = [];
	    
	    if (count($trackings_db) > 0){
	        $parameters[] = [
	            'key' => 'id',
	            'value' => '(' . implode(',', $trackings_db) . ')',
	            'operator' => 'IN',
	        ];
	        $parcels = $bookings->get($parameters);
	    }

        // if($parcels){
        //     $key = get_courier_key($parcels[0]->courier_name);
    	   //  $courier_logo = plugin_dir_url( __DIR__ ) . "images/{$key}-label-logo.png";
        // }

        $dvs_label_size = get_option('dvs_label_shipper_size');

		if($dvs_label_size == '2') {
	    	include_once('dvs-label-template-2.php');
		}
		else if($dvs_label_size == '3') {
	    	include_once('dvs-label-template-3.php');
		}
		else if($dvs_label_size == '4') {
	    	include_once('dvs-label-template-4.php');
		}
		else if($dvs_label_size == '5') {
	    	include_once('dvs-label-template-5.php');
		}										
		else {
			include_once('dvs-label-template-1.php');
		}
	    die();
	}
}



// SALES REPORT
add_action('admin_init', 'dvs_export_shipments');
function dvs_export_shipments() {
    if (!isset($_POST['dvs_export_btn'])) {
        return;
    }
    $orders = $_POST['order'] ?? null;
    $trackings = [];
    $trackings_db = [];
    foreach ($orders as $order) {
        if (isset($order['check'])) {
            $trackings[] = $order['tracking'];
            $trackings_db[] = "'{$order['id']}'";
        }
    }
    $bookings = new CourierBooking([
        'shop_url' =>get_home_url(),
    ]);
	$bookings->paginate_by = (int)get_option('dvs_ucp_courier_pagination');
    $parcels = [];
    if (count($trackings_db) == 0){
        return;
    }
    $parameters[] = [
        'key' => 'id',
        'value' => '(' . implode(',', $trackings_db) . ')',
        'operator' => 'IN',
    ];
    $parcels = $bookings->get($parameters);
	$rows = [];
    $rows[] = [
  		'Booked',
        'Order',
        'Name', 
        'Phone',
        'Address',
        'City',
        'Total',
        'Products',
        'Courier Name',
        'Courier Tracking',
        'Courier Status',
        'Courier COD',
        'Received COD',
        'Shipping Fee',
        'Payment Status',
        'Weight',
        'Invoice',
        'Finance History',
    ];
    foreach ($parcels as $parcel) {
    	$courier_finance = $parcel->courier_finance;
		$courier_finance = json_decode($courier_finance, true);
		$payment_status 	= '';
		$received_cod 		= '';
		$shipping_fee 		= '';
		$shipping_weight 	= '';
		$courier_invoice	= '';
		$finance_history	= '';
		if( current_user_can( 'administrator' ) ){
			if($courier_finance) {
				foreach($courier_finance as $finance) {
					$payment_status		.= $finance['payment'] . "\n";
					$received_cod		.= $finance['cod'] . "\n";
					$shipping_fee		.= $finance['fee'] . "\n";
					$shipping_weight	.= $finance['weight'] . "\n";
					$courier_invoice	.= $finance['invoice'] . "\n";
					$finance_history 	.= $finance['courier'] .' | '. $finance['tracking'] .' | '. $finance['status'] .' | Payment: '. $finance['payment'] .' | COD: '. $finance['cod'] .' | Fee: '. $finance['fee'] . ' | Weight: ' .$finance['weight'] . ' | Invoice: ' . $finance['invoice'] . "\n";
				}
				$payment_status 	= substr($payment_status, 0, -1);
				$received_cod 		= substr($received_cod, 0, -1);
				$shipping_fee		= substr($shipping_fee, 0, -1);
				$shipping_weight	= substr($shipping_weight, 0, -1);
				$courier_invoice	= substr($courier_invoice, 0, -1);
				$finance_history	= substr($finance_history, 0, -1);
			}
			else {
				$payment_status 	= '';
				$received_cod 		= '';
				$shipping_fee		= '';
				$shipping_weight	= '';
				$courier_invoice	= '';
				$finance_history	= '';
			}
		}
        $rows[] = [
            substr($parcel->courier_datetime, 0, 10),
            $parcel->order_name,
            $parcel->consignee_name,
            $parcel->consignee_phone,
            $parcel->consignee_address,
            $parcel->courier_destination,
            (int)$parcel->order_total,
            $parcel->order_products,
            $parcel->courier_name,
            $parcel->courier_tracking,
            $parcel->courier_delivery,
            (int)$parcel->order_amount,
            $received_cod,
            $shipping_fee,
            $payment_status,
            $shipping_weight,
            $courier_invoice,            
            $finance_history,
        ];
    }
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="ucp_sales_report.csv";');
    header('Pragma: no-cache');
    header("Expires: 0");        
    $f = fopen('php://output', 'w'); 
    foreach ($rows as $line) { 
        fputcsv($f, $line); 
    }
    die();
}



// SALES REPORT
add_action('admin_init', 'dvs_export_all_btn');
function dvs_export_all_btn() {
    if (!isset($_POST['dvs_export_all_btn'])) {
        return;
    }
    $orders = $_POST['order'] ?? null;
    $trackings = [];
    $trackings_db = [];
    foreach ($orders as $order) {
        $trackings[] = $order['tracking'];
        $trackings_db[] = "'{$order['id']}'";
    }
    $bookings = new CourierBooking([
        'shop_url' =>get_home_url(),
    ]);
	$bookings->paginate_by = 100000000;
    $parcels = [];
    if (count($trackings_db) == 0){
        return;
    }
    $parameters[] = [
        'key' => 'id',
        'value' => '(' . implode(',', $trackings_db) . ')',
        'operator' => 'IN',
    ];
    $parcels = $bookings->get($parameters);
	$rows = [];
    $rows[] = [
  		'Booked',
  		'Shipped',
  		'Received',
  		'Days',
        'Order',
        'Name', 
        'Phone',
        'Address',
        'City',
        'Total',
        'Products',
        'Courier Name',
        'Courier Tracking',
        'Courier Status',
        'Courier COD',
        'Received COD',
        'Shipping Fee',
        'Payment Status',
        'Weight',
        'Invoice',
        'Finance History',
    ];
    foreach ($parcels as $parcel) {
    	$courier_finance = $parcel->courier_finance;
		$courier_finance = json_decode($courier_finance, true);
		$payment_status 	= '';
		$received_cod 		= '';
		$shipping_fee 		= '';
		$shipping_weight 	= '';
		$courier_invoice	= '';
		$finance_history	= '';
		if( current_user_can( 'administrator' ) ){
			if($courier_finance) {
				foreach($courier_finance as $finance) {
					$payment_status		.= $finance['payment'] . "\n";
					$received_cod		.= $finance['cod'] . "\n";
					$shipping_fee		.= $finance['fee'] . "\n";
					$shipping_weight	.= $finance['weight'] . "\n";
					$courier_invoice	.= $finance['invoice'] . "\n";
					$finance_history 	.= $finance['courier'] .' | '. $finance['tracking'] .' | '. $finance['status'] .' | Payment: '. $finance['payment'] .' | COD: '. $finance['cod'] .' | Fee: '. $finance['fee'] . ' | Weight: ' .$finance['weight'] . ' | Invoice: ' . $finance['invoice'] . "\n";
				}
				$payment_status 	= substr($payment_status, 0, -1);
				$received_cod 		= substr($received_cod, 0, -1);
				$shipping_fee		= substr($shipping_fee, 0, -1);
				$shipping_weight	= substr($shipping_weight, 0, -1);
				$courier_invoice	= substr($courier_invoice, 0, -1);
				$finance_history	= substr($finance_history, 0, -1);
			}
			else {
				$payment_status 	= '';
				$received_cod 		= '';
				$shipping_fee		= '';
				$shipping_weight	= '';
				$courier_invoice	= '';
				$finance_history	= '';
			}
		}




		$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_address,
            $parcel->courier_destination,
            (int)$parcel->order_total,
            $parcel->order_products,
            $parcel->courier_name,
            $parcel->courier_tracking,
            $parcel->courier_delivery,
            (int)$parcel->order_amount,
            $received_cod,
            $shipping_fee,
            $payment_status,
            $shipping_weight,
            $courier_invoice,            
            $finance_history,
        ];
    }
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="ucp_export_all.csv";');
    header('Pragma: no-cache');
    header("Expires: 0");        
    $f = fopen('php://output', 'w'); 
    foreach ($rows as $line) { 
        fputcsv($f, $line); 
    }
    die();
}




// ITEM REPORT
add_action('admin_init', 'dvs_ucp_item_report');
function dvs_ucp_item_report() {
    if (!isset($_POST['dvs_item_report_btn'])) {
        return;
    }
    $orders = $_POST['order'] ?? null;
    $trackings = [];
    $trackings_db = [];
    foreach ($orders as $order) {
        if (isset($order['check'])) {
            $trackings[] = $order['tracking'];
            $trackings_db[] = "'{$order['id']}'";
        }
    }
    $bookings = new CourierBooking([
        'shop_url' =>get_home_url(),
    ]);
	$bookings->paginate_by = (int)get_option('dvs_ucp_courier_pagination');
    $parcels = [];
    if (count($trackings_db) == 0){
        return;
    }
    $parameters[] = [
        'key' => 'id',
        'value' => '(' . implode(',', $trackings_db) . ')',
        'operator' => 'IN',
    ];
    $parcels = $bookings->get($parameters);
	$rows = [];
    $rows[] = [
  		'Qty',
        'Products',
    ];

    $input_strings = [];
    foreach ($parcels as $parcel){
        $input_strings[] = $parcel->order_products;
    }
    // Define a regular expression to match each item
    $item_regex = "/\[ (\d+) x ([^\]]+) \]/";

    // Create an associative array to keep track of the counts of each item
    $item_counts = array();

    // Loop through each input string
    foreach ($input_strings as $input_string) {
        // Use the regular expression to extract all items from the input string
        preg_match_all($item_regex, $input_string, $matches, PREG_SET_ORDER);

        // Loop through each item and update the counts in the associative array
        foreach ($matches as $match) {
            $item_name = trim($match[2]);
            if (array_key_exists($item_name, $item_counts)) {
                $item_counts[$item_name] += intval($match[1]);
            } else {
                $item_counts[$item_name] = intval($match[1]);
            }
        }
    }

    // Print out the results
    foreach ($item_counts as $item_name => $item_count) {
        $rows[] = [$item_count,  $item_name];
    }
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="ucp_item_report.csv";');
    header('Pragma: no-cache');
    header("Expires: 0");        
    $f = fopen('php://output', 'w'); 
    foreach ($rows as $line) { 
        fputcsv($f, $line); 
    }
    die();
}


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

    if (!isset($_POST['dvs_sync_btn'])) {
        return;
    }
	
    $orders = $_POST['order'] ?? null;

    $trackings = [];
    $trackings_db = [];
    foreach ($orders as $order) {
        if (isset($order['check'])) {
            $trackings[] = $order['tracking'];
            $trackings_db[] = "'{$order['id']}'";
        }
    }
    $bookings = new CourierBooking([
        'shop_url' =>get_home_url(),
    ]);
	$bookings->paginate_by = (int)get_option('dvs_ucp_courier_pagination');

    $parcels = [];
    
    if (count($trackings_db) == 0){
        return;
    }

    $parameters[] = [
        'key' => 'id',
        'value' => '(' . implode(',', $trackings_db) . ')',
        'operator' => 'IN',
    ];
    $parcels = $bookings->get($parameters);
    
    foreach($parcels as $parcel){
        dvs_track_shipment($parcel->order_id, $parcel->courier_name, $parcel->courier_tracking, false);
    }
}

function dvs_ucp_common_logs_page($courier_name, $courier_folder) {
    dvs_load_logs_page($courier_name, $courier_folder);
}

function dvs_load_logs_page($courier_name, $courier_folder){
	$parameters = [];
	$form_date = "";
	$form_order = "";
	$form_tracking = "";
	$form_status = "";
	$form_status_type = "";
			
	if (isset($_GET['hxs_search_btn'])) {
		$parameters[] = [
			'key' => 'courier_status',
			'value' => '',
			'operator' => '!=',
		];
		if (isset($_GET['hxs_status']) && !empty($_GET['hxs_status'])) {
			$parameters[] = [
				'key' => 'courier_status',
				'value' => $_GET['hxs_status'],
				'operator' => 'LIKE',
			];
		}		
	    if (isset($_GET['hxs_order']) && !empty($_GET['hxs_order'])) {
	        $form_order = $_GET['hxs_order'];
	        $orders_array = explode(',', $_GET['hxs_order']);
	        foreach ($orders_array as $i => $order_name) {
	            $orders_array[$i] = "'" . trim($order_name) . "'";
	        }
	        $parameters[] = [
	            'key' => 'order_name',
	            'value' => '(' . implode(',', $orders_array) . ')',
	            'operator' => 'IN',
	        ];
	    }
	    if (isset($_GET['hxs_tracking']) && !empty($_GET['hxs_tracking'])) {
	        $form_tracking = $_GET['hxs_tracking'];
	        $tracking_arr = explode(',', $_GET['hxs_tracking']);
	        foreach ($tracking_arr as $i => $tracking_name) {
	            $tracking_arr[$i] = "'" . trim($tracking_name) . "'";
	        }
	        $parameters[] = [
	            'key' => 'courier_tracking',
	            'value' => '(' . implode(',', $tracking_arr) . ')',
	            'operator' => 'IN',
	        ];
	    }
	    if (isset($_GET['hxs_delivery']) && !empty($_GET['hxs_delivery'])) {
	        $form_status = $_GET['hxs_delivery'];
	        $form_status_type = $_GET['hxs_delivery_type'];
	        $status_arr = explode(',', $_GET['hxs_delivery']);
	        if ($form_status_type === 'NOT IN'){
	        	$operator = 'NOT ';
	        	$status_params = ['AND'];
	        }else{
	        	$operator = '';
	        	$status_params = ['OR'];
	        }
	        foreach ($status_arr as $i => $status_name) {
	        	$status_params[] = [
		            'key' => 'courier_delivery',
		            'value' => '%' . trim($status_name) . '%',
		            'operator' => "{$operator}LIKE",
		        ];
	        }
	        $parameters[] = $status_params;			
	    }		
	    if (isset($_GET['hxs_date']) && !empty($_GET['hxs_date'])) {
	        $form_date = $_GET['hxs_date'];
	        $created_at_min = substr($_GET['hxs_date'], 0, 10) . ' 00:00:00';
	        $created_at_max = substr($_GET['hxs_date'], -10) . ' 23:59:59';
	        $parameters[] = [
	            'key' => 'courier_datetime',
	            'value' => "'{$created_at_min}' AND '{$created_at_max}'",
	            'operator' => 'BETWEEN',
	        ];
	    }
	}
	else {
		// $parameters[] = [
		// 	'key' => 'courier_status',
		// 	'value' => 'cancelled',
		// 	'operator' => '!=',
		// ];		
	}


	// FOR TRACKING POST REQUEST
	if(isset($_POST['tracking_numbers'])) {
		$tracking_numbers = $_POST['tracking_numbers'];
        foreach ($tracking_numbers as $i => $tracking_name) {
            $tracking_arr[$i] = "'" . trim($tracking_name) . "'";
        }
        $parameters[] = [
            'key' => 'courier_tracking',
            'value' => '(' . implode(',', $tracking_arr) . ')',
            'operator' => 'IN',
        ];
        $paginate_number = 500;
	}
	else {
		$paginate_number = (int)get_option('dvs_ucp_courier_pagination');
	}


	if($courier_name != 'All') {
		$bookings = new CourierBooking([
		    'shop_url' => get_home_url(),
		    'courier_name' => $courier_name,
		]);
	}
	else {
		$bookings = new CourierBooking([
		    'shop_url' => get_home_url(),
		]);
	}

	$bookings->paginate_by = $paginate_number;
	$page = $_GET['hxs_page'] ?? 1;
	$last_seen = $_GET['hxs_last_seen'] ?? null;
	$dir = $_GET['hxs_dir'] ?? null;	
	$parcels = $bookings->get($parameters, [], $page, $last_seen, $dir);
	$current_page = admin_url("admin.php");

	?>

	<head>
		<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
		<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" 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.6.0/jquery.min.js"></script>
		<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" 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>

		<?php
			if($courier_name == 'All') { ?>
				<style>
					.courier-name-all {
						display: none !important;
					}
					.dvs-btn-woo {
						background-color: #720EEC;
						border-color: #720EEC;
					}
				</style>
		<?php
			}
		?>

		<style>
			.hxs-upload-table tr {
				font-size: 14px;
			}

			.hxs-upload-table td {
			    padding: 2px 3px !important;
			}

			.hxs-upload-table .form-control {
			    font-size: 13px;
			    border: none;
			}
			.form-check-input:checked {
				background-color: unset;
			}
			.nav-link {
				padding: 0px 15px !important;
				margin-top: 5px !important;
				color: #888888 !important;
			}
			.nav-link.active {
				color: #198754 !important;
				background-color: transparent !important;
				border: 1px solid #198754 !important;
			}
			.dvs_log_modal p {
				font-size: 12px;
				margin-bottom: 5px;
			}
			.dvs_log_finance {
				font-size: 12px;
			}
			.finance_btn {
			    width: 100%;
			    padding: 0px;
			    margin-top: 3px;				
			}
			.hxs-upload-table .btn-outline-secondary {
				opacity: 0.3;
			}
			.dvs-table-stats th {
				padding-left: 15px;
				background-color: #eeeeee;
				font-weight: 500;
			}			
			.dvs-table-stats td {
				text-align: center;
			}
			.dvs_courier_stats_head {
				width: 100%;
			    text-align: center;
			    float: left;
			    background-color: #000000;
			    color: #ffffff;
			    padding: 5px 0px;
			    font-weight: bold;				
			}
			.dvs-table-stats td {
				font-size: 13px;
			}
			.dvs-table-stats-couriers th {
				font-size: 12px;
				padding-left: 15px;
				background-color: #eeeeee;				
			}			
			.dvs-table-stats-couriers td {
				font-size: 12px;
				text-align: center;
			}						
		</style>

		<script>
		$(document).on("click", "#hxs_print_btn", function() {
			$('#hxs_date').prop('required',false);
			$('#hxs_delivery').prop('required',false);
		});
		</script>
	</head>
<body>

<?php
	$dvs_admin_url = get_admin_url(null, 'admin.php?page=dvs_ucp_'.$courier_folder.'_logs');
?>

<div class="container-fluid">
	<nav class="navbar navbar-light bg-light">
		<div class="container-fluid">

			<div class="col-2">
				<a class="navbar-brand" href="<?php echo $dvs_admin_url ?>">
					<?php if($courier_name != 'All') { ?>	
				  	<img src="<?php echo plugin_dir_url( __DIR__ ) . "images/{$courier_folder}-label-logo.png"; ?>" alt="Universal Courier" height="35">
				  	<?php } else { echo 'Courier Logs'; } ?>
				</a>
			</div>
			
			<div class="col-8">
				<ul class="nav nav-pills">
					<li class="nav-item"><a class="nav-link <?php if (! isset($_GET['hxs_status'])) echo 'active'; ?>" href="<?php echo $dvs_admin_url ?>">All</a></li>

					<li class="nav-item"><a class="nav-link <?php if (isset($_GET['hxs_status']) && $_GET['hxs_status'] == 'active') echo 'active'; ?>" href="<?php echo $dvs_admin_url ?>&hxs_status=active&hxs_search_btn">Booked</a></li>
					
					<li class="nav-item"><a class="nav-link <?php if (isset($_GET['hxs_status']) && $_GET['hxs_status'] == 'shipped') echo 'active'; ?>" href="<?php echo $dvs_admin_url ?>&hxs_status=shipped&hxs_search_btn">Shipped</a></li>
					
					<li class="nav-item"><a class="nav-link <?php if (isset($_GET['hxs_status']) && $_GET['hxs_status'] == 'refused') echo 'active'; ?>" href="<?php echo $dvs_admin_url ?>&hxs_status=refused&hxs_search_btn">Refused</a></li>
					
					<li class="nav-item"><a class="nav-link <?php if (isset($_GET['hxs_status']) && $_GET['hxs_status'] == 'delivered') echo 'active'; ?>" href="<?php echo $dvs_admin_url ?>&hxs_status=delivered&hxs_search_btn">Delivered</a></li>

					<li class="nav-item"><a class="nav-link <?php if (isset($_GET['hxs_delivery']) && $_GET['hxs_delivery'] == 'return') echo 'active'; ?>" href="<?php echo $dvs_admin_url ?>&hxs_delivery_type=IN&hxs_delivery=return&hxs_search_btn">Returned</a></li>					
					
					<li class="nav-item"><a class="nav-link <?php if (isset($_GET['hxs_status']) && $_GET['hxs_status'] == 'cancelled') echo 'active'; ?>" href="<?php echo $dvs_admin_url ?>&hxs_status=cancelled&hxs_search_btn">Cancelled</a></li>

					<li class="nav-item"><a class="nav-link" href="<?php echo get_admin_url(null, 'admin.php?page=dvs_courier_analytics')?>&hxs_courier=<?php echo $courier_name ?>" target="_blank">Analytics</a></li>

				</ul>
			</div>
			<div class="col-2">

				<!-- Dropdown menu for column head show/hide option -->
				<div class="dropdown" style="display: inline-block">
				    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false">
				    </button>
				    <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton" style="padding: 10px">
				    	<li><input type="checkbox" class="dropdown-item showHideCheckbox" data-column-index="2" checked> Date</li>
				        <li><input type="checkbox" class="dropdown-item showHideCheckbox" data-column-index="4" checked> Name</li>
				        <li><input type="checkbox" class="dropdown-item showHideCheckbox" data-column-index="5" checked> Phone</li>
				        <li><input type="checkbox" class="dropdown-item showHideCheckbox" data-column-index="6" checked> Address</li>
				        <li><input type="checkbox" class="dropdown-item showHideCheckbox" data-column-index="7" checked> City</li>
				        <li><input type="checkbox" class="dropdown-item showHideCheckbox" data-column-index="8" checked> COD</li>
				        <li><input type="checkbox" class="dropdown-item showHideCheckbox" data-column-index="11" checked> Status</li>
				        <?php if( current_user_can('administrator') ){ ?>
				        <li><input type="checkbox" class="dropdown-item showHideCheckbox" data-column-index="12" checked> Finance</li>
				        <?php } ?>
				    </ul>
				</div>

				<?php
				 if (isset($_GET['hxs_page'])) {
					echo '<span class="float-end">Page: ' .$_GET['hxs_page']. '</span>';
				}
				else {
					echo '<span class="float-end">Page: 1</span>';
				}
				?>
			</div>			
		</div>
	</nav>
</div>



<?php 

if(isset($_GET['hxs_type']) && $_GET['hxs_type'] == 'analytics' ) {
	include_once('dvs-ucp-logs-analytics.php');
	die();
}
?>

				
<div class="dvs-upload-table mb-4">
    <br>
    <div class="container-fluid">
        <div class="row">
            <div id="hxs-form-filters pe-0" class="col-7">
                <form class="input-group" method="get" action=""  id="hxs-sheet-form courier-name-all">
                    <?php
                    foreach ($_GET as $key => $value) {
                        if (in_array($key, ['hxs_page', 'hxs_last_seen', 'hxs_dir']))
                            continue;
                        $key = htmlspecialchars($key);
                        $value = htmlspecialchars($value);
                        echo "<input type='hidden' name='$key' value='$value'/>";
                    }
                    ?>
                    <input class="form-control" type="text" name="hxs_date" value="<?= $form_date ?>" autocomplete="off" placeholder="Date Range">
                    <input class="form-control" type="text" name="hxs_order" value="<?= $form_order ?>" autocomplete="off" placeholder="Order #">
                    <input class="form-control" type="text" name="hxs_tracking" value="<?= $form_tracking ?>" autocomplete="off" placeholder="Tracking">
	                <select name="hxs_delivery_type" class="form-select ms-2" required="true" style="max-width: 100px;">
	                        <option value="IN" selected>IN</option>
	                        <option value="NOT IN">NOT IN</option>
	                </select>
                    <input class="form-control" type="text" name="hxs_delivery" value="<?= $form_status ?>" autocomplete="off" placeholder="Type Status">					
                    <button class="btn btn-success" name="hxs_search_btn" type="submit">Filter</button>
                </form>
            </div>

            <div class="col-5 ps-0">
            	<?php 
					$get_params_without_hxs_pagination = '?';
					foreach ($_GET as $key => $value) {
						if (!in_array($key, ['hxs_page', 'hxs_last_seen', 'hxs_dir']))
							$get_params_without_hxs_pagination .= $key . "=" . $value . '&';
					}
				?>
                 <?php if ($next_page = $bookings->get_next()){ ?>
                    <a href="<?= $current_page ?><?= $get_params_without_hxs_pagination ?>hxs_page=<?= $next_page['page_num'] ?>&hxs_last_seen=<?= $next_page['last_seen']?>&hxs_dir=<?= CourierBooking::$NEXT ?>" class="btn btn-outline-primary float-end">Next</a>
        
                <?php } if ($prev_page = $bookings->get_prev()){ ?>
                    <a href="<?= $current_page ?><?= $get_params_without_hxs_pagination ?>hxs_page=<?= $prev_page['page_num'] ?>&hxs_last_seen=<?= $prev_page['last_seen']?>&hxs_dir=<?= CourierBooking::$PREV ?>" class="btn btn-outline-primary me-2 float-end">Back</a>
                <?php } ?> 

    <form class="" method="post" action="" id="hxs-sheet-form">
                <select name="hxs_shipper_profile" class="form-select float-start " style="width: 85px;margin-right: 10px;color: #198754;border-color: #198754;padding: 2px 10px;font-size: 1rem;border-radius: 0.25rem;" required>
                        <option value="0" disabled selected>Profile</option>
                        <option value="1"><?= get_option('dvs_label_shipper_name_1') . " | " . get_option('dvs_label_shipper_phone_1') . " | " . get_option('dvs_label_shipper_address_1') . " | " . get_option('dvs_label_shipper_city_1') ?></option>
                        <?php 
                            if(!empty(trim(get_option('dvs_label_shipper_name_2')))){
                        ?>
                        <option value="2" ><?= get_option('dvs_label_shipper_name_2') . " | " . get_option('dvs_label_shipper_phone_2') . " | " . get_option('dvs_label_shipper_address_2') . " | " . get_option('dvs_label_shipper_city_2') ?></option>
                        <?php }
                            if(!empty(trim(get_option('dvs_label_shipper_name_3')))){
                        ?>
                        <option value="3" ><?= get_option('dvs_label_shipper_name_3') . " | " . get_option('dvs_label_shipper_phone_3') . " | " . get_option('dvs_label_shipper_address_3') . " | " . get_option('dvs_label_shipper_city_3') ?></option>
                    <?php } ?>
                </select>
                <button class="btn btn-success float-start" name="hxs_print_btn" type="submit">Print</i></button>
                <button class="btn btn-primary dvs-btn-woo float-start" id="sync_btn" name="dvs_sync_btn" type="submit" style="margin-left:10px">Track</button>
                <div class="btn-group" role="group" aria-label="Button group with nested dropdown" style="margin-left: 10px;">
                    <div class="btn-group" role="group">
                        <button id="btnGroupDrop1" type="button" class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                        Actions
                        </button>
                        <ul class="dropdown-menu" aria-labelledby="btnGroupDrop1">                    	
                            <li><input type="submit" name="dvs_export_btn" class="dropdown-item" value="Sales Report"></li>
                            <li><input type="submit" name="dvs_item_report_btn" class="dropdown-item" value="Item Report"></li>
                            <li><input type="submit" name="dvs_export_all_btn" class="dropdown-item" value="Export All"></li>
                        </ul>
                    </div>
                </div>
            </div>

        </div> <!-- end row -->
    </div> <!-- end container-fluid -->   

        <table class="table table-bordered table-sm table-responsive hxs-upload-table mt-2">
            <thead class="table-dark" style="text-align: center;">
                <tr>
                    <th scope="col"><input type="checkbox" class="form-check-input bulkcheckbox" value="" id="bulkcheckbox" name="bulkcheckbox"></th>
                    <th scope="col">#</th>
                    <th scope="col">Date</th>
                    <th scope="col">Order</th>
                    <th scope="col">Name</th>
                    <th scope="col">Phone</th>
                    <th scope="col">Address</th>
                    <th scope="col">City</th>
                    <th scope="col">COD</th>
                    <?php if($courier_name == 'All') { ?>
                    <th scope="col">Courier</th>
                	<?php } ?>
                    <th scope="col">Tracking</th>
                    <th scope="col">Status</th>
                    <?php
                    	if( current_user_can('administrator') ){ ?>
                    	<th scope="col">Finance</th>
                	<?php } ?>
                </tr>
            </thead>

            <tbody>
                <?php
				$count = 1;
				$dvs_ucp_display_average = get_option('dvs_ucp_display_average');
				$dvs_ucp_courier_pagination = (int)get_option('dvs_ucp_courier_pagination');
				$dvs_ucp_courier_pagination_minus = $dvs_ucp_courier_pagination - 1;
				
                if (isset($_GET['hxs_page'])) {
                	$dvs_current_page = $_GET['hxs_page'];
	                if ($dvs_current_page == 2 ) {
	                	$count = $dvs_ucp_courier_pagination + 1;
	                }
	                if ($dvs_current_page > 2 ) {
	                	$count = ($dvs_current_page * $dvs_ucp_courier_pagination) - $dvs_ucp_courier_pagination_minus;
	                }                
	            }
	            else {
	            	$count = 1;
	            }

                foreach ($parcels as $parcel) {
                    $order_datetime = $parcel->courier_datetime;
                    $dvs_parcel_days = get_post_meta($parcel->order_id, '_dvs_parcel_days', true);
                    $order_name = $parcel->order_name;
                    $order_id = $parcel->order_id;
                    $consignee_name = $parcel->consignee_name;
                    $consignee_phone = $parcel->consignee_phone;
                    $consignee_address = $parcel->consignee_address;
                    $courier_destination = $parcel->courier_destination;
                    $order_products = $parcel->order_products;
                    $order_amount = $parcel->order_amount;
                    $courier_title = $parcel->courier_name;
                    $courier_tracking = $parcel->courier_tracking;
                    $courier_link = get_post_meta($parcel->order_id, '_dvs_courier_link', true);
                    $courier_delivery = $parcel->courier_delivery;
                    $courier_finance = $parcel->courier_finance;

                    if( current_user_can('administrator') ){
						// $courier_finance = json_decode($courier_finance, true);
						$courier_finance = json_decode($courier_finance ?? '[]', true);
						$finance_record = '';
						if($courier_finance) {
							foreach($courier_finance as $finance) {
								$finance_record .= '<div class="col-6 mb-4">Courier: ' . $finance['courier'] .'<br>Tracking: '. $finance['tracking'] .'<br>Status: '. $finance['status'] .'<br>Payment: '. $finance['payment'] . '<br>COD: Rs '. $finance['cod'] .'<br>Fee: Rs '. $finance['fee'] . '<br> Weight: ' . $finance['weight'] . '<br> Invoice : ' .$finance['invoice'] . '<hr></div>';
							}
							$finance_record = substr($finance_record, 0, -1);
							
							if ($finance['payment'] == 'Paid') {
								$finance_btn = 'Paid';
								$finance_class = 'btn-outline-success';
							}
							else if ($finance['payment'] == 'Un-Paid') {
								$finance_btn = 'Un-Paid';
								$finance_class = 'btn-outline-danger';
							}						
							else {
								$finance_btn = 'Partial';
								$finance_class = 'btn-outline-dark';
							}

						}
						else {
							$finance_record = '<div class="col-6 mb-4">No record found</div>';
							$finance_btn = 'Waiting';
							$finance_class = 'btn-outline-secondary';
						}
					}

                ?>

                    <tr>
                        <td width="2%">
                            <input type="checkbox" class="form-check-input singlecheckbox" value="" id="check_<?= $count ?>" name="order[<?= $count ?>][check]">
                        </td>

                        <td width="4%">
                            <input type="text" class="form-control form-control-sm hxs-center" readonly id="<?= $count ?>" name="<?= $count ?>" value="<?= $count ?>" />
                        </td>

                        <td width="12%">
                            <input type="hidden" class="form-control form-control-sm hxs-center" readonly id="" name="order[<?= $count ?>][id]" value="<?= $parcel->id ?>" required />
                            <?php
                            	if($dvs_parcel_days && $dvs_ucp_display_average) {
                            		$dvs_datetime_column = substr($order_datetime, 0, -3) . ' -- '.$dvs_parcel_days.' Days';
                            		$dvs_datetime_column_width = "width:200px"; 
                            	}
                            	else {
                            		$dvs_datetime_column = substr($order_datetime, 0, -3);
                            		$dvs_datetime_column_width = "";
                            	}
                            ?>
                            <input type="text" class="form-control form-control-sm hxs-center" readonly id="" name="" value="<?= $dvs_datetime_column ?>" style="<?= $dvs_datetime_column_width ?>" required />

                        <td width="8%">
                        	<a class="form-control form-control-sm text-center"  href="<?php echo site_url() ?>/wp-admin/post.php?post=<?php echo $order_id ?>&action=edit" target="blank" style="background-color: #e9ecef;text-decoration: none;"><?= $order_name ?></a>
                        </td>

                        <td width="10%">
                            <input type="text" class="form-control form-control-sm" readonly id="" name="" value="<?= $consignee_name ?>" required />
                        </td>

                        <td width="10%">
                        	<?php

                        		$dvs_ucp_wa_text = get_option('dvs_ucp_wa_tracking_text');

                        		if($dvs_ucp_wa_text) {
                        			$whatsapp_text = $dvs_ucp_wa_text;
									$whatsapp_text = str_replace("[order_number]", $order_name, $whatsapp_text);
									$whatsapp_text = str_replace("[customer_name]", $consignee_name, $whatsapp_text);
									$whatsapp_text = str_replace("[courier_name]", $courier_title, $whatsapp_text);
									$whatsapp_text = str_replace("[courier_tracking]", $courier_tracking, $whatsapp_text);
									$whatsapp_text = str_replace("[courier_link]", $courier_link, $whatsapp_text);
                        		}
                        		else {
                        			$whatsapp_text = "Dear ".$consignee_name.", your order ".$order_name." has been shipped. Courier is ".$courier_name." with Tracking ".$courier_tracking.". Get Live tracking: ".site_url()."/track/";
                        		}

                        		$whatsapp_text = urlencode($whatsapp_text);

						        $custphone = trim($consignee_phone);
						        $custphone = str_replace(["O","o"],['0','0'],$custphone);
						        $custphone = preg_replace("/[^0-9]+/", "", $custphone);                    		
                        	?>

							<a class="form-control form-control-sm text-center" 
							   href="https://wa.me/92<?php echo $custphone ?>?text=<?php echo $whatsapp_text; ?>" 
							   target="_blank" 
							   style="background-color: #e9ecef; text-decoration: none;">
							    <?= $consignee_phone ?>
							</a>
                        </td>

                        <td width="10%">
                            <input type="text" class="form-control form-control-sm hxs-center" readonly id="" name="" value="<?= $consignee_address ?>" required />
                        </td>

                        <td width="10%">
                            <input type="text" class="form-control form-control-sm hxs-center" readonly id="" name="" value="<?= $courier_destination ?>" required />
                        </td>

                        <td width="6%">
                            <input type="text" class="form-control form-control-sm hxs-center" readonly id="" name="" value="Rs <?= substr($order_amount, 0, -3) ?>" required />
                        </td>

                        <?php if($courier_name == 'All') { ?>
	                        <td width="10%">
	                        	<input type="text" class="form-control form-control-sm hxs-center" readonly id="title_<?= $count ?>" name="order[<?= $count ?>][title]" value="<?= $courier_title ?>" required />
	                        </td>
	                    <?php } ?>    

                        <td width="12%">
                        	<?php
                        	add_thickbox();
							echo'<a href="#TB_inline?width=650&height=600&inlineId=dvs-content-track" class="thickbox form-control form-control-sm hxs-center" onclick="dvstrackparcel(\'' . $order_id . '\', \'' . $parcel->courier_name . '\', \'' . $courier_tracking . '\')" style="text-align: center;text-decoration: none; background-color:#e9ecef; color:#198754;">'.$courier_tracking.'</a>'; 
							?>

                            <input type="hidden" class="form-control form-control-sm hxs-center" readonly id="tracking_<?= $count ?>" name="order[<?= $count ?>][tracking]" value="<?= $courier_tracking ?>" required />
                        </td>

                        <td width="12%">
                            <input type="text" class="form-control form-control-sm hxs-center" readonly value="<?= $courier_delivery ?>" required />
                        </td>

                        <?php if( current_user_can('administrator') ){ ?>
	                        <td width="12%">
								<button type="button" class="btn <?= $finance_class ?> btn-sm finance_btn" data-bs-toggle="modal" data-bs-target="#dvsLogModal<?= $count ?>"><?= $finance_btn ?></button>
								<!-- Modal -->
								<div class="modal fade" id="dvsLogModal<?= $count ?>" tabindex="-1" aria-labelledby="dvsLogModalLabel" aria-hidden="true">
								  <div class="modal-dialog">
								    <div class="modal-content">
								      <div class="modal-header">
								        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
								      </div>
								      <div class="modal-body dvs_log_modal">
								      	<div class="row">
								      		<div class="col-6">
								      			<h6 class="modal-title mb-2">Details</h6>
										      	<p><strong>Order: </strong><?= $order_name ?></p>
										      	<p><strong>Date: </strong><?= $order_datetime ?></p>
										      	<p><strong>Name: </strong><?= $consignee_name ?></p>
										      	<p><strong>Phone: </strong><?= $consignee_phone ?></p>
										      	<p><strong>Address: </strong><?= $consignee_address ?></p>
										      	<p><strong>City: </strong><?= $courier_destination ?></p>
										    </div>
										    <div class="col-6">
										    	<h6 class="modal-title mb-2">Shipping</h6>
										      	<p><strong>Courier: </strong><?= $courier_title ?></p>
										      	<p><strong>Tracking: </strong><?= $courier_tracking ?></p>
										      	<p><strong>Status: </strong><?= $courier_delivery ?></p>
										      	<p><strong>Amount: </strong>Rs <?= substr($order_amount, 0, -3) ?></p>
										    </div>
										    <div class="col-12">
										    	<p><strong>Products: </strong><?= $order_products ?></p>
										    </div>
										</div>    	
								      	<hr>
								      	<h6 class="modal-title mb-2">Finance</h6>
								      	<div class="row dvs_log_finance"><?= $finance_record ?></div>
								      </div>
								    </div>
								  </div>
								</div>
	                        </td>
	                    <?php } ?>    
                        <!-- <td width="15%">
                            <i class="bi bi-card-list" style="cursor: pointer; font-size:20px;padding: 5px 10px; float: left;"></i>
                            <i class="bi bi-printer" style="cursor: pointer; font-size:20px;padding: 5px 10px; float: left;"></i>
                            <i class="bi bi-trash" style="cursor: pointer; font-size:20px;padding: 5px 10px; float: left;"></i>
                        </td> -->
                    </tr>
                <?php
                    $count++;
                }
                ?>
            </tbody>
        </table>
    </form>

	<div id="dvs-content-track" style="display:none;">
        <div class="track-thickbox">
            <center><img src="<?php echo plugin_dir_url( __DIR__ ) . 'images/loader.gif'; ?>"></center>
        </div>
    </div>

    <style>
    	#TB_window {
    		width: auto !important;
    	}
    </style>	

    <script type="text/javascript">
        jQuery(function($) {
            $('body').on('change', '#bulkcheckbox', function(e) {
                $('.singlecheckbox').prop('checked', e.currentTarget.checked);
                $('.singlecheckbox').change();
            });
        });
    </script>

	<script type="text/javascript">
		$(function() {
			$('input[name="hxs_date"]').daterangepicker({
				autoUpdateInput: <?php echo empty($form_date) ? 'false' : 'true' ?>,
				locale: {
					cancelLabel: 'Clear',
					format: "YYYY-MM-DD",
				}
			});

			$('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('');
			});

			$('#sync_btn').click(function(e){
				$('#sync_btn').html('<div class="spinner-border" role="status" style="width:1.5rem !important;height:1.5rem !important;"></div>');
			})
		});
	</script>

	<script>
	$(document).ready(function(){
		// Listen for changes in checkboxes' state
		$('.showHideCheckbox').change(function(){
			var columnIndex = $(this).data('column-index');
			var thToToggle = $('table thead th:nth-child(' + (parseInt(columnIndex) + 1) + ')');
			var tdToToggle = $('table tbody td:nth-child(' + (parseInt(columnIndex) + 1) + ')');

			if ($(this).prop('checked')) {
				thToToggle.show();
				tdToToggle.show();
			} else {
				thToToggle.hide();
				tdToToggle.hide();
			}
		});
	});
	</script>
</body>	
<?php
}