<?php
date_default_timezone_set('Asia/Bangkok');
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/' . $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) {    
  
} else {
    header('location: login.php');
    exit;
}

if($currentuser->gm != '1' && $currentuser->chart != '1' ){
	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'));

$receiver_payer = json_decode(file_get_contents('data/receiver_payer.json'));
foreach ($receiver_payer as $r){
	$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';
?>

<form class="formupload" method="POST" style="display:none;" >
<input type="hidden" name="updateremak"  value="1" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
<table style="display:none;" style="width: 100%!important;position: relative;margin-top: 180px;" class="striped responsive-table  tablesorter  "  >

  <tbody>
<?php   

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


if(isset($_POST['datestart2'])){
			$datestart2 = $_POST['datestart2'];
}else{
			$datestart2 = date('Y.m.d',strtotime("first day of january this year"));
}		
if(isset($_POST['dateto2'])){
			$dateto2 = $_POST['dateto2'];
}else{
			$dateto2 = date('Y.m.d');
}


/*
foreach ($data as $key => $values) {       
	$data2[$values['id']] = $values;
}
ksort($data2);
$data = array_values($data2);
*/
foreach($tabs as $tab){
	$tabs2[$tab->id] = $tab;
}
$tabs = $tabs2;
foreach($tabs as $tab){

    // LOOP EACH ENTRY
    $total_receivable = $total_amount = $total_profit = 0;
    $countNo = 0;
	$amountincome = 0;
	$amountpayout = 0;
	$balance = 0;
	
	foreach($currency as $rcurrency){
			if($rcurrency['id'] == $tab->currency ){
				$exchangerate =  $rcurrency['exchangerate'];
				$currencyname =  $rcurrency['currency'];
			} 	
	}
		
	$tygia = json_decode(file_get_contents('currency/'.date('Ymd')));
	for($i = 9; $i >= 0; $i--){			
				//$tygia = json_decode(file_get_contents('currency/'.date('Ymd',strtotime("-".$i." day"))));				
				if($currencyname == "USD"){
					$sumbydate[date('Y-m-d',strtotime("-".$i." day"))] += (floatval($tab->balance)*$tygia->USD);
				}elseif($currencyname == "VND"){
					$sumbydate[date('Y-m-d',strtotime("-".$i." day"))] += (floatval($tab->balance)*$tygia->VND);
				}elseif($currencyname == "RMB"){
					$sumbydate[date('Y-m-d',strtotime("-".$i." day"))] += (floatval($tab->balance));
				}elseif($currencyname == "Baht"){
					$sumbydate[date('Y-m-d',strtotime("-".$i." day"))] += (floatval($tab->balance)*$tygia->THB);
				}
	}
	
	
    foreach ($data as $key => $values) {       
        $appprove = 0; 
        if( $values['tabs'] == '' ){
			foreach ($tabdocfull as $keytab => $r){
				if ( $values['id'] == $r->iddoc && $tab->id == $r->idtab ) {
					$appprove = 1; 
					$rt = $r->idtab;
					$rtname = $tabs[$rt]->name;
					unset($tabdocfull[$keytab]);	break;
				}
			}
			if ($appprove == 0){
             continue;
			}
		}else{
			if ($values['tabs'] != $tab->id ){
				 continue;
			}
			$rt = $values['tabs'];
			$rtname = $tabs[$rt]->name;
		}
		
		foreach ($user as $use){
			if( date('Y.m.d',$values['id']) <  $datestart || date('Y.m.d',$values['id']) >  $dateto ){
				break;
			}
			if($use->id == $values['createbyid']){
				$usercreate[$values['createbyname']]['info'] = $use;
				$usercreate[$values['createbyname']]['count']++;

			}
			if($use->id == $values['modifybyid']){
				$useredit[$values['createbyname']]['info'] = $use;
				$useredit[$values['createbyname']]['count']++;
			}

			if($use->name == $values['financeclicktoapproval'] && ($values['financeclicktoapprovaltime'] - $values['id']) > 86400 ){
				$userviolations[$values['financeclicktoapproval']]['info'] = $use;
				$userviolations[$values['financeclicktoapproval']]['count']++;
			}
			
			if($use->name == $values['controlerrevision']){
				$controler[$values['controlerrevision']]['info'] = $use;
				$controler[$values['controlerrevision']]['revision']++;
			}
			if($use->name == $values['controlerapproval']){
				$controler[$values['controlerapproval']]['info'] = $use;
				$controler[$values['controlerapproval']]['approval']++;
				if($values['controlerapprovaltime'] - $values['financeclicktoapprovaltime'] > 86400 ){
					$controler[$values['controlerapproval']]['violations']++;
				}
			}
		}
		
      
		
		$balance += (($values['amountincome']) - ($values['amountpayout'])) ;
		//$amountincome += (float)$values['amountincome'];
		//$amountpayout += (float)$values['amountpayout'];
		
        // END LOOP
		
		for($i = 9; $i >= 0; $i--){
			if(date('Ymd',strtotime("-".$i." day")) >= date('Ymd',$values['id']) ){
				//$tygia = json_decode(file_get_contents('currency/'.date('Ymd',strtotime("-".$i." day"))));
				if($currencyname == "USD"){
					$sumbydate[date('Y-m-d',strtotime("-".$i." day"))] += (($values['amountincome']) - ($values['amountpayout']))*$tygia->USD;
					$sumbydate['a'.date('Y-m-d',strtotime("-".$i." day"))][] = $values['amountincome'].' - '.$values['amountpayout'].' - '.$sumbydate[date('Y-m-d',strtotime("-".$i." day"))].' - '.$tygia->USD;
				}elseif($currencyname == "VND"){
					$sumbydate[date('Y-m-d',strtotime("-".$i." day"))] += (($values['amountincome']) - ($values['amountpayout']))*$tygia->VND;
					$sumbydate[date('Y-m-d',strtotime("-".$i." day"))] += (($values['amountincomeusd']) - ($values['amountpayoutusd']))*$tygia->VND*$tygia->USDVND;
					
				}elseif($currencyname == "RMB"){
					$sumbydate[date('Y-m-d',strtotime("-".$i." day"))] += (($values['amountincome']) - ($values['amountpayout']));
				}elseif($currencyname == "Baht"){
					$sumbydate[date('Y-m-d',strtotime("-".$i." day"))] += (($values['amountincome']) - ($values['amountpayout']))*$tygia->THB;
				}
			}	
		}
			
		if( date('Y.m.d',$values['id']) >=  $datestart && date('Y.m.d',$values['id']) <=  $dateto ){
			$chart[$tab->location][$values['classification'].' '] += (($values['amountincome']) - ($values['amountpayout']))*$exchangerate/$_SESSION['currencyUser']['exchangerate'];
			
			
		}else{
			$chart[$tab->location][$values['classification'].' '] += 0;
		}
		
		if(!is_array($values['payer'])){
				$values['payer'] = array($values['payer']);
		}
		if( date('Y.m.d',$values['id']) >=  $datestart2 && date('Y.m.d',$values['id']) <=  $dateto2 
		&& ( stripos($values['classification'],'借款-支出') 	!== false 
			|| stripos($values['classification'],'借款-收入') !== false 
			|| stripos($values['classification'],'预收账款') 	!== false 
			|| stripos($values['classification'],'预付账款') 	!== false 
			|| stripos($values['classification'],'垫款-支出') !== false 
			|| stripos($values['classification'],'垫款-收入') !== false
			|| stripos($values['classification'],'汇入') !== false 
			|| stripos($values['classification'],'汇出') !== false			)){
			
			//$borrowing
			$table = '';
			foreach ($values['payer'] as $rpayer){
				if(isset($receiver_payer_id[$rpayer])){
					$table .= $receiver_payer_id[$rpayer]->name;
				}elseif(isset($receiver_payer_name[$rpayer])){
					$table .= $receiver_payer_name[$rpayer]->name;
				}else{
					$table .= $rpayer;
				}
				if(count((array)$values['payer']) > 1){
					$table .= ' | ';
				}
			}
			$table = trim($table);
			
			$borrowing_p['name'] = $borrowing_1['name'] = $borrowing_2['name'] = $table;
			$borrowing_3['name'] = $rtname;
			$borrowing_p['currency'] = $borrowing_1['currency'] = $borrowing_2['currency'] = $borrowing_3['currency'] = $currencyname;
			
			
			if($values['classification'] == '借款-支出'){
				$borrowing_p['expense']	= $borrowing[$table]['expense'] + abs((($values['amountincome']) - ($values['amountpayout'])));//*$exchangerate/$_SESSION['currencyUser']['exchangerate']);
			}
			if($values['classification'] == '借款-收入'){
				$borrowing_p['income']	= $borrowing[$table]['income'] + abs((($values['amountincome']) - ($values['amountpayout'])));//*$exchangerate/$_SESSION['currencyUser']['exchangerate']);
			}
			
			
			if($values['classification'] == '预收账款'){
				$borrowing_1['expense']	= $borrowing[$table]['expense'] + abs((($values['amountincome']) - ($values['amountpayout'])));//*$exchangerate/$_SESSION['currencyUser']['exchangerate']);
			}
			if($values['classification'] == '预付账款'){
				$borrowing_1['income']	= $borrowing[$table]['income'] + abs((($values['amountincome']) - ($values['amountpayout'])));//*$exchangerate/$_SESSION['currencyUser']['exchangerate']);
			}
			
			if($values['classification'] == '垫款-支出'){
				$borrowing_2['expense']	= $borrowing[$table]['expense'] + abs((($values['amountincome']) - ($values['amountpayout'])));//*$exchangerate/$_SESSION['currencyUser']['exchangerate']);
			}
			if($values['classification'] == '垫款-收入'){
				$borrowing_2['income']	= $borrowing[$table]['income'] + abs((($values['amountincome']) - ($values['amountpayout'])));//*$exchangerate/$_SESSION['currencyUser']['exchangerate']);
			}
			
			if($values['classification'] == '汇出'){
				$borrowing_3['expense']	= $borrowing[$rtname]['expense'] + abs((($values['amountincome']) - ($values['amountpayout'])));//*$exchangerate/$_SESSION['currencyUser']['exchangerate']);
			}
			if($values['classification'] == '汇入'){
				$borrowing_3['income']	= $borrowing[$rtname]['income'] + abs((($values['amountincome']) - ($values['amountpayout'])));//*$exchangerate/$_SESSION['currencyUser']['exchangerate']);
			}
			
			if($values['classification'] == '借款-支出' || $values['classification'] == '借款-收入'){
				$borrowing[$table]= $borrowing_p;
			}
			if($values['classification'] == '预收账款' || $values['classification'] == '预付账款'){
				$borrowing1[$table]= $borrowing_1;
			}
			if($values['classification'] == '垫款-收入' || $values['classification'] == '垫款-支出'){
				$borrowing2[$table]= $borrowing_2;
			}
			if($values['classification'] == '汇入' || $values['classification'] == '汇出'){
				$borrowing3[$rtname]= $borrowing_3;
			}
		}
		
		if( date('Y.m.d',$values['id']) >=  $datestart2 && date('Y.m.d',$values['id']) <=  $dateto2 && $values['baddebt'] == 1 ){
			if($values['classification'] == '应收账款'){
				$chartvalue['应收账款坏账 '] += (($values['amountincome']) - ($values['amountpayout']))*$exchangerate/$_SESSION['currencyUser']['exchangerate'];
			}
			if($values['classification'] == '应付账款'){
				$chartvalue['应付账款坏账 '] += (($values['amountincome']) - ($values['amountpayout']))*$exchangerate/$_SESSION['currencyUser']['exchangerate'];
			}
		}else{
			$chartvalue['应收账款坏账 '] += 0;
			$chartvalue['应付账款坏账 '] += 0;
		}
		
		
		if($values['payment'] == '收'){
			if( date('Y.m.d',$values['id']) >=  $datestart2 && date('Y.m.d',$values['id']) <=  $dateto2 ){
				$chartvalue['收入'] += (($values['amountincome']) - ($values['amountpayout']))*$exchangerate/$_SESSION['currencyUser']['exchangerate'];
			}else{
				$chartvalue['收入'] += 0;
			}
		}
		if($values['payment'] == '付'){
			if( date('Y.m.d',$values['id']) >=  $datestart2 && date('Y.m.d',$values['id']) <=  $dateto2 ){
				$chartvalue['支出'] += (($values['amountincome']) - ($values['amountpayout']))*$exchangerate/$_SESSION['currencyUser']['exchangerate'];
			}else{
				$chartvalue['支出'] += 0;
			}
		}
		
		unset($data[$key]);
   }
	
	
	
				
	$remark = '';
	foreach ($TotalRemark as $key => $r){
		if($key == 'remark_'.$tab->id ){
			$remark = $r;
		}
	}
	$balanceusd = $balancermb = $balancevnd = $balancethb = 0;
	
	if($currencyname == "USD"){
		$balanceusd = $balance+floatval($tab->balance);
	}elseif($currencyname == "VND"){
		$balancevnd = $balance+floatval($tab->balance);
	}elseif($currencyname == "RMB"){
		$balancermb = $balance+floatval($tab->balance);
	}elseif($currencyname == "Baht"){
		$balancethb = $balance+floatval($tab->balance);
	}
	$total += ($balance+floatval($tab->balance))*$exchangerate/$_SESSION['currencyUser']['exchangerate'];
	$sumbydate[date('Y-m-d')] = $total;
?>

<tr>
		<td style="width:180px;padding-left:10px!important;" ><?php echo $tab->name; ?></td>
		<td style="text-align:center;display:none;" ><?php echo $currencyname; ?></td>
		<td style="padding-right:5px!important;text-align:right;font-weight:bold;font-size:16px;" ><?php echo number_format((float)$balanceusd,2); ?></td>
		<td style="padding-right:5px!important;text-align:right;font-weight:bold;font-size:16px;" ><?php echo number_format((float)$balancermb,2); ?></td>
		<td style="padding-right:5px!important;text-align:right;font-weight:bold;font-size:16px;" ><?php echo number_format((float)$balancevnd); ?></td>
		<td style="padding-right:5px!important;text-align:right;font-weight:bold;font-size:16px;" ><?php echo number_format((float)$balancethb,2); ?></td>
		<td style="padding-right:5px!important;text-align:right;font-weight:bold;font-size:16px;" ><?php echo number_format(($balance+floatval($tab->balance))*$exchangerate/$_SESSION['currencyUser']['exchangerate'],2); ?></td>
		<td style="padding-left:10px!important;" ><input type="text" name="remark_<?php echo $tab->id; ?>" class="remark" value="<?php echo $remark ?>" /></td>
</tr>


<?php
}
?>
</tbody>
<tfoot>
<tr>
	<td></td><td style="display:none;" ><td></td></td><td></td><td></td><td  style="text-align:right;font-weight:bold;font-size:18px;" ><b>Total:</b></td><td style="text-align:right;font-weight:bold;font-size:18px;" ><?php echo number_format((float)$total,2); ?></td><td></td>
</tr>
</tfoot>
</table>

  <thead>
		<tr>
			<?php for($i = 9; $i >= 0; $i--){ ?>
					<th style="text-align:center;" ><?php echo date('Y-m-d',strtotime("-".$i." day") ) ?></th>
			<?php } ?>
		</tr>
  </thead>
  <tbody>
		<tr>
			<?php for($i = 9; $i >= 0; $i--){
					$data = json_decode(file_get_contents('currency/'.date('Ymd',strtotime("-".$i." day"))));
			?>
					<td style="text-align:center;" >1 USD = <?php echo round($data->USD,2); ?> RMB</td>
			<?php } ?>
		</tr>
		<tr>
			<?php for($i = 9; $i >= 0; $i--){
					$data = json_decode(file_get_contents('currency/'.date('Ymd',strtotime("-".$i." day"))));
				?>
					<td style="text-align:center;" >1 RMB = <?php echo number_format(1/$data->VND); ?> VND</td>
			<?php } ?>
		</tr>
		<tr>
			<?php for($i = 9; $i >= 0; $i--){
					$data = json_decode(file_get_contents('currency/'.date('Ymd',strtotime("-".$i." day"))));
				?>
					<td style="text-align:center;" >1 RMB = <?php echo round(1/$data->THB,3); ?> Bath</td>
			<?php } ?>
		</tr>
		<tr>
			<?php for($i = 9; $i >= 0; $i--){ 
					$data = json_decode(file_get_contents('currency/'.date('Ymd',strtotime("-".$i." day"))));
			?>
					<td style="text-align:center;" ><?php echo number_format((float)$sumbydate[date('Y-m-d',strtotime("-".$i." day"))],2); ?> RMB</td>
			<?php } ?>
		</tr>
  </tbody>
</table>  
</form>
<?php //echo '<pre>';print_r($borrowing);die; ?>
<?php //echo '<pre>';print_r($borrowing3); die;?>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script>
	jQuery("document").ready(function(){
		$('.remark').change(function(){
			$(".formupload").submit();
		});
	});
</script>   
<style>    
.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;
}  
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;
}
</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-1;
		}
		
		$your_date = strtotime(str_replace('.','-',$dateto).' 00:00:00');
		$datediff = round(($now - $your_date)/84600); 
		if($datediff <= 0){
			$numdatto = $datediff;
		}else{
			$numdatto = $datediff-1;
		}
		
		$your_date = strtotime(str_replace('.','-',$datestart2).' 00:00:00'); 
		$datediff = round(($now - $your_date)/84600);
		if($datediff <= 0){
			$numdatstart2 = $datediff;
		}else{
			$numdatstart2 = $datediff-1;
		}
		
		$your_date = strtotime(str_replace('.','-',$dateto2).' 00:00:00');
		$datediff = round(($now - $your_date)/84600); 
		if($datediff <= 0){
			$numdatto2 = $datediff;
		}else{
			$numdatto2 = $datediff-1;
		}
		
		
		$monthchinatext = array('一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月');
		
