<?php
// DISPLAY ALL ERRORS
//error_reporting(E_ALL);
ini_set('display_errors', 0);

// FOR DEBUG ONLY
if (isset($_GET['php']) and $_GET['php'] == 'info') {
    die(phpinfo());
}
// SEARCH HELPER FUNCTION
function contains(array $array, $string) {
    $count = 0;
    foreach ($array as $value) {
        if (false !== stripos($string, $value)) {
            ++$count;
        }
    }
    return $count == count((array)$array);
}

// START & CONFIG
ob_start();
require 'setup/config.php';


$LANG =  'cn';
// SET LANGUAGE
if (isset($_GET['lang'])){	
	$_SESSION['HTTP_ACCEPT_LANGUAGE'] = $_GET['lang'];
}
if (isset($_SESSION['HTTP_ACCEPT_LANGUAGE']) and file_exists('lang/' . $_SESSION['HTTP_ACCEPT_LANGUAGE'] . '.php')) {	
	if((@include 'lang/' . $_SESSION['HTTP_ACCEPT_LANGUAGE'] . '.php') === false){
		echo 'Caught exception: Translate file is wrong';
	}else{
		@include_once('lang/' . $_SESSION['HTTP_ACCEPT_LANGUAGE'] . '.php');
	}
} else {
	if((@include 'lang/' . $LANG . '.php') === false){
		echo 'Caught exception: Translate file is wrong';
	}else{
		@include_once('lang/' . $LANG . '.php');
	}
}


// INI VARs
$found = 0;                     // MARKER HOW MANY HITS FOUND A SEARCH
$done = 0;                     // MARKER HOW MANY ENTRYs ARE DONE
$msg = '';                    // TOAST MESSAGE
$file = '../Docs/data/Departure.json'; // DATA FILE NAME


$Corresponding = json_decode(file_get_contents('data/Corresponding.json'));

foreach ($Corresponding as $r){
	if($r->code < 600 ){
		$codename[] = $r->abbreviation;
	}
}

// LOGIN CHECK
session_start();
$login = check_current_user_login($ARR_USERS, $SALT);
$currentuser = $login['user'];
//var_dump($login);
if ($login['status'] == 200) {
    //var_dump($login);
} else {
    header('location: login.php');
    exit;
}
// DELETE ENTRY IF DEL LINK IS CLICKED
if (@$_GET['delete_id'] != '') {
    $data = json_decode(file_get_contents($file), true);    
    foreach ( $data as $key => $r  ){
        if($r['id'] == @$_GET['delete_id']){
            unset($data[$key]);
        }
    }    
    $convert_array_to_json = array_values($data);
    $write_json = json_encode($convert_array_to_json);
    file_put_contents($file, $write_json);
    header('location: departure.php?msg=' . $i18n['Entry successfully deleted.']);
    
}

// READ DATA
$user = json_decode(file_get_contents('data/User.json'));
$data = json_decode(file_get_contents($file), true);



if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['idport'] != ''  ) {
	$id = time();
	if($_POST['id'] == ''){	   	
        $formdata = array(
        'id' => $id	
		, 'idport' => $_POST['idport']
        , 'port' => $_POST['port']
        , 'location' => $_POST['location']
		, 'createdby' => $currentuser->name
		, 'createddate' => $id
		, 'modifieddate' => ''  
  	);
  	$arr_data = array();
    	if (file_exists($file)) {
        	$jsondata = file_get_contents($file);
        	$arr_data = json_decode($jsondata, true);
    	}
   	$arr_data[] = $formdata;

	}else{
		$arr_data = array();
    		if (file_exists($file)) {
        		$jsondata = file_get_contents($file);
        		$arr_data = json_decode($jsondata, true);
    		}
		foreach ($arr_data as $key => $r){
			if($r['id'] == $_POST['id']){
				$arr_data[$key]['idport'] = $_POST['idport'];
				$arr_data[$key]['port'] = $_POST['port'];
				$arr_data[$key]['location'] = $_POST['location'];		
				$arr_data[$key]['modifieddate'] = $id;
				$arr_data[$key]['modifiedby'] = $currentuser->name;

			}
		}
	}
  
    $jsondata = json_encode($arr_data);
    if (file_put_contents($file, $jsondata)) {
        $msg = $i18n['Data successfully saved!'];
    } else {
        $msg = $i18n['ERROR &mdash; Data not saved!'];
    }
    header('location: departure.php?msg=' . $msg);
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $_GET['msg'] = $i18n['All fields are required!'];
}
// CREATE DATA FILE IF NOT EXISTS
if (!is_file($file)) {
    file_put_contents($file, '');
}

