<?php
ob_start();
date_default_timezone_set('Asia/Bangkok');
error_reporting(E_ALL);
ini_set('display_errors',0);
session_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'];

$currencydate = date('Ymd');
if($_GET['currencydate'] != ''){
	$currencydate = $_GET['currencydate'];
}
$currency = json_decode(file_get_contents('data/Currency.json'), true);



if ($_GET['import'] != ''){
	$_SESSION['import'] = $_GET['import'];
}
if ($currencyUser == ''){
	$currencyUser = '1560829223';
}
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;
		}
	}
}


if ($login['status'] == 200) {
    
} else {
    header('location: login.php');
    exit;
}

$ip = getenv('HTTP_CLIENT_IP')?:
	getenv('HTTP_X_FORWARDED_FOR')?:
	getenv('HTTP_X_FORWARDED')?:
	getenv('HTTP_FORWARDED_FOR')?:
	getenv('HTTP_FORWARDED')?:
	getenv('REMOTE_ADDR'); 

file_put_contents('ipdata',$ip);


$tabs = json_decode(file_get_contents('data/Tabs.json'));
$user = json_decode(file_get_contents('data/User.json'));
$tabdocfull = $tabdoc = json_decode(file_get_contents('data/TabDoc.json'));
$tabfull = $tabs;
$Setting = json_decode(file_get_contents('data/Setting.json'));

if($currentuser->role == 'Operator' || ( $currentuser->role == 'Manager' && $currentuser->gm != 1 )  ){	
	if($currentuser->location == '总公司' && !in_array( $ip , explode(',',$Setting->ipmain)) && $Setting->ipmain != ''  ){
		header('location: login.php');exit;
	}
	if($currentuser->location == '越南' && !in_array( $ip , explode(',',$Setting->ipvn)) && $Setting->ipvn != '' ){
		header('location: login.php');exit;
	}	
	if($currentuser->location == '中国' && !in_array( $ip , explode(',',$Setting->ipcn)) && $Setting->ipcn != '' ){
		header('location: login.php');exit;
	}		
	if($currentuser->location == '泰国'  && !in_array( $ip , explode(',',$Setting->iptha)) && $Setting->iptha != '' ){
		header('location: login.php');exit;
	}		
}
if($currentuser->role == 'Finance' && $Setting->ipcontroller != '' && !in_array( $ip , explode(',',$Setting->ipcontroller)) ){	
	header('location: login.php');exit;
}


// SAVE NEW ENTRY IF FORM POSTED
if (isset($_POST['status'])) {
    if ($_POST['status'] == "") {
        $_POST['status'] = 'YES';
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' and $_POST['sendtoaproval'] == '1' ) {
	$jsonString = file_get_contents($file);
    $data = json_decode($jsonString, true);
	$_POST['iddoc'] = explode(',',$_POST['iddoc']);
    foreach ($data as $key => $entry) {
		if (in_array($entry['id'],$_POST['iddoc'])) {
			 $data[$key]['status'] = 'pending';
			 if($currentuser->role == 'Finance'){
				 $data[$key]['status'] = 'cancel';
				 $data[$key]['controlerrevision'] = $currentuser->name;
				 $data[$key]['controlerrevisiontime'] = time();
			 }
			 if($currentuser->gm != 1 && $currentuser->role != 'Finance' ){
				 $data[$key]['financeclicktoapproval'] = $currentuser->name;
				 $data[$key]['financeclicktoapprovaltime'] = time();
			 }
		}
	}
	
	if (file_put_contents($file, json_encode($data))) {
        $msg = $i18n['Data successfully saved!'];
    } else {
        $msg = $i18n['ERROR &mdash; Data not saved!'];
    }
    header('location: index.php?msg=' . $msg);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' and $_POST['setapproval'] == '1' ) {
	$jsonString = file_get_contents($file);
    $data = json_decode($jsonString, true);
	$_POST['iddoc'] = explode(',',$_POST['iddoc']);
    foreach ($data as $key => $entry) {
		if (in_array($entry['id'],$_POST['iddoc'])) {
			 $data[$key]['status'] = $_POST['type'];
			 if($_POST['note'] != ''){
				$data[$key]['remarks'] .= PHP_EOL.'未通过: '.$_POST['note'];
			 }
			 $data[$key]['controlerapproval'] = $currentuser->name;
			 $data[$key]['controlerapprovaltime'] = time();
		}
	}
	
	if (file_put_contents($file, json_encode($data))) {
        $msg = $i18n['Data successfully saved!'];
    } else {
        $msg = $i18n['ERROR &mdash; Data not saved!'];
    }
    header('location: index.php?msg=' . $msg);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' and $_POST['payment'] != '' and $_POST['classification'] != '' ) {
	 
	 if(count((array)$_FILES['fileupload']['name']) > 0){
		 foreach ($_FILES['fileupload']['name'] as $filekey => $fileu){
			if($_FILES['fileupload']['error'][$filekey] != 0 || strpos($_FILES['fileupload']['filetype'][$filekey],'application/octet-stream') !== false || strpos($fileu,'.php') !== false || strpos($fileu,'.html') !== false ){ continue; }
			
			 $filename_text = time().'_'.$fileu;
			 $filename[] = $fileu;
			 $filetype[] = $_FILES['fileupload']['type'][$filekey];
			 $filesize[] =  $_FILES['fileupload']['size'][$filekey];
			 $filetimeupload[] = time();
			 $filecreatebyid[] = $currentuser->id;
			 $filecreatebyname[] = $currentuser->name;
			 $filepath[] = $filename_text;
			 copy( $_FILES['fileupload']['tmp_name'][$filekey] , __DIR__.'/uploads/'.$filename_text );
		 }
		// print_r($_FILES['fileupload']);;die;
	 }
	if($_SESSION['import'] == 1 && $_POST['date'] != '' ){
		//
	}else{
		//$id = time();
	}
	if($currentuser->gm == 1){
		$id = strtotime(str_replace('.','-',$_POST['date']).' '.date('H:i:s'));
	}else{
		$id = strtotime(str_replace('.','-',$_POST['date']).' '.date('H:i:s'));
		if( $id < strtotime('-6 day') ){
			$id = strtotime('-5 day');
		}
	}
    $formdata = array(
        'id' => $id
		//, 'date' => $_POST['date']
        , 'payment' => $_POST['payment']
        //, 'account' => $_POST['account']
        , 'department' => $_POST['department']
        , 'classification' => $_POST['classification']
        , 'charge' => $_POST['charge']
        , 'summary' => $_POST['summary']
		, 'amountincome' => str_replace(',','',$_POST['amountincome'])
		, 'amountpayout' => str_replace(',','',$_POST['amountpayout'])
		, 'payer' => $_POST['payer']
		, 'requestnumber' => $_POST['requestnumber']
		, 'documentnumber' => $_POST['documentnumber']
		, 'jobnumber' => $_POST['jobnumber']
		//, 'fee' => $_POST['fee']
		, 'billno' => $_POST['billno']
		, 'billto' => $_POST['billto']
		, 'vat' => $_POST['vat']
		, 'wht' => $_POST['wht']		
		, 'remarks' => $_POST['remarks']
		, 'writtenoff' => $_POST['writtenoff']
		, 'location' => $_POST['location']
		, 'createbyname' => $currentuser->name
		, 'createbyid' => $currentuser->id		
		, 'filename' => $filename
		, 'filetype' => $filetype
		, 'filesize' => $filesize
		, 'filetimeupload' => $filetimeupload
		, 'filecreatebyid' => $filecreatebyid
		, 'filecreatebyname' => $filecreatebyname
		, 'filepath' => $filepath
    );
	$tabdocfull =  (array)$tabdocfull; 
	$tabdocfull[] = array(
		'iddoc' => $id,      
		'idtab' => $_POST['tabs'],
	);    
	$tabdocfull = array_values($tabdocfull);
	if(count((array)$tabdocfull) > 0){
		file_put_contents('data/TabDoc.json', json_encode($tabdocfull));
	}
	
    $arr_data = array();
    if (file_exists($file)) {
        $jsondata = file_get_contents($file);
        $arr_data = json_decode($jsondata, true);
    }
    $arr_data[] = $formdata;
    $jsondata = json_encode($arr_data);
    if (file_put_contents($file, $jsondata)) {
        $msg = $i18n['Data successfully saved!'];
    } else {
        $msg = $i18n['ERROR &mdash; Data not saved!'];
    }
    header('location: index.php?msg=' . $msg);
	exit();
}
// CREATE DATA FILE IF NOT EXISTS
if (!is_file($file)) {
    file_put_contents($file, '');
}
// READ DATA
$newdata = array();
$data = json_decode(file_get_contents($file), true);
// HEADER


if(isset($_POST['vendor'])){
			$vendor = $_POST['vendor'];
}		
if(isset($_POST['datestart'])){
			$datestart = $_POST['datestart'];
			$_SESSION['datestart'] = $_POST['datestart'];
}elseif( $_SESSION['datestart'] != '' ){
			$datestart = $_SESSION['datestart'];
}else{
			$datestart = date('Y.m.d',strtotime("-364 day"));
}		
if(isset($_POST['dateto'])){
			$dateto = $_POST['dateto'];
			$_SESSION['dateto'] = $_POST['dateto'];
}elseif( $_SESSION['dateto'] != '' ){
			$dateto = $_SESSION['dateto'];
}else{
			$dateto = date('Y.m.d');
}
if(isset($_POST['acctiveaccount'])){
			$acctiveaccount = $_POST['acctiveaccount'];
}	
include 'tpl/header.php';
ob_end_flush();

?>

<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" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<style>  
.nofulltext p {		padding: 0px;		margin: 0px;	}.tab-content { min-width: 100%; } .section.no-pad-bot { padding-bottom: 0; padding-top: 0; } tfoot td { padding: 7px 0px; } 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; } table.tablesorter tbody td { vertical-align: middle; } table.tablesorter tbody td { padding: 0px; } .helper-text { display:none!important; } .input-field { position: relative;  margin-bottom: 5px; } #modal5 { min-width: 1150px; } .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: calc(100% - 20px); float: left; word-break: break-all; } .fa-sort-down { width: 17px; float: left; } i.fas.fa-sort-down.active { transform: rotateX(180deg); margin-top: 8px; } .responsive-table .btn { line-height: 26px; height: 26px; } .JCLRgrips { display:none!important; } #toast-container{  position: fixed; z-index: 1000; } .filtervendor .select-wrapper { position: absolute; top: 0px; } .filtervendor input { border: none!important; opacity: 0; } .filtervendor svg{ color:#ffffff!important; fill: rgba(255, 255, 255, 0.87)!important; } .filtervendor ul{ min-width: 250px; max-height: 350px; overflow: auto; } } .bsdbk ul li:first-child input , .bsdbk ul li:last-child input , .filtervendor ul li:first-child input { display:none; } .bsdbk ul li:first-child span:before , .bsdbk ul li:last-child span:before , .filtervendor ul li:first-child span:before { display:none; } .bsdbk ul li:first-child ,.bsdbk ul li:last-child , .filtervendor ul li:first-child { text-decoration: none; background-color: #26a69a!important; text-align: center; letter-spacing: .5px; -webkit-transition: background-color .2s ease-out; transition: background-color .2s ease-out; cursor: pointer; } .bsdbk ul li:first-child:hover , .bsdbk ul li:last-child:hover ,.filtervendor ul li:first-child:hover { background-color: #117d73!important; } .bsdbk ul li:first-child [type="checkbox"]+span:not(.lever) , .bsdbk ul li:last-child [type="checkbox"]+span:not(.lever) , .filtervendor ul li:first-child [type="checkbox"]+span:not(.lever) { color: #fff!important;padding-left:0px; } textarea.nofulltext{ border: none; resize: none; line-height: 21px; } table.tablesorter tbody tr:hover td { background: #fffadc; } thead .tr_total td { padding-top:3px; padding-bottom:3px; } th .dropdown-content li>a, .dropdown-content li>span { padding: 4px 10px; } th .dropdown-content li { min-height: 34px; line-height: 16px; } th.filtervendor ul { min-width: 315px; top: 53px!important; } .bsdbk { position: relative; } .bsdbk .select-wrapper { position: absolute; left: -30px; top: 10px; z-index: 1000; } .bsdbk .caret {     margin-top: 7px; width: 36px; height: 36px; fill: rgb(38, 166, 154); box-shadow: 0px 0px 3px #545454a6; } .bsdbk .select-wrapper input.select-dropdown { width: 30px; border: none; color: transparent; } .bsdbk .dropdown-content { min-width:250px; top: 45px!important; } .bsdbk .dropdown-content li { min-height: 20px; } /*PRELOADING------------ */ #overlayer { width:100%; height:100%; position:fixed; z-index:10000; background:rgba(0, 0, 0, 0.97); left:0px; filter:blur(4px); -o-filter:blur(4px); -ms-filter:blur(4px); -moz-filter:blur(4px); -webkit-filter:blur(4px); } .loader { display: inline-block; width: 30px; height: 30px; position: fixed; z-index:30000; border: 4px solid #Fff; top: 50%; animation: loader 2s infinite ease; left: 50%; top: 50%; transform: translate(-50%, -50%); } .loader-inner { vertical-align: top; display: inline-block; width: 100%; background-color: #fff; animation: loader-inner 2s infinite ease-in; } @keyframes loader { 0% { transform: rotate(0deg); } 25% { transform: rotate(180deg); } 50% { transform: rotate(180deg); } 75% { transform: rotate(360deg); } 100% { transform: rotate(360deg); } } @keyframes loader-inner { 0% { height: 0%; } 25% { height: 0%; } 50% { height: 100%; } 75% { height: 100%; } 100% { height: 0%; } } .some-css-class { left: 50%!important; transform: translateX(-50%); } table { /* Not required only for visualizing */ border-collapse: collapse; width: 100%; } table thead tr:nth-child(1) th { /* Important background-color: red; */ position: sticky; z-index: 100; top: 0; } .makesimilarlabel .caret{ margin-top: -25px; } .isleft{ width: 50px; height: 50px; position: fixed; left: 15px; top: 45%; z-index: 1000000; font-size: 54px; opacity: 0.2;cursor: pointer; } .isright{ width: 50px; height: 50px; position: fixed; right: 15px; top: 45%; z-index: 1000000; font-size: 54px; opacity: 0.2;cursor: pointer; } .isleft:hover , .isright:hover{ opacity: 0.5; } .isleft i , .isright i { } #toast-container { top: 10px; max-width: 100%; } .toast.rounded { border-radius: 24px; height: 30px; } .collapsible-body{ background: rgb(218, 219, 219); position: absolute; padding: 0px 15px 0px 5px!important; min-width: 300px; margin-top: 6px; } .ui-autocomplete { top: 134px!important; margin-left: -6px!important; max-height:500px; overflow:auto; } .ui-autocomplete li { border-bottom: 1px solid; cursor:pointer; padding-left: 10px!important; } .ui-autocomplete li:nth-child(even) { background: #f0f0f0; } .ui-autocomplete li:nth-child(even) { background: #eee; } #project::placeholder { /* Firefox, Chrome, Opera */ color: #000; } #project:-ms-input-placeholder { /* Internet Explorer 10-11 */ color:#000; } #project::-ms-input-placeholder { /* Microsoft Edge */ color:#000; } .classdash1:after { content:'-1'; }
</style>

