<?php
date_default_timezone_set('Asia/Bangkok');
error_reporting(E_ALL);
ini_set('display_errors',0);
session_start();
// FOR DEBUG ONLY


// 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/' . $TYPE . '.json'; // DATA FILE NAME
// LOGIN CHECK
$login = check_current_user_login($ARR_USERS, $SALT);
$currentuser = $login['user'];
$currency = json_decode(file_get_contents('data/Currency.json'), true);
$_SESSION['currencyUser'] = '';
if ($currencyUser == ''){
	$currencyUser = '1560828928';
}
if ($_GET['currency'] != ''){
	$currencyUser = $_GET['currency'];
	
	foreach ($currency as $r){
		if($currencyUser == $r['id']){
			$_SESSION['currencyUser'] = $r;
		}
	}
}
if($_SESSION['currencyUser'] == ''){
	foreach ($currency as $r){
		if($currencyUser == $r['id']){
			$_SESSION['currencyUser'] = $r;
		}
	}
}

//var_dump($login);
if ($login['status'] == 200) {   
	if(  $currentuser->gm  != '1'  && $currentuser->condition != 1 ){ 
		header('location: index.php');exit();
	}
} else {
    header('location: login.php');
    exit;
}

$tabs = json_decode(file_get_contents('data/Tabs.json'));
$user = json_decode(file_get_contents('data/User.json'));
$TotalRemark = json_decode(file_get_contents('data/TotalRemark.json'));
$tabdocfull = $tabdoc = json_decode(file_get_contents('data/TabDoc.json'));
$tabfull = $tabs;
$Setting = json_decode(file_get_contents('data/Setting.json'));
$Borrower = json_decode(file_get_contents('data/Borrower.json'), true);
$receiver_payer = json_decode(file_get_contents('data/receiver_payer.json'));
foreach ($receiver_payer as $r){ if( $r->id == '' || $r->name == '' ) { continue; }
	$receiver_payer_name[$r->name] = $r;
	$receiver_payer_id[$r->id] = $r;
}
// READ DATA
$newdata = array();

$data = json_decode(file_get_contents($file), true);

// HEADER
ob_end_flush();

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

include 'tpl/header.php';

if(isset($_POST['datestart'])){
			$datestart = $_POST['datestart'];
}else{
			//$datestart = date('Y.m.d',strtotime("-14 day"));
}		
if(isset($_POST['dateto'])){
			$dateto = $_POST['dateto'];
}else{
			//$dateto = date('Y.m.d');
}

?>
<script type="text/javascript" src="tpl/libs/js-xlsx/xlsx.core.min.js"></script>
<script type="text/javascript" src="tpl/libs/FileSaver/FileSaver.min.js"></script> 
<script type="text/javascript" src="tpl/libs/html2canvas/html2canvas.min.js"></script>
<script type="text/javascript" src="tpl/tableExport.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
<form method="POST" id="formfilter" >
	
<div style=" width: 180px; float:left;    " >
	<b>Date&nbsp; <i class="fa fa-calendar"></i></b>
	<div class="reportrange" style="background: #fff; cursor: pointer; padding: 5px 10px;     border-bottom: 1px solid #b9b9b9;
    margin-top: 11px;" >	 
		<span></span> <i class="fa fa-caret-down"></i>
	</div>
</div>
<div style=" width: 150px; float:left;display:none;" >
	<b>Location/地点</b>
    <select name="location" id="aclocation" >
				<option value="All">All</option>
                <option <?php if($_POST['location'] == '越南' ){ echo "selected"; } ?> value="越南">越南</option>
                <option <?php if($_POST['location'] == '中国' ){ echo "selected"; } ?>value="中国">中国</option>
				<option <?php if($_POST['location'] == '泰国' ){ echo "selected"; } ?> value="泰国">泰国</option>
    </select>            
</div>
<div style=" width: 10%; float:left;    margin-left: 10px;" >
	<b><?php echo $i18n['Accounting']; ?></b>
    <select id="tabexport" name="tabexport[]"  tabindex="-1" multiple  >
				<option class="all" <?php if(in_array( 'All' ,(array)$_POST['charge']) ){ echo "selected"; } ?> value="All">All</option>
				<?php 		
                     foreach($tabs as $tab){						 
						if( $currentuser->gm != 1 && !in_array($tab->id,(array)$currentuser->account) && !in_array($tab->id,(array)$currentuser->accountreadonly) ) { continue; } 
						if(in_array($tab->id  ,(array)$_POST['tabexport']) ){
							echo '<option class="'.$tab->location.'" selected value="'.$tab->id.'">'.$tab->name.'</option>';
						}else{
							echo '<option class="'.$tab->location.'" value="'.$tab->id.'">'.$tab->name.'</option>';
						}
                     }
				?>			
    </select>   