// HEADER
ob_end_flush();
include 'tpl/header.php';
// FORM FOR NEW ENTRY

?>

<script>

function editc(id) {

var obj = jQuery.parseJSON(id);
$('#idport,#port').next().addClass('active');
$('#id').val(obj.id);
$('#idport').val(obj.idport);
$('#port').val(obj.port);
$('#location').val(obj.location);

$('select').formSelect();

}
        
</script>      
<?php       
if($_GET['nocontrol'] == 1){	
?>
<style>
.navbar-fixed {
	display:none;
}
</style>
<script>

</script>
<?php } ?>
       
            
      
<?php
// DATA TABLE
$Client_ID = 'bxH8462TFHX286PXH6';
$Client_Secret = 'C5A892E3E8DC48BF8C6BBF7F5AD9C19A';


$payload = json_encode( array( "appid"=> $Client_ID , "secret"=> $Client_Secret) );

$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://webapi.best-hint.com/XZC/token/?appid=".$Client_ID.'&secret='.$Client_Secret,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_POSTFIELDS => $payload, 
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
'Accept: application/json',
'Content-Type: application/x-www-form-urlencoded',
),
//CURLOPT_POSTFIELDS =>$payload,
));


$response = curl_exec($curl);
$err = curl_error($curl);

$response = json_decode($response);


if($response->data->access_token){
	
	
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://webapi.best-hint.com/XZC/api/Customer/GetCustomerList?searchText=%7B%7D",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_POSTFIELDS => $payload, 
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
'token: '.$response->data->access_token,
'Accept: application/json',
'Content-Type: application/x-www-form-urlencoded',
),
//CURLOPT_POSTFIELDS =>$payload,
));


$data = curl_exec($curl);
$err = curl_error($curl);
$data = json_decode($data,true);
$data = $data['data'];	




$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://webapi.best-hint.com/XZC/api/Job/GetBookingList?searchText=%7B%7D",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_POSTFIELDS => $payload, 
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
'token: '.$response->data->access_token,
'Accept: application/json',
'Content-Type: application/x-www-form-urlencoded',
),
//CURLOPT_POSTFIELDS =>$payload,
));


$data2 = curl_exec($curl);
$err = curl_error($curl);
$data2 = json_decode($data2,true);
$data2 = $data2['data'];	




$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://webapi.best-hint.com/XZC/api/Fee/GetYSYFMXList?searchText=%7B%7D",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_POSTFIELDS => $payload, 
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
'token: '.$response->data->access_token,
'Accept: application/json',
'Content-Type: application/x-www-form-urlencoded',
),
//CURLOPT_POSTFIELDS =>$payload,
));


$data9 = curl_exec($curl);
$err = curl_error($curl);
$data9 = json_decode($data9,true);
$data9 = $data9['data'];	

//echo '<pre>';
//print_r($data9);
//die;
}
//echo '<pre>';
//print_r($data2);
//die;
foreach ($data as $key => $values) {   
    $data4[$data['ShortName']] = $values;
}

foreach ($data2 as $key => $values) {   
    $data3[$data2['WTR']][] = $values;
}



foreach ($data9 as $key => $values) {   
    $datafee[$values['JobID']] += (float)$values['Income'];
    $datafee2[$values['JobID']] += (float)$values['ReceivedAmount'];
    $Remark[$values['JobID']] .= $values['Remark'].'</br>';

    $datafee3[$values['JobID']] += (float)$values['Income'];
    $datafee4[$values['JobID']] += (float)$values['OutCome'];
    $Remar2[$values['JobID']] .= $values['Remark'].'</br>';
}

