<?php
// DISPLAY ALL ERRORS
//error_reporting(E_ALL);
ini_set('display_errors', 0);
session_start();
// 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 = 'data/newconsignee.json';
// LOGIN CHECK

$login = check_current_user_login($ARR_USERS, $SALT);
$currentuser = $login['user'];
//var_dump($login);
if ($login['status'] == 200) {
    
} else {
    header('location: login.php');
    exit;
}

$corresponding = json_decode(file_get_contents('data/Corresponding.json'));
foreach ($corresponding as $r){ 
	$corresponding_id[$r->id] = $r;
        $corresponding2[ (int) filter_var($r->fullname, FILTER_SANITIZE_NUMBER_INT)] = $r;
}

if($_GET['newconsignee'] == 1){
    $data = json_decode(file_get_contents($file), true);
    $csv = array();
    $lines = file('import.csv', FILE_IGNORE_NEW_LINES);

    foreach ($lines as $key => $value)
    {
        $csv[$key] = str_getcsv($value);
    }
    unset($csv[0]);
    $id = time();
    foreach ($csv as $r){
        $id++;
        foreach($r as $key => $r1){
            $r[$key] = trim($r1);
        }
        $corresponding_id = array();
        foreach ($corresponding as $ra){ 
            if(stripos($ra->fullname,$r[2]) !== false){
                $corresponding_id[] = $ra->id;
            }
        }
        
        
         $formdata = array(
                'id' => $id
		, 'PortofDeparture' => $r[4]
                , 'DestinationPort' => $r[5]
                , 'tax' => $r[6]
                , 'currency' => '1560828928'
                , 'paidunpaid' => $r[7]
                , 'ContractNo' => $r[1]
                , 'ContactUnit' => $corresponding_id
                , 'corresponding' => $r[2]
                , 'ProductName' => $r[3]
		, 'DutiableValue' => $r[8]
		, 'Paid' => $r[9]
                , 'unpaid' => $r[10]
                , 'SecondPayeePayer' => $r[11]
                , 'remark' => ''
                
                
		, 'createdby' => $currentuser->name
		, 'createddate' => $id
		, 'modifieddate' => '' 				
		, 'filename' => '' 	
		, 'filetype' => '' 	
		, 'filesize' => '' 	
		, 'filetimeupload' => '' 	
		, 'filecreatebyid' => '' 	
		, 'filecreatebyname' => '' 	
		, 'filepath' => '' 	
	);
        $data[] = $formdata;
    }
 
    
    
    $convert_array_to_json = array_values($data);
    $write_json = json_encode($convert_array_to_json);
    file_put_contents($file, $write_json);
    die;
}
// 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: newconsignee.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);
$currency = json_decode(file_get_contents('data/Currency.json'), true);

$customer = json_decode(file_get_contents('data/Customer.json'));
$departure = json_decode(file_get_contents('data/Departure.json'));
$product = json_decode(file_get_contents('data/Product.json'));
foreach ($customer as $r){
    $customername[$r->id] = $r->fullname;
}
foreach ($departure as $r){
    $departurename[$r->id] = $r->port;
}
foreach ($product as $r){
    $productname[$r->id] = $r->name;
}
$stt = 1;
foreach ($data as $r){
	if( $_POST['location'] == $r['location']  ){
		$stt++;
	}
}
$stt =  $_POST['location'].str_pad( $stt , 5, '0', STR_PAD_LEFT); 