</div>
<div style=" width: 10%; float:left;    margin-left: 10px;" >
	<b><?php echo $i18n['费用归类']; ?></b>
   <select name="classification[]" multiple id="classification"  tabindex="-1"  >       
		<option class="all" <?php if(in_array( 'All' ,(array)$_POST['charge']) ){ echo "selected"; } ?> value="All">All</option>
		<?php 
			$containers_op = $Setting->Container;
			$containers_op = explode(PHP_EOL,$containers_op );
            foreach($containers_op as $container_op ){
				$container_op = explode('|',$container_op );
				$container_op[0] = str_replace(array("\n","\r\n","\r",PHP_EOL,' '), '',$container_op[0]);										
				$container_op[1] = str_replace(array("\n","\r\n","\r",PHP_EOL,' '), '',$container_op[1]);
				$container_op[2] = str_replace(array("\n","\r\n","\r",PHP_EOL,' '), '',$container_op[2]);
            ?> 
                  <option  <?php if(in_array( $container_op[0] ,(array)$_POST['classification'])){ echo "selected"; } ?> value="<?php echo $container_op[0]; ?>" color="<?php echo $container_op[1]; ?>" freetext="<?php echo $container_op[2]; ?>" ><?php $n++; echo $n.'. '; if($i18n[$container_op[0]] != ''){ echo $i18n[$container_op[0]]; }else{ echo $container_op[0]; } ?></option>
                <?php
            }
        ?>

	</select>
</div>
<div style=" width: 11%; float:left;    margin-left: 10px;display:none;" >
	<b><?php echo $i18n['费用明细']; ?></b>
    <select name="charge[]" multiple id="charge"  tabindex="-1"  >    
		
							<option class="all" <?php if(in_array( 'All' ,(array)$_POST['charge']) ){ echo "selected"; } ?> value="All">All</option>                
                       		<?php 
									$subContainer = $Setting->subContainer;
									$subContainers = explode(PHP_EOL,$subContainer );
                                    foreach($subContainers as $subContainer ){
										$subContainer = explode('|',$subContainer );
										$subContainer[1] = str_replace(array("\n","\r\n","\r",PHP_EOL,' '), '',$subContainer[1]);
										if($subContainer[0] != $fgni){
											$fgni = $subContainer[0];
											$dhere = 1;
										}else{
											$dhere++;
										}
										$erjkik[$subContainer[1]] =  $dhere.'. ';
                                        ?> 
                                            <option <?php if(in_array( $subContainer[1] ,(array)$_POST['charge'])){ echo "selected"; } ?>  class="<?php echo $subContainer[0]; ?>" value="<?php echo $subContainer[1]; ?>"><?php echo $dhere; ?> <?php if($i18n[$subContainer[1]] != ''){ echo $i18n[$subContainer[1]]; }else{ echo $subContainer[1]; } ?></option>
                                        <?php
                                    }
                            ?>
							<option  class="novalue" value=""></option>                
	</select>	
</div>
    
<div style=" width: 10%; float:left;    margin-left: 10px;position: relative;" >

        <b><?php echo $i18n["Corresponding"]; ?></b>
	<select name="corresponding[]" id="corresponding"  class="exclude" multiple >  
                        <option value="">-----<?php echo $i18n["Corresponding"]; ?>-----</option>       
                        <?php foreach ($corresponding as $rp){
                        if($rp->accept == 1){
                            ?>
                        <option value="<?php echo $rp->id; ?>" <?php if(in_array($rp->id, (array)$_POST['corresponding'])){ echo 'selected'; } ?> ><?php echo $rp->fullname; ?></option>  
                        <?php }} ?>	
        </select>	
       
</div>
<div style=" width: 10%; float:left;    margin-left: 10px;" >
	<b><?php echo $i18n['凭证号']; ?></b>
	<input 
                        value="<?php echo $_POST['documentnumber']; ?>" 
                        id="documentnumber" 
                        name="documentnumber" 
                        type="text" 
                        class="validate"     
						placeholder="VNG/CNG/THG..."				
    />
</div>
<div style=" width: 10%; float:left;    margin-left: 10px;" >
	<b>Payer/收/付款人</b>
	<select name="payer[]" class="exclude" multiple id="payer"  tabindex="-1"  >    
				<?php 
					foreach ($data as $key => $values){  $rt = '-1';
//                                                if( $currentuser->gm != 1 ){
//						foreach ($tabdocfull as $r){
//							if ( $values['id'] == $r->iddoc ) {
//								$rt = $r->idtab;break;			
//							}
//						}
//                                                }
//						if( $currentuser->gm != 1 && !in_array($rt,(array)$currentuser->account) && !in_array($rt,(array)$currentuser->accountreadonly) ) { continue; } 
						$payer[] =  $values['payer'];
					}
					$payer = array_unique($payer); 
					foreach ($payer as $r){
				?>
				 <option <?php if(in_array( $r ,(array)$_POST['payer'])){ echo "selected"; } ?>   value="<?php echo $r; ?>"><?php echo $r; ?></option>
                                     
				<?php } ?>
	</select>
	