// LOOP EACH ENTRY
?>
<div id="tabs" style="float: left;width: 100%;">
  <ul>
    <li><a href="#tabs-1">Booking</a></li>
    <li><a href="#tabs-2">Customer</a></li>
  </ul>
  <div id="tabs-1" class="thelistside">
      
 <table class="striped responsive-table hoverable tablesorter" id="tab-table2">
            <thead>
                <tr>
					
                                        <th>JobNo</th>
                                        <th>WTR</th> 
										
					<th style="width:210px;">Etd</th>
					<th>PortLoading</th>
					<th>PlaceDelivery </th>
					
					<th>Vessel</th>
					<th>VoyNo</th>
					<th>Carrier</th>
					<th>CntrNumStr</th>
					<th style="width:160px;">BillDate</th>
                                        <th>BranchCode</th>
                                        <th>ContainerNos</th>
                                        <th>Sales</th>
                                        <th>Remark</th>
                                        <th>应收</th>
                                        <th>已收</th>
                                        <th>未收</th>
                </tr>
            </thead>
        <tbody>
   <?php 
   
        foreach ($data2 as $key => $values) {   
                    
                     $amount_array[$values['WTR']] += (float)$datafee[$values['JobID']] ;
                     $amount_array2[$values['WTR']] += (float)$datafee2[$values['JobID']] ;
                     $booking_array[$values['WTR']][] = $values['JobNo'] ;
					 
					 
					 $CntrNumStr = explode('X',$values['CntrNumStr']);
					 $Container_array[$values['WTR']][date('Y-m',strtotime($values['Etd']))] += (float)$CntrNumStr[0];

					 
	            ?>    
                <tr>
					
                                    <td style="padding-left: 6px;"><?= $values['JobNo'];?></td>
                                <td style="padding-left: 6px;"><?= $values['WTR'];?></td>
                                                 
					<td style="padding-left: 6px;"><?= date('d-m-Y',strtotime($values['Etd']));?></td>
					<td style="padding-left: 6px;"><?= $values['PortLoading'];?></td>
					<td style="padding-left: 6px;"><?= $values['PlaceDelivery'];?></td>
					
					<td style="padding-left: 6px;"><?= $values['Vessel'];?></td>
                                        <td style="padding-left: 6px;"><?= $values['VoyNo'];?></td>
                                        <td style="padding-left: 6px;"><?= $values['Carrier'];?></td>
                                        <td style="padding-left: 6px;"><?= $values['CntrNumStr'];?></td>
                                        <td style="padding-left: 6px;"><?= date('d-m-Y',strtotime($values['BillDate']));?></td>
                                        <td style="padding-left: 6px;"><?= $values['BranchCode'];?></td>
                                        <td style="padding-left: 6px;"><?= $values['ContainerNos'];?></td>
                                        <td style="padding-left: 6px;"><?= $values['Sales'];?></td>
                                       <td style="padding-left: 6px;width: 350px;"><?= $Remark[$values['JobID']]; ?></td>
                                        <td style="padding-left: 6px;"><?= number_format((float)$datafee2[$values['JobID']]); ?></td>

                                         <td style="padding-left: 6px;"><?= number_format((float)$datafee[$values['JobID']]); ?></td>
                                        <td style="padding-left: 6px;"><?php 
                                        $sjdbjk = $datafee2[$values['JobID']]-$datafee[$values['JobID']];
                                        echo number_format((float)$sjdbjk); 
                                        if($sjdbjk != 0){ echo '<br><span style="color:red;" >Not match</span>';}
                                        ?></td>
                    
                </tr>
            <?php  }  ?>
        </tbody>
    </table>
  </div>
  <div id="tabs-2" class="thelistside">
		<div id="conpermonth" >
		
		</div>
  
  
        <table class="striped responsive-table hoverable tablesorter" id="tab-table">
            <thead>
                <tr>
					
                    <th>ShortName/Company</th> 
					 <th style="" >Container</th>
					
					
                                        <th style="" >Booking</th>
                                        <th>应收</th>
                                        <th>已收</th>
                                        <th>未收</th>
                </tr>
            </thead>
        <tbody>
   <?php 
   
        foreach ($data as $key => $values) {   
		
				if(!in_array($values['ShortName'],$codename)){
					continue;
				}
				if(array_sum($Container_array[$values['ShortName']]) == 0){
					continue;
				}
	            ?>    
                <tr>
					
                    <td style="padding-left: 6px;"><?= $values['ShortName'];?><br>
					<?= $values['NameC'];?>
					<span style="display:none;" ><?= $values['CustomerID']; ?>
					<?= $values['CustomerNo'];?></span>
					</td>
                          
				
				
                                    <td style="padding-left: 6px;width:35%"><table><?php
										$ashi = 0;
										ksort($Container_array[$values['ShortName']]);
										
										
										echo '<tr>';
										foreach (array_keys($Container_array[$values['ShortName']]) as $c){
											echo '<td>'.date('m/y',strtotime($c.'-01')).'</td>';
										}
										
										echo '<td style="text-align: right;" ><b>Total</b></td></tr>';
										echo '<tr>';
										foreach ($Container_array[$values['ShortName']] as $month => $c){
											echo '<td>'.$c.'</td>';
											$ashi += (float)$c;
											
											$ttbymonth[$month] += (float)$c;
											$ccbymonth[$month] ++;
										}
										echo '<td style="text-align: right;" >'.$ashi.'</td></tr>';

									 ?>
									 
									 
									 </table></td>
                                        <td style="padding-left: 6px;width:45%"><b>Orders:</b><?php echo count((array)$booking_array[$values['ShortName']]).' '; echo implode(', ', $booking_array[$values['ShortName']]) ; ?></td>
                                         <td style="padding-left: 6px;"><?php echo number_format((float)$amount_array2[$values['ShortName']]); ?></td>
                                        <td style="padding-left: 6px;"><?php echo number_format((float)$amount_array[$values['ShortName']]); ?></td>
                                        <td style="padding-left: 6px;"><?php 
                                        echo number_format((float)$amount_array2[$values['ShortName']]-$amount_array[$values['ShortName']]); ?></td>
                    
                </tr>
            <?php  }  ?>
        </tbody>
    </table>
  </div>    