<div id="overlayer" style="display:none;" ></div>
<span class="loader" style="display:none;" >
  <span class="loader-inner"></span>
</span>
<?php if($_SESSION['import'] != 1 && 0 == 1){ ?>
<?php } if($_GET['onlyform'] == 1) { ?>
<style>  
	.navbar-fixed {
		display:none;
	}
	body{
		overflow: hidden;
		background: transparent;
	}
	html{
		background: transparent;
	}
	.row {   
		margin-bottom: 0px;
	}
	
</style>  
<?php } ?>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">

<?php if($_GET['onlyform'] != 1) { ?>	
	<br>
<?php } ?>	
    <ul style="display:flex;background:#eeeeee;align-items:center;height:unset;<?php if($_GET['none']) ?><?php if($_GET['onlyform'] == 1) { ?>display:none;<?php } ?>" class="tabs">
          
            <?php
              foreach($tabs as $tab){
				  if( $currentuser->gm != 1 && $currentuser->role != 'Finance' && $tab->iduser != $currentuser->id && !in_array($tab->id,$currentuser->account) && !in_array($tab->id,$currentuser->accountreadonly) ) { continue; } 
				  foreach($currency as $rcurrency){
						if($rcurrency['id'] == $tab->currency){
							$currencyname =  $rcurrency['currency'];
						} 	
				  }
                  if ( $currentuser->gm != 1 && $currentuser->role != 'Finance' ){	
						if(in_array($tab->id,$currentuser->accountreadonly)){
							echo '<li data-tab="tab-'.$tab->id.'" data-id="'.$tab->id.'" style="color: #222;    border-top: 3px solid #eeeeee;" class="tab-link">'.$tab->name.'('.$currencyname.')</li>';
						}else{
							echo '<li data-tab="tab-'.$tab->id.'" data-id="'.$tab->id.'" class="tab-link">'.$tab->name.'('.$currencyname.')</li>';
						}
                  }else{
                        foreach ($user as $us){
                            if ($us->id == $tab->iduser) {
                                $name = $us->name;             
	                   	break;
                            }
                        }
						  if ( $kk++ == 0){
							  $current= 'current';
						  }else{
							  $current= '';
						  }  
                       echo '<li data-tab="tab-'.$tab->id.'" balance="'.$tab->balance.'" data-id="'.$tab->id.'" location="'.$tab->location.'" name="'.$tab->name.'" info="'.$tab->info.'" currency="'.$tab->currency.'"  special="'.$tab->special.'"   special2="'.$tab->special2.'" class="tab'.$tab->id.' tab-link '.$current.'">'.$tab->name.'('.$currencyname.')<span class="tabdescription" style="display:none;" >'.$tab->tabdescription.'</span></li>';
					   echo '<button class="tab-'.$tab->id.' tabnameSave" id="tabnameSave" > <i class="material-icons">edit</i></button>                      
							<a href="#" onclick="if (confirm(\'Are you sure delete this account ?\')) { window.location.replace(\'?delete_tab='.$tab->id.'\');}" class="material-icons close tab-'.$tab->id.'">close</a>' ;
				  }
                }   
        ?>
        </ul>
	
    <?php
foreach ($data as $key => $values) {       
	${'data'.$values['tabs']}[$values['id']] = $values;	
}
	
//foreach ($data as $key => $values) {       
//	$data2[$values['id']] = $values;
//}
//ksort($data2);
//$data = array_values($data2);
	
foreach($currency as $rcurrency){	
	if( $rcurrency['default'] != 1){
		if($rcurrency['currency'] == 'USD'){
			$exchangeratetext2[] = '1 '.$rcurrency['currency'].' = '.$rcurrency['exchangerate'].$exchangeratetext;
		}elseif($rcurrency['currency'] == 'VND'){
			$exchangeratetext2[] = '1'.$exchangeratetext.' = '.(number_format((1/$rcurrency['exchangerate']),0)).' '.$rcurrency['currency'];
		}elseif($rcurrency['currency'] == 'Baht'){
			$exchangeratetext2[] = '1'.$exchangeratetext.' = '.(floor((1/$rcurrency['exchangerate'])*100)/100).' '.$rcurrency['currency'];
		}elseif($rcurrency['currency'] == 'USDVND'){
			$exchangeratetext2[] = '1 USD = '.number_format((float)$rcurrency['exchangerate']).' VND';
		}
	}else{
		$exchangeratetext = ' '.$rcurrency['currency'];
	}
}		
		
	
	
foreach($tabs as $tab){
	 ksort(${'data'.$tab->id});
	 ${'data'.$tab->id} = array_values(${'data'.$tab->id});
	 foreach (${'data'.$tab->id} as $key => $values) {
		 
			$appprove = 0; 
			if( $values['tabs'] == '' ){
				foreach ($tabdocfull as $r){
					if ( $values['id'] == $r->iddoc && $tab->id == $r->idtab ) {
						$appprove = 1; 
						$rt = $r->idtab;
						$newtab_tabdocfull[] = $r; 	break;
					}
				}
				if ($appprove == 0){
				 continue;
				}
			}else{
				if ($values['tabs'] != $tab->id ){
				 continue;
				}
				$rt = $values['tabs'];
			}
			
			if(!isset($balance[$rt])){	
				//$balance[$rt] += floatval($tab->balance);
			}
			if ($appprove == 0){
				 continue;
			}
			if( date('Y.m.d',$values['id']) >=  $datestart  ){
				 
			}else{
				//$balance[$rt] += floatval($values['amountincome']) - floatval($values['amountpayout']) ;
			}
			
			$groupdocumentnumber[] = $values['documentnumber'];
			if ( $values['documentnumber'] == '' || strpos($values['documentnumber'], '-') !== false || date('Ym') != date('Ym',$values['id']) ){
				 continue;
			}
	  
			if($values['classification'] == '管理费用'){
				if( $nextvalue1[$tab->location] < substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3)){
					$nextvalue1[$tab->location] = substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3);
				}
			}
			if($values['classification'] == '应收账款'){
				if( $nextvalue2[$tab->location] < substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3)){
					$nextvalue2[$tab->location] = substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3);
				}
			}
			if($values['classification'] == '应付账款'){			
				if( $nextvalue3[$tab->location] < substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3)){
					$nextvalue3[$tab->location] = substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3);
				}
			}			
	}
	
