<?php
date_default_timezone_set('Asia/Bangkok');
error_reporting(E_ERROR);
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_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);die;
if ($login['status'] == 200) {
   if($currentuser->gm != 1 && $currentuser->total != '1'  ){
		header('location: login.php');
		exit;
	}
} else {
    header('location: login.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' and $_POST['updateremak'] == 1 ) {
	$income = json_decode( file_get_contents("data/income.json"),true );
	$cost = json_decode( file_get_contents("data/cost.json"),true );
	foreach ($_POST as $key => $r){
		$r =  str_replace(',','',$r);
		if(strpos($key,'income_') !== false){
			if(strpos($key,'越南') !== false){
				$income['越南'][str_replace(array('越南_','income_'),'',$key)] = $r;
			}elseif(strpos($key,'中国') !== false){
				$income['中国'][str_replace(array('中国_','income_'),'',$key)] = $r;
			}elseif(strpos($key,'泰国') !== false){
				$income['泰国'][str_replace(array('泰国_','income_'),'',$key)] = $r;
			}			
		}
		if(strpos($key,'cost_') !== false){
			if(strpos($key,'越南') !== false){
				$cost['越南'][str_replace(array('越南_','cost_'),'',$key)] = $r;
			}elseif(strpos($key,'中国') !== false){
				$cost['中国'][str_replace(array('中国_','cost_'),'',$key)] = $r;
			}elseif(strpos($key,'泰国') !== false){
				$cost['泰国'][str_replace(array('泰国_','cost_'),'',$key)] = $r;
			}			
		}
	}
	file_put_contents("data/income.json", json_encode($income));
	file_put_contents("data/cost.json", json_encode($cost));
	header('location: total_profit.php?msg=' . $msg);
}


$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'));

$income = json_decode(file_get_contents('data/income.json'),true);
$cost = json_decode(file_get_contents('data/cost.json'),true);



// READ DATA
$newdata = array();
$data = json_decode(file_get_contents('data/Documents.json'), true);

// HEADER
ob_end_flush();
include 'tpl/header.php';
?>
<?php if($currentuser->gm  == '1' || $currentuser->location == '总公司' ){  ?>
<style>
.navbar-fixed{
	display:none;
}
</style>
<?php } ?>
<script>
	jQuery("document").ready(function(){
		
                $('.jksahjkb').val('公司账户').change();
	});
</script>   
<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">



<?php   
$monthschedule = -11;
if($_GET['monthschedule'] != ''){
	$monthschedule = $_GET['monthschedule'];	
}
$subContainer = $Setting->subContainer;
$subContainers = explode(PHP_EOL,$subContainer );
foreach($subContainers as $subContainer ){
$subContainer = explode('|',$subContainer );
$subContainer[1] = str_replace(array("\n","\r\n","\r",PHP_EOL,' '), '',$subContainer[1]);
$subContainer[0] = str_replace(array("\n","\r\n","\r",PHP_EOL,' '), '',$subContainer[0]);
if(count((array)$group[$subContainer[0]]) == 0){
	//$group[$subContainer[0]][] = '';
}
$group[$subContainer[0]][] = $subContainer[1];
}
//$group['管理费用'][] = '';
//$group['财务费用'][] = '';

$quocgia = array('越南','中国','泰国');

foreach ($data as $key => $values) {
	/*
	if(strpos($values['documentnumber'],'VN') !== false ){
		$data2['1'.$values['id']] = $values;
	}elseif(strpos($values['documentnumber'],'CN') !== false ){
		$data2['2'.$values['id']] = $values;
	}elseif(strpos($values['documentnumber'],'THG') !== false ){
		$data2['3'.$values['id']] = $values;
	}else{
		
	}
	*/
	if( strpos($values['documentnumber'],'VN') !== false || 
		strpos($values['documentnumber'],'CN') !== false ||
		strpos($values['documentnumber'],'THG') !== false){
		$ab = explode('-',$values['documentnumber']);
		if ($ab[1] < 10){
			$ab = '0'.$ab[1];
		}else{
			$ab = $ab[1];
		}
		
		
		
		if(strpos($values['documentnumber'],'-') !== false){
			$abdu = explode('-',$values['documentnumber']);
			if($abdu[1] < 10){
				$abdu[1] =  '0'.$abdu[1];
			}
			$abdu = $abdu[0].'-'.$abdu[1];
			$data2[preg_replace("/[^0-9.]/", "", str_replace('-','.',$abdu)).$values['id']] = $values;
		}else{
			$data2[preg_replace("/[^0-9.]/", "", $values['documentnumber'].'.00'.$values['id'])] = $values;
		}
		
	}else{
		$data2[$values['id']] = $values;
	}
}
ksort($data2);
$data = $data2;

foreach($tabs as $tab){

    // LOOP EACH ENTRY
    $total_receivable = $total_amount = $total_profit = 0;
    $countNo = 0;
	$amountincome = 0;
	$amountpayout = 0;
	$balance = 0;
	
    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;		
					unset($tabdocfull[$keytab]);	break;
				}
			}
			if ($appprove == 0){
             continue;
			}
		}else{
			if ($values['tabs'] != $tab->id ){
				 continue;
			}
			$rt = $values['tabs'];
		}
		
		$decimal = 2;
		if($tab->currency == '1560829223'){
				$decimal = 0;
		}
        for ($i = ($monthschedule - 1) ; $i < 1 ; $i++){
			if(date('m_Y',strtotime('first day of '.$i.' month')) == date('m_Y',$values['id']) ){
				
				$account_in[$tab->id][date('m_Y',strtotime('first day of '.$i.' month'))] += (float)$values['amountincome'];
				
				if($tab->special3 == 1){
					$account_usd_in[$tab->id][date('m_Y',strtotime('first day of '.$i.' month'))] += (float)$values['amountincomeusd'];
					$account_usd_out[$tab->id][date('m_Y',strtotime('first day of '.$i.' month'))] += (float)$values['amountpayoutusd'];
					
				}
				
				$account_out[$tab->id][date('m_Y',strtotime('first day of '.$i.' month'))] += (float)$values['amountpayout'];
				
			}			
		}
	
		unset($data[$key]);
   }
  
}
$decimal = 0;