</div>  

<div id="dsakldn" style="display:none;" >  
  
	<table>
			<tr>
			<td>
			</td>
		  <?php
		  
		  ksort($ttbymonth);
		  ksort($ccbymonth);
		  
				foreach (array_keys($ttbymonth) as $c){
					echo '<td>'.date('m/y',strtotime($c.'-01')).'</td>';
				}

		  ?>
			</tr>
			<tr>
			<td> Containers </td>
		  <?php
				foreach ($ttbymonth as $c){
					echo '<td>'.$c.'</td>';
				}

		  ?>
			</tr>
			
			<tr>
			<td> Customers </td>
		  <?php
				foreach ($ccbymonth as $c){
					echo '<td>'.$c.'</td>';
				}

		  ?>
			</tr>
	</table>


</div>
<style>
    table.tablesorter thead tr th {
        background-color: #1b278a;
    color: #fff;
	  position: sticky;
    top: 0px;
}

</style>
<?php
// FOOTER
include 'tpl/footer.php';
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" integrity="sha512-uto9mlQzrs59VwILcLiRYeLKPPbS/bT71da/OEBYEwcdNUk8jYIy+D176RYoop1Da+f9mvkYrmj5MCLZWEtQuA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script><!-- comment -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" integrity="sha512-urpIFwfLI9ZDL81s6eJjgBF7LpG+ROXjp1oNwTj4gSlCw00KiV1rWBrfszV3uf5r+v621fsAwqvy1wRJeeWT/A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/css/theme.default.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/js/jquery.tablesorter.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/js/jquery.tablesorter.widgets.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/js/extras/jquery.tablesorter.pager.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/js/parsers/parser-input-select.min.js"></script>