</div>
<?php if($currentuser->gm  == '1'){ ?>
<div style=" width: 10%; float:left;    margin-left: 10px;display: none;" >
	<b>Violations/违规</b>
	<select name="user" id="user">
							<option value="" >------</option>
							<optgroup label="中国">
							<?php foreach($user as $r){ 
									if( $r->location != '中国' || $r->role == 'Manager' ) { continue; }
									if($r->role == 'Finance'){ $r->role= 'Controller'; }
									if($r->role == 'Operator'){ $r->role= 'Finance'; }
									
								?>
								<option value="<?php echo $r->id; ?>"  ><?php echo $r->name.'/'.$r->role; ?></option>
							<?php } ?>
							</optgroup>
							<optgroup label="越南">
							<?php foreach($user as $r){ 
									if( $r->location != '越南' || $r->role == 'Manager' ) { continue; }
									if($r->role == 'Finance'){ $r->role= 'Controller'; }
									if($r->role == 'Operator'){ $r->role= 'Finance'; }
									
								?>
								<option value="<?php echo $r->id; ?>"  ><?php echo $r->name.'/'.$r->role; ?></option>
							<?php } ?>
							</optgroup>
							<optgroup label="泰国">
							<?php foreach($user as $r){ 
									if( $r->location != '泰国' || $r->role == 'Manager'  ) { continue; }
									if($r->role == 'Finance'){ $r->role= 'Controller'; }
									if($r->role == 'Operator'){ $r->role= 'Finance'; }
									
								?>
								<option value="<?php echo $r->id; ?>" ><?php echo $r->name.'/'.$r->role; ?></option>
							<?php } ?>
							</optgroup>
							
     </select>
	 <script>
		$("#user").val('<?php echo $_POST['user']; ?>');
	 </script>
</div>
<?php } ?>
<div style=" width: 105px; float:left;    margin-left: 10px;display:none " >
	<b>摘要</b>
					<label class="pure-material-checkbox" style="margin-top: 16px;" >
							
							<input value="<?php echo $_POST['summary']; ?>" id="summary" name="summary" type="text" class="validate">
						  
					</label>
</div>
<div style=" width: 105px; float:left;    margin-left: 10px;padding-top: 30px;display:none;"  >
					<label class="pure-material-checkbox" style="margin-top: 16px;" >
						  <input type="checkbox"  value="1"  id="idbaddebt" <?php if($_POST['baddebt'] == 1 ){ echo 'checked'; } ?>  name="baddebt"  >
						  <span><?php echo $i18n["坏账损失"];  ?></span>
					</label>
</div>
<div style=" width: 70px; float:left;padding-top: 27px;" >
<button class="colortoptran btn waves-effect waves-light" style="float: right;   " type="submit" name="action"> <?php echo $i18n['Go']; ?> </button>
</div>
<div style=" width: 70px; float:left;padding-top: 27px;margin-left:5px;" >
<button id="btnExport" style="display:none;" class="colortoptran btn waves-effect waves-light" type="button" onclick="fnExcelReport();"> <?php echo $i18n['Excel']; ?> </button>
</div>
	<input value="<?php echo $datestart; ?>" id="datestart" name="datestart" type="hidden" />
	<input value="<?php echo $dateto; ?>" id="dateto" name="dateto" type="hidden" />	
</form>		

<table id="dbsakblk" class="striped responsive-table  tablesorter  " style="width:100%;" >
<thead>
<tr data-tableexport-fillColor="[52, 73, 94]" data-tableexport-textColor="[255, 255, 255]" >
	
	<th style="width: 80px;"><?php echo $i18n['日期'] ?></th>
	<th style="width: 70px;" >地点</th>
	<th style="width: 105px;">帐户</th>
	<th style="width:53px;" ><?php echo $i18n['收/付']; ?></th> 
       
	<th style="width:130px;" >
            <select id="selectdnoon1" onchange="jQuery(this).parents('th').eq(0).find('.dnoon').val(jQuery(this).val()).change();" >
                <option value="">----------</option>  
                <option value="管理费用" color="" freetext="">1 管理费用</option>
                <option value="财务费用" color="" freetext="">2 财务费用</option>
                <option value="应收账款" color="" freetext="freetext">3 应收账款</option>
                <option value="应付账款" color="" freetext="freetext">4 应付账款</option>
                <option value="预收账款" color="" freetext="freetext">5 预收账款</option>
                <option value="预付账款" color="#0000b3" freetext="freetext">6 预付账款</option>
                <option value="借款-支出" color="#ff0000" freetext="freetext">7 借款-支出</option>
                <option value="借款-收入" color="" freetext="freetext">8 借款-收入</option>
                <option value="代收" color="" freetext="freetext">9 代收</option>
                <option value="代付" color="#de7300" freetext="freetext">10 代付</option>
                <option value="内部转账" color="" freetext="freetext">11 内部转账</option>
                <option value="汇入" color="" freetext="freetext">12 汇入</option>
                <option value="汇出" color="" freetext="freetext">13 汇出</option>
                <option value="取现金" color="" freetext="freetext">14 取现金</option>
            </select>
            <input class="dnoon" ref="1" type="text"   style="color: #fff;display:none;"    placeholder="搜: <?php echo $i18n["费用归类"]; ?>" /></th>
	<th style="width:130px;" >
            <div class="asn1" style="color: #fff;" >
            <select id="selectdnoon2" onchange="jQuery(this).parents('th').eq(0).find('.dnoon').val(jQuery(this).val()).change();" >
                <option value="">----------</option>    
                <option class="管理费用" value="工资">1 工资</option>
                <option class="管理费用" value="社保">2 社保</option>
                <option class="管理费用" value="奖金">3 奖金</option>
                <option class="管理费用" value="员工年终奖">4 员工年终奖</option>
                <option class="管理费用" value="房租车租类">5 房租车租类</option>
                <option class="管理费用" value="水电网话物类">6 水电网话物类</option>
                <option class="管理费用" value="差旅费">7 差旅费</option>
                <option class="管理费用" value="办公费">8 办公费</option>
                <option class="管理费用" value="快递费">9 快递费</option>
                <option class="管理费用" value="福利费">10 福利费</option>
                <option class="管理费用" value="服务费-GM">11 服务费-GM</option>
                <option class="管理费用" value="业务费">12 业务费</option>
                <option class="管理费用" value="坏账损失">13 坏账损失</option>
                <option class="管理费用" value="其他">14 其他</option>
            </select>
            </div>  
            <div class="asn2" style="color: #fff;display:none;" >
             <select id="selectdnoon3"  onchange="jQuery(this).parents('th').eq(0).find('.dnoon').val(jQuery(this).val()).change();" >
                <option value="">----------</option>   
                <option class="财务费用" value="利息">1 利息</option>
                <option class="财务费用" value="手续费">2 手续费</option>
                <option class="财务费用" value="汇兑损失">3 汇兑损失</option>
                <option class="财务费用" value="汇兑收益">4 汇兑收益</option>
                <option class="财务费用" value="承兑收益">5 承兑收益</option>
            </select>
            </div>
            <div class="asn3" style="color: #fff;display:none;" >
            <input class="dnoon chargefreetext" ref="2" type="text"   style="color: #fff;"      placeholder="搜: <?php echo $i18n["费用明细"]; ?>" />
            </div>
            </th>
	<th style="width:150px;" ><?php echo $i18n["摘要"]; ?></th>
	<th style="width:150px;"><?php echo $i18n["收入金额"]; ?></th>
        
	<th style="width:150px;" ><?php echo $i18n["支出金额"]; ?></th>
        <th style="width:150px;" ><?php echo $i18n["Corresponding"]; ?></th>
        
	<th style="width:120px;"><?php echo $i18n["收付款人"]; ?></th>
	<th style="width:120px;" ><?php echo $i18n["催/请款单号"]; ?></th>
	<th style="width:80px;" ><?php echo $i18n["凭证号"]; ?></th>
	<th style="width:120px;"><?php echo $i18n["是否回收"]; ?></th>
	<th style="width:85px;" ><?php echo $i18n['是否核销']; ?></th>
	<th style="min-width:120px;" ><?php echo $i18n['备注']; ?></th>