?>
<style>
table.tablesorter thead tr th {
    position: sticky;
    z-index: 100;
    top: 0px;
}
</style>
<form id="dakb" method="get" style="    margin-bottom: 10px;">
	<select name="monthschedule" onchange="jQuery('#dakb').submit();" >
		<option value="-11"  >12 months</option>
		<option value="-17" <?php if($monthschedule == -17){ echo 'selected'; } ?> >18 months</option>
		<option value="-23" <?php if($monthschedule == -23){ echo 'selected'; } ?> >24 months</option>
	</select>
</form>	
<?php if($monthschedule < -11){ ?>
	<style>
		.asbdkkb {
			
		}
		
	</style>
<div class="ansdlnasld" >	
<?php } ?>
<table style="width: 100%!important;position: relative;" class="striped responsive-table  tablesorter asbdkkb " >
		<thead>
			<tr>
                        <th rowspan="2" style="width:160px;    background-color: #ccc;" ><div style="    text-align: right;" >类别</div>
			<select class="jksahjkb" onchange="if($(this).val() == 0){ $('.fullaccount1').show();  $('.fullttaccount1').hide(); $('.全部1').show();   }else{  $('.fullttaccount1').hide(); $('.fullaccount1').hide(); $('.'+$(this).val()+'1').show(); }" >
				<option value="0" >全部</option>
                                <option value="公司账户" selected="" >公司账户</option>
				<option value="供应商账户" >供应商账户</option>
				<option value="停用账户" >停用账户</option>
				<option value="已注销账户" >已注销账户</option>
			</select>
			
			</th>    
			<th style="width: 10%;">
			<div style="    text-align: right;">Months</div>
				<div style="
						border: 1px solid;
						transform: rotateZ(16deg);
						width: 113%;
						margin-left: -6%;
					"></div>
			<div>Accounts</div></th>
			</th>
			<?php for ($i = $monthschedule ; $i < 1 ; $i++){ ?>
						<th><?php echo date('m/Y',strtotime('first day of '.$i.' month')); ?></th>
			<?php } ?>
			<th style="width:8%;" >总类型/Total</th>
			</tr>
		</thead>
		<tbody>
		<?php foreach($tabs as $tab){ 
				foreach($currency as $rcurrency){
						if($rcurrency['id'] == $tab->currency ){
							$exchangerate =  $rcurrency['exchangerate'];
							$currencyname =  $rcurrency['currency'];
						} 	
				}
					
		?>			
		<tr class="fullaccount1 <?php echo $tab->tabsg.'1'; ?>" >
                                <td><b><?php echo $tab->tabsg; ?></b></td>
				<td style="width:180px;padding-left:6px!important;    font-weight: bold;" ><?php  echo $tab->name;  ?><br><?php if($tab->special3 == 1){ ?>USD/<?php } ?><?php echo $currencyname ?></td>
				<?php $aa = 0;$bb = 0;$cc = 0;$dd = 0; 
					for ($i = $monthschedule ; $i < 1 ; $i++){ 
					$aa += (float)$account_in[$tab->id][date('m_Y',strtotime('first day of '.$i.' month'))]; 
					$bb += (float)$account_out[$tab->id][date('m_Y',strtotime('first day of '.$i.' month'))];
					if($tab->special3 == 1){
						$cc += (float)$account_usd_in[$tab->id][date('m_Y',strtotime('first day of '.$i.' month'))]; 
						$dd += (float)$account_usd_out[$tab->id][date('m_Y',strtotime('first day of '.$i.' month'))];
					}
				?>
						<td style="text-align: right;padding-right:3px!important;" >
						<?php if($tab->special3 == 1){ ?>
						<span style="color:green;" ><?php echo number_format((float)$account_usd_in[$tab->id][date('m_Y',strtotime('first day of '.$i.' month'))] ,$decimal); ?></span> USD
						<br>
						<span style="color:red;" ><?php echo number_format((float)$account_usd_out[$tab->id][date('m_Y',strtotime('first day of '.$i.' month'))] ,$decimal); ?></span> USD
						<br>
						<span style="color:red;" ><?php echo number_format((float)$account_out[$tab->id][date('m_Y',strtotime('first day of '.$i.' month'))] ,$decimal); ?></span> 
						<?php }else{ ?>
						<span style="color:green;" ><?php echo number_format((float)$account_in[$tab->id][date('m_Y',strtotime('first day of '.$i.' month'))] ,$decimal); ?></span><br><span style="color:red;" ><?php echo number_format((float)$account_out[$tab->id][date('m_Y',strtotime('first day of '.$i.' month'))] ,$decimal); ?></span>
						<?php } ?>
						</td>
				<?php } ?>
				<td style="padding-right:3px!important; font-weight: bold;text-align: right;" >
					<?php if($tab->special3 == 1){ ?>
					<span style="color:green;" ><?php echo number_format((float)$cc  ,$decimal); ?></span> USD <br>
					<span style="color:red;" ><?php echo number_format((float)$dd  ,$decimal); ?> USD <br>
					<span style="color:red;" ><?php echo number_format((float)$bb  ,$decimal); ?></span>
					<?php }else{ ?>
					<span style="color:green;" ><?php echo number_format((float)$aa  ,$decimal); ?></span><br><span style="color:red;" ><?php echo number_format((float)$bb  ,$decimal); ?></span>
					<?php } ?>
				</td>
		</tr>
		<?php } ?>