if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['ContractNo'] != ''   ) {
	$id = time();
	if(count((array)$_FILES['fileupload']['name']) > 0){
			 foreach ($_FILES['fileupload']['name'] as $filekey => $fileu){
				if($_FILES['fileupload']['error'][$filekey] != 0 || strpos($_FILES['fileupload']['filetype'][$filekey],'application/octet-stream') !== false || strpos($fileu,'.php') !== false || strpos($fileu,'.html') !== false ){ continue; }
				
				 $filename_text = time().'_'.$fileu;
				 $filename[] = $fileu;
				 $filetype[] = $_FILES['fileupload']['type'][$filekey];
				 $filesize[] =  $_FILES['fileupload']['size'][$filekey];
				 $filetimeupload[] = time();
				 $filecreatebyid[] = $currentuser->id;
				 $filecreatebyname[] = $currentuser->name;
				 $filepath[] = $filename_text;
				 copy( $_FILES['fileupload']['tmp_name'][$filekey] , '../Docs/uploads/'.$filename_text );
			 }
			
	}
		
	if($_POST['id'] == ''){	
   	
        $formdata = array(
        'id' => $id
		, 'PortofDeparture' => $_POST['PortofDeparture'] 
        , 'DestinationPort' => $_POST['DestinationPort']
        , 'tax' => $_POST['tax']
                , 'currency' => $_POST['currency']
                , 'paidunpaid' => $_POST['paidunpaid']
                , 'ContractNo' => $_POST['ContractNo']
                , 'ContactUnit' => $_POST['ContactUnit']
                , 'ProductName' => $_POST['ProductName']
                
		, 'DutiableValue' => $_POST['DutiableValue']
		, 'Paid' => $_POST['Paid']
                , 'unpaid' => $_POST['unpaid']
                , 'SecondPayeePayer' => $_POST['SecondPayeePayer']
                , 'remark' => $_POST['remark']
                
                
		, 'createdby' => $currentuser->name
		, 'createddate' => $id
		, 'modifieddate' => '' 				
		, 'filename' => $filename
		, 'filetype' => $filetype
		, 'filesize' => $filesize
		, 'filetimeupload' => $filetimeupload
		, 'filecreatebyid' => $filecreatebyid
		, 'filecreatebyname' => $filecreatebyname
		, 'filepath' => $filepath
		);
		$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){
                    
                    
              
//                    foreach ($product as $k){
//                        if($k->name == $arr_data[$key]['ProductName']){
//                            $arr_data[$key]['ProductName'] = $k->id;
//                            break;
//                        }
//                    }
//                     foreach ($departure as $k){
//                        if($k->port == $arr_data[$key]['PortofDeparture']){
//                            $arr_data[$key]['PortofDeparture'] = $k->id;
//                            break;
//                        }
//                    }
//                     foreach ($departure as $k){
//                        if($k->port == $arr_data[$key]['DestinationPort']){
//                            $arr_data[$key]['DestinationPort'] = $k->id;
//                            break;
//                        }
//                    }
//                     foreach ($customer as $k){
//                        if($k->fullname == $arr_data[$key]['SecondPayeePayer']){
//                            $arr_data[$key]['SecondPayeePayer'] = $k->id;
//                            break;
//                        }
//                    }

               



                                
			if($r['id'] == $_POST['id'] ){
				// write logs
				foreach ($arr_data[$key] as $keylog => $logs ){
                                        if($keylog == 'modifiedby' || $keylog == 'createdby' || $keylog == 'createddate' || $keylog == 'modifieddate' || $keylog == 'modifiedby'  ){
                                            continue;
                                        }
						if(is_array($_POST[$keylog])){
							$_POST[$keylog] = implode(', ',$_POST[$keylog]);
							$logs = implode(', ',$logs);
						}
						if( $_POST[$keylog] != $logs){
								
								if($_POST[$keylog] == ''){ 
									$textlog = date('Y-m-d H:i:s').' - '.$currentuser->name.': changed '.$keylog.' from '.$logs.' to empty'  ;
								}else{
									$textlog = date('Y-m-d H:i:s').' - '.$currentuser->name.': changed '.$keylog.' from '.$logs.' to '.$_POST[$keylog]  ;
								}
								file_put_contents('logsnewconsignee/'.$_POST['id'],file_get_contents('logs/'.$_POST['id']).$textlog.PHP_EOL,8);
						}
					
					
				}
                                
                                if(!is_countable($_POST['ContactUnit'])){
                                    $_POST['ContactUnit'] = array($_POST['ContactUnit']);
                                }
				$arr_data[$key]['PortofDeparture'] = $_POST['PortofDeparture'];
                                $arr_data[$key]['DestinationPort'] = $_POST['DestinationPort'];
                                $arr_data[$key]['tax'] = $_POST['tax'];
                                $arr_data[$key]['ContractNo'] = $_POST['ContractNo'];
                                if($_POST['ContactUnit']){
                                    $arr_data[$key]['ContactUnit'] = $_POST['ContactUnit'];
                                    $arr_data[$key]['corresponding'] = '';
                                }
                                $arr_data[$key]['ProductName'] = $_POST['ProductName'];
                                
                                
                           
                                $arr_data[$key]['currency'] = $_POST['currency'];
                                $arr_data[$key]['DutiableValue'] = $_POST['DutiableValue'];
                                $arr_data[$key]['Paid'] = $_POST['Paid'];
                                $arr_data[$key]['unpaid'] = $_POST['unpaid'];
                                $arr_data[$key]['SecondPayeePayer'] = $_POST['SecondPayeePayer'];
                                $arr_data[$key]['unpaid'] = $_POST['unpaid'];
                                $arr_data[$key]['paidunpaid'] = $_POST['paidunpaid'];
				$arr_data[$key]['remark'] = $_POST['remark'];
				$arr_data[$key]['modifieddate'] = $id;
				$arr_data[$key]['modifiedby'] = $currentuser->name;
				$arr_data[$key]['contracttermsstart'] = $_POST['contracttermsstart'];
				$arr_data[$key]['contracttermsend'] = $_POST['contracttermsend'];
				if(count((array)$filename) > 0){
					$arr_data[$key]['filename'] = $filename;
					$arr_data[$key]['filetype'] = $filetype;
					$arr_data[$key]['filesize'] = $filesize;
					$arr_data[$key]['filetimeupload'] = $filetimeupload;
					$arr_data[$key]['filecreatebyid'] = $filecreatebyid;
					$arr_data[$key]['filecreatebyname'] = $filecreatebyname;
					$arr_data[$key]['filepath'] = $filepath;
				}
			}
		}
	}
  
    $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: newconsignee.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>