</tr>
</thead>
<tbody>
<?php   


foreach ($data as $key => $values) {       
	$data2[$values['id']] = $values;
}
ksort($data2);
$data3 = $data2;
$data = array_values($data2);


	
foreach ($data as $key => $values) {  
  
        $appprove = 0; 
		
				  
		if( date('Y.m.d',$values['id']) <  $datestart || date('Y.m.d',$values['id']) >  $dateto ){
			unset($data[$key]);continue;
		}
//        foreach ($tabdocfull as $r){
//            if ( $values['id'] == $r->iddoc ) {
//				$rt = $r->idtab;				
//            }
//        }
		$rt = $values['tabs'];
		if ( count((array)$_POST['tabexport']) > 0 && !in_array('All',(array)$_POST['tabexport']) && !in_array($rt,(array)$_POST['tabexport'])){
			unset($data[$key]);continue;
		}
		
                if ( count((array)$_POST['corresponding']) > 0 && !in_array('All',(array)$_POST['corresponding']) ){
                    $dontmatch = 0;
                    foreach ($values['corresponding'] as $p){
                        if(in_array($p,(array)$_POST['corresponding'])){
                            $dontmatch = 1;
                        }
                    }
                    if($dontmatch == 0){    
			unset($data[$key]);continue;
                    }
		}
		
                
		if( $currentuser->gm != 1 && !in_array($rt,(array)$currentuser->account) && !in_array($rt,(array)$currentuser->accountreadonly) ) { continue; } 
               
                $exchangerate = $currencyname = '';
		foreach($tabs as $tab){
			if($rt == $tab->id){
				
		
				foreach($currency as $rcurrency){
						if($rcurrency['id'] == $tab->currency ){
							$exchangerate =  $rcurrency['exchangerate'];
							$currencyname =  $rcurrency['currency'];
                                                        break;
						} 	
				}
				$tabname = $tab->name;	
				$tablocation = $tab->location;	
                                break;
			}
		}
		$tablocation = $values['department'];
                
		if ( $_POST['location'] != '' && $_POST['location'] != 'All' && $_POST['location'] != $tablocation ){
			unset($data[$key]);continue;
		}
		if ( count((array)$_POST['classification']) > 0 && !in_array('All',(array)$_POST['classification']) && !in_array($values['classification'] ,(array)$_POST['classification'])){
			unset($data[$key]);continue;
		}
		if ( count((array)$_POST['charge']) > 0 && !in_array('All',(array)$_POST['charge']) &&  !in_array($values['charge'] ,(array)$_POST['charge'])){
			unset($data[$key]);continue;
		}
        if($_POST['documentnumber'] != '' && strpos($values['documentnumber'],$_POST['documentnumber']) === false ){
			unset($data[$key]);continue;
		}
		 if($_POST['payer'] != '' && strpos(implode(',',$_POST['payer']),$values['payer']) === false ){
			unset($data[$key]);continue;
		}
		if($_POST['user'] != '' && ( $_POST['user'] != $values['createbyid'] || ($values['financeclicktoapprovaltime'] - $values['id']) < 86400 ) ){
			unset($data[$key]);continue;
		}
		if($_POST['baddebt'] == 1 && $values['baddebt'] != 1 ){
			unset($data[$key]);continue;
		}
		if($_POST['summary'] != '' && stripos($values['summary'],$_POST['summary']) === false ){
			unset($data[$key]);continue;
		}
		
		$totalin[$currencyname]+=(float)$values['amountincome'];
		$totalout[$currencyname]+=(float)$values['amountpayout'];
		$ad++;
		$marching = array();
		if($values['classification'] == '借款-支出') { 			
			foreach ($Borrower as $keyb => $r){				
				$inputbenchovay =  explode(',',$r['inputbenchovay']);
				$inputbennhantien = '';
				if( in_array($values['id'],(array)$inputbenchovay) ){ 
					$inputbennhantien =  explode(',',$r['inputbennhantien']);
				}
				foreach ($inputbennhantien as $k){
					foreach($tabs as $tab){
						if($data3[$k]['tabs'] == $tab->id){
							foreach($currency as $rcurrency){
									if($rcurrency['id'] == $tab->currency ){
										$currencynamesub =  $rcurrency['currency'];
									} 	
							}			
						}
					}
					if($data3[$k]['amountincome'] > 0){
						$marching[] = ''.number_format((float)$data3[$k]['amountincome']).' '.$currencynamesub.' ('.date('Y.m.d',$data3[$k]['id']).')'; 
					}
				}
			}
		}
		
                
                $classification[$values['classification']] = $values['classification'];
                $charge[$values['charge']] = $values['charge'];
                if($currencyname == 'VND' || $currencyname == 'IDR'){
                    $decimal =  0;
                }else{
                    $decimal =  2;
                }
?>	
<tr>
		<td><?php echo date('Y.m.d',$values['id']); ?></td>		
		<td style="width:60px;" ><?php echo $tablocation; ?></td>
		<td><?php echo $tabname;; ?></td>
		<td style="width:53px;" ><?php echo (($i18n[$values['payment']] != '')?$i18n[$values['payment']]:$values['payment']); ?></td> 
                
               
		<td><?php echo (($i18n[$values['classification']] != '')?$i18n[$values['classification']]:$values['classification']); ?></td>
		<td><?php echo (($i18n[$values['charge']] != '')?$i18n[$values['charge']]:$values['charge']); ?></td>
		<td><textarea style="width:150px;border:0;" ><?php echo $values['summary']; ?></textarea></td>
		<td><?php echo number_format((float)$values['amountincome'],$decimal).' '.(($values['amountincome'] != '')?$currencyname:''); ?></td>
		<td><?php echo number_format((float)$values['amountpayout'],$decimal).' '.(($values['amountpayout'] != '')?$currencyname:''); ?></td>
                <td><?php foreach ($values['corresponding'] 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> ';
		}  ?></td>
		<td><?php foreach ($values['payer'] as $rpayer){
			if(isset($receiver_payer_id[$rpayer])){
				echo '<a data-target="modal8" class="modal-trigger payerdetail" ref="'.$rpayer.'" title="编号 Numbering：'.$receiver_payer_id[$rpayer]->name.'&#010;收付款人简称 Abbreviation：'.$receiver_payer_id[$rpayer]->abbreviation.'&#010;详细信息 Details:：'.$receiver_payer_id[$rpayer]->description.' " >'.$receiver_payer_id[$rpayer]->name.'</a>';
			}elseif(isset($receiver_payer_name[$rpayer])){
				echo '<a data-target="modal8" class="modal-trigger payerdetail" ref="'.$rpayer.'" title="编号 Numbering：'.$receiver_payer_name[$rpayer]->name.'&#010;收付款人简称 Abbreviation：'.$receiver_payer_name[$rpayer]->abbreviation.'&#010;详细信息 Details:：'.$receiver_payer_name[$rpayer]->description.' " >'.$receiver_payer_name[$rpayer]->name.'</a>';
			}else{
				echo $rpayer;
			}
			if(count((array)$values['payer']) > 1){
				echo ' | ';
			}
		}

		//echo $values['payer']; ?></td>
                
                
                
                
		<td><textarea style="width:120px;border:0;" ><?php echo $values['requestnumber']; ?></textarea></td>
		<td><textarea style="width:120px;border:0;" ><?php echo $values['documentnumber']; ?></textarea></td>
		<td style="width:120px;"><?php echo implode('<br>',$marching); ?></td>
		<td><?php echo (($i18n[$values['writtenoff']] != '')?$i18n[$values['writtenoff']]:$values['writtenoff']); ?></td>
		<td><textarea style="width:95%;" ><?php echo $values['remarks']; ?></textarea>
                <?php if( $currentuser->gm  == '1' ){  ?>
                    <a style="display:none;" ref="#" target="_blank" class="editmode" href="index.php?openid=<?php echo $values['id']; ?>&opentab=<?php echo $values['tabs']; ?>&datestart=<?php echo date('Y.m.d',$values['id']-86400*7); ?>&dateto=<?php echo date('Y.m.d',$values['id']+86400*7); ?>" ></a>
                <?php } ?>
                </td>
</tr>
<?php
		unset($data[$key]);
}	
 ?>