<script>
$(document).ready(function(){
 $( "#tabs" ).tabs();
 
 $( "#conpermonth" ).html($( "#dsakldn" ).html());
 
 $('.tablesorter').tablesorter({
    theme: 'blackice',
    widthFixed: false,
    showProcessing: false,
    headerTemplate: '{content}',
    onRenderTemplate: null, 
    onRenderHeader: function (index) {
        $(this).find('div.tablesorter-header-inner').addClass('roundedCorners');
    },

    cancelSelection: true,
    dateFormat: "mmddyyyy",
    sortMultiSortKey: "shiftKey",
    sortResetKey: 'ctrlKey',
    usNumberFormat: true,
    delayInit: false,
    serverSideSorting: false,
    headers: {
        0: {
            sorter: "text",sortInitialOrder: 'desc'
        },
        1: {
            sorter: "text"
        },
        3: {
            sorter: "select" 
        }
    },
    
    ignoreCase: true,
    sortForce: null,
    sortList: [
        [0, 1],
        [1, 0],
        [2, 0]
    ],

    sortAppend: null,
    sortInitialOrder: "asc",
    sortLocaleCompare: false,
    sortReset: false,
    sortRestart: false,
    emptyTo: "bottom",
    stringTo: "max",
    
    textExtraction: {
        0: function (node) {
            return $(node).text();
        },
        1: function (node) {
            return $(node).text();
        }
    },

    textSorter: null,
    initWidgets: true,
    widgets: ['zebra', 'columns', "filter" ],
    widgetOptions: {
        
        zebra: [
            "ui-widget-content even",
            "ui-state-default odd"],
        uitheme: 'jui',
        columns: [
            "primary",
            "secondary",
            "tertiary"],
        columns_tfoot: true,
        columns_thead: true,
        filter_childRows: false,
        filter_columnFilters: true,
        filter_cssFilter: "tablesorter-filter",
        filter_functions: null,
        filter_hideFilters: false,
        filter_ignoreCase: true,
        filter_reset: null,
        filter_searchDelay: 300,
        filter_serversideFiltering: false,
        filter_startsWith: false,
        filter_useParsedData: false,
        resizable: true,
        saveSort: true,
        stickyHeaders: "tablesorter-stickyHeader"
    },

   
    initialized: function (table) {},

    // *** CSS CLASS NAMES ***
    tableClass: 'tablesorter',
    cssAsc: "tablesorter-headerSortUp",
    cssDesc: "tablesorter-headerSortDown",
    cssHeader: "tablesorter-header",
    cssHeaderRow: "tablesorter-headerRow",
    cssIcon: "tablesorter-icon",
    cssChildRow: "tablesorter-childRow",
    cssInfoBlock: "tablesorter-infoOnly",
    cssProcessing: "tablesorter-processing",
    selectorHeaders: '> thead th, > thead td',
    selectorSort: "th, td",
    selectorRemove: "tr.remove-me",
    debug: false

}).tablesorterPager({

    
    container: $(".pager"),
    ajaxUrl: null,
    ajaxProcessing: function(ajax) {
        if (ajax && ajax.hasOwnProperty('data')) {
            // return [ "data", "total_rows" ]; 
            return [ajax.data, ajax.total_rows];
        }
    },

    
    output: '{startRow} to {endRow} ({totalRows})',
    updateArrows: true,
    page: 0,
    size: 'all',
    fixedHeight: true,
    removeRows: false,
    cssNext: '.next',
    cssPrev: '.prev',
    cssFirst: '.first',
    cssLast: '.last',
    cssGoto: '.gotoPage',
    cssPageDisplay: '.pagedisplay',
    cssPageSize: '.pagesize',
    cssDisabled: 'disabled'
});


$.extend($.tablesorter.themes.jui, {
    table: 'ui-widget ui-widget-content ui-corner-all', // table classes
    header: 'ui-widget-header ui-corner-all ui-state-default', // header classes
    icons: 'ui-icon', // icon class added to the <i> in the header
    sortNone: 'ui-icon-carat-2-n-s',
    sortAsc: 'ui-icon-carat-1-n',
    sortDesc: 'ui-icon-carat-1-s',
    active: 'ui-state-active', // applied when column is sorted
    hover: 'ui-state-hover', // hover class
    filterRow: '',
    even: 'ui-widget-content', // even row zebra striping
    odd: 'ui-state-default' // odd row zebra striping
});
});
</script>