$(document).ready(function(){
    $('select:not(".exclude"), .dgjksd').formSelect();
    $('select.exclude ').select2({width: '100%'});
    $('select:not(".exclude")').formSelect();
    $('.class1as').trigger('click');
});
function editb(id) {
	var obj = jQuery.parseJSON(id);
	$('#idbad').val(obj.id);
	$('#PortofDeparture,#DestinationPort,#tax,#remark,#paidunpaid,#DutiableValue,#Paid,#unpaid,#SecondPayeePayer,#ContractNo,#ContactUnit,#ProductName').next().addClass('active');
	$('#PortofDeparture').val(obj.PortofDeparture);
	$('#DestinationPort').val(obj.DestinationPort);
	$('#tax').val(obj.tax);
        $('#paidunpaid').val(obj.paidunpaid);
        $('#DutiableValue').val(obj.DutiableValue);
        $('#Paid').val(obj.Paid);
        $('#unpaid').val(obj.unpaid);
        $('#currency').val(obj.currency);
        $('#SecondPayeePayer').val(obj.SecondPayeePayer);
         
        $('#ContractNo').val(obj.ContractNo);
        $('#ContactUnit').val(obj.ContactUnit);
        $('#ProductName').val(obj.ProductName);
         
         
	$('#remark').val(obj.remark);
        $('select.exclude').select2({width: '100%'});
	$('#paidunpaid').formSelect();
}
function editc(id) {

var obj = jQuery.parseJSON(id);
$('#name').next().addClass('active');
$('#acronym').next().addClass('active');
$('#contracttermsstart').next().addClass('active');
$('#contracttermsend').next().addClass('active');
$('#id').val(obj.id);

$('#contracttermsstart').val(obj.contracttermsstart);
$('#contracttermsend').val(obj.contracttermsend);

$('#name').val(obj.name);
$('#acronym').val(obj.acronym);
$('#invoicetype').val(obj.invoicetype);
$("#location").val(obj.location).change();
$("#agent").val(obj.agent).change();
$("#remarkdsa").val(obj.remark);
for (var i = 0; i < 5; i++){
	if( obj.cusfrom[i] != '' ){
		if(i > 0){
			$(".addmore").trigger('click');
		}
		$('#cusfrom'+i).val(obj.cusfrom[i]);
		$('#custo'+i).val(obj.custo[i]);
		$('#cusprice'+i).val(obj.cusprice[i]);
		$('#cuscurrency'+i).val(obj.cuscurrency[i]);
		$('.isblock'+i+' label').addClass('active');
	}
}
//$("#remarkdsa").val(obj.remark);

$('input:radio[name="type"][value='+obj.type+']').prop('checked', true);


$("#dayofmonth").val(obj.dayofmonth).change();
$('select:not(".exclude")').formSelect();
}  

</script> 
<div class="row">
<div class="s12">
    <ul style="   display:none; border-bottom: 2px solid #e2e2e2;background:#eeeeee;align-items:center;height:unset;<?php if($_GET['none']) ?>" class="tabs">
         <li data-tab="tab-0" class="tab-link class1as current" style="background: #fcff77;" ><?php echo $i18n['Blacklist']; ?></li>
        <li data-tab="tab-1" class="tab-link   "><?php echo $i18n['Current']; ?></li>
       
		<li data-tab="tab-2" class="tab-link  " style="background: #ffcaca;color: #000;" ><?php echo $i18n['Dangerous']; ?></li>
		<li data-tab="tab-3" class="tab-link  " style="background: #cfffca;color: #000;" ><?php echo $i18n['Controversial']; ?></li>
    </ul>