</tbody>
<tfoot>
<tr style="    background: antiquewhite;    font-weight: bold;font-size: 15px;" >
	<td colspan="5" ></td>
	<td style="    text-align: right; " >Total: </td>
	<td colspan="2" style="    text-align: right; " ><?php foreach($totalin as $currencyname => $r){ ?> <div class="tt1" ><?php echo number_format((float)$r,$decimal).' '.$currencyname; ?></div> <?php } ?></td>
	<td style="    text-align: right; " ><?php foreach($totalout as $currencyname => $r){ ?> <div class="tt2"  ><?php echo number_format((float)$r,$decimal).' '.$currencyname; ?></div> <?php } ?></td>
	<td colspan="6" ></td>
</tr>
</tfoot>
</table>

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script>
	jQuery("document").ready(function(){
                jQuery("#selectdnoon1").change(function(){
                    if(jQuery(this).val() == '管理费用'){
                        jQuery('.asn1').show();
                        jQuery('.asn2').hide();
                        jQuery('.asn3').hide();
                    }else if(jQuery(this).val() == '财务费用'){
                        jQuery('.asn2').show();
                        jQuery('.asn1').hide();
                        jQuery('.asn3').hide();
                    }else{
                        jQuery('.asn3').show();
                        jQuery('.asn1').hide();
                        jQuery('.asn2').hide();
                    }
                    jQuery('.chargefreetext').val('');
                });
                
                
		$('.remark').change(function(){
			$(".formupload").submit();
		});
                
                <?php foreach($classification as $r){ ?>
               // $('#selectdnoon1').append('<option value="<?php echo $r; ?>" color="" freetext=""><?php echo $r; ?></option>');
                <?php } ?>
                    
                <?php foreach($charge as $r){ ?>
              //  $('#selectdnoon2').append('<option value="<?php echo $r; ?>" color="" freetext=""><?php echo $r; ?></option>');
                <?php } ?>    
               jQuery('.editmode').click(function(){
                   window.open(jQuery(this).attr('href'), '_blank').focus();
                    
               });	
	});