if( $currentuser->gm != 1 && $currentuser->role != 'Finance' && $tab->iduser != $currentuser->id && !in_array($tab->id,$currentuser->account) && !in_array($tab->id,$currentuser->accountreadonly) ) { continue; } 

	$numtab = 0 ;	
  // TABLE HEADER
  if ( $ml++ == 0){
      $current= 'current';
  }else{
      $current= '';
  }  
  if($tab->special == 1){
	  $isdho = "<style> #tab-".$tab->id." .havepecial { display:table-cell!important; } </style>";
  }else{
	  $isdho = "";
  }  
  
  if($tab->special2 == 1){
	  $isdho = "<style> #tab-".$tab->id." .havepecial2 { display:table-cell!important; } </style>";
	  $isdho2 = "width: 125%!important; min-width: 1800px; ";
  }else{
	  $isdho2 = $isdho = "";
  }  
   foreach($currency as $rcurrency){
			if($rcurrency['id'] == $tab->currency ){
				$currencyname =  $rcurrency['currency'];
			} 	
		}		
  if($_GET['onlyform'] == 1) { $isdho2 = 'display:none;'; } 
  $table = $isdho.'<table style="    position: relative;width: 100%!important;'.$isdho2.' margin-top: 40px;" class="striped responsive-table tablesorter tab-content '.$current.' "  id="tab-'.$tab->id.'"  >
  <thead>
  <tr>';
  if ($currentuser->role == 'Manager' ) {
  $table .= '<th style="text-align:center;width:68px;"></th>';
  }elseif ( $currentuser->role == 'Operator') {
  $table .= '<th style="text-align:center;width:30px;"></th>';
  }
  $table .= '<th style="text-align:center;width:26px;"></th>';
  $table .= '<th style="width:80px;    background-image: none;" >'.$i18n['日期'].'
  <div class="reportrange" style="     cursor: pointer;    position: absolute;    z-index: 1000;    top: 12px;    right: 0px;    width: 100%;">
<i class="material-icons " style="float:right;" >date_range</i> 
	</div>