?>

<script>
$(document).ready(function () {
	
	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('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
   
		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);
	
	
	var start2 = moment().subtract(<?php echo $numdatstart2; ?>, 'days');
    var end2 = moment().subtract(<?php echo $numdatto2; ?>, 'days');
	
	function cb2(start2, end2 , sub) {		
		$('.reportrange2 span').html(start2.format('MMMM D, YYYY') + ' - ' + end2.format('MMMM D, YYYY'));
   
		jQuery('#datestart2').val(start2.format('YYYY.MM.DD')); 
		jQuery('#dateto2').val(end2.format('YYYY.MM.DD')); 
		if(sub != 1){
			jQuery("#formfilter2").submit();
		}
    }
	
	$('.reportrange2').daterangepicker({
        startDate: start2,
        endDate: end2,
		linkedCalendars: false,
        ranges: {
           '<?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')]
        }
    }, cb2);
	cb2(start2, end2 , 1);
	
	
});     

                         
</script>						
<!-- Styles -->
<style>
#chartdiv1, #chartdiv2, #chartdiv3  {
  width: 98%;
  height: 350px;
}
#chartdiv11{
  width: 98%;
  height: 220px;	
}
#chartdiv12{
  width: 98%;
  height: <?php echo count((array)$borrowing)*50; ?>px;	
}
#chartdiv13{
  width: 98%;
  height: <?php echo count((array)$borrowing1)*75; ?>px;	
}
#chartdiv14{
  width: 98%;
  height: <?php echo count((array)$borrowing2)*75; ?>px;	
}
#chartdiv15{
  width: 98%;
  height: <?php echo count((array)$borrowing3)*75; ?>px;	
}
#chartdiv10{
  width: 98%;
  height: 220px;	
}
#chartdiv5 , #chartdiv6 , #chartdiv8 {
  width: 49%;
  height: 400px;	
  float:left;
  margin-bottom:30px;
}
#chartdiv7 , #chartdiv9 {
  width: 49%;
  height: 400px;	
  float:left;
  margin-bottom:30px;
  border-right: 1px solid #ccc;
  margin-right: 1%;
  padding-right: 1%;
}
#chartdiv5 {
    padding-right: 1%;
    border-right: 1px solid #ccc;
    margin-right: 1%;
}
</style>
<form method="POST" id="formfilter" >
	<input value="<?php echo $datestart; ?>" id="datestart" name="datestart" type="hidden" />
	<input value="<?php echo $dateto; ?>" id="dateto" name="dateto" type="hidden" />	