</script>   
<style> 
<?php
 if($ad > 0){  ?> 
 #btnExport {display:block!important;} 
<?php }  ?>
#formfilter {
	position: sticky;
    z-index: 101;
    top: 0;
	background:#ffffff;
	height: 75px;
    width: 100%;
    padding-top: 5px;
	
} 
.tablesorter thead tr th {
    position: sticky;
    z-index: 100;
    top: 70px;
}  
.tablesorter input[type=text]:not(.browser-default){
    height: 22px;
	    margin-bottom: 3px;
}	
table.tablesorter tbody td, table.tablesorter thead tr th {
    border: 1px solid #ccc;
}  
table.tablesorter thead tr th {
    background-color: #1b278a;
    color: #fff;
}  
.select2-container .select2-search--inline .select2-search__field {
   
    height: 37px;
}
table.striped tr {
    cursor: pointer;
}
.navbar-fixed nav {
	padding: 0 30px;
}
table.tablesorter tbody td {
    vertical-align: middle;
}
table.tablesorter tbody td {
    padding: 0px;
}
.helper-text {
	display:none!important;
}
.input-field {
    position: relative;
    margin-top: 5px;
    margin-bottom: 5px;
}
#modal5 {   
    min-width: 1150px;
}
.ui-resizable-e , .ui-resizable-se {
	display:none!important;
}
.ui-resizable-s {    
    height: 10px;    
    bottom: -5px;
}
li.disabled{
	display:none;
}
#tabnameSave {
    position: relative;
    margin-right: 24px;
    transform: none;
}
.modal-fixed {
    width: 600px !important;
}
.nofulltext {
	display:block!important;
    /*height: 19px;*/
    overflow: hidden;
	width: 90%;
    float: left;
}
.fa-sort-down {
	width: 10%;
    float: right;
}
.dropdown-content li>a, .dropdown-content li>span {
    font-size: 16px;
    color: #26a69a;
    display: block;
    line-height: 22px;
    padding: 6px 13px;
}
table.striped>tbody>tr:nth-child(odd) {
    background-color: rgba(226, 226, 226, 0.75);
}
.select-dropdown{
    min-width: 120px;
}

#dbsakblk .select-wrapper input.select-dropdown {
    color:#ffffff;
}

.dropdown-content li {
   
    min-width: 150px;
}
</style>
<script src="https://htlservice.net/Docs/tpl/js/colResizable-1.6.min.js"></script>
<script src="tpl/js/jquery-ui.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>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />

<?php  
		
		$now = strtotime(date('Y-m-d 00:00:00')); // or your date as well
		//echo $datestart.'-'.$dateto;
		$your_date = strtotime(str_replace('.','-',$datestart).' 00:00:00'); 
		$datediff = round(($now - $your_date)/84600);
		if($datediff <= 0){
			$numdatstart = $datediff;
		}else{
			$numdatstart = $datediff;
		}
		
		$your_date = strtotime(str_replace('.','-',$dateto).' 00:00:00');
		$datediff = round(($now - $your_date)/84600); 
		if($datediff <= 0){
			$numdatto = $datediff;
		}else{
			$numdatto = $datediff-1;
		}
		
		$monthchinatext = array('一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月');
		
?>

<script>