</th>
  <th style="width:53px;" >'.$i18n['收/付'].'</th> 
  <th style="width:100px;" >'.$i18n['费用归类'].'</th>
  <th style="width:100px;" >'.$i18n['费用明细'].'</th>
  <th class="havepecial" style="display:none;width:50px;" >'.$i18n['部门'].'</th>
  <th class="havepecial2" style="display:none;" >'.$i18n['Bill No.'].'</th>
  <th class="havepecial2" style="display:none;" >'.$i18n['Bill to'].'</th>
  <th class="havepecial2" style="display:none;" >'.$i18n['增值税'].'</th>
  <th class="havepecial2" style="display:none;" >'.$i18n['预扣税'].'</th>
  <th style="width:150px;" >'.$i18n['摘要'].'</th>
  <th style="width:105px;"  >'.$i18n['收入金额'].'</th>
  <th style="width:105px;"  >'.$i18n['支出金额'].'</th>
  <th style="width:105px;"  >'.$i18n['余额'].'</th>
  <th style="width:106px;     background-image: none;    z-index: 100;" class="filtervendor" >'.$i18n['收付款人'].'  <select class="shkabkasb" style="display:none;" id="vendorid'.$tab->id.'" multiple ><option value="clicktosearch" > << Click to Search >> </option></select> <i class="material-icons right" style="  line-height: 1.5;    position: absolute;        top: 8px;right:5px;">search</i></th>
  <th style="width:140px;" >'.$i18n['催/请款单号'].'</th>
  <th style="width:115px;"  >'.$i18n['凭证号'].'</th>
  <th style="width:85px;" >'.$i18n['是否核销'].'</th>
  <th style="min-width:55px;" >'.$i18n['文件'].'</th>
  <th style="min-width:55px;" >'.$i18n['备注'].'</th>';
  $table .= '<th style="text-align:center;width:119px;">'.$i18n['审核'].'</th>';
  $table .= '</tr>
  <tr class="treopit modal-trigger" data-target="showmoreinfo"   style="    position: absolute;    top: -40px;    width: 100%;    text-align: center;" >
	<td  colspan="14" style="display: block; text-align: center;   width: 100%;  padding: 5px;    font-weight: bold;    font-size: 18px;"  >'.$tab->info.'<span class="tabdescription" style="display:none;" >'.$tab->tabdescription.'</span></td>
  </tr>
  ';
  // LOOP EACH ENTRY
  $total_receivable = $total_amount = $total_profit = 0;
  $countNo = 0;
  //$rt = 0;$balance[0] = 0;
  
	$rt = $tab->id;	
	$decimal = 2;
	if($currencyname == 'VND'){
			$decimal = 0;
	}
	
  if ($currentuser->role == 'Manager' || $currentuser->role == 'Operator') {
  $table .='<tr class="tr_total"><td colspan="7" >'.$i18n["From"].':'.$datestart.' - '.$i18n["To"].':'.$dateto.'</td><td class="havepecial" style="display:none;"  >&nbsp;</td><td class="havepecial2" colspan="4" style="display:none;"  >&nbsp;</td><td  colspan="2" style="padding-left:6px!important;text-align:right;" ></td><td  style="    font-weight: normal;padding-left:6px!important;" ></td><td>&nbsp;</td><td colspan="6"  style="text-align:right;" >汇买价 '.implode(', ',$exchangeratetext2).'</td></tr>';
  }else{
  $table .='<tr class="tr_total"><td colspan="7" >'.$i18n["From"].':'.$datestart.' - '.$i18n["To"].':'.$dateto.'</td><td class="havepecial" style="display:none;"  >&nbsp;</td><td class="havepecial2" colspan="4" style="display:none;"  >&nbsp;</td><td  colspan="1" style="padding-left:6px!important;text-align:right;" ></td><td  style="    font-weight: normal;padding-left:6px!important;" ></td><td>&nbsp;</td><td  colspan="6"   style="text-align:right;" >汇买价 '.implode(', ',$exchangeratetext2).'</td></tr>';
    
  }
  $table .='</thead>
  <tbody>';
 
  foreach (${'data'.$tab->id} as $key => $values) {
        $appprove = 0; 
		$values['classification'] =  str_replace(array("\n","\r\n","\r",PHP_EOL,' '), '',$values['classification']);
		if( $values['tabs'] == '' ){
			foreach ($newtab_tabdocfull as $keytab => $r){
				if ( $values['id'] == $r->iddoc && $tab->id == $r->idtab ) {
					$appprove = 1; 
					$rt = $r->idtab;		
					unset($newtab_tabdocfull[$keytab]);	break;
				}
			}
			if ($appprove == 0){
             continue;
			}
		}else{
			if ($values['tabs'] != $tab->id ){
				 continue;
			}
			$rt = $values['tabs'];
		}
		
		if ($values['status'] != 'cancel'){          
			unset($data[$key]);continue;
        }
		if( date('Y.m.d',$values['id']) <  $datestart || date('Y.m.d',$values['id']) >  $dateto ){
			if( $values['documentnumber'] != '' && date('Ym') == date('Ym',$values['id']) ){
				$phieubosung .= '<td style="display:none;" class="tddocumentnumber'.$values['classification'].$tab->location.' '.$values['documentnumber'].'" >' . $values['documentnumber'] .'</td>';
			}
			continue;
		}		
		if($values['payer'] != ''){
			if( strpos($vendor, $values['payer']) === false ){
				$payer[$rt][] = "<option value='".$values['payer']."' >".$values['payer']."</option>";
			}else{
				$payer[$rt][] = "<option value='".$values['payer']."' selected='' >".$values['payer']."</option>";
			}
		}
		
		if( $vendor != '' && $vendor != 'clicktosearch' && strpos($vendor, $values['payer']) === false ){
			continue;
		}	
		
		$countNo++;
        $numtab++;
      	
        // SET TABLE LINE
        //$css = '';
        //require 'types/' . $TYPE . '/status.php';
        $toast = 'M.toast({html: "<span>' . $values['requestnumber'] . '</span>' .
                '<a href=?delete_id=' . $values['id']  . ' class=toast-action>' .
                $i18n['DELETE'] . '</a> &nbsp; &nbsp;"});';
		if($tab->special2 == 1){
			$balance[$rt] += floatval($values['amountincome']) - floatval($values['amountpayout']) - floatval($values['vat']) + floatval($values['wht']);
		}else{
			$balance[$rt] += floatval($values['amountincome']) - floatval($values['amountpayout']) ;
		}
			$income[$rt] += floatval($values['amountincome']);
			$expend[$rt] += floatval($values['amountpayout']);
		$rowclass = 'row'.$tab->id.$values['id'];	
		if($values['status'] == ''){
			$table .= '<tr class="'.$rowclass.'" style="" >';
		}elseif($values['status'] == 'pending'){
			$table .= '<tr class="'.$rowclass.'" style="background-color: #dddddd;" >';
		}elseif($values['status'] == 'approval'){
			$table .= '<tr class="'.$rowclass.'" style="background-color: #d1f9a9;"  >';
		}elseif($values['status'] == 'notapproval'){
			$table .= '<tr class="'.$rowclass.'" style="background-color: #ffe5e5;" >';
		}
		if ($currentuser->gm == '1' && file_exists("logs/".$values['id'])) {
			$logs = file_get_contents("logs/".$values['id']);
			$logs = str_replace(PHP_EOL,'<br>',$logs);
			$logsmode = '<a  href="#" data-target="modal6" class="modal-trigger cllogcontent" ><span style="display:none;" >'. $logs .'</span><i class="grey-text small material-icons">content_paste</i></a>';
		}else{
			$logsmode = '';
		}
		
        if ($currentuser->role == 'Manager' ) {
            $table .= '<td style="text-align:left;"><a style="display:none;" href="#" data-target="modal5" class="modal-trigger editmode" ref="edit.php?id=' . $values['id']  . '" ><i class="grey-text small ' .
                    'material-icons">mode_edit</i></a>';
            $table .= '<a href="#" onclick=\'' . $toast . '\'><i class="red-text text-darken-4 small ' .
                    'material-icons">delete_forever</i></a>'.$logsmode.'</td>';
        }
		
		$file = ''; 
		
		foreach ($values['filename'] as $keyfile => $dataf ){
				$fnjf++;
				if ( strpos($values['filetype'][$keyfile] , 'pdf')  !== false ) {
						
						
						if( $currentuser->location == '中国' ){
							$file .=  '<a ref="https://htlservice.net/expense/uploads/'.rawurlencode($values['filepath'][$keyfile]).'" data-target="readfile" class="modal-trigger isreadder'.$fnjf.'" isreadder="'.$fnjf.'" href="javascript:void(0);" onclick="$(\'.isleft,.isright\').attr(\'nextread\',\''.$fnjf.'\');$(\'.iframereadfile\').attr(\'src\',$(this).attr(\'ref\'));" ><img src="https://htlservice.net/Docs/tpl/img/pdf.png" style="width:24px;height:auto;" /></a>';
						}else{
							$file .=  '<a ref="https://drive.google.com/viewerng/viewer?url=https://htlservice.net/expense/uploads/'.urlencode($values['filepath'][$keyfile]).'?pid=explorer&efh=false&a=v&chrome=false&embedded=true" data-target="readfile" class="modal-trigger isreadder'.$fnjf.'" isreadder="'.$fnjf.'" href="javascript:void(0);" onclick="$(\'.isleft,.isright\').attr(\'nextread\',\''.$fnjf.'\');$(\'.iframereadfile\').attr(\'src\',$(this).attr(\'ref\'));" ><img src="https://htlservice.net/Docs/tpl/img/pdf.png" style="width:24px;height:auto;" /></a>';
						}
				} elseif ( strpos($values['filetype'][$keyfile] , 'sheet')  !== false || strpos($values['filepath'][$keyfile] , '.xls')  !== false ) { 
						$file .=  '<a ref="https://view.officeapps.live.com/op/embed.aspx?src=https://htlservice.net/expense/uploads/'.$values['filepath'][$keyfile].'" data-target="readfile" class="modal-trigger isreadder'.$fnjf.'" isreadder="'.$fnjf.'" href="javascript:void(0);" onclick="$(\'.isleft,.isright\').attr(\'nextread\',\''.$fnjf.'\');$(\'.iframereadfile\').attr(\'src\',$(this).attr(\'ref\'));" ><img src="https://htlservice.net/Docs/tpl/img/excel.png" style="width:24px;height:auto;" /></a>';
				} elseif ( strpos($values['filetype'][$keyfile] , 'zip')  !== false ) { 
						$file .=  '<a download href="uploads/'.$values['filepath'][$keyfile].'" ><img src="https://htlservice.net/Docs/tpl/img/zip.png" style="width:24px;height:auto;" /></a>';
				} elseif ( strpos($values['filetype'][$keyfile] , 'doc')  !== false ) { 
						$file .=  '<a ref="https://view.officeapps.live.com/op/embed.aspx?src=https://htlservice.net/expense/uploads/'.$values['filepath'][$keyfile].'" data-target="readfile" class="modal-trigger isreadder'.$fnjf.'" isreadder="'.$fnjf.'"  href="javascript:void(0);" onclick="$(\'.isleft,.isright\').attr(\'nextread\',\''.$fnjf.'\');$(\'.iframereadfile\').attr(\'src\',$(this).attr(\'ref\'));" ><img src="https://htlservice.net/Docs/tpl/img/word.png" style="width:24px;height:auto;" /></a>';
				} elseif ( strpos($values['filetype'][$keyfile] , 'image')  !== false ) { 
						$file .=  '<a ref="uploads/'.$values['filepath'][$keyfile].'" data-target="readfile" class="modal-trigger isreadder'.$fnjf.'" isreadder="'.$fnjf.'" href="javascript:void(0);" onclick="$(\'.isleft,.isright\').attr(\'nextread\',\''.$fnjf.'\');$(\'.iframereadfile\').attr(\'src\',$(this).attr(\'ref\'));"  ><img src="https://htlservice.net/Docs/tpl/img/png.png" style="width:24px;height:auto;" /></a>';
				} else{
						$file .=  '<a download href="uploads/'.$values['filepath'][$keyfile].'" ><img src="https://htlservice.net/Docs/tpl/img/file.png" style="width:24px;height:auto;" /></a>';
				}
		}
		if( $currentuser->role == 'Operator' && !in_array($tab->id,$currentuser->account) && in_array($tab->id,$currentuser->accountreadonly)){
					$table .= '<td style="text-align:center"></td>';
		}else{
			if ($currentuser->role == 'Operator' && ( $values['status'] == '' ) ){
					$table .= '<td style="text-align:center"><a class="tooltipped" data-position="top" ' .
						'data-tooltip="' . $i18n['Click alert link for delete!'] . '" ' .
						'href="#" onclick=\'' . $toast . '\'><i class="red-text text-darken-4 small ' .
						'material-icons">delete_forever</i></a> </td>';
			}elseif ($currentuser->role == 'Operator') {
					$table .= '<td style="text-align:center"></td>';
			}	
		}
		if( $currentuser->role == 'Operator' && !in_array($tab->id,$currentuser->account) && in_array($tab->id,$currentuser->accountreadonly)){
				$editmode = '';
		}else{
			if ($currentuser->role == 'Operator' && ( $values['status'] == '' ||  $values['status'] == 'notapproval' )) {
				$editmode = '<a style="display:none;" href="#" data-target="modal5" class="modal-trigger editmode" ref="edit.php?id=' . $values['id']  . '" ><i class="grey-text small ' .
			'material-icons">mode_edit</i></a>';
			}else{
				$editmode = '';
			}	
		}
		
		$decimal = 2;
		if($currencyname == 'VND'){
			$decimal = 0;
		}
		if( $currentuser->role == 'Operator' && !in_array($tab->id,$currentuser->account) && in_array($tab->id,$currentuser->accountreadonly)){
			$table .= '<td style="text-align:center"></td>';
		}else{
			$table .= '<td  style="padding-left:6px!important;"><input status="'.$values['status'].'" style="    opacity: 1;    position: relative;  pointer-events: auto;  z-index: 10;" type="checkbox" class="bskue" value="'.$values['id'].'" /></td>';
        }
		$moreinfo = $classdash1 = '';
		if(strpos($values['documentnumber'],'-') === false){
			if(in_array($values['documentnumber'].'-2',$groupdocumentnumber) && !in_array($values['documentnumber'].'-1',$groupdocumentnumber)){
				$strdocumentnumber = $values['documentnumber'].'-1';
				$classdash1 = 'classdash1';
				$moreinfo = '-1';
			}
		}
		if( $erjkik[$values['charge']] == '' && ( $values['classification'] == '管理费用' || $values['classification'] == '财务费用' ) ){
			$notinlist = 'color:red;';	
		}else{
			$notinlist = '';
		}
		
		$table .= '<td  style="padding-left:6px!important;"><span style="display:none;" >'.$values['id'].'</span><a href="#"  title="'.$values['createbyname'].'" >' . date('Y.m.d',$values['id']) .
	    '</a>'.$editmode.'</td><td style="padding-left:6px!important;">'.(($i18n[$values['payment']] != '')?$i18n[$values['payment']]:$values['payment']).
	    '</td><td style="padding-left:6px!important;">' .(($i18n[$values['classification']] != '')?$i18n[$values['classification']]:$values['classification']).
		'</td><td style="padding-left:6px!important;'.$notinlist.'">' .$erjkik[$values['charge']].(($i18n[$values['charge']] != '')?$i18n[$values['charge']]:$values['charge']).
		'</td><td class="havepecial" style="padding-left:6px!important;display:none;">' . $values['department'].
		'</td><td class="havepecial2" style="padding-left:6px!important;display:none;">' . $values['billno'].
		'</td><td class="havepecial2" style="padding-left:6px!important;display:none;">' . $values['billto'].
		'</td><td class="havepecial2" style="padding-left:6px!important;display:none;">' . $values['vat'].
		'</td><td class="havepecial2" style="padding-left:6px!important;display:none;">' . $values['wht'].
		'</td><td style="padding-left:6px!important;"><div class="nofulltext" >' . $values['summary'].
		'</div><i class="fas fa-sort-down" style="color: #000;    font-size: 17px;"></i></td>'.
		'<td style="padding-left:6px!important;">' . number_format((float)$values['amountincome'],$decimal).
		'</td><td style="padding-left:6px!important;">' . number_format((float)$values['amountpayout'],$decimal).
		'</td><td style="padding-left:6px!important;">' . number_format((float)$balance[$rt],$decimal) .
		'</td><td style="padding-left:6px!important;"><div class="nofulltext" >' . $values['payer'].
		'</div><i class="fas fa-sort-down" style="color: #000;    font-size: 17px;"></i></td>'.
		'<td style="padding-left:6px!important;">' . $values['requestnumber'].	
		'</td>'.
		//'<td style="padding-left:6px!important;"><div class="nofulltext" >' . $values['jobnumber'].'</div><i class="fas fa-sort-down" style="color: #000;    font-size: 17px;"></i></td>'.
		'<td style="padding-left:6px!important;" class="'.$classdash1.' tddocumentnumber'.$values['classification'].$tab->location.' '.$values['documentnumber'].'" >' . $values['documentnumber'] .
		'</td>'.
		'<td style="padding-left:6px!important;">' .(($i18n[$values['writtenoff']] != '')?$i18n[$values['writtenoff']]:$values['writtenoff']).
		'<td style="padding-left:6px!important;">' . $file.
		'</td><td style="padding-left:6px!important;"><div class="nofulltext" ><p>' .str_replace(PHP_EOL,'</p><p>',str_replace(array('  ','/n','/r','/t'),'',trim($values['remarks']))). '</p></div><i class="fas fa-sort-down" style="color: #000;    font-size: 17px;"></i></td>';
			if( $currentuser->role == 'Operator' && !in_array($tab->id,$currentuser->account) && in_array($tab->id,$currentuser->accountreadonly)){
					if($values['status'] == ''){
						$table .= '<td style="padding-left:6px!important;" >等待财务完成</td>';
					}elseif($values['status'] == 'pending'){
						$table .= '<td style="padding-left:6px!important;" ><a href="#" title="'.$values['financeclicktoapproval'].' - '.date('Y.m.d H:i',$values['financeclicktoapprovaltime']).'" >待审核...</a></td>';
					}elseif($values['status'] == 'approval'){
						$table .= '<td style="padding-left:6px!important;" ><a href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">已审核 by '.$values['controlerapproval'].'</a></td>';
					}elseif($values['status'] == 'notapproval'){
						$table .= '<td style="padding-left:6px!important;" ><a style="color:red;" href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">未通过 by '.$values['controlerapproval'].'</a></td>';
					}
			}else{
				if($currentuser->role == 'Operator'){
					if($values['status'] == ''){
						$table .= '<td><button style="width:100%;" id="'.$values['id'].'" class="btn waves-effect waves-light sendtoaproval ">发送</button></td>';
					}elseif($values['status'] == 'pending'){
						$table .= '<td style="padding-left:6px!important;" ><a href="#" title="'.$values['financeclicktoapproval'].' - '.date('Y.m.d H:i',$values['financeclicktoapprovaltime']).'" >待审核...</a></td>';
					}elseif($values['status'] == 'approval'){
						$table .= '<td style="padding-left:6px!important;" ><a href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">已审核 by '.$values['controlerapproval'].'</a></td>';
					}elseif($values['status'] == 'notapproval'){
						$table .= '<td style="padding-left:6px!important;" ><a href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">未通过 by '.$values['controlerapproval'].'</a></td>';
					}
				}
				
				if($currentuser->role == 'Finance'  ){
					if($values['status'] == ''){
						$table .= '<td style="padding-left:6px!important;" >等待财务完成</td>';
					}elseif($values['status'] == 'pending'){
						$table .= '<td><button id="'.$values['id'].'" title="'.$values['financeclicktoapproval'].' - '.date('Y.m.d H:i',$values['financeclicktoapprovaltime']).'" id="'.$values['id'].'" class="btn waves-effect waves-light approval">Yes</button><button  id="'.$values['id'].'" title="'.$values['financeclicktoapproval'].' - '.date('Y.m.d',$values['financeclicktoapprovaltime']).'" id="'.$values['id'].'" class="btn red waves-effect waves-light deny">No</button></td>';				
					}elseif($values['status'] == 'approval'){
						$table .= '<td style="padding-left:6px!important;" ><a href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">已审核 by '.$values['controlerapproval'].'</a><button style="width:100%;    background: #a0a0a0;" id="'.$values['id'].'" class="btn btn-danger waves-effect waves-light sendtoaproval ">'.$i18n['rollback'].'</button></td>';
					}elseif($values['status'] == 'notapproval'){
						$table .= '<td style="padding-left:6px!important;" ><a style="color:red;" href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">未通过 by '.$values['controlerapproval'].'</a><button style="width:100%;    background: #a0a0a0;" id="'.$values['id'].'" class="btn btn-danger waves-effect waves-light sendtoaproval ">'.$i18n['rollback'].'</button></td>';
					}
				}elseif($currentuser->gm == 1){
					if($values['status'] == ''){
						$table .= '<td style="padding-left:6px!important;" >等待财务完成</td>';
					}elseif($values['status'] == 'pending'){
						$table .= '<td><button id="'.$values['id'].'" title="'.$values['financeclicktoapproval'].' - '.date('Y.m.d H:i',$values['financeclicktoapprovaltime']).'" id="'.$values['id'].'" class="btn waves-effect waves-light approval">Yes</button><button  id="'.$values['id'].'" title="'.$values['financeclicktoapproval'].' - '.date('Y.m.d',$values['financeclicktoapprovaltime']).'" id="'.$values['id'].'" class="btn red waves-effect waves-light deny">No</button></td>';				
					}elseif($values['status'] == 'approval'){
						$table .= '<td style="padding-left:6px!important;" ><a href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">已审核 by '.$values['controlerapproval'].'</a></td>';
					}elseif($values['status'] == 'notapproval'){
						$table .= '<td style="padding-left:6px!important;" ><a style="color:red;" href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">未通过 by '.$values['controlerapproval'].'</a></td>';
					}elseif($values['status'] == 'cancel'){
						$table .= '<td style="padding-left:6px!important;" class="revision" >'.$values['controlerapproval'].' 请求返回 <button style="width:80%;    background: #ffee58;    color: #000;" id="'.$values['id'].'" class="btn waves-effect waves-light pulse  sendtoaproval darken-2 ">是</button></td>';
					}
				}elseif($currentuser->role == 'Manager'){
					if($values['status'] == ''){
						$table .= '<td style="padding-left:6px!important;" >等待财务完成</td>';
					}elseif($values['status'] == 'pending'){
						$table .= '<td style="padding-left:6px!important;" ><a href="#" title="'.$values['financeclicktoapproval'].' - '.date('Y.m.d H:i',$values['financeclicktoapprovaltime']).'" >待审核...</a></td>';
					}elseif($values['status'] == 'approval'){
						$table .= '<td style="padding-left:6px!important;" ><a href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">已审核 by '.$values['controlerapproval'].'</a></td>';
					}elseif($values['status'] == 'notapproval'){
						$table .= '<td style="padding-left:6px!important;" ><a style="color:red;" href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">未通过 by '.$values['controlerapproval'].'</a></td>';
					}elseif($values['status'] == 'cancel'){
						$table .= '<td style="padding-left:6px!important;" ><button style="width:100%;" id="'.$values['id'].'" class="btn waves-effect waves-light sendtoaproval ">'.$i18n['Go Back'].'</button></td>';
					}
				}
			}
        $table .= '</tr>';
        // END LOOP

		//$classification[$rt][] = $values['classification'];
		if($values['documentnumber'] != ''){
						$datasreach .= '{
							value: "'.str_replace(array('"',''),'',trim($values['documentnumber']).$moreinfo).'",
							label: "'.str_replace(array('"',''),'',trim($values['documentnumber']).$moreinfo).'",
							desc: "'.str_replace(array('"',''),'',trim($values['summary'])).' - '.str_replace(array('"',''),'',trim($tab->info)).'",
							tab: "'.str_replace(array('"',''),'',trim($tab->id)).'",
							id: ".'.str_replace(array('"',''),'',trim($rowclass)).'"
						  },';
		}
		unset($data[$key]);
    }
	
	if ($currentuser->role == 'Manager' || $currentuser->role == 'Operator') {
		if ($countNo > 0) {
        $table .= '</tbody><tfoot><tr class="tr_total"><td colspan="6" >'.$i18n["From"].':'.$datestart.' - '.$i18n["To"].':'.$dateto.'</td><td class="havepecial" style="display:none;"  >&nbsp;</td><td class="havepecial2" colspan="4" style="display:none;"  >&nbsp;</td><td>&nbsp;</td><td>'.number_format((float)$income[$rt],$decimal).'</td><td  style="padding-left:6px!important;" >'.number_format((float)$expend[$rt],$decimal).'</td><td  style="padding-left:6px!important;" >'.number_format((float)$balance[$rt],$decimal).'</td><td style="padding-left:6px!important;font-weight: normal;"  >('.$currencyname.')</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr></tfoot>';
		}
	}else{
		if ($countNo > 0) {
        $table .= '</tbody><tfoot><tr class="tr_total"><td colspan="6" >'.$i18n["From"].':'.$datestart.' - '.$i18n["To"].':'.$dateto.'</td><td class="havepecial" style="display:none;"  >&nbsp;</td><td class="havepecial2" colspan="4" style="display:none;"  >&nbsp;</td><td>'.number_format((float)$income[$rt],$decimal).'</td><td style="padding-left:6px!important;" >'.number_format((float)$expend[$rt],$decimal).'</td><td style="padding-left:6px!important;" >'.number_format((float)$balance[$rt],$decimal).'</td><td style="padding-left:6px!important;font-weight: normal;"  >('.$currencyname.')</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr></tfoot>';
		}
	}
	
    echo $table . '</table>
		<script>
			jQuery("#vendorid'.$tab->id.'").append("'.implode('',array_unique($payer[$rt])).'");
		</script>
	';
}

	$nextvalue1['越南'] =  substr( $nextvalue1['越南']+1001 , 1 , 3 );
	$nextvalue1['中国'] =  substr( $nextvalue1['中国']+1001 , 1 , 3 );
	$nextvalue1['泰国'] =  substr( $nextvalue1['泰国']+1001 , 1 , 3 );
	
	$nextvalue2['越南'] =  substr( $nextvalue2['越南']+1001 , 1 , 3 );
	$nextvalue2['中国'] =  substr( $nextvalue2['中国']+1001 , 1 , 3 );
	$nextvalue2['泰国'] =  substr( $nextvalue2['泰国']+1001 , 1 , 3 );
	
	$nextvalue3['越南'] =  substr( $nextvalue3['越南']+1001 , 1 , 3 );
	$nextvalue3['中国'] =  substr( $nextvalue3['中国']+1001 , 1 , 3 );	
	$nextvalue3['泰国'] =  substr( $nextvalue3['泰国']+1001 , 1 , 3 );
	
	echo '
	
		<input type="hidden" class="nextvalue1越南" value="'.$nextvalue1['越南'].'" />
		<input type="hidden" class="nextvalue1中国" value="'.$nextvalue1['中国'].'" />
		<input type="hidden" class="nextvalue1泰国" value="'.$nextvalue1['泰国'].'" />
		
		<input type="hidden" class="nextvalue2越南" value="'.$nextvalue2['越南'].'" />
		<input type="hidden" class="nextvalue2中国" value="'.$nextvalue2['中国'].'" />
		<input type="hidden" class="nextvalue2泰国" value="'.$nextvalue2['泰国'].'" />
		
		<input type="hidden" class="nextvalue3越南" value="'.$nextvalue3['越南'].'" />
		<input type="hidden" class="nextvalue3中国" value="'.$nextvalue3['中国'].'" />
		<input type="hidden" class="nextvalue3泰国" value="'.$nextvalue3['泰国'].'" />'.'<table><tr>'.$phieubosung.'</tr></table>';