</form>		

<form method="POST" id="formfilter2" >
	<input value="<?php echo $datestart2; ?>" id="datestart2" name="datestart2" type="hidden" />
	<input value="<?php echo $dateto2; ?>" id="dateto2" name="dateto2" type="hidden" />	
</form>	
<!-- Resources -->
<script src="https://www.amcharts.com/lib/4/core.js"></script>
<script src="https://www.amcharts.com/lib/4/charts.js"></script>
<script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>
<?php
$containers_op = $Setting->Container;
$containers_op = explode(PHP_EOL,$containers_op );
foreach($containers_op as $container_op ){
$container_op = explode('|',$container_op );
$datasort[] = str_replace(array("\n","\r\n","\r",PHP_EOL,' '), '',$container_op[0]);
}
$datasort = array_reverse($datasort);
//print_r($datasort);
 ?>
<!-- Chart code -->
<script>
am4core.ready(function() {
// Themes begin
am4core.useTheme(am4themes_animated);
// Themes end
// Add data
<?php 
									
										
	//ksort($chart);
	foreach ($chart as $key => $r){ 
	$num++;
	if($currentuser->gm  != '1' &&  $currentuser->role  != 'Finance' &&  $currentuser->location != $key  && $currentuser->location != '总公司' ){ 
		continue;
	}
?>	
	// Create chart instance
	var chart<?php echo $num; ?> = am4core.create("chartdiv<?php echo $num; ?>", am4charts.XYChart);
	<?php	echo 'chart'.$num.'.data = [';
			$r3 = array();
			foreach ($datasort as $pk){
				$r3[$pk] = 0;
				foreach ($r as $key2 => $r2 ){
					if($pk == str_replace(' ','',$key2)){
						//(($pk == '取现金' || $pk == '换汇')?"z":'').
						$r3[str_replace(' ','',$key2)] = $r2 ; break;
					}
				}
			}
			
			$r = $r3; 	
		$dbu = 0;
		foreach ($r as $key2 => $r2 ){ $dbu++;
			//if(str_replace(' ','',$key2) == '应收账款' || str_replace(' ','',$key2) == '应收账款'){ continue ; }
	?>
		  {
			"region": "<?php echo $key; ?>",
			"state": "<?php echo  str_replace(' ','',$key2); ?>",
			"sales": "<?php echo round(abs($r2),2); ?>"
		  },
	<?php }
		echo '];';
	?>
// Create axes
var yAxis<?php echo $num; ?> = chart<?php echo $num; ?>.yAxes.push(new am4charts.CategoryAxis());
yAxis<?php echo $num; ?>.dataFields.category = "state";
yAxis<?php echo $num; ?>.renderer.grid.template.location = 0;
yAxis<?php echo $num; ?>.renderer.labels.template.fontSize = 10;
yAxis<?php echo $num; ?>.renderer.minGridDistance = 10;

var xAxis<?php echo $num; ?> = chart<?php echo $num; ?>.xAxes.push(new am4charts.ValueAxis());

// Create series
var series<?php echo $num; ?> = chart<?php echo $num; ?>.series.push(new am4charts.ColumnSeries());
series<?php echo $num; ?>.dataFields.valueX = "sales";
series<?php echo $num; ?>.dataFields.categoryY = "state";
series<?php echo $num; ?>.columns.template.tooltipText = "{categoryY}: [bold]{valueX}[/]";
series<?php echo $num; ?>.columns.template.strokeWidth = 0;

// as by default columns of the same series are of the same color, we add adapter which takes colors from chart.colors color set
series<?php echo $num; ?>.columns.template.adapter.add("fill", function(fill, target) {
  return chart<?php echo $num; ?>.colors.getIndex(target.dataItem.index);
});

/*
series<?php echo $num; ?>.columns.template.adapter.add("fill", function(fill, target) {
  if (target.dataItem) {
    switch(target.dataItem.dataContext.region) {     
      case "中国":
        return chart<?php echo $num; ?>.colors.getIndex(9);
        break;
      case "越南":
        return chart<?php echo $num; ?>.colors.getIndex(11);
        break;
      case "泰国":
        return chart<?php echo $num; ?>.colors.getIndex(1);
        break;
    }
  }
  return fill;
});
*/
chart<?php echo $num; ?>.cursor = new am4charts.XYCursor();


let title<?php echo $num; ?> = chart<?php echo $num; ?>.titles.create();
title<?php echo $num; ?>.text = "费用归类<?php echo $key; ?> <?php echo $datestart.' - '.$dateto; ?>";
title<?php echo $num; ?>.fontSize = 22;
title<?php echo $num; ?>.marginBottom = 20;
<?php } ?>


// Create chart instance
var chart10 = am4core.create("chartdiv10", am4charts.XYChart);
chart10.data = [{
			"region": "中国",
			"state": "",
			"sales": "0"
			},{
			"region": "中国",
			"state": "收入",
			"sales": "<?php echo round(abs($chartvalue['收入']),2); ?>"
			},{
			"region": "中国",
			"state": "支出",
			"sales": "<?php echo round(abs($chartvalue['支出']),2); ?>"
		  }];// Create axes
var yAxis10 = chart10.yAxes.push(new am4charts.CategoryAxis());
yAxis10.dataFields.category = "state";
yAxis10.renderer.grid.template.location = 0;
yAxis10.renderer.labels.template.fontSize = 10;
yAxis10.renderer.minGridDistance = 10;

var xAxis10 = chart10.xAxes.push(new am4charts.ValueAxis());

// Create series
var series10 = chart10.series.push(new am4charts.ColumnSeries());
series10.dataFields.valueX = "sales";
series10.dataFields.categoryY = "state";
series10.columns.template.tooltipText = "{categoryY}(RMB): [bold]{valueX}[/]";
series10.columns.template.strokeWidth = 0;

// as by default columns of the same series are of the same color, we add adapter which takes colors from chart.colors color set
series10.columns.template.adapter.add("fill", function(fill, target) {
  return chart10.colors.getIndex(target.dataItem.index);
});

chart10.cursor = new am4charts.XYCursor();


let title10 = chart10.titles.create();
title10.text = "收入/支出 汇总表(RMB) <?php echo $datestart2.' - '.$dateto2; ?>";
title10.fontSize = 22;
title10.marginBottom = 20;


// Create chart instance
var chart11 = am4core.create("chartdiv11", am4charts.XYChart);
chart11.data = [{
			"region": "中国",
			"state": "",
			"sales": "0"
			},{
			"region": "中国",
			"state": "应收账款坏账",
			"sales": "<?php echo round(abs($chartvalue['应收账款坏账 ']),2); ?>"
			},{
			"region": "中国",
			"state": "应付账款坏账",
			"sales": "<?php echo round(abs($chartvalue['应付账款坏账 ']),2); ?>"
		  }];// Create axes
var yAxis11 = chart11.yAxes.push(new am4charts.CategoryAxis());
yAxis11.dataFields.category = "state";
yAxis11.renderer.grid.template.location = 0;
yAxis11.renderer.labels.template.fontSize = 10;
yAxis11.renderer.minGridDistance = 10;

var xAxis11 = chart11.xAxes.push(new am4charts.ValueAxis());

// Create series
var series11 = chart11.series.push(new am4charts.ColumnSeries());
series11.dataFields.valueX = "sales";
series11.dataFields.categoryY = "state";
series11.columns.template.tooltipText = "{categoryY}(RMB): [bold]{valueX}[/]";
series11.columns.template.strokeWidth = 0;

// as by default columns of the same series are of the same color, we add adapter which takes colors from chart.colors color set
series11.columns.template.adapter.add("fill", function(fill, target) {
  return chart11.colors.getIndex(target.dataItem.index);
});

chart11.cursor = new am4charts.XYCursor();


let title11 = chart11.titles.create();
title11.text = "坏账(RMB) <?php echo $datestart2.' - '.$dateto2; ?>";
title11.fontSize = 22;
title11.marginBottom = 20;


	

}); // end am4core.ready()