$(document).ready(function () {
    
    $(".dnoon").on('keyup change',function(){
		  var input, filter, table, tr, td, i, txtValue  , cur , cur2 ;
                  var tt1 = 0;
                  var tt2 = 0;
		  input = $(this).val();
		  filter = input.toUpperCase();
                  if(!filter){
                      //$("#selectdnoon1").val('');
                      //$("#selectdnoon1").select({width: "100%"});
                  }
		  table = $(this).parents('table');
		  tr = table.find('tbody tr');
		  for (i = 0; i < tr.length; i++) {
				if($(this).attr('ref') == 1){
					td = tr[i].getElementsByTagName("td")[4];
				}
				if($(this).attr('ref') == 2){
					td = tr[i].getElementsByTagName("td")[5];
				}
				
			   
			   if (td) {
				  txtValue = td.textContent || td.innerText;
                                  
                                
				  if (txtValue.toUpperCase().indexOf(filter) > -1) {
					tr[i].style.display = "";
					tr[i].style.display = "";
                                        if(tr[i].getElementsByTagName("td")[7].textContent){
                                            var mmn = tr[i].getElementsByTagName("td")[7].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);
                                            tt1 += mmn;
                                        }
                                        if(tr[i].getElementsByTagName("td")[8].textContent){
                                            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);
                                            tt2 += mmn;
                                        }
                                        
                                        var sasd = tr[i].getElementsByTagName("td")[7].textContent;
                                        if(sasd.indexOf('VND') > -1){
                                            cur = ' VND';
                                        }
                                        if(sasd.indexOf('RMB') > -1){
                                            cur = ' RMB';
                                        }
                                        if(sasd.indexOf('USD') > -1){
                                            cur = ' USD';
                                        }
                                        
                                        
                                        var sasd2 = tr[i].getElementsByTagName("td")[8].textContent;
                                        if(sasd2.indexOf('VND') > -1){
                                            cur2 = ' VND';
                                        }
                                        if(sasd2.indexOf('RMB') > -1){
                                            cur2 = ' RMB';
                                        }
                                        if(sasd2.indexOf('USD') > -1){
                                            cur2 = ' USD';
                                        }
                                        
				  } else {
					tr[i].style.display = "none";
				  }
				}
		  }
                  if(cur){
                    $(".tt1").html((tt1).toLocaleString('en-US', {  style: 'currency',  currency: 'VND',})+cur);
                  }else{
                    $(".tt1").html('');  
                  }
                  if(cur2){
                    $(".tt2").html((tt2).toLocaleString('en-US', {  style: 'currency',  currency: 'VND',})+cur2);
                  }else{
                    $(".tt2").html('');
                  }
                  
                  if(!filter){
                      $(".tt1").html('<?php foreach($totalin as $currencyname => $r){ ?> <?php echo number_format((float)$r,$decimal).' '.$currencyname; ?> <?php } ?>');  
                      $(".tt2").html('<?php foreach($totalout as $currencyname => $r){ ?> <?php echo number_format((float)$r,$decimal).' '.$currencyname; ?> <?php } ?>');
                  }
	});	
        
	var tabexportyyes = 0;
		
	var map = $("#tabexport").on("change",function(){
		var comp = $("#tabexport option:selected").map(function() {
				return this.value;
			}).get(),
			set1 = map.filter(function(i) {
				return comp.indexOf(i) < 0;
			}),
			set2 = comp.filter(function(i) {
				return map.indexOf(i) < 0;
			}),
			last = (set1.length ? set1 : set2)[0];

		map = comp; 
		
		if(last == 'All' ){
			if(tabexportyyes == 0){
				if($("#tabexport").val().indexOf("All") !== -1 ){
					$('#tabexport option').prop('selected', true);
					$("#tabexport").formSelect();
					tabexportyyes = 1;
				}				
			}else{
				tabexportyyes = 0;
				$('#tabexport option').prop('selected', false);
				$("#tabexport").formSelect();
			}
		}else{
			if($("#tabexport").val().indexOf("All") !== -1 ){ 
				if(tabexportyyes == 0){
					tabexportyyes = 1;
					$('#tabexport option').prop('selected', true);
					$("#tabexport").formSelect();
				}else{
					$('#tabexport option.all').prop('selected', false);
					$("#tabexport").formSelect();
					tabexportyyes = 0;
				}
				
			}
		}
	}).find('option:selected').map(function() {return this.value}).get();
	
	var classificationyes = 0;	
	var map1 = $("#classification").on("change",function(){
		var comp1 = $("#classification option:selected").map(function() {
				return this.value;
			}).get(),
			set1 = map1.filter(function(i) {
				return comp1.indexOf(i) < 0;
			}),
			set2 = comp1.filter(function(i) {
				return map1.indexOf(i) < 0;
			}),
			last = (set1.length ? set1 : set2)[0];

		map1 = comp1; 
		
		if(last == 'All' ){
			if(classificationyes == 0){
				$('#classification option').prop('selected', true);
				$("#classification").formSelect();
				classificationyes = 1;
			}else{
				$('#classification option').prop('selected', false);
				$("#classification").formSelect();
				classificationyes = 0;
			}
		}else{
			if($("#classification").val().indexOf("All") !== -1 ){
				if(classificationyes == 0){
					classificationyes = 1;
					$('#classification option').prop('selected', true);
					$("#classification").formSelect();
				}else{
					$('#classification option.all').prop('selected', false);
					$("#classification").formSelect();
					classificationyes = 0;
				}
			}
		}
	}).find('option:selected').map(function() {return this.value}).get();
	
	var chargeyes = 0;	
	var map2 = $("#charge").on("change",function(){
		var comp2 = $("#charge option:selected").map(function() {
				return this.value;
			}).get(),
			set3 = map2.filter(function(i) {
				return comp2.indexOf(i) < 0;
			}),
			set4 = comp2.filter(function(i) {
				return map2.indexOf(i) < 0;
			}),
			last3 = (set3.length ? set3 : set4)[0];

		map2 = comp2; 
		
		if(last3 == 'All' ){
			//if($("#charge").val().indexOf("All") !== -1 ){
				if(chargeyes == 0){
					$('#charge option').prop('selected', true);
					$("#charge").formSelect();
					chargeyes = 1;
				}else{
					$('#charge option').prop('selected', false);
					$("#charge").formSelect();
					chargeyes = 0;
				}
			//}
		}else{
			if($("#charge").val().indexOf("All") !== -1 ){
				if(chargeyes == 0){
					$('#charge option').prop('selected', true);
					$("#charge").formSelect();
					chargeyes = 1;
				}else{
					$('#charge option.all').prop('selected', false);
					$("#charge").formSelect();
					chargeyes = 0;
				}
			}
		}
	}).find('option:selected').map(function() {return this.value}).get();
	
	/*
	$("#tabexport").change(function(){
			var latest_value = $("option:selected:last",this).val();
			
			var string = $(this).val();
			if(latest_value == 'All' ){
				$('#tabexport option').prop('selected', true);
				$("#tabexport").formSelect();
				$("#tabexport").formSelect();
			}else{
				//$(this).val('[]');
				
			}
			
			//		
	});
	*/
	var start = moment().subtract(<?php echo $numdatstart; ?>, 'days');
    var end = moment().subtract(<?php echo $numdatto; ?>, 'days');
	
	function cb(start, end , sub) {		
		$('.reportrange span').html(start.format('YYYY.MM.D') + ' - ' + end.format('YYYY.MM.D'));
   
		jQuery('#datestart').val(start.format('YYYY.MM.DD')); 
		jQuery('#dateto').val(end.format('YYYY.MM.DD')); 
		if(sub != 1){
			//jQuery("#formfilter").submit();
		}
    }
	
	$('.reportrange').daterangepicker({
        startDate: start,
        endDate: end,
		linkedCalendars: false,
        ranges: {
           '今天': [moment(), moment()],
           '昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
           '七天内': [moment().subtract(6, 'days'), moment()],
           '三十天内': [moment().subtract(29, 'days'), moment()],
           '<?php echo $monthchinatext[(date('n')-1)].' '.date('Y'); ?>': [moment().startOf('month'), moment().endOf('month')],
           '<?php echo $monthchinatext[(date('n', strtotime('last month')) - 1 )].' '.date('Y'); ?>': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -2 month')) - 1 )].' '.date('Y'); ?>': [moment().subtract(2, 'month').startOf('month'), moment().subtract(2, 'month').endOf('month')],
			'<?php echo $monthchinatext[(date('n', strtotime('first day of -3 month')) - 1 )].' '.date('Y',strtotime('first day of -3 month')); ?>': [moment().subtract(3, 'month').startOf('month'), moment().subtract(3, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -4 month')) - 1 )].' '.date('Y',strtotime('first day of -4 month')); ?>': [moment().subtract(4, 'month').startOf('month'), moment().subtract(4, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -5 month')) - 1 )].' '.date('Y',strtotime('first day of -5 month')); ?>': [moment().subtract(5, 'month').startOf('month'), moment().subtract(5, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -6 month')) - 1 )].' '.date('Y',strtotime('first day of -6 month')); ?>': [moment().subtract(6, 'month').startOf('month'), moment().subtract(6, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -7 month')) - 1 )].' '.date('Y',strtotime('first day of -7 month')); ?>': [moment().subtract(7, 'month').startOf('month'), moment().subtract(7, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -8 month')) - 1 )].' '.date('Y',strtotime('first day of -8 month')); ?>': [moment().subtract(8, 'month').startOf('month'), moment().subtract(8, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -9 month')) - 1 )].' '.date('Y',strtotime('first day of -9 month')); ?>': [moment().subtract(9, 'month').startOf('month'), moment().subtract(9, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -10 month')) - 1 )].' '.date('Y',strtotime('first day of -10 month')); ?>': [moment().subtract(10, 'month').startOf('month'), moment().subtract(10, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -11 month')) - 1 )].' '.date('Y',strtotime('first day of -11 month')); ?>': [moment().subtract(11, 'month').startOf('month'), moment().subtract(11, 'month').endOf('month')]
        
		}
    }, cb);
	cb(start, end , 1);
	
	$(".sandjnas").change(function(){
		if($( ".sandjnas option:selected" ).hasClass('isspeci')){
			$(".isdepartmentform").show();
		}else{
			$(".isdepartmentform").hide();
		}
	});
	
        <?php if( $currentuser->gm  == '1' ){ ?>
        
        jQuery(".tablesorter tbody tr").dblclick(function() {
		$('.modal-overlay').trigger("click");
		if($(this).find('.editmode').length){
			///$('.frameedit').css('height','auto');
			$(this).find('.editmode').trigger('click').click();
			//$('#modal5').modal('open'); 
		}else{
			alert("This order can\'t edit.");
		}	
	});
        <?php } ?>
        
        
}); 
function fnExcelReport()
{
	var dt = new Date();
	var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();

	$('#dbsakblk').tableExport({htmlContent: true,fileName: 'Export_'+time,type: 'xlsx'});
}          


 </script>
<iframe id="txtArea1" style="display:none"></iframe>							
<!-- Styles -->
<div id="modal5" class="modal">
  <iframe class="frameedit" src="" width="100%" style="height:auto;    min-height: 321px;" ></iframe>
</div>
						
<?php    
// FOOTER
include 'tpl/footer.php';