</tbody>
<tfoot>
	<?php for ($i = -12 ; $i < 1 ; $i++){ ?>
		<th></th>
	<?php } ?>
</tfoot>
</table>
<?php if($monthschedule < -11){ ?>
</div>
<?php } ?>


<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;
}
.toast.rounded div {
	height:300px;
	overflow:auto;
}
td, th {
    padding: 5px 5px;
   
}
#toast-container {   
    top: 250px!important;
}
.toast.rounded  {
	
}
.dfjaksku {
	position: absolute;
	top:-26px;
	right:0px;
	color:red;
	font-weight:bold;
	font-size:30px;    cursor: pointer;
}
</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;
		}
		
		$monthchinatext = array('一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月');
		
?>

<script>
$(document).ready(function () {
		
		$( "body" ).delegate( '#toast-container tr' , "click", function() {
			$('#datestart').val($(this).attr('datestart'));
			$('#dateto').val($(this).attr('dateto'));
			$('#rowclick').val($(this).attr('rowclick'));
			$('#tabclick').val($(this).attr('tabclick'));			
			$('#formjump').submit();
		});
		$( "body" ).delegate( '.dfjaksku' , "click", function() {	
			$('.toast.rounded').hide();
		});
		$(".sandjnas").change(function(){
			if($( ".sandjnas option:selected" ).hasClass('isspeci')){
				$(".isdepartmentform").show();
			}else{
				$(".isdepartmentform").hide();
			}
		});
	
		$("input[data-type='currency']").each(function(){
			formatCurrency($(this)); 
		});
		$("input[data-type='currency']").on({
            keyup: function() {
            formatCurrency($(this));
        },
			blur: function() { 
			formatCurrency($(this), "blur");
        }
        });
        function formatNumber(n) {
            return n.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")
        }
		function formatCurrency(input, blur) {                             
			var input_val = input.val(); 
			if (input_val === "" || input_val == "0.00") { return; }
				var original_len = input_val.length;
				var caret_pos = input.prop("selectionStart");
			if (input_val.indexOf(".") >= 0) {
				var decimal_pos = input_val.indexOf(".");
				var left_side = input_val.substring(0, decimal_pos);
				var right_side = input_val.substring(decimal_pos);
				left_side = formatNumber(left_side);
				right_side = formatNumber(right_side);
				if (blur === "blur") {
					// right_side += "00";
				}
				right_side = right_side.substring(0, $decimal);
				input_val =  left_side + "." + right_side;
			} else {
				input_val = formatNumber(input_val);
				input_val =  input_val;
				// final formatting
				if (blur === "blur") {
				//input_val += ".00";
				}
			}
			input.val(input_val);
			var updated_len = input_val.length;
			caret_pos = updated_len - original_len + caret_pos;
			input[0].setSelectionRange(caret_pos, caret_pos);
			}
			
});                          
 </script>
						
<!-- Styles -->
<form method="POST" id="formjump" action="index.php" target="_blank" >
	<input value="" id="datestart" name="datestart" type="hidden" />
	<input value="" id="dateto" name="dateto" type="hidden" />
	<input value="" id="rowclick" name="rowclick" type="hidden" />
	<input value="" id="tabclick" name="tabclick" type="hidden" />	
</form>
						
<?php    
// FOOTER
include 'tpl/footer.php';