?>

		<div id="readfile" class="modal" style="    width: 80%!important;" >
			<a onclick="$('.modal-overlay').trigger('click');" style="       background: transparent;    color: red;    font-weight: bold;    font-size: 35px;	    font-family: cursive;    width: 30px;    height: 30px;    top: 0px;    right: 20px;    position: absolute;    left: unset;    bottom: unset;    display: block;    cursor: pointer;" >x</a>
			<iframe class="iframereadfile" src="" width="100%" style="height:auto;    min-height: 550px;" ></iframe>
			<div class="isleft" ><i class="fas fa-chevron-left"></i></div>
			<div class="isright" ><i class="fas fa-chevron-right"></i></div>		
		</div>
		
		<div id="showmoreinfo" class="modal modal-fixed ">
			<div class="modal-content">
				<h5>Accounting Description</h5>
				<textarea class="snmnln" style="width:100%;border:none;min-height: 250px;" disabled ></textarea>
			</div>			
		</div>
        <div id="addNewTab" class="modal modal-fixed ">
        <div class="modal-content">
            <h4 style="margin-bottom: -20px;" >Accounting Infomation</h4>
            <form method="post" style="    margin-bottom: -15px;" >
				<br>
				<div class=" col s12">
                    <select name="currency" id="currency"  tabindex="-1">                           
                       		<?php foreach($currency as $r){
									$sel = '';
									if ($data['incomecurency'][$key] == '' && $r['id'] == $_SESSION['currencyUser']['id'] ){ $sel = "selected"; }
									if ($data['incomecurency'][$key] == $r['id'] ) {$sel = "selected";}	
							?>
								<option value="<?php echo $r['id']; ?>" <?php echo $sel; ?> ><?php echo $r['currency']; ?></option>
							<?php } ?>	
					</select>
                </div>
				<div class=" col s12">
					<span>Account From</span>
                    <select name="location" id="aclocation">
                        <option value="越南">越南</option>
                        <option value="中国">中国</option>
						<option value="泰国">泰国</option>
                    </select>                
                </div>		
                <div class=" col s12">
                    <input id="tab" type="text" class="validate"  placeholder="Account Name" name="tab" required>                  
                </div>				
				<div class="col s12">
                    <input id="tabinfo" type="text" class="validate"   placeholder="Account Quick Info"  name="tabinfo" >                    
                </div>
				<div class=" col s12">
                    <input <?php if( $currentuser->gm != 1 && $currentuser->role != "Finance"  ){ echo 'readonly=""'; } ?> data-type='currency' id="Balance" type="text" class="validate"   placeholder="Balance Default:0.00"  name="balance" >                    
                </div>
				<div class="col s12">
                    <textarea id="tabdescription" class=""  placeholder="Account Description"  name="tabdescription" style="    height: 90px;" ></textarea>                 
                </div>
				<div class="col s12" style="    height: 30px;" >
				<div class="col s12" style="    height: 30px;" >
						<label class="pure-material-checkbox">
						  <input type="checkbox"  value="1"  id="special"   name="special"  >
						  <span>Special Account ? 部门 </span>
						</label>
                </div>
				<div class="col s12" style="    height: 60px;" >
						<label class="pure-material-checkbox">
						  <input type="checkbox"  value="1"  id="special2"   name="special2"  >
						  <span>Special Account have Bill No.& Bill to ?</span>
						</label>
                </div>
				<div class=" col s12">
                    <button class="colortoptran btn waves-effect waves-light" style="display:block;margin:auto;right:0;left: 0;" type="submit" name="action">
                        Save
                    </button>
                </div>
			
				<input id="id_tabname" type="hidden" class="validate"  name="id_tabname" >
            </form>
        </div>
    </div>
	</div>