</div>	
<div class="tab-content col s12" id="tab-0" style="    padding: 0;">	
<?php if( $currentuser->customer  == '1' || $currentuser->gm == 1 ){ ?>
		<div class="badge grey lighten-3 create-user" style="padding: 0px 15px;float: left;    width: 100%;padding-top: 22px;">
			<form action="" method="POST"  enctype="multipart/form-data"  >
				<input value=""  id="idbad" name="id" type="hidden"  />
				<input value="1"  id="blacklist" name="blacklist" type="hidden"  />
                                
                          <div class="input-field col s1">
                        <input 
                            value="" 
                            id="ContractNo" 
                            name="ContractNo" 
                            type="text" 
                            class="validate" 
                           
                            data-length="32" 
                              autocomplete="off"  />
                        <label for="ContractNo">合同号</label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                          
                        </span>
                    </div> 	   
                                
                                  <div class="input-field col s1 fdsjkbfkjds">
                   
                        <select name="ContactUnit[]" id="ContactUnit"  class="exclude" multiple >  
							<option value="">-----往来单位-----</option>       
							<?php foreach ($corresponding as $rp){
                                                        if($rp->accept == 1){
                                                            ?>
							<option value="<?php echo $rp->id; ?>"><?php echo $rp->fullname; ?></option>  
                                                        <?php }} ?>	
					</select>	
                        <label for="ContactUnit">往来单位</label>
                       
                                  </div>
                                
                                 <div class="input-field col s1">
                                     
                                         <select name="ProductName" id="ProductName"  class="exclude"  >  
							<option value="">-----品名-----</option>       
							<?php foreach ($product as $rp){ ?>
							<option value="<?php echo $rp->id; ?>"><?php echo $rp->name; ?></option>  
                                                        <?php } ?>	
					</select>	
                     
                        <label for="ProductName">品名</label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                          
                        </span>
                                  </div>
                                
                                <div class="input-field col s1">
                                    
                                      <select name="PortofDeparture" id="PortofDeparture"  class="exclude"  >  
							<option value="">-----起运港-----</option>       
							<?php foreach ($departure as $rp){ ?>
							<option value="<?php echo $rp->id; ?>"><?php echo $rp->idport.'-'.$rp->port; ?></option>  
                                                        <?php } ?>	
					</select>	
                        
                        <label for="PortofDeparture">起运港</label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                          
                        </span>
                    </div> 	
				<div class="input-field col s1">
                                      <select name="DestinationPort" id="DestinationPort"  class="exclude"  >  
							<option value="">-----目的港-----</option>       
							<?php foreach ($departure as $rp){ ?>
							<option value="<?php echo $rp->id; ?>"><?php echo $rp->idport.'-'.$rp->port; ?></option>  
                                                        <?php } ?>	
					</select>	
                      
                        <label for="DestinationPort">目的港</label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                          
                        </span>
                    </div> 			
		    <div class="input-field col s1">
                        <input 
                            value="" 
                            id="tax" 
                            name="tax" 
                            type="text" 
                            class="validate" 
                            
                              autocomplete="off"  />
                        <label for="tax">税金</label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                           
                        </span>
                    </div> 
                    <div class="input-field col s1">
                    <select name="paidunpaid" id="paidunpaid"  tabindex="-1">       
                        <option value="" ></option>
                        <option value="Yes" >Yes</option>
                        <option value="No" >No</option>
                    </select>
                        <label for="liabilities">已付/未付</label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                           
                        </span>
                    </div> 
                    <div class="input-field col s1">
                        <input 
                            value="" 
                            id="DutiableValue" 
                            name="DutiableValue" 
                            type="text" 
                            class="validate"                             
                              autocomplete="off"  />
                        <label for="DutiableValue">完税价格</label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                           
                        </span>
                    </div> 
                                <div class="input-field col s1">
                        <input 
                            value="" 
                            id="Paid" 
                            name="Paid" 
                            type="text" 
                            class="validate" 
                            
                              autocomplete="off"  />
                        <label for="Paid">已付</label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                           
                        </span>
                    </div> 
                                <div class="input-field col s1">
                        <input 
                            value="" 
                            id="unpaid" 
                            name="unpaid" 
                            type="text" 
                            class="validate" 
                            
                              autocomplete="off"  />
                        <label for="unpaid">未付</label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                           
                        </span>
                    </div> 
                                
                    <div class="input-field col s1">
                        <select name="currency" id="currency"  tabindex="-1">                           
                        <?php foreach($currency as $r){	?>
                            <option value="<?php echo $r['id']; ?>" <?php echo $sel; ?> ><?php echo $r['currency']; ?></option>
                        <?php } ?>	
                        </select>
                    </div> 
                                
                    <div class="input-field col s1">
                        <select name="SecondPayeePayer" id="SecondPayeePayer" class="exclude" >
								<option value="" >第二抬头/收付款人</option>
								<?php foreach ($customer as $r){ if($r == ''){continue;} ?>
									<option value="<?php echo $r->id; ?>" ><?php echo $r->fullname; ?></option>
								<?php } ?>				
							</select>		
                     
                        <label for="SecondPayeePayer">第二抬头/收付款人</label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                          
                        </span>
                    </div> 		            
                                
                                
					
					<div class="input-field col s3">
						<input 
                            value="<?php echo @$_POST['remark']; ?>" 
                            id="remark" 
                            name="remark" 
                            type="text" 
                            class="validate" 
                          
                           autocomplete="off"  />
                        <label for="remark"><?php echo $i18n["Remarks"]; ?></label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                            
                        </span>
					</div> 
                                
					<div class="input-field col s3  dhkasbdbas"  >
						<div class="file-field">
							<div class="btn btn-primary btn-sm float-left" style="padding: 3px;" >
								  <span><?php echo $i18n['Choose file']; ?></span>
								  <input type="file"  name="fileupload[]"  id="fileupload"  multiple="multiple" >
							</div>
							<div class="file-path-wrapper">
								  <input class="file-path validate" type="text" placeholder=" 附件/海关进口VAT 税单+付款水单">
							</div>
						</div>
					
					</div>	
					 <div class="input-field col s1" style="    text-align: right;">
                        <button class="colortoptran btn waves-effect waves-light" type="submit" name="action">
                            <?php echo $i18n['Save New Issue']; ?>
                        </button>
                    </div>
                    <div class="input-field col s1 ">
                        <a style="    background: #4e4e4e;" class="btn  btn-default waves-effect waves-light" href="./index.php">
                            <?php echo $i18n['Go Back']; ?>
                        </a>
                    </div>
			</form>
		</div>
<?php } ?>		
  		<table class="striped responsive-table  tablesorter" >
            <thead>
                <tr>
                    <th >序号</th>
                    <th >合同号</th>
                    <th class="sbnkln" style="    width: 140px;">
                        <select class="exclude" style="display:none;"  onchange="jQuery('.dnoon').val(jQuery(this).val());jQuery('.dnoon').change();">  
							<option value="">-----往来单位-----</option>       
							<?php foreach ($corresponding as $rp){
                                                        if($rp->accept == 1){
                                                            ?>
							<option value="<?php echo str_replace(array('0','1','2','3','4','5','6','7','8','9'),'',$rp->fullname); ?>"><?php echo $rp->fullname; ?></option>  
                                                        <?php }} ?>	
					</select>	
                        <input style="display:none;" class="dnoon" ref="1" type="text" placeholder="搜: 往来单位" /></th>
                    <th style="    width: 240px;"  >品名</th>
                    <th >起运港</th>
                    <th >目的港</th>
                        


                    <th>税金</th>
                    <th>已付/未付</th>
                    <th style="    width: 140px;" >完税价格</th>					
                    <th style="    width: 120px;">已付 </th>
                    <th style="    width: 120px;">未付</th>			
                    <th>第二抬头/收付款人</th>
                    <th style="    width: 200px;" >备注</th>	
                    <th>附件/海关进口VAT<br>税单+付款水单</th>	
                    <th><?php echo $i18n["Modified"]; ?></th>
                    <th></th>
                </tr>
            </thead>
        <tbody>
   <?php 
     $total_receivable = $total_amount = $total_profit = 0;
     $countNo = 0; $i = 0;
	 
	$tt0 = $tt1 = $tt2 = $tt3 = 0;
	 
        foreach ($data as $key => $values) {   
		     $toast = 'M.toast({html: "<span>' . $values['name'] . '</span>' .
                    '<a href=\"?delete_id=' . $values['id'] . '\" class=\"toast-action\">' .
                    $i18n['DELETE'] . '</a> &nbsp; &nbsp;"});';
					$file = '';
					foreach ($values['filename'] as $keyfile => $dataf ){
										$fnjf++;
										if ( strpos($values['filetype'][$keyfile] , 'pdf')  !== false ) {												
												
												if( $currentuser->location == '中国' ){
													$file .=  '<a ref="https://htlservice.net/Docs/uploads/'.rawurlencode($values['filepath'][$keyfile]).'" data-target="readfile" class="modal-trigger isreadder'.$fnjf.'" isreadder="'.$fnjf.'" href="javascript:void(0);" onclick="$(\'.isleft,.isright\').attr(\'nextread\',\''.$fnjf.'\');$(\'.iframereadfile\').attr(\'src\',$(this).attr(\'ref\'));" ><img src="https://htlservice.net/Docs/tpl/img/pdf.png" style="width:24px;height:auto;" /></a>';
												}else{
													$file .=  '<a ref="https://drive.google.com/viewerng/viewer?url=https://htlservice.net/Docs/uploads/'.urlencode($values['filepath'][$keyfile]).'?pid=explorer&efh=false&a=v&chrome=false&embedded=true" data-target="readfile" class="modal-trigger isreadder'.$fnjf.'" isreadder="'.$fnjf.'" href="javascript:void(0);" onclick="$(\'.isleft,.isright\').attr(\'nextread\',\''.$fnjf.'\');$(\'.iframereadfile\').attr(\'src\',$(this).attr(\'ref\'));" ><img src="https://htlservice.net/Docs/tpl/img/pdf.png" style="width:24px;height:auto;" /></a>';
												}
										} elseif ( strpos($values['filetype'][$keyfile] , 'sheet')  !== false || strpos($values['filepath'][$keyfile] , '.xls')  !== false ) { 
												$file .=  '<a ref="https://view.officeapps.live.com/op/embed.aspx?src=https://htlservice.net/Docs/uploads/'.$values['filepath'][$keyfile].'" data-target="readfile" class="modal-trigger isreadder'.$fnjf.'" isreadder="'.$fnjf.'" href="javascript:void(0);" onclick="$(\'.isleft,.isright\').attr(\'nextread\',\''.$fnjf.'\');$(\'.iframereadfile\').attr(\'src\',$(this).attr(\'ref\'));" ><img src="https://htlservice.net/Docs/tpl/img/excel.png" style="width:24px;height:auto;" /></a>';
										} elseif ( strpos($values['filetype'][$keyfile] , 'zip')  !== false ) { 
												$file .=  '<a download href="uploads/'.$values['filepath'][$keyfile].'" ><img src="https://htlservice.net/Docs/tpl/img/zip.png" style="width:24px;height:auto;" /></a>';
										} elseif ( strpos($values['filetype'][$keyfile] , 'doc')  !== false ) { 
												$file .=  '<a ref="https://view.officeapps.live.com/op/embed.aspx?src=https://htlservice.net/Docs/uploads/'.$values['filepath'][$keyfile].'" data-target="readfile" class="modal-trigger isreadder'.$fnjf.'" isreadder="'.$fnjf.'"  href="javascript:void(0);" onclick="$(\'.isleft,.isright\').attr(\'nextread\',\''.$fnjf.'\');$(\'.iframereadfile\').attr(\'src\',$(this).attr(\'ref\'));" ><img src="https://htlservice.net/Docs/tpl/img/word.png" style="width:24px;height:auto;" /></a>';
										} elseif ( strpos($values['filetype'][$keyfile] , 'image')  !== false ) { 
												$file .=  '<a ref="https://htlservice.net/Docs/uploads/'.$values['filepath'][$keyfile].'" data-target="readfile" class="modal-trigger isreadder'.$fnjf.'" isreadder="'.$fnjf.'" href="javascript:void(0);" onclick="$(\'.isleft,.isright\').attr(\'nextread\',\''.$fnjf.'\');$(\'.iframereadfile\').attr(\'src\',$(this).attr(\'ref\'));"  ><img src="https://htlservice.net/Docs/tpl/img/png.png" style="width:24px;height:auto;" /></a>';
										} else{
												$file .=  '<a download href="https://htlservice.net/Docs/uploads/'.$values['filepath'][$keyfile].'" ><img src="https://htlservice.net/Docs/tpl/img/file.png" style="width:24px;height:auto;" /></a>';
										}
					}
					 foreach($currency as $r){ 
						if($values['currency'] == $r['id']){
							$currencyname = $r['currency'];
							$exchangerate =  $r['exchangerate'];
						}
					 }
					
					$total += (float)str_replace(',','',$values['liabilities'])*(float)$exchangerate;
				
	            ?>    
                <tr>
                    <td  style="padding-left:6px"><?php echo ++$k; ?> </td>
                    <td  style="padding-left:6px"><?= $values['ContractNo'] ?> </td>
                    <td  style="padding-left:6px"><?php  $testname = 0;
                            foreach ($values['ContactUnit'] as $rcorresponding){
                                   echo '<a data-target="modal8" class="modal-trigger " ref="'.$rcorresponding.'" title="Code/代码：'.$corresponding_id[$rcorresponding]->code.'&#010;Abbreviation/简称：'.$corresponding_id[$rcorresponding]->abbreviation.'&#010;Fullname/全名:：'.$corresponding_id[$rcorresponding]->fullname.' " >'.$corresponding_id[$rcorresponding]->fullname.'</a> ';
                            }
                            if(count((array)$values['ContactUnit']) == 0){
                                echo $values['corresponding'];
                            }
                            
                            
                    ?> </td>
                    <td  style="padding-left:6px"><?php $ProductName[$values['ProductName']] =  $values['ProductName'];
                    echo  $productname[$values['ProductName']];
                    
                    
                    ?> </td>
                    <td  style="padding-left:6px"><?php $PortofDeparture[$values['PortofDeparture']] = $values['PortofDeparture']; echo $departurename[$values['PortofDeparture']]; ?> </td>
                    <td  style="padding-left:6px"><?php $PortofDeparture[$values['DestinationPort']] = $values['DestinationPort']; echo $departurename[$values['DestinationPort']]; ?> </td>
                    <td style="padding-left:6px"><?php if($values['tax']){ $tt0 += (float)str_replace(',','',$values['tax']);  echo $values['tax']; ?> <?= $currencyname; } ?></td>
					
                    <td style="padding-left:6px"><?= $values['paidunpaid']?></td>
					<td style="padding-left:6px"><?php if($values['DutiableValue']){ $tt1 += (float)str_replace(',','',$values['DutiableValue']); echo $values['DutiableValue'];  ?> <?= $currencyname; } ?></td>
                                        <td style="padding-left:6px"><?php if($values['Paid']){ $tt2 += str_replace(',','',$values['Paid']); echo $values['Paid'];?> <?= $currencyname; } ?></td>
                                        <td style="padding-left:6px"><?php if($values['unpaid']){ $tt3 += str_replace(',','',$values['unpaid']); echo $values['unpaid'];?> <?= $currencyname; } ?></td>
                                        <td style="padding-left:6px"><?php $SecondPayeePayer[$values['SecondPayeePayer']] = $values['SecondPayeePayer'];  echo $customername[$values['SecondPayeePayer']];?></td>
					
					<td style="padding-left:6px"><?= $values['remark']?></td>
                                        <td style="padding-left:6px"><?php echo $file;  ?></td>
                    <td style="padding-left:6px"><a title="<?= date('d/m/y h:i',$values['createddate']); ?>" ><?= $values['createdby']?></a></td>
					
					
                    <td style="padding-left:6px">
                        
                        <?php 
                                if ($currentuser->gm == '1' && file_exists("logsnewconsignee/".$values['id'])) {
                                $logs = file_get_contents("logsnewconsignee/".$values['id']);
                                $logs = str_replace(PHP_EOL,'<br>',$logs);
                                $logsmode = '<a  href="#" data-target="modal6" class="modal-trigger cllogcontent" ><span style="display:none;" >'. $logs .'</span><i class="grey-text small material-icons">content_paste</i></a>';
                        }else{
                                $logsmode = '';
                        } 
                        
                        echo $logsmode;
                        ?>
						<?php if( $currentuser->gm == 1){  ?>
                        <a class="tooltipped" data-position="top" data-tooltip="<?= $i18n['Click alert link for delete!']?>" href="#" onclick='<?php echo $toast; ?>' >
                            <i class="red-text text-darken-4 small material-icons">delete_forever</i>
                        </a>
						<?php } ?>
						<?php if( $currentuser->customer  == '1' || $currentuser->gm == 1 ){ ?>
                        <a class="tooltipped" data-position="top" data-tooltip="<?= $i18n['EDIT'] ?>" href="#" onclick='editb("<?php echo addslashes(json_encode($values)); ?>")'>
                            <i class="grey-text small material-icons">mode_edit</i>
                        </a>
						<?php  } ?>
                    </td>
                </tr>
            <?php  }  ?>
        </tbody>
		<tfoot>
			<tr>
				<td></td>
				
				<td></td>
				<td style="padding-left:6px;font-weight:bold;"></td>
				<td></td>
                                <td></td>
                                <td><b style="float:right;" >Total/总:</b></td>
                                <td><span class="p1" ><?= $currencyname;?> <?php echo number_format((float)$tt0,2); ?></span></td>
				<td></td>
				<td><span class="p2" ><?= $currencyname;?> <?php echo number_format((float)$tt1,2); ?></span></td>
				
				<td><span class="p3"><?= $currencyname;?> <?php echo number_format((float)$tt2,2); ?></span></td>
				<td><span class="p4" ><?= $currencyname;?> <?php echo number_format((float)$tt3,2); ?></span></td>
                                <td></td>
                                <td></td>
			</tr>
		</tfoot>
        </table>