</script>

<!-- HTML -->
<div class="reportrange" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc; width: 350px" >
  <i class="fa fa-calendar"></i>&nbsp;
    <span></span> <i class="fa fa-caret-down"></i>
</div>
<?php $num = 0; foreach ($chart as $key => $r){ 
$num++;
if($currentuser->gm  != '1' &&  $currentuser->role  != 'Finance' &&  $currentuser->location != $key   && $currentuser->location != '总公司'  ){ 
		continue;
}
 ?>
<div id="chartdiv<?php echo $num; ?>"></div>					
<?php } 
if($currentuser->gm  == '1' || $currentuser->location == '总公司'){ 
?>	
<script>
am4core.ready(function() {

// Themes begin
am4core.useTheme(am4themes_animated);
// Themes end

/**
 * Chart design taken from Samsung health app
 */

var chart5 = am4core.create("chartdiv5", am4charts.XYChart);
chart5.hiddenState.properties.opacity = 0; // this creates initial fade-in

chart5.paddingBottom = 30;

chart5.data = [
<?php foreach($usercreate as $r){ if($r['info']->gm == 1){continue;} ?>
{
    "name": "<?php echo $r['info']->name.'/'.$r['info']->location; ?>",
    "steps": <?php echo $r['count']; ?>,
    "href": "https://lehuuthoai.com/wp-content/uploads/2019/03/person-icon-blue-18.png"
},
<?php } ?>
];

var categoryAxis5 = chart5.xAxes.push(new am4charts.CategoryAxis());
categoryAxis5.dataFields.category = "name";
categoryAxis5.renderer.grid.template.strokeOpacity = 0.1;
categoryAxis5.renderer.minGridDistance = 10;
categoryAxis5.renderer.labels.template.dy = 35;
categoryAxis5.renderer.tooltip.dy = 35;

var valueAxis5 = chart5.yAxes.push(new am4charts.ValueAxis());
valueAxis5.renderer.inside = true;
valueAxis5.renderer.labels.template.fillOpacity = 0.7;
valueAxis5.renderer.grid.template.strokeOpacity = 0.1;
valueAxis5.min = 0;
valueAxis5.cursorTooltipEnabled = false;
valueAxis5.renderer.baseGrid.strokeOpacity = 0;

var series5 = chart5.series.push(new am4charts.ColumnSeries);
series5.dataFields.valueY = "steps";
series5.dataFields.categoryX = "name";
series5.tooltipText = "{valueY.value}";
series5.tooltip.pointerOrientation = "vertical";
series5.tooltip.dy = - 6;
series5.columnsContainer.zIndex = 100;

var columnTemplate = series5.columns.template;
columnTemplate.width = am4core.percent(20);
columnTemplate.maxWidth = 36;
columnTemplate.column.cornerRadius(10, 10, 10, 10);
columnTemplate.strokeOpacity = 0;

series5.heatRules.push({ target: columnTemplate, property: "fill", dataField: "valueY", min: am4core.color("#e5dc36"), max: am4core.color("#5faa46") });
series5.mainContainer.mask = undefined;

var cursor = new am4charts.XYCursor();
chart5.cursor = cursor;
cursor.lineX.disabled = true;
cursor.lineY.disabled = true;
cursor.behavior = "none";

var bullet = columnTemplate.createChild(am4charts.CircleBullet);
bullet.circle.radius = 20;
bullet.valign = "bottom";
bullet.align = "center";
bullet.isMeasured = true;
bullet.mouseEnabled = false;
bullet.verticalCenter = "bottom";
bullet.interactionsEnabled = false;

var hoverState = bullet.states.create("hover");

var outlineCircle = bullet.createChild(am4core.Circle);
outlineCircle.adapter.add("radius", function (radius, target) {
    var circleBullet = target.parent;
    return circleBullet.circle.pixelRadius + 0;
})

var image = bullet.createChild(am4core.Image);
image.width = 36;
image.height = 36;
image.horizontalCenter = "middle";
image.verticalCenter = "middle";
image.propertyFields.href = "href";

image.adapter.add("mask", function (mask, target) {
    var circleBullet = target.parent;
    return circleBullet.circle;
})

var previousBullet;
chart5.cursor.events.on("cursorpositionchanged", function (event) {
    var dataItem = series5.tooltipDataItem;

    if (dataItem.column) {
        var bullet = dataItem.column.children.getIndex(1);

        if (previousBullet && previousBullet != bullet) {
            previousBullet.isHover = false;
        }

        if (previousBullet != bullet) {

            var hs = bullet.states.getKey("hover");
            hs.properties.dy = -bullet.parent.pixelHeight + 0;
            bullet.isHover = true;

            previousBullet = bullet;
        }
    }
})

let title5 = chart5.titles.create();
title5.text = "Created/创建 <?php echo $datestart.' - '.$dateto; ?>";
title5.fontSize = 22;
title5.marginBottom = 20;


var chart6 = am4core.create("chartdiv6", am4charts.XYChart);
chart6.hiddenState.properties.opacity = 0; // this creates initial fade-in

chart6.paddingBottom = 30;

chart6.data = [
<?php foreach($useredit as $r){ if($r['info']->gm == 1){continue;} ?>
{
    "name": "<?php echo $r['info']->name.'/'.$r['info']->location; ?>",
    "steps": <?php echo $r['count']; ?>,
    "href": "https://lehuuthoai.com/wp-content/uploads/2019/03/person-icon-blue-18.png"
},
<?php } ?>
];

var categoryAxis6 = chart6.xAxes.push(new am4charts.CategoryAxis());
categoryAxis6.dataFields.category = "name";
categoryAxis6.renderer.grid.template.strokeOpacity = 0.1;
categoryAxis6.renderer.minGridDistance = 10;
categoryAxis6.renderer.labels.template.dy = 35;
categoryAxis6.renderer.tooltip.dy = 35;

var valueAxis6 = chart6.yAxes.push(new am4charts.ValueAxis());
valueAxis6.renderer.inside = true;
valueAxis6.renderer.labels.template.fillOpacity = 0.7;
valueAxis6.renderer.grid.template.strokeOpacity = 0.1;
valueAxis6.min = 0;
valueAxis6.cursorTooltipEnabled = false;
valueAxis6.renderer.baseGrid.strokeOpacity = 0;

var series6 = chart6.series.push(new am4charts.ColumnSeries);
series6.dataFields.valueY = "steps";
series6.dataFields.categoryX = "name";
series6.tooltipText = "{valueY.value}";
series6.tooltip.pointerOrientation = "vertical";
series6.tooltip.dy = - 6;
series6.columnsContainer.zIndex = 100;

var columnTemplate = series6.columns.template;
columnTemplate.width = am4core.percent(20);
columnTemplate.maxWidth = 36;
columnTemplate.column.cornerRadius(10, 10, 10, 10);
columnTemplate.strokeOpacity = 0;

series6.heatRules.push({ target: columnTemplate, property: "fill", dataField: "valueY", min: am4core.color("#e5dc36"), max: am4core.color("#5faa46") });
series6.mainContainer.mask = undefined;

var cursor = new am4charts.XYCursor();
chart6.cursor = cursor;
cursor.lineX.disabled = true;
cursor.lineY.disabled = true;
cursor.behavior = "none";

var bullet = columnTemplate.createChild(am4charts.CircleBullet);
bullet.circle.radius = 20;
bullet.valign = "bottom";
bullet.align = "center";
bullet.isMeasured = true;
bullet.mouseEnabled = false;
bullet.verticalCenter = "bottom";
bullet.interactionsEnabled = false;

var hoverState = bullet.states.create("hover");

var outlineCircle = bullet.createChild(am4core.Circle);
outlineCircle.adapter.add("radius", function (radius, target) {
    var circleBullet = target.parent;
    return circleBullet.circle.pixelRadius + 0;
})

var image = bullet.createChild(am4core.Image);
image.width = 36;
image.height = 36;
image.horizontalCenter = "middle";
image.verticalCenter = "middle";
image.propertyFields.href = "href";

image.adapter.add("mask", function (mask, target) {
    var circleBullet = target.parent;
    return circleBullet.circle;
})

var previousBullet;
chart6.cursor.events.on("cursorpositionchanged", function (event) {
    var dataItem = series6.tooltipDataItem;

    if (dataItem.column) {
        var bullet = dataItem.column.children.getIndex(1);

        if (previousBullet && previousBullet != bullet) {
            previousBullet.isHover = false;
        }

        if (previousBullet != bullet) {

            var hs = bullet.states.getKey("hover");
            hs.properties.dy = -bullet.parent.pixelHeight + 0;
            bullet.isHover = true;

            previousBullet = bullet;
        }
    }
})

let title6 = chart6.titles.create();
title6.text = "Modified/改性 <?php echo $datestart.' - '.$dateto; ?>";
title6.fontSize = 22;
title6.marginBottom = 20;


// Create chart instance
var chart7 = am4core.create("chartdiv7", am4charts.XYChart);

// Add data
chart7.data = [
<?php foreach($controler as $r){  ?>
	{
	  "User": "<?php echo $r['info']->name; ?>",
	  "expenses": <?php echo (int)$r['revision']; ?>,
	  "income": <?php echo (int)$r['approval']; ?>,
	  "violations": <?php echo (int)$r['violations']; ?>
	},
<?php } ?>
];

// Create axes
var categoryAxis7 = chart7.yAxes.push(new am4charts.CategoryAxis());
categoryAxis7.dataFields.category = "User";
categoryAxis7.numberFormatter.numberFormat = "#";
categoryAxis7.renderer.inversed = true;
categoryAxis7.renderer.grid.template.location = 0;
categoryAxis7.renderer.cellStartLocation = 0.1;
categoryAxis7.renderer.cellEndLocation = 0.9;

var  valueAxis7 = chart7.xAxes.push(new am4charts.ValueAxis()); 
valueAxis7.renderer.opposite = true;

// Create series
function createSeries(field, name) {
  var series7 = chart7.series.push(new am4charts.ColumnSeries());
  series7.dataFields.valueX = field;
  series7.dataFields.categoryY = "User";
  series7.name = name;
  series7.columns.template.tooltipText = "{name}: [bold]{valueX}[/]";
  series7.columns.template.height = am4core.percent(100);
  series7.sequencedInterpolation = true;

  var valueLabel7 = series7.bullets.push(new am4charts.LabelBullet());
  valueLabel7.label.text = "{valueX}";
  valueLabel7.label.horizontalCenter = "left";
  valueLabel7.label.dx = 10;
  valueLabel7.label.hideOversized = false;
  valueLabel7.label.truncate = false;

  var categoryLabel7 = series7.bullets.push(new am4charts.LabelBullet());
  categoryLabel7.label.text = "{name}";
  categoryLabel7.label.horizontalCenter = "right";
  categoryLabel7.label.dx = -10;
  categoryLabel7.label.fill = am4core.color("#fff");
  categoryLabel7.label.hideOversized = false;
  categoryLabel7.label.truncate = false;
}

createSeries("income", "Approval/Deny/批准/拒绝");
createSeries("expenses", "Revision/调整");
createSeries("violations", "Violations/违规 24h");
let title7 = chart7.titles.create();
title7.text = "Controller progress <?php echo $datestart.' - '.$dateto; ?>";
title7.fontSize = 22;
title7.marginBottom = 20;



var chart8 = am4core.create("chartdiv8", am4charts.XYChart);
chart8.hiddenState.properties.opacity = 0; // this creates initial fade-in

chart8.paddingBottom = 30;

chart8.data = [
<?php foreach($userviolations as $r){ if($r['info']->gm == 1){continue;} ?>
{
    "name": "<?php echo $r['info']->name.'/'.$r['info']->location; ?>",
    "steps": <?php echo $r['count']; ?>,
    "href": "https://lehuuthoai.com/wp-content/uploads/2019/03/person-icon-blue-18.png"
},
<?php } ?>
];

var categoryAxis8 = chart8.xAxes.push(new am4charts.CategoryAxis());
categoryAxis8.dataFields.category = "name";
categoryAxis8.renderer.grid.template.strokeOpacity = 0.1;
categoryAxis8.renderer.minGridDistance = 10;
categoryAxis8.renderer.labels.template.dy = 35;
categoryAxis8.renderer.tooltip.dy = 35;

var valueAxis8 = chart8.yAxes.push(new am4charts.ValueAxis());
valueAxis8.renderer.inside = true;
valueAxis8.renderer.labels.template.fillOpacity = 0.7;
valueAxis8.renderer.grid.template.strokeOpacity = 0.1;
valueAxis8.min = 0;
valueAxis8.cursorTooltipEnabled = false;
valueAxis8.renderer.baseGrid.strokeOpacity = 0;

var series8 = chart8.series.push(new am4charts.ColumnSeries);
series8.dataFields.valueY = "steps";
series8.dataFields.categoryX = "name";
series8.tooltipText = "{valueY.value}";
series8.tooltip.pointerOrientation = "vertical";
series8.tooltip.dy = - 6;
series8.columnsContainer.zIndex = 100;

var columnTemplate = series8.columns.template;
columnTemplate.width = am4core.percent(20);
columnTemplate.maxWidth = 36;
columnTemplate.column.cornerRadius(10, 10, 10, 10);
columnTemplate.strokeOpacity = 0;

series8.heatRules.push({ target: columnTemplate, property: "fill", dataField: "valueY", min: am4core.color("#e5dc36"), max: am4core.color("#5faa46") });
series8.mainContainer.mask = undefined;

var cursor = new am4charts.XYCursor();
chart8.cursor = cursor;
cursor.lineX.disabled = true;
cursor.lineY.disabled = true;
cursor.behavior = "none";

var bullet = columnTemplate.createChild(am4charts.CircleBullet);
bullet.circle.radius = 20;
bullet.valign = "bottom";
bullet.align = "center";
bullet.isMeasured = true;
bullet.mouseEnabled = false;
bullet.verticalCenter = "bottom";
bullet.interactionsEnabled = false;

var hoverState = bullet.states.create("hover");

var outlineCircle = bullet.createChild(am4core.Circle);
outlineCircle.adapter.add("radius", function (radius, target) {
    var circleBullet = target.parent;
    return circleBullet.circle.pixelRadius + 0;
})

var image = bullet.createChild(am4core.Image);
image.width = 36;
image.height = 36;
image.horizontalCenter = "middle";
image.verticalCenter = "middle";
image.propertyFields.href = "href";

image.adapter.add("mask", function (mask, target) {
    var circleBullet = target.parent;
    return circleBullet.circle;
})

var previousBullet;
chart8.cursor.events.on("cursorpositionchanged", function (event) {
    var dataItem = series8.tooltipDataItem;

    if (dataItem.column) {
        var bullet = dataItem.column.children.getIndex(1);

        if (previousBullet && previousBullet != bullet) {
            previousBullet.isHover = false;
        }

        if (previousBullet != bullet) {

            var hs = bullet.states.getKey("hover");
            hs.properties.dy = -bullet.parent.pixelHeight + 0;
            bullet.isHover = true;

            previousBullet = bullet;
        }
    }
})

let title8 = chart8.titles.create();
title8.text = "Violations/违规 <?php echo $datestart.' - '.$dateto; ?>";
title8.fontSize = 22;
title8.marginBottom = 20;

<?php
$mywork = json_decode(file_get_contents('data/mywork.json'));
foreach ($mywork as $r){
	foreach($user as $u){ 
		if($u->id == $r->who ){
								$uinfo = $u;break;
		}
	}
	$task[$r->who]['info'] = $uinfo;
	$task[$r->who]['total'] = $task[$r->who]['total']+1;
	if($r->status == 'complete') { 
		$task[$r->who]['complete'] = $task[$r->who]['complete']+1;
	}  							
	
}
 ?>
// Create chart instance
var chart9 = am4core.create("chartdiv9", am4charts.XYChart);

// Add data
chart9.data = [
<?php foreach($task as $r){  ?>
	{
	  "User": "<?php echo $r['info']->name; ?>",
	  "expenses": <?php echo (int)$r['total']; ?>,
	  "income": <?php echo (int)$r['complete']; ?>
	},
<?php } ?>
];



// Create axes
var categoryAxis9 = chart9.yAxes.push(new am4charts.CategoryAxis());
categoryAxis9.dataFields.category = "User";
categoryAxis9.numberFormatter.numberFormat = "#";
categoryAxis9.renderer.inversed = true;
categoryAxis9.renderer.grid.template.location = 0;
categoryAxis9.renderer.cellStartLocation = 0.1;
categoryAxis9.renderer.cellEndLocation = 0.9;

var  valueAxis9 = chart9.xAxes.push(new am4charts.ValueAxis()); 
valueAxis9.renderer.opposite = true;

// Create series
function createSeries1(field, name) {
  var series9 = chart9.series.push(new am4charts.ColumnSeries());
  series9.dataFields.valueX = field;
  series9.dataFields.categoryY = "User";
  series9.name = name;
  series9.columns.template.tooltipText = "{name}: [bold]{valueX}[/]";
  series9.columns.template.height = am4core.percent(100);
  series9.sequencedInterpolation = true;

  var valueLabel9 = series9.bullets.push(new am4charts.LabelBullet());
  valueLabel9.label.text = "{valueX}";
  valueLabel9.label.horizontalCenter = "left";
  valueLabel9.label.dx = 10;
  valueLabel9.label.hideOversized = false;
  valueLabel9.label.truncate = false;

  var categoryLabel9 = series9.bullets.push(new am4charts.LabelBullet());
  categoryLabel9.label.text = "{name}";
  categoryLabel9.label.horizontalCenter = "right";
  categoryLabel9.label.dx = -10;
  categoryLabel9.label.fill = am4core.color("#fff");
  categoryLabel9.label.hideOversized = false;
  categoryLabel9.label.truncate = false;
}
createSeries1("expenses", "Task/任务");
createSeries1("income", "Complete/完成");

let title9 = chart9.titles.create();
title9.text = "Task manager/任务管理器 <?php echo $datestart.' - '.$dateto; ?>";
title9.fontSize = 22;
title9.marginBottom = 20;

// Create chart instance
var chart12 = am4core.create("chartdiv12", am4charts.XYChart);

// Add data
chart12.data = [
<?php $maxvalue = 0;  foreach( $borrowing as $r){ 
	if($r['income'] > $maxvalue ) { $maxvalue = $r['income']; }
	if($r['expense'] > $maxvalue ) { $maxvalue = $r['expense']; }
 ?>
	{
	  "person": "<?php echo $r['name']; ?>",
	  "income": <?php echo $r['income']; ?>,	  
	  "expenses": <?php echo $r['expense']; ?>,
	  "cur": "<?php echo $r['currency']; ?>"
	},
<?php } ?>
];

// Create axes



var categoryAxis12 = chart12.yAxes.push(new am4charts.CategoryAxis());
categoryAxis12.dataFields.category = "person";
categoryAxis12.numberFormatter.numberFormat = "#,###";
categoryAxis12.renderer.inversed = true;
categoryAxis12.renderer.grid.template.location = 0;
categoryAxis12.renderer.cellStartLocation = 0.1;
categoryAxis12.renderer.cellEndLocation = 0.9;

var  valueAxis12 = chart12.xAxes.push(new am4charts.ValueAxis()); 
valueAxis12.renderer.opposite = true;

var axisBreak = valueAxis12.axisBreaks.create();
axisBreak.startValue = <?php echo round($maxvalue/50); ?>;
axisBreak.endValue = <?php echo $maxvalue*0.99; ?>;

// fixed axis break
//var d = (axisBreak.endValue - axisBreak.startValue) / (valueAxis.max - valueAxis.min);
axisBreak.breakSize = 0.0005; // 0.05 means that the break will take 5% of the total value axis height

// make break expand on hover
var hoverState = axisBreak.states.create("hover");
hoverState.properties.breakSize = 1;
hoverState.properties.opacity = 0.1;
hoverState.transitionDuration = 1500;

axisBreak.defaultState.transitionDuration = 1000;


// Create series
function createSeries12(field, name) {
  var series = chart12.series.push(new am4charts.ColumnSeries());
  series.dataFields.valueX = field;
  series.dataFields.categoryY = "person";
  series.name = name;
  series.columns.template.tooltipText = "{name} {cur}: [bold]{valueX}[/]";
  series.columns.template.height = am4core.percent(100);
  series.sequencedInterpolation = true;

  var valueLabel = series.bullets.push(new am4charts.LabelBullet());
  valueLabel.label.text = "{valueX} {cur}";
  valueLabel.label.horizontalCenter = "left";
  valueLabel.label.dx = 10;
  valueLabel.label.hideOversized = false;
  valueLabel.label.truncate = false;

  var categoryLabel = series.bullets.push(new am4charts.LabelBullet());
  categoryLabel.label.text = "{name}";
  categoryLabel.label.horizontalCenter = "right";
  categoryLabel.label.dx = -10;
  categoryLabel.label.fill = am4core.color("#fff");
  categoryLabel.label.hideOversized = false;
  categoryLabel.label.truncate = false;
}

createSeries12("income", "借款-收入");
createSeries12("expenses", "借款-支出");

let title12 = chart12.titles.create();
title12.text = "借款-支出/借款-收入 <?php echo $datestart2.' - '.$dateto2; ?>";
title12.fontSize = 22;
title12.marginBottom = 20;




// Create chart instance
var chart13 = am4core.create("chartdiv13", am4charts.XYChart);

// Add data
chart13.data = [
<?php $maxvalue = 0;  foreach( $borrowing1 as $r){ 
	if($r['income'] > $maxvalue ) { $maxvalue = $r['income']; }
	if($r['expense'] > $maxvalue ) { $maxvalue = $r['expense']; }
 ?>
	{
	  "person": "<?php echo $r['name']; ?>",
	  "income": <?php echo $r['income']; ?>,	  
	  "expenses": <?php echo $r['expense']; ?>,
	  "cur": "<?php echo $r['currency']; ?>"
	},
<?php } ?>
];

// Create axes

var categoryAxis13 = chart13.yAxes.push(new am4charts.CategoryAxis());
categoryAxis13.dataFields.category = "person";
categoryAxis13.numberFormatter.numberFormat = "#,###";
categoryAxis13.renderer.inversed = true;
categoryAxis13.renderer.grid.template.location = 0;
categoryAxis13.renderer.cellStartLocation = 0.1;
categoryAxis13.renderer.cellEndLocation = 0.9;

var  valueAxis13 = chart13.xAxes.push(new am4charts.ValueAxis()); 
valueAxis13.renderer.opposite = true;




// Create series
function createSeries13(field, name) {
  var series = chart13.series.push(new am4charts.ColumnSeries());
  series.dataFields.valueX = field;
  series.dataFields.categoryY = "person";
  series.name = name;
  series.columns.template.tooltipText = "{name} {cur}: [bold]{valueX}[/]";
  series.columns.template.height = am4core.percent(100);
  series.sequencedInterpolation = true;

  var valueLabel = series.bullets.push(new am4charts.LabelBullet());
  valueLabel.label.text = "{valueX} {cur}";
  valueLabel.label.horizontalCenter = "left";
  valueLabel.label.dx = 10;
  valueLabel.label.hideOversized = false;
  valueLabel.label.truncate = false;

  var categoryLabel = series.bullets.push(new am4charts.LabelBullet());
  categoryLabel.label.text = "{name}";
  categoryLabel.label.horizontalCenter = "right";
  categoryLabel.label.dx = -10;
  categoryLabel.label.fill = am4core.color("#fff");
  categoryLabel.label.hideOversized = false;
  categoryLabel.label.truncate = false;
}

createSeries13("income", "预付账款");
createSeries13("expenses", "预收账款");

let title13 = chart13.titles.create();
title13.text = "预收账款/预付账款 <?php echo $datestart2.' - '.$dateto2; ?>";
title13.fontSize = 22;
title13.marginBottom = 20;


// Create chart instance
var chart14 = am4core.create("chartdiv14", am4charts.XYChart);

// Add data
chart14.data = [
<?php $maxvalue = 0;  foreach( $borrowing2 as $r){ 
	if($r['income'] > $maxvalue ) { $maxvalue = $r['income']; }
	if($r['expense'] > $maxvalue ) { $maxvalue = $r['expense']; }
	if($r['currency'] == 'VND'){
		$r['income'] = round($r['income']/1000);
		$r['expense'] = round($r['expense']/1000);
		$r['currency'] = ' (x1,000 VND)';
	}
 ?>
	{
	  "person": "<?php echo $r['name']; ?>",
	  "income": <?php echo $r['income']; ?>,	  
	  "expenses": <?php echo $r['expense']; ?>,
	  "cur": "<?php echo $r['currency']; ?>"
	},
<?php } ?>
];

// Create axes


var categoryAxis14 = chart14.yAxes.push(new am4charts.CategoryAxis());
categoryAxis14.dataFields.category = "person";
categoryAxis14.numberFormatter.numberFormat = "#,###";
categoryAxis14.renderer.inversed = true;
categoryAxis14.renderer.grid.template.location = 0;
categoryAxis14.renderer.cellStartLocation = 0.1;
categoryAxis14.renderer.cellEndLocation = 0.9;

var  valueAxis14 = chart14.xAxes.push(new am4charts.ValueAxis()); 
valueAxis14.renderer.opposite = true;




// Create series
function createSeries14(field, name) {
  var series = chart14.series.push(new am4charts.ColumnSeries());
  series.dataFields.valueX = field;
  series.dataFields.categoryY = "person";
  series.name = name;
  series.columns.template.tooltipText = "{name} {cur}: [bold]{valueX}[/]";
  series.columns.template.height = am4core.percent(100);
  series.sequencedInterpolation = true;

if(field == 'income' ){
	 series.fill =  am4core.color("green")
  }
  if(field == 'expenses' ){
	 series.fill =  am4core.color("red")
  }
  
  var valueLabel = series.bullets.push(new am4charts.LabelBullet());
  valueLabel.label.text = "{valueX} {cur}";
  valueLabel.label.horizontalCenter = "left";
  valueLabel.label.dx = 10;
  valueLabel.label.hideOversized = false;
  valueLabel.label.truncate = false;

  var categoryLabel = series.bullets.push(new am4charts.LabelBullet());
  categoryLabel.label.text = "{name}";
  categoryLabel.label.horizontalCenter = "right";
  categoryLabel.label.dx = -10;
  categoryLabel.label.fill = am4core.color("#fff");
  categoryLabel.label.hideOversized = false;
  categoryLabel.label.truncate = false;
}

createSeries14("income", "垫款-收入");
createSeries14("expenses", "垫款-支出");

let title14 = chart14.titles.create();
title14.text = "垫款-支出/垫款-收入 <?php echo $datestart2.' - '.$dateto2; ?>";
title14.fontSize = 22;
title14.marginBottom = 20;



// Create chart instance
var chart15 = am4core.create("chartdiv15", am4charts.XYChart);

// Add data
chart15.data = [
<?php $maxvalue = 0;  foreach( $borrowing3 as $r){ 
	if($r['income'] > $maxvalue ) { $maxvalue = $r['income']; }
	if($r['expense'] > $maxvalue ) { $maxvalue = $r['expense']; }
	if($r['currency'] == 'VND'){
		$r['income'] = round($r['income']/1000);
		$r['expense'] = round($r['expense']/1000);
		$r['currency'] = ' (x1,000 VND)';
	}
 ?>
	{
	  "person": "<?php echo $r['name']; ?>",
	  "income": <?php if($r['income']){echo $r['income'];}else{echo '0';} ?>,	  
	  "expenses": <?php if($r['expense']){echo $r['expense'];}else{echo '0';} ?>,
	  "cur": "<?php echo $r['currency']; ?>"
	},
<?php } ?>
];

// Create axes


var categoryAxis15 = chart15.yAxes.push(new am4charts.CategoryAxis());
categoryAxis15.dataFields.category = "person";
categoryAxis15.numberFormatter.numberFormat = "#,###";
categoryAxis15.renderer.inversed = true;
categoryAxis15.renderer.grid.template.location = 0;
categoryAxis15.renderer.cellStartLocation = 0.1;
categoryAxis15.renderer.cellEndLocation = 0.9;

var  valueAxis15 = chart15.xAxes.push(new am4charts.ValueAxis()); 
valueAxis15.renderer.opposite = true;




// Create series
function createSeries15(field, name) {
  var series = chart15.series.push(new am4charts.ColumnSeries());
  series.dataFields.valueX = field;
  series.dataFields.categoryY = "person";
  series.name = name;
  series.columns.template.tooltipText = "{name} {cur}: [bold]{valueX}[/]";
  series.columns.template.height = am4core.percent(100);
  series.sequencedInterpolation = true;

  if(field == 'income' ){
	 series.fill =  am4core.color("green")
  }
  if(field == 'expenses' ){
	 series.fill =  am4core.color("red")
  }
  
  var valueLabel = series.bullets.push(new am4charts.LabelBullet());
  valueLabel.label.text = "{valueX} {cur}";
  valueLabel.label.horizontalCenter = "left";
  valueLabel.label.dx = 10;
  valueLabel.label.hideOversized = false;
  valueLabel.label.truncate = false;
  
  

  var categoryLabel = series.bullets.push(new am4charts.LabelBullet());
  categoryLabel.label.text = "{name}";
  categoryLabel.label.horizontalCenter = "right";
  categoryLabel.label.dx = -10;
  categoryLabel.label.fill = am4core.color("#fff");
  categoryLabel.label.hideOversized = false;
  categoryLabel.label.truncate = false;
}

createSeries15("income", "汇入");
createSeries15("expenses", "汇出");

let title15 = chart15.titles.create();
title15.text = "汇出/汇入 <?php echo $datestart2.' - '.$dateto2; ?>";
title15.fontSize = 22;
title15.marginBottom = 20;

}); 
</script>

<!-- HTML -->
<div class="reportrange2" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc; width: 350px" >
  <i class="fa fa-calendar"></i>&nbsp;
    <span></span> <i class="fa fa-caret-down"></i>
</div>
<div id="chartdiv11"></div>
<div id="chartdiv10"></div>
<div id="chartdiv12"></div>
<div id="chartdiv13"></div>
<div id="chartdiv14"></div>
<div id="chartdiv15"></div>
<div id="chartdiv5"></div>

<div id="chartdiv6"></div>
<div id="chartdiv7"></div>
<div id="chartdiv8"></div>
<div id="chartdiv9"></div>							
<?php    
}
// FOOTER
include 'tpl/footer.php';