<form method="post" style="display:none;" id="adddoctotab" >
   <input id="idtab" type="hidden"  name="idtab" value="" >
   <input id="iddoc" type="hidden"  name="iddoc" value="" >
   <input id="task" type="hidden"  name="adddoctotab" value="1" >
</form>

<form method="post" style="display:none;" id="fromsendtoaproval" >
   <input class="iddoc" type="hidden"  name="iddoc" value="" >
   <input id="task" type="hidden"  name="sendtoaproval" value="1" >
</form>

<?php if ($currentuser->role == "Manager"  || $currentuser->role == "Finance"  ){ ?>
<form method="post" style="display:none;" id="fromapproval" >
	<input class="note" type="hidden"  name="note" value="" >
    <input class="iddoc" type="hidden"  name="iddoc" value="" >
	<input class="type" type="hidden"  name="type" value="" >
    <input id="task" type="hidden"  name="setapproval" value="1" >
</form>
<?php } ?>
<div id="modal5" class="modal">
  <iframe class="frameedit" src="" width="100%" style="height:auto;    min-height: 321px;" ></iframe>
</div>
<?php if ($currentuser->gm == "1"  ){ ?>	
<div id="modal6" class="modal">
  <div class="logcontent" style="padding: 15px;" ></div>
</div>
<?php } ?>
<form method="POST" id="formfilter" >
	<input value="<?php echo $vendor; ?>" id="vendor" name="vendor" type="hidden" />
	<input value="<?php echo $datestart; ?>" id="datestart" name="datestart" type="hidden" />
	<input value="<?php echo $dateto; ?>" id="dateto" name="dateto" type="hidden" />
	<input value="<?php echo $acctiveaccount; ?>" id="acctiveaccount" name="acctiveaccount" type="hidden" />			
</form>		

<?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;
		}
		if($_SESSION['HTTP_ACCEPT_LANGUAGE'] == 'cn'){
			$monthchinatext = array('一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月');
		}elseif($_SESSION['HTTP_ACCEPT_LANGUAGE'] == 'tha'){
			$monthchinatext = array('มกราคม ',' กุมภาพันธ์ ',' มีนาคม ',' เมษายน ',' พฤษภาคม ',' มิถุนายน ',' กรกฎาคม ',' สิงหาคม ',' กันยายน ',' ตุลาคม ',' ตุลาคม ',' พฤศจิกายน ',' ธันวาคม');
		}else{
			$monthchinatext = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
		}
		
		
?>
	
<script type="text/javascript">

$(window).load(function() {
$(".loader").delay(1000).fadeOut("slow");
$("#overlayer").delay(1000).fadeOut("slow");

 
$("#classification option").each(function(){
			if($(this).attr('color') != ''){
				var adf = $(this).text();var color = $(this).attr('color');
				$(this).parents().eq(1).find('li').each(function(){
					if($(this).find('span').text() == adf){
						$(this).find('span').css('color',color);$(this).find('span').css('font-weight','bold');
					}
				});
			}
});

	var start = moment().subtract(<?php echo $numdatstart; ?>, 'days');
    var end = moment().subtract(<?php echo $numdatto; ?>, 'days');

    function cb(start, end , sub) {		
		jQuery('#datestart').val(start.format('YYYY.MM.DD')); 
		jQuery('#dateto').val(end.format('YYYY.MM.DD')); 
		if(sub != 1){
			jQuery("#formfilter").submit();
		}
    }
	
	function cb2(start, end , sub) {
		jQuery('#datestart2').val(start.format('YYYY.MM.DD')); 
		jQuery('#dateto2').val(end.format('YYYY.MM.DD')); 
		jQuery('.bsdbk .select-dropdown').trigger('click');
		jQuery('.bsdbk ul li:first-child label span').text(start.format('YYYY.MM.DD')+' to '+end.format('YYYY.MM.DD')+' ?');
    }	

    $('.reportrange').daterangepicker({
        startDate: start,
        endDate: end,
		linkedCalendars: false,
        ranges: {
           '<?php echo $i18n['今天']; ?>': [moment(), moment()],
           '<?php echo $i18n['昨天']; ?>': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
           '<?php echo $i18n['七天内']; ?>': [moment().subtract(6, 'days'), moment()],
           '<?php echo $i18n['三十天内']; ?>': [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('-2 month')) - 1 )].' '.date('Y'); ?>': [moment().subtract(2, 'month').startOf('month'), moment().subtract(2, 'month').endOf('month')]
        }
    }, cb);
	
	$('.reportrange2').daterangepicker({
        startDate: start,
        endDate: end,
		linkedCalendars: false,
		customClass: 'some-css-class',
		locale: { direction: 'some-css-class' } ,
        ranges: {
           '<?php echo $i18n['今天']; ?>': [moment(), moment()],
           '<?php echo $i18n['昨天']; ?>': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
           '<?php echo $i18n['七天内']; ?>': [moment().subtract(6, 'days'), moment()],
           '<?php echo $i18n['三十天内']; ?>': [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('-2 month')) - 1 )].' '.date('Y'); ?>': [moment().subtract(2, 'month').startOf('month'), moment().subtract(2, 'month').endOf('month')]
        }
    }, cb2);
    cb(start, end , 1);
});
</script>
<?php if($_GET['showsearch'] == 1){ ?>
<script>
    var projects = [
		<?php echo $datasreach; ?>
    ];
  
    jQuery( "#project" ).autocomplete({
      minLength: 0,
      source: projects,
      focus: function( event, ui ) {
        jQuery( "#project" ).val( ui.item.label );
        return false;
      },
      select: function( event, ui ) {
		 
        //$( "#project" ).val( ui.item.label );
        //$( "#project-id" ).val( ui.item.value );
        //$( "#project-description" ).html( ui.item.desc );
        //$( "#project-icon" ).attr( "src", "images/" + ui.item.icon );
 
        return false;
      }
    })
    .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
      return jQuery( "<li class='searchresult' tab='" + item.tab + "' row='" + item.id + "'  >" )
        .append( "<div>" + item.label + "<br>" + item.desc + "</div>" )
        .appendTo( ul );
    };
//  });
</script>
<?php } ?>
<script type="text/javascript">
$(function() {  	
	jQuery('.editmode').click(function(){
		jQuery('.frameedit').attr( 'src',jQuery(this).attr('ref'));
	});	
});

function closeiframe(){
	$('.modal-overlay').trigger('click');
}
function closeiframereload(){
	$('.modal-overlay').trigger('click');
	location.reload();
}
function changewidthframe(){
	$('.frameedit').css('height','510px');
}