</div>    
    

	

</div>	
<script>
$(document).ready(function(){   
<?php if ($currentuser->gm == "1"  ){ ?>	
	$(".cllogcontent").click(function(){
		$(".logcontent").html($(this).find('span').html());
	});	
	<?php } ?>
	
jQuery( "body" ).delegate( ".departure , .arrival  ", "change", function() {	
	if($(this).val() == 'addnew' ){
		$(this).parents().eq(0).hide();
		$(this).parents().eq(1).find('.cblockadd').fadeIn();
	}
});



	var tt = 1;
	$(".addmore").click(function(){ 
		if(tt < 5){
			$(".isblock"+tt).show();
			tt++;
		}else{
			alert('Maximum/最大值');
		}
	});
	$(".removecusprice").click(function(){
		$(this).parents().eq(1).find('input').val('');
		$(this).parents().eq(1).hide();
		tt--;
	});
	$(".nofulltext").each(function(){
		if($(this).text().length < 9 && $(window).width() >= 1400){
			$(this).next().hide();
		}		
		if($(this).text().length < 9 && $(window).width() < 1400){
			$(this).next().hide();
		}
	});
	$('.fa-sort-down').click(function(){
		if($(this).hasClass('active')){
			$(this).parents().eq(1).find('.nofulltext').removeAttr('style');
			$(this).parents().eq(1).find('.fa-sort-down').removeClass('active');
		}else{
			$(this).parents().eq(1).find('.nofulltext').css('height','auto');
			$(this).parents().eq(1).find('.fa-sort-down').addClass('active');
		}
	});
	$('.isleft').click(function(){
		if($('.isreadder'+$(this).attr('nextread')).prev().hasClass('modal-trigger')){
			$('.isreadder'+$(this).attr('nextread')).prev().trigger('click');
		}
	});
	$('.isright').click(function(){
		if($('.isreadder'+$(this).attr('nextread')).next().hasClass('modal-trigger')){
			$('.isreadder'+$(this).attr('nextread')).next().trigger('click');
		}
	});
});
$("input[data-type='currency']").each(function(){
			formatCurrency($(this)); 
		});
                
                
                
	$(".dnoon").on('keyup change',function(){
		  var input, filter, table, tr, td, i, txtValue;
		  input = $(this).val();
		  filter = input.toUpperCase();
		  table = $(this).parents('table');
		  tr = table.find('tbody tr');
                    var tt1 = 0;
                  var tt2 = 0;
                   var tt3 = 0;
                    var tt4 = 0;
		  for (i = 0; i < tr.length; i++) {
				if($(this).attr('ref') == 1){
					td = tr[i].getElementsByTagName("td")[2];
				}
				
			   
			   if (td) {
				  txtValue = td.textContent || td.innerText;
                                  

				  if (txtValue.toUpperCase().indexOf(filter) > -1) {
					tr[i].style.display = "";
					tr[i].style.display = "";
                                        
                                            var mmn = tr[i].getElementsByTagName("td")[6].textContent;
                                            mmn = mmn.replace(",", "");
                                            mmn = mmn.replace(",", "");
                                            mmn = mmn.replace(",", "");
                                            mmn = mmn.replace(" VND", "");
                                            mmn = mmn.replace(" RMB", "");
                                            mmn = mmn.replace(" USD", "");
                                            mmn = parseFloat(mmn);
                                            //alert(mmn);
                                            if(isNaN(mmn) === false){
                                            tt1 += mmn;
                                            }
                                            
                                            var mmn = tr[i].getElementsByTagName("td")[8].textContent;
                                            mmn = mmn.replace(",", "");
                                            mmn = mmn.replace(",", "");
                                            mmn = mmn.replace(",", "");
                                            mmn = mmn.replace(" VND", "");
                                            mmn = mmn.replace(" RMB", "");
                                            mmn = mmn.replace(" USD", "");
                                            mmn = parseFloat(mmn);
                                            //alert(mmn);
                                            if(isNaN(mmn) === false){
                                            tt2 += mmn;
                                            }
                                            
                                            var mmn = tr[i].getElementsByTagName("td")[9].textContent;
                                            mmn = mmn.replace(",", "");
                                            mmn = mmn.replace(",", "");
                                            mmn = mmn.replace(",", "");
                                            mmn = mmn.replace(" VND", "");
                                            mmn = mmn.replace(" RMB", "");
                                            mmn = mmn.replace(" USD", "");
                                            mmn = parseFloat(mmn);
                                            //alert(mmn);
                                            if(isNaN(mmn) === false){
                                            tt3 += mmn;
                                            }
                                            
                                            var mmn = tr[i].getElementsByTagName("td")[10].textContent;
                                            mmn = mmn.replace(",", "");
                                            mmn = mmn.replace(",", "");
                                            mmn = mmn.replace(",", "");
                                            mmn = mmn.replace(" VND", "");
                                            mmn = mmn.replace(" RMB", "");
                                            mmn = mmn.replace(" USD", "");
                                            mmn = parseFloat(mmn);
                                            //alert(mmn);
                                            if(isNaN(mmn) === false){
                                            tt4 += mmn;
                                            }
                                            
				  } else {
					tr[i].style.display = "none";
				  }
				}
		  }
                  
                  $('.p1').text((tt1).toLocaleString('en-US', {  style: 'currency',  currency: 'RMB',}));
                  $('.p2').text((tt2).toLocaleString('en-US', {  style: 'currency',  currency: 'RMB',}));
                  $('.p3').text((tt3).toLocaleString('en-US', {  style: 'currency',  currency: 'RMB',}));
                  $('.p4').text((tt4).toLocaleString('en-US', {  style: 'currency',  currency: 'RMB',}));
                  
	});	
        
        
		$("input[data-type='currency']").on({
            keyup: function() {
            formatCurrency($(this));
        },
			blur: function() { 
			formatCurrency($(this), "blur");
        }
        });
        function formatNumber(n) {
            return n.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")
        }
		function formatCurrency(input, blur) {                             
			var input_val = input.val(); 
			if (input_val === "" || input_val == "0.00") { return; }
				var original_len = input_val.length;
				var caret_pos = input.prop("selectionStart");
			if (input_val.indexOf(".") >= 0) {
				var decimal_pos = input_val.indexOf(".");
				var left_side = input_val.substring(0, decimal_pos);
				var right_side = input_val.substring(decimal_pos);
				left_side = formatNumber(left_side);
				right_side = formatNumber(right_side);
				if (blur === "blur") {
					// right_side += "00";
				}
				right_side = right_side.substring(0, 2);
				input_val =  left_side + "." + right_side;
			} else {
				input_val = formatNumber(input_val);
				input_val =  input_val;
				// final formatting
				if (blur === "blur") {
				//input_val += ".00";
				}
			}
			input.val(input_val);
			var updated_len = input_val.length;
			caret_pos = updated_len - original_len + caret_pos;
			input[0].setSelectionRange(caret_pos, caret_pos);
			}
			
