<?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->borrow != '1'  ){ 
		header('location: index.php');exit();
	}
} else {
    header('location: login.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' &&  $_POST['id'] != '' || ( $_POST['inputbenchovay'] != '' && $_POST['inputbennhantien'] != '' )){
	
	$Borrower = json_decode(file_get_contents('data/Borrower.json'), true);
	if($_POST['removed'] == 1){
		if( $Borrower[$_POST['id']]['complete'] == 1 ){
			if($currentuser->role  == 'Manager'){
				unset($Borrower[$_POST['id']]);
			}
		}else{
			unset($Borrower[$_POST['id']]);
		}
	}else{
		if($_POST['id'] == ''){
			if($currentuser->role  == 'Manager'){
				$Borrower[time()] = array( 'inputbenchovay' => $_POST['inputbenchovay'], 'inputbennhantien' => $_POST['inputbennhantien'] , 'complete' => $_POST['complete']);
			}else{
				$Borrower[time()] = array( 'inputbenchovay' => $_POST['inputbenchovay'], 'inputbennhantien' => $_POST['inputbennhantien'] , 'complete' => '');
			}
		}else{
			if($currentuser->role  == 'Manager'){
				$Borrower[$_POST['id']]['complete'] = $_POST['complete'];
			}
		}
	}
	
	file_put_contents('data/Borrower.json',json_encode($Borrower));
	header('location: total_borrower.php?msg=');
}

$Borrower = json_decode(file_get_contents('data/Borrower.json'), true);
$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'));
$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();
include 'tpl/header.php';

if(isset($_POST['datestart'])){
			$datestart = $_POST['datestart'];
}else{
			$datestart = date('Y-m-d',time()-86400*365); //date('Y').'.01.08';//date('Y.m.d',strtotime("-90 day"));
}		
if(isset($_POST['dateto'])){
			$dateto = $_POST['dateto'];
}else{
			$dateto = date('Y.m.d');
}
foreach ($data as $key => $values) {    
	if( $values['classification'] == '代收' || $values['classification'] == '代付') { 
		$subname[trim($values['charge'])] = trim($values['charge']);
	}
}
?>
<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" style="    width: 90%;    margin-left: 20px;float: left;">

<div style=" width: 250px; float:left;" >
	<b>费用明细</b>
    <select name="subname" id="aclocation" class="exclude" >
				<option value="">-------</option>
				<?php foreach ($subname as $r){ ?>
				<option <?php if($r == $_POST['subname']){ echo 'selected'; } ?> value="<?php echo $r ?>"><?php echo $r ?></option>
				<?php } ?>
				
    </select>            
</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>

</form>		
	
<div id="table1" style="width:49%;float:left;margin-left:1%;overflow:auto;position:relative;" >
<h3 style="    text-align: right;    background: #1b278a;    color: #ffffff;    padding: 5px 5px;">
<label class="pure-material-checkbox" style="    float: left;    margin-left: 20px; text-align:left;    top: 7px;    color: #ffffff;" ></label>
代收 <button id="btnExport" class="btn waves-effect waves-light" type="button" onclick="fnExcelReport();" style="    float: right;    margin-top: -4px;    margin-left: 9px;
"> <?php echo $i18n['Excel']; ?> </button></h3>
<table  class="striped responsive-table  tablesorter  "  >
<thead>
<tr data-tableexport-fillColor="[52, 73, 94]" data-tableexport-textColor="[255, 255, 255]" >
	<th></th>
	<th><?php echo $i18n['日期'] ?></th>
	<th>费用明细</th>
	<th>地点</th>
	<th style="width:120px;" >帐户</th>
	<th style="width:100px;" ><?php echo $i18n["费用明细"]; ?></th>
	<th style="width:150px;" ><?php echo $i18n["摘要"]; ?></th>
	<th><?php echo $i18n["收入金额"]; ?></th>
	<th style="width:150px;border-right: 0;"><?php echo $i18n["收付款人"]; ?></th>

</tr>
</thead>
<tbody>
<?php   


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


	
foreach ($data as $key => $values) {       
        $appprove = 0; 
		if($values['classification'] != '代收') { continue; }
		if( trim($values['charge']) != $_POST['subname'] || $_POST['subname'] == '') { continue; }
		/*		  
		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;				
            }
        }
		
		
		
		if( $currentuser->gm != 1 && !in_array($rt,$currentuser->account) && !in_array($rt,$currentuser->accountreadonly) ) { continue; } 
		
		foreach($tabs as $tab){
			if($rt == $tab->id){
				
		
				foreach($currency as $rcurrency){
						if($rcurrency['id'] == $tab->currency ){
							$exchangerate =  $rcurrency['exchangerate'];
							$currencyname =  $rcurrency['currency'];
						} 	
				}
				$tabname = $tab->name;	
				$tablocation = $tab->location;					
			}
		}
		
		
		
		$totalin[$currencyname]+=(float)$values['amountincome'];
		if($values['amountpayout'] > 0){$totalout[$currencyname]+=(float)$values['amountpayout'];}
		$ad++;
		$class = ''; $idgroup = '';
		
		if(!is_array($values['payer'])){
				$values['payer'] = array($values['payer']);
		}
		$namepayee = '';
		foreach ($values['payer'] as $rpayer){
				if(isset($receiver_payer_id[$rpayer])){
					$namepayee .= $receiver_payer_id[$rpayer]->name;
				}elseif(isset($receiver_payer_name[$rpayer])){
					$namepayee .= $receiver_payer_name[$rpayer]->name;
				}else{
					$namepayee .= $rpayer;
				}
				if(count((array)$values['payer']) > 1){
					$namepayee .= ' | ';
				}
			}		
		
?>	
<tr style=""  class="groupby <?php echo $class; ?>" idgroup="<?php echo $idgroup; ?>"  >	
		<td></td>	
		<td><?php echo date('Y.m.d',$values['id']); ?></td>		
		<td style="width:100px;" ><?php echo $values['charge']; ?></td>
		<td style="width:60px;" ><?php echo $tablocation; ?></td>
		<td><?php echo $tabname;; ?></td>
		<td><?php echo (($i18n[$values['charge']] != '')?$i18n[$values['charge']]:$values['charge']); ?></td>
		<td><textarea disabled style="width:150px;border:0;" ><?php echo $values['summary']; ?></textarea></td>
		<td><?php echo number_format((float)$values['amountincome'],$decimal).' '.(($values['amountincome'] != '')?$currencyname:''); ?>
		<?php if($values['amountpayout'] != ''){ ?> <br> <span style="color:red;" >Expend?: <?php echo number_format((float)$values['amountpayout'],$decimal).' '.(($values['amountpayout'] != '')?$currencyname:''); ?></span> <?php } ?>
		</td>
		<td><?php echo $namepayee; ?></td>

</tr>
<?php
		unset($data[$key]);
}	
 ?>
</tbody>
<tfoot class="tfoot" >
<tr style="    background: antiquewhite;    font-weight: bold;font-size: 15px;" >
	<td colspan="6" ></td>
	<td style="    text-align: right; " >Total In: </td>
	<td colspan="2"><?php foreach($totalin as $currencyname => $r){ ?> <div><?php echo number_format((float)$r,$decimal).' '.$currencyname; ?></div> <?php } ?></td>
	
</tr>
<?php if($totalout){ ?>
<tr style="    background: antiquewhite;    font-weight: bold;font-size: 15px;" >
	<td colspan="6" ></td>
	<td style="    text-align: right; " >Total Out: </td>
	<td colspan="2"><?php foreach($totalout as $currencyname => $r){ ?> <div><?php echo number_format((float)$r,$decimal).' '.$currencyname; ?></div> <?php } ?></td>
</tr>
<?php } ?>
</tfoot>


</table>
</div>

<div  id="table2" style="width:49%;float:left;margin-left:1%;overflow:auto;position:relative;" >
<h3 style="    text-align: right;    background: #1b278a;    color: #ffffff;    padding: 5px 5px;">
<label class="pure-material-checkbox" style="    float: left;    margin-left: 20px;   top: 7px;    color: #ffffff; text-align:left;" ></label>代付
  <button id="btnExport" class="btn waves-effect waves-light" type="button" onclick="fnExcelReport1();" style="    float: right;    margin-top: -4px;    margin-left: 9px;
"> <?php echo $i18n['Excel']; ?> </button></h3>
<table class="striped responsive-table  tablesorter  " >
<thead>
<tr data-tableexport-fillColor="[52, 73, 94]" data-tableexport-textColor="[255, 255, 255]" >
	<th></th>
	<th><?php echo $i18n['日期'] ?></th>
	<th>费用明细</th>
	<th>地点</th>
	<th style="width:120px;" >帐户</th>
	<th style="width:100px;" ><?php echo $i18n["费用明细"]; ?></th>
	<th  style="width:150px;" ><?php echo $i18n["摘要"]; ?></th>
	<th><?php echo $i18n["支出金额"]; ?></th>
	
	<th style="width:150px;border-right: 0;"><?php echo $i18n["收付款人"]; ?></th>

</tr>
</thead>
<tbody>
<?php   
$totalin = array();
$totalout = array();

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


	
foreach ($data as $key => $values) {       
        $appprove = 0; 
		if($values['classification'] != '代付') { continue; }
		if( trim($values['charge']) != $_POST['subname'] || $_POST['subname'] == '') { continue; }
				  
	
        foreach ($tabdocfull as $r){
            if ( $values['id'] == $r->iddoc ) {
				$rt = $r->idtab;				
            }
        }
		
		
		foreach($tabs as $tab){
			if($rt == $tab->id){
				
		
				foreach($currency as $rcurrency){
						if($rcurrency['id'] == $tab->currency ){
							$exchangerate =  $rcurrency['exchangerate'];
							$currencyname =  $rcurrency['currency'];
						} 	
				}
				$tabname = $tab->name;	
				$tablocation = $tab->location;					
			}
		}
		

	
		$ad++;
		$class = ''; $idgroup = '';
		
		$checkkotronglist = 0;

		if($checkkotronglist == 0 ){
			if($values['amountincome'] > 0){ $totalin[$currencyname]+=(float)$values['amountincome']; }
			$totalout[$currencyname]+=(float)$values['amountpayout'];
		}
		if(!is_array($values['payer'])){
				$values['payer'] = array($values['payer']);
		}
		$namepayee = '';
		foreach ($values['payer'] as $rpayer){
				if(isset($receiver_payer_id[$rpayer])){
					$namepayee .= $receiver_payer_id[$rpayer]->name;
				}elseif(isset($receiver_payer_name[$rpayer])){
					$namepayee .= $receiver_payer_name[$rpayer]->name;
				}else{
					$namepayee .= $rpayer;
				}
				if(count((array)$values['payer']) > 1){
					$namepayee .= ' | ';
				}
			}			
?>	
<tr class="groupby <?php echo $class; ?>" idgroup="<?php echo $idgroup; ?>" >
		<td></td>		
		<td><?php echo date('Y.m.d',$values['id']); ?></td>		
		<td style="width:100px;" ><?php echo $values['charge']; ?></td>
		<td style="width:60px;" ><?php echo $tablocation; ?></td>
		<td><?php echo $tabname;; ?></td>
		<td><?php echo (($i18n[$values['charge']] != '')?$i18n[$values['charge']]:$values['charge']); ?></td>
		<td><textarea disabled style="width:150px;border:0;" ><?php echo $values['summary']; ?></textarea></td>
		<td><?php echo number_format((float)$values['amountpayout'],$decimal).' '.(($values['amountpayout'] != '')?$currencyname:''); ?>
		<?php if($values['amountincome'] != ''){ ?> <br> <span style="color:red;" >Income?: <?php echo number_format((float)$values['amountincome'],$decimal).' '.(($values['amountincome'] != '')?$currencyname:''); ?></span> <?php } ?>
		</td>
		<td><?php echo $namepayee; ?></td>

</tr>
<?php
		unset($data[$key]);
}	
 ?>
</tbody>
<tfoot class="tfoot" >
<tr style="    background: antiquewhite;    font-weight: bold;font-size: 15px;" >
	<td colspan="6" ></td>
	<td style="    text-align: right; " >Total Out: </td>
	<td colspan="2"><?php foreach($totalout as $currencyname => $r){ ?> <div><?php echo number_format((float)$r,$decimal).' '.$currencyname; ?></div> <?php } ?></td>
</tr>
<?php if($totalin){ ?>
<tr style="    background: antiquewhite;    font-weight: bold;font-size: 15px;" >
	<td colspan="6" ></td>
	<td style="    text-align: right; " >Total In: </td>
	<td colspan="2"><?php foreach($totalin as $currencyname => $r){ ?> <div><?php echo number_format((float)$r,$decimal).' '.$currencyname; ?></div> <?php } ?></td>
</tr>
<?php } ?>
</tfoot>
</table>
</div>

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script>
	$('.itemtable1').text($('#table1 .backgroudisgreen').length);
	$('.itemtable2').text($('#table2 .backgroudisgreen').length);
	function addCommas(nStr)
	{
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	}
	jQuery("document").ready(function(){
		
		var tongsotienthu = {VND: 0, RMB: 0, USD:0 , Baht:0};
		var tongsotienchi = {VND: 0, RMB: 0, USD:0 , Baht:0};
		
		$('.groupby').mousedown(function(){
			if($(this).attr('idgroup') == ''){
				$('.groupby').removeClass('addoverplay');
				if(jQuery('#id').val() != ''){
					tongsotienthu = {VND: 0, RMB: 0, USD:0 , Baht:0};
					tongsotienchi = {VND: 0, RMB: 0, USD:0 , Baht:0};
					jQuery('#id').val('');
					jQuery('#inputbenchovay,#inputbennhantien').val('');
					jQuery('.amount1,.amount2').text('');
					jQuery('.sndkl,.sndkl2').text(0);
					jQuery('#complete').prop('checked',false);
					jQuery('.sfgd').hide();
					
				}
				
			}else{
				if($(this).hasClass('backgroudisred')){
					jQuery('#complete').prop('checked',false);
				}else{
					jQuery('#complete').prop('checked',true);
				}
				if($(this).parents().eq(2).attr('id') == 'table2'){
					
					jQuery('#table1').animate({
						scrollTop: 0
					}, 0);
					var d = $("#table1 [idgroup="+$(this).attr('idgroup')+"]").eq(0).offset().top - 250;
					jQuery('#table1').animate({
						scrollTop: d
					}, 2500);
				}else{
					
					jQuery('#table2').animate({
						scrollTop: 0
					}, 0);
					var d = $("#table2 [idgroup="+$(this).attr('idgroup')+"]").eq(0).offset().top - 250;
					jQuery('#table2').animate({
						scrollTop: d
					}, 2500);
				}
				jQuery('#inputbenchovay,#inputbennhantien').val('');
				jQuery('.sfgd').show();	
				jQuery('#id').val($(this).attr('idgroup'));
				tongsotienthu = {VND: 0, RMB: 0, USD:0 , Baht:0};
				tongsotienchi = {VND: 0, RMB: 0, USD:0 , Baht:0};
				var item1 = 0;var item2 = 0;
				jQuery('.sndkl,.sndkl2').text(0);
				$('.groupby:not(.backgroudisred):not(.backgroudisgreen) input').prop('checked',false);
				$('.groupby').addClass('addoverplay');
				$("[idgroup="+$(this).attr('idgroup')+"]").removeClass('addoverplay');
				$("#table1 [idgroup="+$(this).attr('idgroup')+"] input").each(function(){
					jQuery('#inputbenchovay').val( jQuery('#inputbenchovay').val()+jQuery(this).val()+',');
					tongsotienthu[jQuery(this).attr('c')] += parseInt(jQuery(this).attr('v'));
					item1++;
				});
				$("#table2 [idgroup="+$(this).attr('idgroup')+"] input").each(function(){
					jQuery('#inputbennhantien').val( jQuery('#inputbennhantien').val()+jQuery(this).val()+',');
					tongsotienchi[jQuery(this).attr('c')] += parseInt(jQuery(this).attr('v'));
					item2++;
				});
				jQuery('.sndkl').text(item1);
				jQuery('.sndkl2').text(item2);
				jQuery('.amount1,.amount2').text('');
				for (var key in tongsotienthu) {
					if(tongsotienthu[key] > 0){
						jQuery('.amount1').text(jQuery('.amount1').text()+addCommas(tongsotienthu[key])+key+' ');
					}
				}
				for (var key in tongsotienchi) {
					if(tongsotienchi[key] > 0){
						jQuery('.amount2').text(jQuery('.amount2').text()+addCommas(tongsotienchi[key])+key+' ');
					}
				}
				
			}
			
		});
		$('.showcomplete').change(function(){
			$('.groupby').removeClass('addoverplay');
			tongsotienthu = {VND: 0, RMB: 0, USD:0 , Baht:0};
			tongsotienchi = {VND: 0, RMB: 0, USD:0 , Baht:0};
			jQuery('#id').val('');
			jQuery('#inputbenchovay,#inputbennhantien').val('');
			jQuery('.amount1,.amount2').text('');
			jQuery('.sndkl,.sndkl2').text(0);
			jQuery('#complete').prop('checked',false);
			jQuery('.sfgd').hide();			
			
			if(jQuery(this).is(':checked')){
				<?php if( $currentuser->role  != 'Manager' ){ ?>
					$("#formfilter2 button").addClass('diofhg');
				<?php } ?>
				$('.showcomplete').prop('checked', true);
				$('.groupby,.tfoot tr').hide();$('.tfoot2 tr').show();
				$('.backgroudisgreen').css('display','table-row');
			}else{
				<?php if( $currentuser->role  != 'Manager' ){ ?>
					$("#formfilter2 button").removeClass('diofhg');
				<?php } ?>
				$('.showcomplete').prop('checked', false);
				$('.groupby,.tfoot tr').show();$('.tfoot2 tr').hide();
				$('.backgroudisgreen').removeAttr('style');
			}
		});
		
		$('.bennhan, .benvay').change(function(){
			
			if(jQuery(this).is(':checked')){
					jQuery(this).parents().eq(1).addClass('yellow');
					if(jQuery(this).parents().eq(1).attr('idgroup') == ''){
						if(jQuery(this).attr('loai') == '借款-支出'){ 
							jQuery('.amount1').text('');
							jQuery('.sndkl').text( parseInt(jQuery('.sndkl').text())+1);			
							jQuery('#inputbenchovay').val(jQuery('#inputbenchovay').val()+jQuery(this).val()+',');
							tongsotienthu[jQuery(this).attr('c')] += parseInt(jQuery(this).attr('v'));
							for (var key in tongsotienthu) {
								if(tongsotienthu[key] > 0){
									jQuery('.amount1').text(jQuery('.amount1').text()+addCommas(tongsotienthu[key])+key+' ');
								}
							}
						}
						if(jQuery(this).attr('loai') == '借款-收入'){ 
							jQuery('.amount2').text('');
							jQuery('.sndkl2').text( parseInt(jQuery('.sndkl2').text())+1);
							tongsotienchi[jQuery(this).attr('c')] += parseInt(jQuery(this).attr('v'));
							jQuery('#inputbennhantien').val( jQuery('#inputbennhantien').val()+jQuery(this).val()+',');
							for (var key in tongsotienchi) {
								if(tongsotienchi[key] > 0){
									jQuery('.amount2').text(jQuery('.amount2').text()+addCommas(tongsotienchi[key])+key+' ');
								}
							}
						}
					}
			}else{	
					jQuery(this).parents().eq(1).removeClass('yellow');
					if(jQuery(this).parents().eq(1).attr('idgroup') == ''){
						if(jQuery(this).attr('loai') == '借款-支出'){ 
							var inputbenchovay = jQuery('#inputbenchovay').val();
							jQuery('.amount1').text('');
							jQuery('.sndkl').text( parseInt(jQuery('.sndkl').text())-1);
							tongsotienthu[jQuery(this).attr('c')] -= parseInt(jQuery(this).attr('v'));
							jQuery('#inputbenchovay').val(inputbenchovay.replace(jQuery(this).val()+',',''));
							for (var key in tongsotienthu) {
								if(tongsotienthu[key] > 0){
									jQuery('.amount1').text(jQuery('.amount1').text()+addCommas(tongsotienthu[key])+key+' ');
								}
							}
						}
						if(jQuery(this).attr('loai') == '借款-收入'){ jQuery('.amount2').text('');
							var inputbennhantien = jQuery('#inputbennhantien').val();
							jQuery('.sndkl2').text( parseInt(jQuery('.sndkl2').text())-1);
							tongsotienchi[jQuery(this).attr('c')] -= parseInt(jQuery(this).attr('v'));
							jQuery('#inputbennhantien').val( inputbennhantien.replace(jQuery(this).val()+',',''));
							for (var key in tongsotienchi) {
								if(tongsotienchi[key] > 0){
									jQuery('.amount2').text(jQuery('.amount2').text()+addCommas(tongsotienchi[key])+key+' ');
								}
							}
						}
					}
			}
			
		});
		
	});
	
</script>   
<style> 

table.tablesorter tbody td {
    padding-left: 5px!important;
}
.addoverplay {
	opacity:0.9;
}
.addoverplay td { position: relative; }
.addoverplay td:after { 
	content:"";
	position:absolute;
	width:100%;
	height:100%;
	top:0px;
	left:0px;
	background: rgba(33, 33, 33, 0.7);
 } 
.yellow td{
	background: #fff2a8;
}
.backgroudisgreen {
	background: #cdffad!important;display:none;
}
.backgroudisred {
	background: #ffadad!important;
}
<?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: 39px;
}  
 h3 {
	position: sticky;
    top: 0px;
    z-index: 100;
    width: 100%;
}
.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);
}
#table1,#table2 {
	    max-height: 757px;
}
@media only screen and (max-width: 1400px){
	#table1,#table2 {
	    max-height: 500px;
	}
}
.diofhg {
	display:none!important;
}
td, th {
    padding: 10px 5px;
}
</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 () {
	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();
		}
	});
	
}); 
function fnExcelReport()
{
	var dt = new Date();
	var time = dt.getYear()+'.'+(dt.getMonth()+1)+'.'+dt.getDate()+' '+dt.getHours() + "-" + dt.getMinutes() + "-" + dt.getSeconds();
	$('#tableexport').empty();
	$('#table1 tr').each(function(){
		if($(this).css('display') != 'none' ){
			$(this).clone().appendTo("#tableexport");
		}
	});
	$('#tableexport tr td:first-child ,#tableexport tr th:first-child').remove();
	$('#tableexport').tableExport({htmlContent: true,fileName: 'Export_借款-支出_'+time,type: 'xlsx'});
	$('#tableexport').empty();
}   
function fnExcelReport1()
{
	var dt = new Date();
	var time = dt.getYear()+'.'+(dt.getMonth()+1)+'.'+dt.getDate()+' '+dt.getHours() + "-" + dt.getMinutes() + "-" + dt.getSeconds();
	$('#tableexport').empty();
	$('#table2 tr').each(function(){
		if($(this).css('display') != 'none' ){
			$(this).clone().appendTo("#tableexport");
		}
	});
	$('#tableexport tr td:first-child ,#tableexport tr th:first-child').remove();
	$('#tableexport').tableExport({htmlContent: true,fileName: 'Export_借款-收入_'+time,type: 'xlsx'});
	$('#tableexport').empty();
}                      
 </script>
<iframe id="txtArea1" style="display:none"></iframe>							
<!-- Styles -->

<table id="tableexport" >

</table>
					
<?php    
// FOOTER
include 'tpl/footer.php';