$(document).ready(function () {
	
	$(this).bind("contextmenu", function(e) {
		e.preventDefault();
	});
	$( "body" ).delegate( '.searchresult' , "click", function() {
		var row = $(this).attr('row');
		$('.tab'+$(this).attr('tab')).trigger('click');
		$($(this).attr('row')).css('background','#c5d9ff');
		$([document.documentElement, document.body]).animate({
			scrollTop: $($(this).attr('row')).offset().top - 100
		}, 2000);
		setTimeout(function(){
			$(row).removeAttr('style');
		}, 7000);
		
	});
	$('.collapsible').collapsible();
	$('.isleft').click(function(){
		if($('.isreadder'+$(this).attr('nextread')).prev().hasClass('modal-trigger')){
			$('.isreadder'+$(this).attr('nextread')).prev().trigger('click');
		}
	});
	$('.isright').click(function(){
		if($('.isreadder'+$(this).attr('nextread')).next().hasClass('modal-trigger')){
			$('.isreadder'+$(this).attr('nextread')).next().trigger('click');
		}
	});
	$('.ranges li:last-child').text('搜寻');
	
	$("#bifdnino").submit(function(e){		
		var issubmit = 1 ;
		$('#overlayer,.loader').show();
		$('.ismoreadd').each(function(index){
			if(jQuery(this).hasClass('act')){ 
				var self = this;
				//setTimeout(function () {
				$(self).find("iframe").contents().find("#bifdnino").submit();
				$(self).hide();$(self).removeClass('act');
				//}, index*1500);
				issubmit = 0;
			}
		});
		if(issubmit == 0){
			e.preventDefault();
			setTimeout(function () { $("#bifdnino").submit(); }, 5000);
		}
	});
	
	$("#dsjdbksa").submit(function(e){
		if( $("#tabexport").val() == null ) {
			$('.bsdbk .select-dropdown').trigger('click');
			e.preventDefault();
		}
	});
	
	$("#tabexport").change(function(){
		var string = $(this).val();
		if(string.indexOf("clicktosearch") !== -1 ){
			jQuery(".reportrange2").trigger('click');
			$(this).prop('selected',false);
			$(this).val('[]');
			$("#tabexport").formSelect();
			
		}
		if(string.indexOf("-1") !== -1 ){
			$("#dsjdbksa").submit();
			setTimeout(function(){
				$("#tabexport").val('[]');
				$("#tabexport").formSelect();
			}, 2000);
		}
	});
	
	$(".shkabkasb").change(function(){
		jQuery('#vendor').val($(this).val()); 
		var string = $(this).val();
		if(string.indexOf("clicktosearch") !== -1 ){
			jQuery("#formfilter").submit();
		}
	});

	$(".nofulltext").each(function(){
		if($(this).text().length < 9 && $(window).width() >= 1400){
			$(this).next().hide();
		}		
		if($(this).text().length < 9 && $(window).width() < 1400){
			$(this).next().hide();
		}
	});
	$('.fa-sort-down').click(function(){
		if($(this).hasClass('active')){
			$(this).parents().eq(1).find('.nofulltext').removeAttr('style');
			$(this).parents().eq(1).find('.fa-sort-down').removeClass('active');
		}else{
			$(this).parents().eq(1).find('.nofulltext').css('height','auto');
			$(this).parents().eq(1).find('.fa-sort-down').addClass('active');
		}
	});
	
	$(".sandjnas").change(function(){
		if($( ".sandjnas option:selected" ).hasClass('isspeci')){
			$(".isdepartmentform").show();
		}else{
			$(".isdepartmentform").hide();
		}
		
		if($( ".sandjnas option:selected" ).hasClass('isspeci2')){
			$(".inputisspeci2").show();
		}else{
			$(".inputisspeci2").hide();
		}
	});
	$(".sandjnas").change();

	
	$('.tab-link').on('click',function(){
 
		 $("#documentnumber").val('');$("#classification").val('');
         $(".sandjnas").val($(this).attr("data-id")).change();
		 $("#acctiveaccount").val($(this).attr("data-id"));
		 $(".sandjnas").formSelect();
		 $("#classification").formSelect();
		 $(".formchiem").empty();
		 var date = new Date();
		 var minutes = 1440;
		 date.setTime(date.getTime() + (minutes * 60 * 1000));
		 $.cookie("tabremenber", $(this).attr("data-id") , { expires: date });
	});
	$('.treopit').on('click',function(){
		$(".snmnln").text($(this).find('.tabdescription').text());
	});
	
	$(".tabnameSave").click(function(){		
		$(".sdastr").trigger("click");
		$("#addNewTab #currency").val($(this).prev().attr('currency'));
		$('#addNewTab #currency').formSelect();
		$("#addNewTab #id_tabname").val($(this).prev().attr('data-id'));
		$("#addNewTab #tab").val($(this).prev().attr('name'));
		$("#addNewTab #Balance").val($(this).prev().attr('balance'));
		$("#addNewTab #tabinfo").val($(this).prev().attr('info'));
		$("#addNewTab #tabdescription").val($(this).prev().find('.tabdescription').text());
		$("#addNewTab #aclocation").val($(this).prev().attr('location'));		
		$('#aclocation').formSelect();
		if($(this).prev().attr('special') == 1){
			$("#addNewTab #special").prop('checked',true);
		}else{
			$("#addNewTab #special").prop('checked',false);
		}
		
		if($(this).prev().attr('special2') == 1){
			$("#addNewTab #special2").prop('checked',true);
		}else{
			$("#addNewTab #special2").prop('checked',false);
		}
	});
	function pad (str, max) {
	  str = str.toString();
	  return str.length < max ? pad("0" + str, max) : str;
	}
	$(".makesimilar").change(function(){
		var str = $(this).val();
		/*
		if( str.indexOf('-') !== -1 ){
			var res = str.split("-");
			var sotang = res[1].match(/\d+/); 
			var main = res[1].replace(sotang, '');
			if(res[1].length > 3){
				$("#documentnumber").val(res[0]+'-'+main+(pad(parseInt(sotang)+1, 3)));
			}else{
				for ( var i = 3; i < 999; i++){
					if( arrlist2.indexOf(res[0]+'-'+i) == -1 ){
						$("#documentnumber").val(res[0]+'-'+i);
						break;
					}
				}
			}
		}else{
			$("#documentnumber").val($(this).val()+'-2');
		}*/
		//arrlist2.indexOf(res[0]+'-'+i) == -1
		var res = str.split("-");
		for ( var i = 2; i <= 999; i++){			
			if(!$('.'+res[0]+'-'+i<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> ).length ){
					$("#documentnumber").val(res[0]+'-'+i);
					$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>)).append( '<td class="'+res[0]+'-'+i+'" >'+res[0]+'-'+i+'</td> ' );
					break;
			}
		}
		$("#documentnumber").attr('readonly','');
	});
	
	function pad (str, max) {
	  str = str.toString();
	  return str.length < max ? pad("0" + str, max) : str;
	}


	$("#classification").change(function(){
		$('#charge').val('');$("#documentnumber").val('');
		jQuery('.makesimilar').empty();
		jQuery('.makesimilar').formSelect();
		jQuery('#iscontinue').prop('checked',false);
		$("#documentnumber").removeAttr('readonly');
		if($(this).val() != ''){
			$('#charge').prop('disabled',false);
			$('#charge option').prop('disabled',true);
			if( $("#classification option:selected").attr('freetext') == 'freetext' ){
				$('.charge').hide();
				$('#chargefreetext,.chargefreetext').show();
				$('#chargefreetext').val('');
				$('#chargefreetext').prop('disabled',false);
			}else{
				$('.charge').show();
				$('#chargefreetext,.chargefreetext').hide();
				$('#chargefreetext').val('');
				$('#chargefreetext').prop('disabled',true);
				if( $('.'+$(this).val()).length ){
					$('.'+$(this).val()).prop('disabled',false);
				}else{
					$('.novalue').prop('disabled',false);
					$('.novalue').attr('value',$(this).val());
					$('.novalue').text($(this).val());
				}
				
			}
		}else{
			$('#charge').prop('disabled',true);
		}
		$('#charge').formSelect();
		
		var location = $( ".sandjnas option:selected" ).attr('location');
		if( $( ".sandjnas option:selected" ).hasClass('isspeci') && $("#department").val() != '' ){
			location = $("#department").val();
		}
		
		var tabvalue = $( ".sandjnas" ).val();
		var date = "<?php echo date("ym"); ?>"+'';		
		
		if($(this).val() == "管理费用"){			
			if(location == '越南'){
				var num = $( ".nextvalue1越南" ).val();	
					num = parseInt(num);				
				for ( ; num <= 999; num++){
					if( !$('.'+'VNG'+date+pad(num, 3)<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> ).length ){
						break;
					}
				}				
				$("#documentnumber").val('VNG'+date+pad(num, 3));				
				$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>)).append( '<td class="tddocumentnumber管理费用越南 '+'VNG'+date+pad(num, 3)+'" >'+'VNG'+date+pad(num, 3)+'</td> ' );
				
			}
			if(location == '中国'){
				var num = $( ".nextvalue1中国" ).val();
				num = parseInt(num);		
				for ( ; num <= 999; num++){
					if( !$('.'+'CNG'+date+pad(num, 3)<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>).length ){
						break;
					}
				}				
				$("#documentnumber").val('CNG'+date+pad(num, 3));
				
				$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>)).append( '<td class="tddocumentnumber管理费用中国 '+'CNG'+date+pad(num, 3)+'" >'+'CNG'+date+pad(num, 3)+'</td> ' );
			}
			if(location == '泰国'){
				var num = $( ".nextvalue1泰国" ).val();
				num = parseInt(num);
				for ( ; num <= 999; num++){
					if( !$('.'+'THG'+date+pad(num, 3)<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>).length ){
						break;
					}
				}				
				$("#documentnumber").val('THG'+date+pad(num, 3));				
				$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>) ).append( '<td class="tddocumentnumber管理费用泰国 '+'THG'+date+pad(num, 3)+'" >'+'THG'+date+pad(num, 3)+'</td> ' );
			}
			$("#documentnumber").attr('readonly','');
		}
		if($(this).val() == "应收账款"){ 
			if(location == '越南'){
				var num = $( ".nextvalue2越南" ).val();
				num = parseInt(num);				
				for ( ; num <= 999; num++){
					if( !$('.'+'VNS'+date+pad(num, 3)<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> ).length ){
						break;
					}
				}				
				$("#documentnumber").val('VNS'+date+pad(num, 3));
				$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>)).append( '<td class="tddocumentnumber应收账款越南 '+'VNS'+date+pad(num, 3)+'" >'+'VNS'+date+pad(num, 3)+'</td> ' );
				
			}
			if(location == '中国'){
				var num = $( ".nextvalue2中国" ).val();
				num = parseInt(num);				
				for ( ; num <= 999; num++){
					if( !$('.'+'CNS'+date+pad(num, 3)<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> ).length ){
						break;
					}
				}		
				$("#documentnumber").val('CNS'+date+pad(num, 3));
				$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>)).append( '<td class="tddocumentnumber应收账款中国 '+'CNS'+date+pad(num, 3)+'" >'+'CNS'+date+pad(num, 3)+'</td> ' );
				
			}
			if(location == '泰国'){
				var num = $( ".nextvalue2泰国" ).val();
				num = parseInt(num);				
				for ( ; num <= 999; num++){
					if( !$('.'+'THS'+date+pad(num, 3)<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> ).length ){
						break;
					}
				}		
				$("#documentnumber").val('THS'+date+pad(num, 3));
				$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>)).append( '<td class="tddocumentnumber应收账款泰国 '+'THS'+date+pad(num, 3)+'" >'+'THS'+date+pad(num, 3)+'</td> ' );
				
			}
			$("#documentnumber").attr('readonly','');
		}		
		if($(this).val() == "应付账款"){			
			
			if(location == '越南'){
				var num = $( ".nextvalue3越南" ).val();
				num = parseInt(num);				
				for ( ; num <= 999; num++){
					if( !$('.'+'VNF'+date+pad(num, 3)<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> ).length ){
						break;
					}
				}		
				$("#documentnumber").val('VNF'+date+pad(num, 3));
				$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>)).append( '<td class="tddocumentnumber应付账款越南 '+'VNF'+date+pad(num, 3)+'" >'+'VNF'+date+pad(num, 3)+'</td> ' );
				
			}
			if(location == '中国'){
				var num = $( ".nextvalue3中国" ).val();
				num = parseInt(num);				
				for ( ; num <= 999; num++){
					if( !$('.'+'CNF'+date+pad(num, 3)<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> ).length ){
						break;
					}
				}		
				$("#documentnumber").val('CNF'+date+pad(num, 3));
				$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>)).append( '<td class="tddocumentnumber应付账款中国 '+'CNF'+date+pad(num, 3)+'" >'+'CNF'+date+pad(num, 3)+'</td> ' );
				
			}
			if(location == '泰国'){
				var num = $( ".nextvalue3泰国" ).val();
				num = parseInt(num);				
				for ( ; num <= 999; num++){
					if( !$('.'+'THF'+date+pad(num, 3)<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> ).length ){
						break;
					}
				}	
				$("#documentnumber").val('THF'+date+pad(num, 3));
				$( $('.formchiem'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>)).append( '<td class="tddocumentnumber应付账款泰国 '+'THF'+date+pad(num, 3)+'" >'+'THF'+date+pad(num, 3)+'</td> ' );
				
			}
			$("#documentnumber").attr('readonly','');
		}		
	});	
	<?php 	if ($currentuser->role == 'Finance' || $currentuser->gm == 1 ) { ?>
		jQuery(".bskue").each(function(){
			if( jQuery(this).attr('status') != 'pending' ){		
				jQuery(this).hide();
			}	
		});
	<?php }elseif ($currentuser->role == 'Manager'){ ?>
		jQuery(".bskue").each(function(){
			jQuery(this).hide();	
		});
	<?php }elseif ($currentuser->role == 'Operator'){ ?>
		jQuery(".bskue").each(function(){
			if( jQuery(this).attr('status') != '' ){		
				jQuery(this).hide();
			}		
		});
	<?php }	?>
	jQuery(".bskue").click(function(){
		if(jQuery(this).is(':checked')){	
			<?php 	if ($currentuser->role == 'Finance' || $currentuser->gm == 1 ) { ?>
				M.Toast.dismissAll();
				if( jQuery(this).attr('status') == 'pending' ){					
					M.toast({displayLength: 12000,html: "<button style='margin-right: 10px;' class='btn waves-effect waves-light mapproval'>Yes</button><button class='btn red waves-effect waves-light mdeny'>No</button>" });
				}else{
					jQuery(this).prop('checked',false);
					jQuery(this).prop('disabled',true);
				}
			<?php }elseif ($currentuser->role == 'Operator'){ ?>
				M.Toast.dismissAll();
				if( jQuery(this).attr('status') == '' ){					
					M.toast({displayLength: 12000,html: "<button style='width:100%;' class='btn waves-effect waves-light msendtoaproval '>发送</button>" });
				}else{
					jQuery(this).prop('checked',false);
					jQuery(this).prop('disabled',true);
				}
			<?php }	?>
		}
	});
	<?php if ($currentuser->role == 'Manager' || $currentuser->role == 'Operator') { ?>      
	jQuery(".tablesorter tbody tr").dblclick(function() {
		$('.modal-overlay').trigger("click");
		if($(this).find('.editmode').length){
			$('.frameedit').css('height','auto');
			$(this).find('.editmode').trigger('click').click();
			$('#modal5').modal('open'); 
		}else{
			alert("This order can\'t edit.");
		}	
	});
	<?php } ?>
	<?php if ($currentuser->gm == "1"  ){ ?>	
	$(".cllogcontent").click(function(){
		$(".logcontent").html($(this).find('span').html());
	});	
	<?php } ?>
	$('.sendtoaproval').click(function(){ 
			//if (confirm('Are you sure send to approval, can\'t modify after approval  ?')) {
				$("#fromsendtoaproval .iddoc").val($(this).attr('id'));
				$("#fromsendtoaproval").submit();
			//}
	});
	<?php if ($currentuser->role == "Operator"  ){ ?>	
	
		
		$( "body" ).delegate( ".msendtoaproval", "click", function() {
			var mapproval = '';
			$(".bskue").each(function(){
				if(jQuery(this).is(':checked')){
					if(mapproval == ''){
					mapproval += jQuery(this).val();
					}else{	
					mapproval += ','+jQuery(this).val();
					}
				}	
			});
			$("#fromsendtoaproval .iddoc").val(mapproval);
			$("#fromsendtoaproval").submit();
		});		
	<?php } ?>
	<?php if ($currentuser->role == "Manager"  || $currentuser->role == "Finance"  ){ ?>
		$('.approval').click(function(){
			if (confirm('Are you sure set to approval ?')) {
				$("#fromapproval .type").val('approval');
				$("#fromapproval .iddoc").val($(this).attr('id'));
				$("#fromapproval").submit();
			}
		});	
		$('.deny').click(function(){
			var newnote = window.prompt("Are you sure set to deny ?", "Reason Why");
			if ( newnote != '' ) {
				$("#fromapproval .note").val(newnote);
				$("#fromapproval .type").val('notapproval');
				$("#fromapproval .iddoc").val($(this).attr('id'));
				$("#fromapproval").submit();
			}
		});
		$( "body" ).delegate( ".mapproval", "click", function() {
				$("#fromapproval .type").val('approval');
				var mapproval = '';
				$(".bskue").each(function(){
					if(jQuery(this).is(':checked')){
						if(mapproval == ''){
						mapproval += jQuery(this).val();	
						}else{
						mapproval += ','+jQuery(this).val();
						}
					}	
				});
				$("#fromapproval .iddoc").val(mapproval);
				$("#fromapproval").submit();
		});
		$( "body" ).delegate( ".mdeny", "click", function() {	
				$("#fromapproval .type").val('notapproval');
				var mapproval = '';
				$(".bskue").each(function(){
					if(jQuery(this).is(':checked')){
						if(mapproval == ''){
						mapproval += jQuery(this).val();
						}else{	
						mapproval += ','+jQuery(this).val();
						}
					}	
				});
				$("#fromapproval .iddoc").val(mapproval);
				$("#fromapproval").submit();
		});	
	<?php } ?>	
	 <?php if ( $currentuser->gm == 1 || $currentuser->role == 'Finance' ) {  ?>   
		$('.tab-link').on('click',function(){
          //  $('.tabs button:not(.sdastr),.tabs a').hide();
		});
        $('.tab-link').on('dblclick',function(){
            //var tab_id = $(this).attr('data-tab');
            //$('.' + tab_id).css({"display":"block"});
           // $(this).css({"display":"none"});
        });
    <?php } ?>
	var arrlist2 = [];
	$("#iscontinue").change(function(){
		if($("#classification").val() == ''){
			alert('select <?php echo $i18n['费用归类']; ?> first ');
			jQuery('.makesimilar').empty();
			jQuery('.makesimilar').formSelect();
			jQuery('#iscontinue').prop('checked',false);
			return;
		}
		if(jQuery(this).is(':checked')){
			var location = $( ".sandjnas option:selected" ).attr('location');
			if( $( ".sandjnas option:selected" ).hasClass('isspeci') && $("#department").val() != '' ){
				location = $("#department").val();
			}
			var classification = $("#classification").val();
			if( classification == "管理费用"){			
				if(location == '越南'){
					var arr =  $('.tddocumentnumber管理费用越南'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> );
				}
				if(location == '中国'){
					var arr =  $('.tddocumentnumber管理费用中国'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> );
				}
				if(location == '泰国'){
					var arr =  $('.tddocumentnumber管理费用泰国'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> );
				}
			}
			if( classification == "应收账款"){ 
				if(location == '越南'){
					var arr =  $('.tddocumentnumber应收账款越南'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> );
				}
				if(location == '中国'){
					var arr =  $('.tddocumentnumber应收账款中国'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> );
				}
				if(location == '泰国'){
					var arr =  $('.tddocumentnumber应收账款泰国'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> );
				}
			}		
			if( classification == "应付账款"){			
				
				if(location == '越南'){
					var arr =  $('.tddocumentnumber应付账款越南'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> );
				}
				if(location == '中国'){
					var arr =  $('.tddocumentnumber应付账款中国'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?> );
				}
				if(location == '泰国'){
					var arr =  $('.tddocumentnumber应付账款泰国'<?php if($_GET['onlyform'] == 1) { ?> , window.parent.document <?php } ?>);
				}
			}
			jQuery('.makesimilar').empty();
			$('.asbkdbsak').empty();
			var arrlist = [];			
			jQuery(arr).each(function( index ) {
				//if(jQuery(this).text() != '' && arrlist.indexOf(jQuery(this).text()) == -1 ){
				jQuery(this).text($.trim(jQuery(this).text()));	
				var str = jQuery(this).text();
				if(jQuery(this).text() != ''){
					arrlist2.push(jQuery(this).text());
				}
				if(jQuery(this).text() != '' && arrlist.indexOf(jQuery(this).text()) == -1 && str.indexOf('-') == -1 ){
					var text = jQuery(this).parents().eq(0).html();
					text = text.replace(/td/g,'div');
					text = text.replace(/div>/g,'div>  ');
					jQuery('.asbkdbsak').append('<div class="is'+jQuery(this).text()+'" ><div style="width:300px;" >'+jQuery(this).parents().eq(2).find('.treopit td').html()+'</div><br>'+text+'</div>');
					var str = jQuery(this).text();
					
					var totalnum = 1;
					for ( var i = 2; i <= 999; i++){
						if( $('.'+jQuery(this).text()+'-'+i).length ){
							totalnum++;
						}else{
							break;
						}
					}
					var str = '('+totalnum+')';
					if(str == '(1)'){
						str = '';
					}
					jQuery('.makesimilar').append("<option  value='"+jQuery(this).text()+"' >"+jQuery(this).text()+" "+str+"</option>");
					arrlist.push(jQuery(this).text());
				}
			});
			
			var options = $('.makesimilar option');
			var arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
			arr.sort(function(o1, o2) { return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0; });
			options.each(function(i, o) {
			  o.value = arr[i].v;
			  $(o).text(arr[i].t);
			});
			
			jQuery('.makesimilar').formSelect();
			
			jQuery('.asbkdbsak button , .asbkdbsak select , .asbkdbsak i  , .asbkdbsak input , .asbkdbsak .modal-trigger').remove();
			jQuery('.asbkdbsak .nofulltext').removeClass('nofulltext');
			
			jQuery('.asbkdbsak a').attr('onclick','');
			jQuery('.makesimilarlabel .dropdown-trigger').css('opacity',1); 
			
			
	
		}else{
			jQuery('.makesimilarlabel .dropdown-trigger').css('opacity',0.4);
			jQuery('.makesimilar').empty();
			jQuery('.makesimilar').formSelect();
		}
	});
	
	
	$( "body" ).delegate( '.makesimilarlabel .select-dropdown.dropdown-content li' , "mouseover", function() {	
				 $('.toast.rounded').hide();
				 //M.Toast.dismissAll();
				 var isclass =  $(this).text();
				 isclass = isclass.split(" ");
				 M.toast({html: jQuery('.is'+isclass[0]).html(),  classes: 'rounded' , displayLength: 6000 , inDuration: 50 , outDuration: 50 });
			});

	$( "body" ).delegate( '.makesimilarlabel .select-dropdown.dropdown-content li' , "mouseout", function() {
				 $('.toast.rounded').hide();
				 //M.Toast.dismissAll();
			});

	$('.tab-link').each(function(){
		if( $.cookie("tabremenber") == $(this).attr('data-id') ){
			$(this).trigger("click");
		}
	});
							
		$("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, 2);
				input_val =  left_side + "." + right_side;
			} else {
				input_val = formatNumber(input_val);
				input_val =  input_val;
				// final formatting
				if (blur === "blur") {
				//input_val += ".00";
				}
			}
			input.val(input_val);
			var updated_len = input_val.length;
			caret_pos = updated_len - original_len + caret_pos;
			input[0].setSelectionRange(caret_pos, caret_pos);
			}
	<?php 	if ($currentuser->gm == 1 ) { ?>
		$(".tab-link").each(function(){
			if ( $('#tab-'+$(this).attr('data-id')+' .revision').length > 0){
				$(this).append('<span style="    background: #ffd600;    Color: #000;    padding: 0px 6px;       margin-left: 5px; border-radius: 50%;" >'+$('#tab-'+$(this).attr('data-id')+' .revision').length+'</span>');
			}
		});	
	<?php } ?>		
});
</script>
<div style="display:none" class="asbkdbsak" ></div>
<?php if($_GET['onlyform'] != 1) { ?>
<table style="display:none" ><tr class="formchiem" > <tr><table>
<br>
<?php } ?>
	
<?php    
// FOOTER
include 'tpl/footer.php'; ?>