</script>
<style>
table thead tr th {
    position: sticky;
    z-index: 100;
    top: 0;
}
.dropdown-content li>a, .dropdown-content li>span {   
    padding: 7px 16px;
}
.nofulltext { display:block!important; height: 19px; overflow: hidden; width: calc(100% - 20px); float: left; word-break: break-all; }
.nofulltext p {		padding: 0px;		margin: 0px;	}
.input-field {
    position: relative;
    margin-top: 0rem;
    margin-bottom: 0rem;
}
table.tablesorter thead tr th {
    background-color: #ddd;
}
.fdsjkbfkjds .select-dropdown , .sbnkln .select-dropdown {
    display: none!important;
}
.select2-container--open .select2-dropdown--below {
   
    min-width: 250px;
}
.isleft{ width: 50px; height: 50px; position: fixed; left: 15px; top: 45%; z-index: 1000000; font-size: 54px; opacity: 0.2;cursor: pointer; } .isright{ width: 50px; height: 50px; position: fixed; right: 15px; top: 45%; z-index: 1000000; font-size: 54px; opacity: 0.2;cursor: pointer; } .isleft:hover , .isright:hover{ opacity: 0.5; } .isleft i , .isright i { } 
</style>           
<div id="readfile" class="modal" style="    width: 80%!important;" >
			<a onclick="$('.modal-overlay').trigger('click');" style="       background: transparent;    color: red;    font-weight: bold;    font-size: 35px;	    font-family: cursive;    width: 30px;    height: 30px;    top: 0px;    right: 20px;    position: absolute;    left: unset;    bottom: unset;    display: block;    cursor: pointer;" >x</a>
			<iframe class="iframereadfile" src="" width="100%" style="height:auto;    min-height: 550px;" ></iframe>
			<div class="isleft" ><i class="fas fa-chevron-left"></i></div>
			<div class="isright" ><i class="fas fa-chevron-right"></i></div>		
</div>	
<?php if ($currentuser->gm == "1"  ){ ?>	
<div id="modal6" class="modal">
  <div class="logcontent" style="padding: 15px;" ></div>
</div>
<?php } ?>	
<?php
// FOOTER
$id = time();
$data = array();
//foreach ($ProductName as $r){
//        $id++;
//        $formdata = array(
//                'id' => $id
//		, 'productid' => ++$k
//                , 'name' => $r
//               
//	);
//        $data[] = $formdata;
//}
//$convert_array_to_json = array_values($data);
//$write_json = json_encode($convert_array_to_json);
//file_put_contents('data/Product.json', $write_json);


//foreach ($PortofDeparture as $r){
//     $id++;
//      $formdata = array(
//                'id' => $id
//                , 'port' => $r
//	);
//        $data[] = $formdata;
//}

//
//foreach ($SecondPayeePayer as $r){
//     $id++;
//      $formdata = array(
//                'id' => $id
//                , 'fullname' => $r
//	);
//        $data[] = $formdata;
//}
//
//
//$convert_array_to_json = array_values($data);
//$write_json = json_encode($convert_array_to_json);
//file_put_contents('data/Customer.json', $write_json);


include 'tpl/footer.php';
?>
