<?php
ob_start();
date_default_timezone_set('Asia/Bangkok');
error_reporting(E_ALL);
ini_set('display_errors',0);
session_start();
// FOR DEBUG ONLY
if (isset($_GET['php']) and $_GET['php'] == 'info') {
    die(phpinfo());
}

function recurse_copy($src,$dst) { 
    $dir = opendir($src); 
    @mkdir($dst); 
    while(false !== ( $file = readdir($dir)) ) { 
        if (( $file != '.' ) && ( $file != '..' )) { 
            if ( is_dir($src . '/' . $file) ) { 
                recurse_copy($src . '/' . $file,$dst . '/' . $file); 
            } 
            else { 
                copy($src . '/' . $file,$dst . '/' . $file); 
            } 
        } 
    } 
    closedir($dir); 
} 

// SEARCH HELPER FUNCTION
function contains(array $array, $string) {
    $count = 0;
    foreach ($array as $value) {
        if (false !== stripos($string, $value)) {
            ++$count;
        }
    }
    return $count == count((array)$array);
}
// START & CONFIG

require 'setup/config.php';

// LOGIN CHECK
$login = check_current_user_login($ARR_USERS, $SALT);
$currentuser = $login['user'];
$LANG =  'cn';

if($currentuser->location == '印尼' && !isset($_GET['lang']) ){
    $LANG = $_GET['lang'] = 'en';
}
// 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




if($_GET['revertbackup'] == 1 && $_GET['date'] != '' && $_GET['id'] != ''){
	if ($currentuser->gm == 1 ){
		$data = json_decode(file_get_contents($file), true);
		$file2 = 'backup/'.$_GET['date'].'/Documents.json'; 
		echo $file2 ;
		if(isset($file2)){
			$data2 = json_decode(file_get_contents($file2), true);
			foreach ( $data2 as $key => $r  ){
				if(!isset($data3[$r['id']])){
				$data3[$r['id']] = $r;
				}
			}
			echo '<pre>';print_r($data3[$_GET['id']]);echo '</pre>';
			foreach ( $data as $key => $r  ){
				if($r['id'] == $_GET['id']){
					$data[$key] = $data3[$_GET['id']];
					$dareplace = 1;
					echo 'Replace. ';
				}
			}
			if($dareplace == '' && isset($data3[$_GET['id']]) ){
				$data[] = $data3[$_GET['id']];
				echo 'Import new. ';
			}
			$convert_array_to_json = array_values($data);
			$write_json = json_encode($convert_array_to_json);
			file_put_contents($file, $write_json);
		}else{
			echo 'Not found '.$file2.'. ';
		}
		echo 'done';
	}
	die;
}

$currencydate = date('Ymd');
if($_GET['currencydate'] != ''){
	$currencydate = $_GET['currencydate'];
}

if($_GET['datestart'] != ''){
	 $_POST['datestart'] = $_GET['datestart'];
}


if($_GET['dateto'] != ''){
	$_POST['dateto'] = $_GET['dateto'];
}



$currency = json_decode(file_get_contents('data/Currency.json'), true);

foreach ($currency as $r){
	$currencyex[$r['id']] = $r;
}


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) {
    // make backup
    $backup = __DIR__."/backup/";
    if (!file_exists($backup)) {
        mkdir($backup, 0777);
    }// backup today
	
	// check file toan ven
	if(is_countable(json_decode(file_get_contents('data/Noti.json'))) == 0){
		$folder = scandir(__DIR__."/backup/", SCANDIR_SORT_DESCENDING);	
		copy(__DIR__."/backup/".$folder[1].'/Noti.json', __DIR__."/data/Noti.json"  );  
	}
	if(is_countable(json_decode(file_get_contents('data/mywork.json'))) == 0){
		$folder = scandir(__DIR__."/backup/", SCANDIR_SORT_DESCENDING);	
		copy(__DIR__."/backup/".$folder[1].'/mywork.json', __DIR__."/data/mywork.json"  );  
	}
	if(is_countable(json_decode(file_get_contents('data/TabDoc.json'))) == 0){
		$folder = scandir(__DIR__."/backup/", SCANDIR_SORT_DESCENDING);	
		copy(__DIR__."/backup/".$folder[1].'/TabDoc.json', __DIR__."/data/TabDoc.json"  );  
	}
	if(is_countable(json_decode(file_get_contents('data/Documents.json'))) == 0){
		$folder = scandir(__DIR__."/backup/", SCANDIR_SORT_DESCENDING);	
		copy(__DIR__."/data/Documents_bk.json",__DIR__."/error_data/Documents_bk_".date('Y-m-d h:i:s').".json");
		copy(__DIR__."/data/Documents.json" , __DIR__."/error_data/Documents_".date('Y-m-d h:i:s').".json");  
		if(filemtime(__DIR__."/data/Documents_bk.json") > (time()-3600) ){
			copy(__DIR__."/data/Documents_bk.json" , __DIR__."/data/Documents.json" );
		}else{
			copy(__DIR__."/backup/".$folder[1].'/Documents.json', __DIR__."/data/Documents.json"  );  
		}
	}
	if(is_countable(json_decode(file_get_contents('data/Tabs.json'))) == 0){
		$folder = scandir(__DIR__."/backup/", SCANDIR_SORT_DESCENDING);	
		copy(__DIR__."/backup/".$folder[1].'/Tabs.json', __DIR__."/data/Tabs.json"  );  
	}	
	if(is_countable(json_decode(file_get_contents('data/Setting.json'))) == 0){
		$folder = scandir(__DIR__."/backup/", SCANDIR_SORT_DESCENDING);	
		copy(__DIR__."/backup/".$folder[1].'/Setting.json', __DIR__."/data/Setting.json"  );  
	}
	if(is_countable(json_decode(file_get_contents('data/User.json'))) == 0){
		$folder = scandir(__DIR__."/backup/", SCANDIR_SORT_DESCENDING);	
		copy(__DIR__."/backup/".$folder[1].'/User.json', __DIR__."/data/User.json"  );  
	}
    $backuptoday = $backup.date('YmdH').'/';  
    if (!file_exists($backuptoday)) {
      recurse_copy(__DIR__."/data/",$backuptoday);  
    }
	$cookie_name = "usergotofile";
    setcookie($cookie_name, $currentuser->name , time() + (6400), "/");
    if($currentuser->name == 'GM'){ 
            setcookie('userdata', 'Docs' , time() + 6400, "/");
            setcookie('key', 'Aa0OHHIODd8a4s984d' , time() + (6400), "/");
    }
	
    
} 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'));
$receiver_payer = json_decode(file_get_contents('data/receiver_payer.json'));
$corresponding = json_decode(file_get_contents('data/Corresponding.json'));
foreach ($receiver_payer as $r){ if( $r->id == '' || $r->name == '' ) { continue; }
	$receiver_payer_name[$r->name] = $r;
	$receiver_payer_id[$r->id] = $r;
}
foreach ($corresponding as $r){ 
	$corresponding_id[$r->id] = $r;
}
if ($_GET['checkveri'] == '') {
//echo '<div style="display:none;">ip='.$ip.'</div>';
}

if($currentuser->name == 'LEX'){
        //$currentuser->role 1;
}
if(( $currentuser->role == 'Operator' ||  $currentuser->role == 'Manager'  ) && $currentuser->gm != 1 && $currentuser->name != 'LEX' && $currentuser->name != 'SAM' && $currentuser->cherry != 1   ){	//

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

// DELETE ENTRY IF DEL LINK IS CLICKED
if (@$_GET['delete_id'] != '') {
    $data = json_decode(file_get_contents($file), true);
    foreach ( $data as $key => $r  ){
        if($r['id'] == @$_GET['delete_id']){
			if ($currentuser->role == 'Manager' || ( $currentuser->role == 'Operator' && $r['status'] == '' ) ) {
				unset($data[$key]);
			}
        }
    }
	
	$textlog = date('Y-m-d H:i:s').' - '.$currentuser->name.': delete expense'  ;
	file_put_contents('logs/'.$_GET['delete_id'],file_get_contents('logs/'.$_GET['delete_id']).$textlog.PHP_EOL);
	
    $convert_array_to_json = array_values($data);
    $write_json = json_encode($convert_array_to_json);
    file_put_contents($file, $write_json);
    header('location: index.php?msg=' . $i18n['Entry successfully deleted.']);
}
if (@$_GET['checkveri'] != '') {
	$solan = 0;
	$data = json_decode(file_get_contents($file),true);
	foreach ($data as $key => $values) {   
		if( stripos($values['documentnumber'],$_GET['veri']) !== false ) {
			$solan++;
		}
	}
	if($solan){
		echo '-'.($solan+1);
	}else{
		echo '';
	}
	die;
}
if (@$_GET['highlight'] == '1' && @$_GET['id'] != '') {
    $data = json_decode(file_get_contents($file), true);
    foreach ( $data as $key => $r  ){
        if($r['id'] == @$_GET['id']){
			if($r['highlight'] == 1){
				$data[$key]['highlight'] = 0;
			}else{
				$data[$key]['highlight'] = 1;
			}
        }
    }
	
    $convert_array_to_json = array_values($data);
    $write_json = json_encode($convert_array_to_json);
    file_put_contents($file, $write_json);
    header('location: index.php');
}        
// ADD NEW TAB
if($_POST['adddoctotab'] == '1'){
    foreach ($tabdocfull as $vt => $tb) {
        if($tb->iddoc == $_POST['iddoc']){
             unset($tabdocfull[$vt]);
        }
    }
    $tabdocfull = array_values($tabdocfull);
    if ($_POST['idtab']){
    $tabdocfull[] = array(
        'iddoc' => $_POST['iddoc'],      
        'idtab' => $_POST['idtab'],
    );    
    }
    file_put_contents('data/TabDoc.json', json_encode($tabdocfull));
    header('location: index.php?msg=' . $i18n['Tab Imported']);
}
$_SESSION['stttang'] = 18000;

function excel_to_array($inputFileName,$row_callback=null){
    if (!class_exists('PHPExcel')) return false;
    try {
        $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($inputFileName);
    } catch(Exception $e) {
        return ('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
    }
	$results = array();
	foreach ($objPHPExcel->getWorksheetIterator() as $sheet) {
		
		//$sheet = $objPHPExcel->getSheet(0); 
		$highestRow = $sheet->getHighestRow(); 
		$highestColumn = 'T';
		//$highestColumn = $sheet->getHighestColumn(); echo $highestColumn;die;
		$keys = array();
		
		  
			for ($row = 1; $row <= $highestRow; $row++){  
				$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,null,true,false);
				
					$record = array();
					foreach($rowData[0] as $pos=>$value) { 
						if(count((array)$record) == 0 ){
							if(PHPExcel_Shared_Date::ExcelToPHP($value)+$_SESSION['stttang'] > 0 && strpos($value,'.') === false ){
								$record[] = PHPExcel_Shared_Date::ExcelToPHP($value)+$_SESSION['stttang'];
							}else{
								$record[] = strtotime(str_replace('.','-',$value))+$_SESSION['stttang'];
							}
								//$record['timegoc'] = $value;
						}else{
							$record[]  = $value;
						}
						$_SESSION['stttang'] = $_SESSION['stttang']+1;
						
					}
					$record['cat'] = '1590394139';
					//$record['cat'] = $sheet->getTitle();
					
					if(strpos($sheet->getTitle(),'中林') !== false){
						//$record['cat'] = '1572838595';
					}
					/*
					if(strpos($sheet->getTitle(),'8272') !== false){
						$record['cat'] = '1563435423';
					}
					if(strpos($sheet->getTitle(),'3438') !== false){
						$record['cat'] = '1563435355';
					}
					if(strpos($sheet->getTitle(),'0174') !== false){
						$record['cat'] = '1563435383';
					}					
					if(strpos($sheet->getTitle(),'1995') !== false){
						$record['cat'] = '1564799222';
					}
					
					if(strpos($sheet->getTitle(),'0372') !== false){
						$record['cat'] = '1563596274';
					}
					*/
					if($record[6] > 0 || $record[7] > 0){  		
						$results[] = $record;           
					}
			} 
			
	}
    return $results;
    
}
$companyinfo = json_decode(file_get_contents('data/companyinfo.json'), true);

if (@$_GET['formcompanyinfo_delete_id'] != '' && $currentuser->gm  == '1' ) {
    $data = json_decode(file_get_contents('data/companyinfo.json'), true);
    foreach ( $data as $key => $r  ){
        if($r['id'] == @$_GET['formcompanyinfo_delete_id']){
			if ($currentuser->gm == 1 || $currentuser->role == 'Manager' || ( $currentuser->role == 'Operator' && $r['status'] == '' ) ) {
				unset($data[$key]);
			}
        }
    }
	
    $convert_array_to_json = array_values($data);
    $write_json = json_encode($convert_array_to_json);
    file_put_contents('data/companyinfo.json', $write_json);	
}


if( $_POST['formcompanyinfo']  == 1){
    $companyinfo = json_decode(file_get_contents('data/companyinfo.json'), true);
    
    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 );
			 }
			
    }	
    

        if($_POST['id'] == ''){		
		
                $formdata = array(
                'id' => time()
                , 'contractnumber' => $_POST['contractnumber']
                , 'validityperiod' => $_POST['validityperiod']
                , 'validityperiod2' => $_POST['validityperiod2']        
                , 'remarks' => $_POST['remarks']
		, 'corresponding' => $_POST['corresponding']
		, 'savepoint' => $_POST['savepoint']                      
		//, 'financeclicktoapproval' => $_POST['financeclicktoapproval']
		//, 'financeclicktoapprovaltime' => $_POST['financeclicktoapprovaltime']
		, 'createby' => $currentuser->name
		, 'filename' => $filename
		, 'filetype' => $filetype
		, 'filesize' => $filesize
		, 'filetimeupload' => $filetimeupload
		, 'filecreatebyid' => $filecreatebyid
		, 'filecreatebyname' => $filecreatebyname
		, 'filepath' => $filepath
		);
                if ($currentuser->gm == 1 ){
                    
                    $formdata['status'] = 'pending';
                    $formdata['financeclicktoapproval'] = $currentuser->name;
                    $formdata['financeclicktoapprovaltime'] =  time();
                }
		$arr_data = array();
		if (file_exists('data/companyinfo.json')) {
			$jsondata = file_get_contents('data/companyinfo.json');
			$arr_data = json_decode($jsondata, true);
		}
		$arr_data[] = $formdata;
	}else{
		$arr_data = array();
			if (file_exists('data/companyinfo.json')) {
        		$jsondata = file_get_contents('data/companyinfo.json');
        		$arr_data = json_decode($jsondata, true);
    		}
		foreach ($arr_data as $key => $r){
			if($r['id'] == $_POST['id']){ 
				if(file_exists('logs/'.$_POST['id'])){
					$textlog = '----------------------'.date('Y-m-d H:i:s').' - '.$currentuser->name.'----------------------'.PHP_EOL.$_POST['content'];
				}else{
					$textlog = $arr_data[$key]['Content'].PHP_EOL.'----------------------'.date('Y-m-d H:i:s').' - '.$currentuser->name.'----------------------'.PHP_EOL.$_POST['content'];
				}
				$arr_data[$key]['contractnumber'] = $_POST['contractnumber'];
				$arr_data[$key]['validityperiod'] = $_POST['validityperiod'];
                                $arr_data[$key]['validityperiod2'] = $_POST['validityperiod2'];
				$arr_data[$key]['remarks'] = $_POST['remarks'];
				$arr_data[$key]['corresponding'] = $_POST['corresponding'];
				$arr_data[$key]['savepoint'] = $_POST['savepoint'];	
				$arr_data[$key]['financeclicktoapproval'] = $_POST['financeclicktoapproval'];
				$arr_data[$key]['financeclicktoapprovaltime'] = $_POST['financeclicktoapprovaltime'];			
				$arr_data[$key]['filename'] = $_POST['filename'];
				if(count((array)$filename) > 0){
					if(is_array($arr_data[$key]['filename'])){
						$arr_data[$key]['filename'] = array_merge($filename,$arr_data[$key]['filename']);
					}else{
						$arr_data[$key]['filename'] = $filename;
					}
					
					if(is_array($arr_data[$key]['filepath'])){
						$arr_data[$key]['filepath'] = array_merge($filepath,$arr_data[$key]['filepath']);
					}else{
						$arr_data[$key]['filepath'] = $filepath;
					}
					
					
					if(is_array($arr_data[$key]['filetype'])){
						$arr_data[$key]['filetype'] = array_merge($filetype,$arr_data[$key]['filetype']);
					}else{
						$arr_data[$key]['filetype'] = $filetype;
					}
					
					//$arr_data[$key]['filetype'] = array_merge($filetype,$arr_data[$key]['filetype']);
					$arr_data[$key]['filesize'] = array_merge($filesize,$arr_data[$key]['filesize']);
					$arr_data[$key]['filetimeupload'] = array_merge($filetimeupload,$arr_data[$key]['filetimeupload']);
					$arr_data[$key]['filecreatebyid'] = array_merge($filecreatebyid,$arr_data[$key]['filecreatebyid']);
					$arr_data[$key]['filecreatebyname'] = array_merge($filecreatebyname,$arr_data[$key]['filecreatebyname']);
					//$arr_data[$key]['filepath'] = array_merge($filepath,$arr_data[$key]['filepath']);
				}
				file_put_contents('logs/'.$_POST['id'],file_get_contents('logs/'.$_POST['id']).$textlog.PHP_EOL);
			}			
		}
		
	}
    
    $arr_data = array_values($arr_data);
    $jsondata = json_encode($arr_data);
    if (file_put_contents('data/companyinfo.json', $jsondata)) {
        $msg = $i18n['Data successfully saved!'];
    } else {
        $msg = $i18n['ERROR &mdash; Data not saved!'];
    }
}
$companyinfo = json_decode(file_get_contents('data/companyinfo.json'), true);

if ($_GET['updatedata'] == 1  ){
    
    $jsonString = file_get_contents($file);
    $data = json_decode($jsonString, true);
    foreach ($data as $key => $entry) {
        
       
        if($entry['classification'] == '垫款-支出'){
            $data[$key]['classification'] = '借款-支出';
             $dataexport[] = $entry;
        }
        if($entry['classification'] == '垫款-收入'){
            $data[$key]['classification'] = '借款-收入';
             $dataexport[] = $entry;
        }
      
        
        
    }
	
    
        // Open a file in write mode ('w') 
        $fp = fopen(__DIR__.'/backupclassification.csv', 'w'); 

        // Loop through file pointer and a line 
        foreach ($dataexport as $fields) { 
            fputcsv($fp, $fields); 
        } 

        fclose($fp); 
    
//    copy(__DIR__.'/data/Documents.json',__DIR__.'/data/Documents_bk.json');
//    $arr_data = $data;
//    $jsondata = json_encode($arr_data);
//    if (file_put_contents($file, $jsondata)) {
//        $msg = $i18n['Data successfully saved!'];
//    } else {
//        $msg = $i18n['ERROR &mdash; Data not saved!'];
//    }
//    
    echo 'done';die;
}

if ($_GET['isimport'] == 1  ){
	
	$data = json_decode(file_get_contents($file),true);
	require_once(__DIR__.'/PHPExcel.php');
	echo '<pre>';
	
	if ($handle = opendir('import')) {
		
		while (false !== ($entry = readdir($handle))) {

			if ($entry != "." && $entry != "..") {
				$accountid = explode('.',$entry);
				$accountid =  $accountid[0];
				//echo $entry;die;
				$dataimport = excel_to_array('import/'.$entry);
				//echo '<pre>';print_r($dataimport);die;
				$arr_data = array();
				if (file_exists($file)) {
					$jsondata = file_get_contents($file);
					$arr_data = json_decode($jsondata, true);
				}
				/*//////////
				foreach ($dataimport as $r2){
					$iddungroi[] =  $r2[0];
					foreach ($arr_data as $key => $r){
						if(	$r['tabs'] == '1563596274' 
							&& $r['amountincome'] == str_replace(',','',$r2[6]) 
							&& $r['amountpayout'] == str_replace(',','',$r2[7])  
							&& $r['summary'] == $r2[5]
							&& $r['classification'] == $r2[2]
							&& $r['requestnumber'] == $r2[10]
							&& $r['documentnumber'] == $r2[11]
							&& $r['payer'] == $r2[9]
							&& !in_array($r['id'], $iddungroi)
						){
							
							echo '------<pre>'.date('Y.m.d',$arr_data[$key]['id']).' _ '.date('Y.m.d',$r2[0]).' ';print_r($r);
							$arr_data[$key]['id'] = $r2[0];
							print_r($arr_data[$key]);echo '</pre>';
							
							break;
						}
					}
				}
				
				$arr_data = array_values($arr_data);
				$jsondata = json_encode($arr_data);
				file_put_contents($file, $jsondata);
				echo 'done';die;
				///////*/
				$tabdocfull =  (array)$tabdocfull; 	
				
				foreach ($dataimport as $r){
					
						$arr_data[] = array(
							'id' => $r[0]
							, 'payment' => $r[1]
							, 'classification' => $r[2]
							, 'charge' => str_replace(' 1. ','',$r[3])
							, 'summary' => $r[5]
							, 'amountincome' => str_replace(',','',$r[6])
							, 'amountpayout' => str_replace(',','',$r[7])
							, 'payer' => $r[9]
							, 'requestnumber' => $r[10]
							, 'documentnumber' =>  $r[11]
							, 'createbyname' => $currentuser->name
							, 'createbyid' => $currentuser->id	
							, 'tabs' => $r['cat']
						);
					
					$tabdocfull[] = array(
					'iddoc' => $r[0],      
					'idtab' => $r['cat'],
					);
				}
				
					
				
				file_put_contents('data/TabDoc.json', json_encode($tabdocfull));			
				$jsondata = json_encode($arr_data);
				file_put_contents($file, $jsondata);
				
				
			}
		}

		closedir($handle);
		
	}
	
	echo 'done';
	die;
}

if ($_GET['isimport'] == 2  ){
	
	$data = json_decode(file_get_contents($file),true);
	require_once(__DIR__.'/PHPExcel.php');
	echo '<pre>';
	
	if ($handle = opendir('import2')) {
		
		while (false !== ($entry = readdir($handle))) {

			if ($entry != "." && $entry != "..") {
				$accountid = explode('.',$entry);
				$accountid =  $accountid[0];				
				$dataimport = excel_to_array('import2/'.$entry);	

				foreach ($dataimport as $r){
				 $formdata = array(
					'id' => $r[0]
					, 'payment' => $r[1]
					, 'classification' => ''
					, 'charge' => ''
					, 'summary' => $r[6]
					, 'amountincome' => str_replace(',','',$r[7])
					, 'amountpayout' => str_replace(',','',$r[8])
					, 'payer' => $r[3]
					, 'billno' => $r[4]
					, 'billto' => $r[5]
					, 'vat' => $r[9]
					, 'wht' => $r[10]
					, 'remarks' => $r[13]
					//, 'requestnumber' => $r[9]
					, 'documentnumber' =>  $r[2]
					, 'createbyname' => $currentuser->name
					, 'createbyid' => $currentuser->id		
				);
				$tabdocfull =  (array)$tabdocfull; 		
				$tabdocfull[] = array(
					'iddoc' => $r[0],      
					'idtab' => $accountid,
				);    
				//echo '<pre>';print_r($formdata);die;
				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);
				file_put_contents($file, $jsondata);
				
				}
				
			}
		}

		closedir($handle);
		
	}
	
	echo 'done';
	die;
}


if ($_SERVER['REQUEST_METHOD'] == 'POST' &&  $_POST['exportexcel'] == '1' && ($currentuser->gm == 1 || $currentuser->name == 'DANNA') ){ // clock export
	
	$data = json_decode(file_get_contents($file),true);
	foreach ($data as $key => $values) {   
		if( !in_array($values['tabs'],$_POST['tabexport']) ) {
			continue;
		}
		$data2[] = $values;
	}
	ksort((array)$data2);
	$data = array_values($data2);

	$tabs = json_decode(file_get_contents('data/Tabs.json'));
	$tabdocfull = $tabdoc = json_decode(file_get_contents('data/TabDoc.json'));
	$Setting = json_decode(file_get_contents('data/Setting.json'));	
    $arr_data = json_decode($jsondata, true);
	require_once(__DIR__.'/PHPExcel.php');
	$filename =  'Expense_Export_'.date('Y-m-d H:i:s').'.xls'; 
	$objPHPExcel = new PHPExcel(); 
	$tabkeydbc = 0;
	
	if(isset($_POST['datestart'])){
			$datestart = $_POST['datestart'];
	}else{
			$datestart = date('Y.m.d',strtotime("-30 day"));
	}		
	if(isset($_POST['dateto'])){
			$dateto = $_POST['dateto'];
	}else{
			$dateto = date('Y.m.d');
	}
		
		
	foreach($tabs as $tabkey => $tab){
	$array =  array();
	if(count((array)$_POST['tabexport']) > 0){
		if( $currentuser->gm != 1 && $currentuser->role != 'Finance' && $tab->iduser != $currentuser->id && !in_array($tab->id,$currentuser->account)  ) { continue; }
		if( !in_array($tab->id,$_POST['tabexport'] )) {
			continue;
		}
	}else{
		if( $currentuser->gm != 1 && $currentuser->role != 'Finance' && $tab->iduser != $currentuser->id && !in_array($tab->id,$currentuser->account) ) { continue; } 
	}
	
	
	$array[] =  array('','','','','','','','','','','','','','','','','','','' );
    //$array[] =  array('日期','收付','费用归类','费用明细','部门','摘要','收入金额','支出金额','余额','收/付款人','请款单号','工作号','凭证号','是否核销','文件','备注','复核','创造者','改性','时间修改' );
	$array[] =  array('日期','收/付','费用归类','费用明细','部门','摘要','收入金额','支出金额','余额','收/付款人','催/请款单号','凭证号','是否核销','文件','备注','复核','创造者','最后修改人','时间修改' );
	
	$rt = 0;$balance[0] = 0;
	foreach ($data as $key => $values) { 
        /*    
        $appprove = 0; 
		foreach ($tabdocfull as $r){
            if ( $values['id'] == $r->iddoc && $tab->id == $r->idtab ) {
                $appprove = 1; 
				$rt = $r->idtab;				
            }
        }*/
 	$appprove = 1; 
        $rt = $values['tabs'];
        if ($appprove == 0){
             continue;
        }
	/*	
	if( date('Ymd',$values['id']) >=  date('Ymd',strtotime(str_replace('.','-',$datestart)))  ){
			unset($data[$key]);
			continue;
		}
		
		$balance[$rt] += floatval($values['amountincome']) - floatval($values['amountpayout']) ;
	*/
		if( date('Ymd',$values['settime']) <  date('Ymd',strtotime(str_replace('.','-',$datestart)))  ){
                        $balance[$rt] += floatval($values['amountincome']) - floatval($values['amountpayout']) ;
			unset($data[$key]);
			continue;
		}	
	}
	$decimal = 2;
	if($currencyname == 'VND'){
			$decimal = 0;
	}
	$balance[$rt] += floatval($tab->balance);
	
	$array[] =  array('','','','','','','','Balance',number_format((float)$balance[$rt],$decimal),'','','','','','','','','','' );
	
	foreach ($data as $key => $values) {  
			/*
			$appprove = 0; 
			foreach ($tabdocfull as $r){
				if ( $values['id'] == $r->iddoc && $tab->id == $r->idtab ) {
					$appprove = 1; 
					$rt = $r->idtab;				
				}
			}
                        */
                        $appprove = 1; 
                        $rt = $values['tabs'];
			if ($appprove == 0){
				 continue;
			}
//echo date('Ymd',$values['id']).'-'.date('Ymd',strtotime(str_replace('.','-',$datestart))).'-'.date('Ymd',strtotime(str_replace('.','-',$dateto))).'<br>';

			if( date('Ymd',$values['settime']) <  date('Ymd',strtotime(str_replace('.','-',$datestart))) || date('Ymd',$values['settime']) >  date('Ymd',strtotime(str_replace('.','-',$dateto))) ){
				continue;
			}		

			foreach($currency as $rcurrency){
				if($rcurrency['id'] == $tab->currency ){
					$currencyname =  $rcurrency['currency'];
				} 	
			}			
			$decimal = 2;
			if($currencyname == 'VND'){
				$decimal = 0;
			}			
			// SET TABLE LINE	
			if(!is_array($values['payer'])){
				$values['payer'] = array($values['payer']);
			}			
			$rows = array();
			$balance[$rt] += (($values['amountincome']) - ($values['amountpayout'])) ;			
			$rows[] = date('Y.m.d',(int)$values['id']);
			$rows[] = $values['payment'].' ';
			$rows[] = $values['classification'].' ';
			$rows[] = $values['charge'].' ';
			$rows[] = $values['department'].' ';
			$rows[] = $values['summary'].' ';
			$rows[] = number_format((float)$values['amountincome'],$decimal).' ';
			$rows[] = number_format((float)$values['amountpayout'],$decimal).' ';
			$rows[] = number_format((float)$balance[$rt],$decimal).' ';
			$namepayee = '';
			
			foreach ($values['payer'] as $rpayer){
				if(isset($receiver_payer_id[$rpayer])){
					$namepayee .= $receiver_payer_id[$rpayer]->name;
				}elseif(isset($receiver_payer_name[$rpayer])){
					$namepayee .= $receiver_payer_name[$rpayer]->name;
				}else{
					$namepayee .= $rpayer;
				}
				if(count((array)$values['payer']) > 1){
					$namepayee .= ' | ';
				}
			}
			$rows[] = $namepayee.' ';
			
			$rows[] = $values['requestnumber'].' ';
			//$rows[] = $values['jobnumber'].' ';
			$rows[] = $values['documentnumber'].' ';
			$rows[] = $values['writtenoff'].' ';
			$rows[] = implode(', ',$values['filename']);
			$rows[] = $values['remarks']+' ';
			if($values['status'] == ''){
				$rows[] = '等待财务完成';
			}elseif($values['status'] == 'pending'){
				$rows[] = '待批准...';
			}elseif($values['status'] == 'approval'){
				$rows[] = '赞同';
			}elseif($values['status'] == 'notapproval'){
				$rows[] = '不批准';
			}
			$rows[] = $values['createbyname'].' ';
			$rows[] = $values['modifybyname'].' ';
			if($values['timemodify'] != ''){
				$rows[] = date('Y.m.d',(int)$values['timemodify']);
			}else{
				$rows[] = '';
			}
			$array[] = $rows;
			}
				
			$objPHPExcel->createSheet($tabkeydbc); 					
			$objPHPExcel->setActiveSheetIndex($tabkeydbc)->setTitle($tab->name);
			$objPHPExcel->setActiveSheetIndex($tabkeydbc)->fromArray($array);
			$objPHPExcel->getDefaultStyle()->getAlignment()->setWrapText(true);
			$from = "A2"; // or any value
			$to = "T2"; // or any value			
			$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth('20');
			$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth('7');
			$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth('15');
			$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth('15');
			$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth('7');
			$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth('40');
			$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth('15');
			$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth('15');
			$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth('20');
			$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth('15');
			$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth('20');
			$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth('40');
			$objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth('15');
			$objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth('65');
			$objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth('20');
			$objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth('20');
			$objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth('20');
			$objPHPExcel->getActiveSheet()->getColumnDimension('R')->setWidth('15');
			$objPHPExcel->getActiveSheet()->getColumnDimension('S')->setWidth('15');
			$objPHPExcel->getActiveSheet()->getColumnDimension('T')->setWidth('10');			
			$objPHPExcel->getActiveSheet()->mergeCells('A1:T1');	
			$objPHPExcel->getActiveSheet()->getCell('A1')->setValue($tab->info);
			$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold( true );			
			$objPHPExcel->getActiveSheet()->getStyle("$from:$to")->getFont()->setBold( true );
			$objPHPExcel->getActiveSheet()->getStyle("$from:$to")->getFill()->applyFromArray(array(
			'type' => PHPExcel_Style_Fill::FILL_SOLID,
			'startcolor' => array(
				 'rgb' => 'F0F0F0'
			)
			));
			
			$objPHPExcel->getActiveSheet()->getStyle("A1:T100")->applyFromArray(
					array(
						'borders' => array(
							'allborders' => array(
								'style' => PHPExcel_Style_Border::BORDER_THIN,
								'color' => array('rgb' => '666666')
							)
						)
					)
				);				
				
			$objPHPExcel->getActiveSheet()->getColumnDimension()->setAutoSize(true);
			$tabkeydbc++;	
		}
		
		header( 'Content-Type: application/vnd.ms-excel' );
		header( 'Content-Disposition: attachment; filename="' . $filename . '";' );
		header("Content-type: text/csv; charset=UTF-8");
		header('Pragma: no-cache');
		header('Expires: 0');
		$objPHPExcel->setActiveSheetIndex(0); 
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
}

// EDIT TAB
if($_POST['tab'] != '' && $_POST['id_tabname'] == '' ){
    $dataFile = file_get_contents('data/Tabs.json');
    $data = json_decode($dataFile,true);
    $ta['id'] = time();
	$ta['name'] = $_POST['tab'];
    $ta['iduser'] = $currentuser->id;
    $ta['currency'] = $_POST['currency'];
	$ta['info'] = $_POST['tabinfo'];
	$ta['special'] = $_POST['special'];
	$ta['special2'] = $_POST['special2'];
	$ta['special3'] = $_POST['special3'];
	$ta['location'] = $_POST['location'];
	$ta['balance'] = str_replace(',','',$_POST['balance']);
	$ta['tabdescription'] = $_POST['tabdescription'];	
	$data[] = $ta;
    $data = array_values($data);
    $data = json_encode($data);
    file_put_contents('data/Tabs.json',$data);
    header('location: index.php?msg=' . $i18n['Tab Created']);
}
//DELETE TAB
$delIdTab = $_GET['delete_tab'];

if($delIdTab){
    $tabfull = (array) $tabfull;
    $tabdocfull = (array) $tabdocfull;
    foreach ($tabfull as $key => $t) {       
        if($t->id == $delIdTab){
            unset($tabfull[$key]);
        }
    }
    foreach ($tabdocfull as $vt => $tb) {
        if($tb->idtab == $delIdTab){
            unset($tabdocfull[$vt]);
        }
    }
    file_put_contents('data/Tabs.json',json_encode($tabfull));
    file_put_contents('data/TabDoc.json',json_encode($tabdocfull));
    header('location: index.php?msg=' . $i18n['Entry successfully deleted.']);
}

if($_POST['tab'] != '' && $_POST['id_tabname'] !=''){
    $dataFile = file_get_contents('data/Tabs.json');
    $data = json_decode($dataFile,true);
    //for($i=0;$i<count((array)$data);$i++){
	foreach ($data as $i => $r)	{
        if($data[$i]['id'] == $_POST['id_tabname']){
            $data[$i]['name'] = $_POST['tab'];
			$data[$i]['currency'] = $_POST['currency'];
			$data[$i]['info'] = $_POST['tabinfo'];
			$data[$i]['tabdescription'] = $_POST['tabdescription'];			
			$data[$i]['special'] = $_POST['special'];
			$data[$i]['special2'] = $_POST['special2'];
			$data[$i]['special3'] = $_POST['special3'];
			$data[$i]['location'] = $_POST['location'];
			$data[$i]['balance'] = str_replace(',','',$_POST['balance']);
			$data[$i]['modifyname'] = $currentuser->name;
			$data[$i]['modifytime'] = time();
            break;
        }
    }
	$data = array_values($data);
    $data = json_encode($data);
    file_put_contents('data/Tabs.json',$data);
    header('location: index.php');
}

// SAVE NEW ENTRY IF FORM POSTED
if (isset($_POST['status'])) {
    if ($_POST['status'] == "") {
        $_POST['status'] = 'YES';
    }
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' and $_POST['editremark'] == '1' ) {
	if ($currentuser->role == 'Finance' || $currentuser->name == 'LEX') {
		$jsonString = file_get_contents($file);
		$data = json_decode($jsonString, true);
		
		// right logs	
		foreach ($data as $key => $entry) {
			if ( $entry['id'] == $_POST['idorder'] ) {
				$remarksbefore = $data[$key]['remarks'];
				$data[$key]['remarks'] = $_POST['controlerremark'];
				break;
			}
		}	
		$data = array_values($data);
		$textlog = date('Y-m-d H:i:s').' - '.$currentuser->name.': change remark form '.$remarksbefore.' to '.$_POST['controlerremark'];
		file_put_contents('logs/'.$_POST['idorder'],file_get_contents('logs/'.$_POST['idorder']).$textlog.PHP_EOL);
		copy(__DIR__.'/data/Documents.json',__DIR__.'/data/Documents_bk.json');
		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['sendtoaproval'] == '1' ) {
    
    if($_POST['typeapp'] == 1){
        $file = 'data/companyinfo.json';
    }
    $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'])) {
			 $datadjj = $data[$key]['status'];
			 $data[$key]['status'] = 'pending';
			 if($currentuser->role == 'Finance' || $currentuser->name == 'LEX'){
				 if($datadjj == ''){
					$data[$key]['financeclicktoapproval'] = $currentuser->name;
					$data[$key]['financeclicktoapprovaltime'] = time();
				 }else{
					$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();
			 }
		}
	}
	copy(__DIR__.'/data/Documents.json',__DIR__.'/data/Documents_bk.json');
	if (file_put_contents($file, json_encode($data))) {
        $msg = $i18n['Data successfully saved!'];
    } else {
        $msg = $i18n['ERROR &mdash; Data not saved!'];
    }
    if($_POST['typeapp'] == 1){
        header('location: index.php?typeapp=1&msg=' . $msg);
    }else{
        header('location: index.php?msg=' . $msg);
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' and $_POST['setapproval'] == '1' ) {
    
    if($_POST['typeapp'] == 1){
        $file = 'data/companyinfo.json';
    }
    
	$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();
		}
	}
	copy(__DIR__.'/data/Documents.json',__DIR__.'/data/Documents_bk.json');
	if (file_put_contents($file, json_encode($data))) {
        $msg = $i18n['Data successfully saved!'];
    } else {
        $msg = $i18n['ERROR &mdash; Data not saved!'];
    }
    if($_POST['typeapp'] == 1){
        header('location: index.php?typeapp=1&msg=' . $msg);
    }else{
        header('location: index.php?msg=' . $msg);
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' and $_POST['password'] != '' ) {
	
	$jsondata = json_decode( file_get_contents("data/User.json"),true );
	foreach ($jsondata as $key => $r){
		if( $r['id'] == $currentuser->id ){
			$jsondata[$key]['password'] = $_POST['password'];
		}
	}
	if (file_put_contents("data/User.json", json_encode($jsondata))) {
        $msg = $i18n['Data successfully saved!'];
    } else {
        $msg = $i18n['ERROR &mdash; Data not saved!'];
    }
    header('location: index.php?msg=' . $msg);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' &&  $_POST['idaccount'] != '' ){
	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($currentuser->gm == 1){
		if($_POST['timepicker'] != ''){
			$id = strtotime(str_replace('.','-',$_POST['date']).' '.$_POST['timepicker'].date(':s'));
		}else{
			$id = strtotime(str_replace('.','-',$_POST['date']).' '.date('H:i:s'));
		}
	}else{
		if($_POST['timepicker'] != ''){
			$id = strtotime(str_replace('.','-',$_POST['date']).' '.$_POST['timepicker'].date(':s'));
		}else{
			$id = strtotime(str_replace('.','-',$_POST['date']).' '.date('H:i:s'));
		}
		if( $id < strtotime('-15 day') ){
			$id = strtotime('-14 day');
		}
	}
	$formdata = array(
        'id' => $id		
        , 'payment' => '付'
        , 'department' => ''
        , 'classification' => '代付'
        , 'charge' => '结汇'
        , 'summary' => $_POST['summary']
		, 'tygiausdtovnd' => $_POST['monneyexchangerate']
		, 'exchangeusdtovnd' => $_POST['monneyexchangerate']
		, 'amountincomeusd' => ''
		, 'amountpayoutusd' => $_POST['amountexchange']
		, 'currency' => ''		
		, 'amountincome' => str_replace(',','',$_POST['amountexchange'])*$_POST['monneyexchangerate']
		, 'amountpayout' => ''
		, 'payer' => ''
		, 'requestnumber' => ''
		, 'documentnumber' => ''
		, 'jobnumber' => ''
		, 'baddebt' => ''
		, 'billno' => ''
		, 'billto' => ''
		, 'vat' => ''
		, 'wht' => ''
		, 'remarks' => $_POST['remarks']
		, 'writtenoff' => ''
		, 'location' => ''
		, 'createbyname' => $currentuser->name
		, 'createbyid' => $currentuser->id		
		, 'filename' => $filename
		, 'filetype' => $filetype
		, 'filesize' => $filesize
		, 'filetimeupload' => $filetimeupload
		, 'filecreatebyid' => $filecreatebyid
		, 'filecreatebyname' => $filecreatebyname
		, 'filepath' => $filepath
		, 'tabs' => $_POST['idaccount']
    );
	$tabdocfull =  (array)$tabdocfull; 
	$tabdocfull[] = array(
		'iddoc' => $id,      
		'idtab' => $_POST['idaccount'],
	);    
	$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();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' and $_POST['payment'] != '' and $_POST['classification'] != '' and $cannotedit != 1) {
	 
	 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 ||  $currentuser->name == 'DANNA' ){
		if($_POST['timepicker'] != ''){
			$id = strtotime(str_replace('.','-',$_POST['date']).' '.$_POST['timepicker'].date(':s'));
		}else{
			$id = strtotime(str_replace('.','-',$_POST['date']).' '.date('H:i:s'));
		}
	}else{
		if($_POST['timepicker'] != ''){
			$id = strtotime(str_replace('.','-',$_POST['date']).' '.$_POST['timepicker'].date(':s'));
		}else{
			$id = strtotime(str_replace('.','-',$_POST['date']).' '.date('H:i:s'));
		}
		if( $id < strtotime('-15 day') ){
			$id = strtotime('-14 day');
		}
	}
	if($_POST['tygiausdtovnd'] != ''){
		if($_POST['currency'] != '1560829223'){
			$_POST['amountincomeusd'] = str_replace(',','',$_POST['amountincome']);		
			$_POST['amountincome'] = '';
		}
		if($_POST['currency'] == '1560829162'){
			$_POST['amountpayoutusd'] = str_replace(',','',$_POST['amountpayout']);
			$_POST['amountpayout'] = '';
		}
	}else{
		$_POST['currency'] = '';
	}
	
	if($_POST['payer_more'] == ''){
	
	}else{
		$data1 = json_decode(file_get_contents('data/receiver_payer.json'), true);
		$idre = time();
		$data1[] = array(
						'id' => $idre
						, 'name' => $_POST['payer_more']
						, 'abbreviation' => ''
						, 'description' => ''
						, 'createdby' => $currentuser->name
						, 'createddate' => $id
						, 'modifieddate' => ''  
		);
		file_put_contents('data/receiver_payer.json', json_encode($data1) );
		$_POST['payer'] = array($idre);
	}
	
        $arr_data = array();
        if (file_exists($file)) {
            $jsondata = file_get_contents($file);
            $arr_data = json_decode($jsondata, true);
        }
    
    
        check:
	// check Verification 
	if($_POST['documentnumber'] != ''){
		foreach ($arr_data as $ar){
			if($ar['documentnumber'] == $_POST['documentnumber'] ){

                                
                                $documentnumber = substr($_POST['documentnumber'], 0,3);
                                $documentnumber2 = substr($_POST['documentnumber'], 3,7);
                                $_POST['documentnumber'] = $documentnumber.((float)$documentnumber2+1);
                                if(++$k < 10){
                                    goto check;
                                }else{
                                    $msg = 'Verification '.$_POST['documentnumber'].' is used. Try other number'.$i18n['ERROR &mdash; Data not saved!'];
                                    header('location: index.php?msg=' . $msg);
                                    xeit();
                                }
                                
			}
		}
	}
        
	//if(str_replace(',','',$_POST['feeexrate']) == '' || str_replace(',','',$_POST['feeexrate']) == 0){ $_POST['feeexrate'] = 1; }
	//$amountpayout_asbb = (str_replace(',','',$_POST['feeex'])/str_replace(',','',$_POST['feeexrate']));
	//if($amountpayout_asbb <= 0) { $amountpayout_asbb = 0; }
	//if($_POST['amountpayout'] == ''){ $amountpayout_asbb = '';}
    $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']
		, 'tygiausdtovnd' => $_POST['tygiausdtovnd']
		, 'amountincomeusd' => $_POST['amountincomeusd']
		, 'amountpayoutusd' => $_POST['amountpayoutusd']
		, 'currency' => $_POST['currency']		
		, 'amountincome' => str_replace(',','',$_POST['amountincome'])
		, 'amountpayout' => str_replace(',','',$_POST['amountpayout'])
		, 'payer' => $_POST['payer']
		, 'corresponding' => $_POST['corresponding']
		, 'requestnumber' => $_POST['requestnumber']
		, 'documentnumber' => $_POST['documentnumber']
		, 'jobnumber' => $_POST['jobnumber']
		
		, 'exchangeamout' => $_POST['exchangeamout']
		, 'currencyex' => $_POST['currencyex']
		, 'tabsex' => $_POST['tabsex']
		, 'amountaccountex' => $_POST['amountaccountex']
		, 'feeex' => $_POST['feeex']
		
		//, 'fee' => $_POST['fee']
		, 'baddebt' => $_POST['baddebt']
		, '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
		, 'tabs' => $_POST['tabs']
    );
	
	

	
	//check id duplicate
	foreach ($arr_data as $ar){
		if($ar['id'] == $id ){
			$msg = 'ID '.$id .' is used. Try again. ID 用来. 再试一次.';
			header('location: index.php?msg=' . $msg);
			exit();
		}
	}
	
	$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));
	}
        

	
	foreach ($arr_data as $ar){
		if( stripos($ar['documentnumber'],'VNI'.date('ymd')) !== false ){
		 $coad++;		
		}
	}
	//echo '<pre>';print_r($formdata);
	if( $formdata['classification'] == '汇出' && count((array)$formdata['tabsex']) > 0 ){
		
		foreach ($formdata['tabsex'] as $adn){
			$id++;
			$formdata1 = $formdata;
			$formdata1['id'] =  $id;
			$formdata1['payment'] = '收';
			$formdata1['amountincome'] = str_replace(',','',$formdata['amountaccountex'][$adn])-(str_replace(',','',$formdata['feeex'])/count((array)$formdata['tabsex']));
			$formdata1['classification'] = '汇入';
			$formdata1['amountaccountex'] = '';
			$formdata1['tabsex'] = '';
			$formdata1['amountpayout'] = '';
			$formdata1['currencyex'] = '';
			$formdata1['exchangeamout'] = '';
			$formdata1['feeex'] = '';
			
			$formdata1['tabs'] = $adn;
			if($coad == 0){
				$formdata1['documentnumber'] = 'VNI'.date('ymd');
			}else{
				$formdata1['documentnumber'] = 'VNI'.date('ymd').'-'.($coad+1);
			}
			$coad++;
			//print_r($formdata1);
			$arr_data[] = $formdata1;
		}
		/*
		if($formdata['feeex'] > 0){
			$id++;
			$formdata1 = $formdata;
			$formdata1['id'] =  $id;
			$formdata1['classification'] = '财务费用';
			$formdata1['charge'] = '手续费';			
			$formdata1['amountpayout'] = $formdata['feeex'];
			$formdata1['amountincome'] = '';
			$formdata1['amountaccountex'] = '';
			$formdata1['tabsex'] = '';
			$formdata1['currencyex'] = '';
			$formdata1['exchangeamout'] = '';
			$formdata1['feeex'] = '';
			$formdata1['documentnumber'] = '';
			$arr_data[] = $formdata1;
		}*/
		
	}
	//die;
	//echo '<pre>';print_r($_POST).print_r($formdata);die;
    $arr_data[] = $formdata;
    $jsondata = json_encode($arr_data);
	
	copy(__DIR__.'/data/Documents.json',__DIR__.'/data/Documents_bk.json');
    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();
$hassettime = 0;
$data = json_decode(file_get_contents($file), true);
if(1 == 1){
	foreach($data as $kk => $da){
		if(!isset($da['settime'])){
			$da['settime'] = $da['id'];
			$data[$kk] = $da;
			$hassettime++;
		}
		/*if(in_array($da['id'], array(1675217357))){
			$da['settime'] = $da['id'];
			$data[$kk] = $da;
			$hassettime++;
		}*/
		/*if(in_array($da['id_invoice'], array(1673252303))){
			$da['settime'] = $da['id'];
			$data[$kk] = $da;
			$hassettime++;
		}*/
		/*if(in_array($da['id'], array(1673489133,1673489249,1673489251))){
			$da['settime'] = $da['id'];
			$data[$kk] = $da;
			$hassettime++;
		}*/
		/*if($da['id'] == 1672998906){
			$da['amountpayout'] = '1386.00';
			$data[$kk] = $da;
			$hassettime++;
		}*/
	}
	if($hassettime > 0){
		//echo '<br/>hassettime='.$hassettime;
		file_put_contents($file, json_encode($data));
	}
}
if(1 == 0){
	//find data
	foreach($data as $kk => $da){
		/*if(in_array($da['id_invoice'], array(1673252303))){
			echo '<pre>'; print_r($da); echo 'settime='.date('Ymd',$da['settime']).'|id='.date('Ymd',$da['id']); die();
		}*/
		if(in_array($da['id'], array(1675217357))){
			echo '<pre>'; print_r($da); echo '<br/>settime='.date('Ymd',$da['settime']);echo '<br/>id='.date('Ymd',$da['id']); die();
		}
	}
}
function array_sort($array, $on, $order=SORT_ASC)
{
    $new_array = array();
    $sortable_array = array();
    
    if (is_countable($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
            break;
            case SORT_DESC:
                arsort($sortable_array);
            break;
        }

        foreach ($sortable_array as $k => $v) {
            $new_array[$k] = $array[$k];
        }
    }

    return $new_array;
}
//HEADER
if(isset($_POST['categoryf'])){
			$categoryf = $_POST['categoryf'];
}	
if(isset($_POST['subcategoryf'])){
			$subcategoryf = $_POST['subcategoryf'];
}
if(isset($_POST['vendor'])){
			$vendor = $_POST['vendor'];
}	
if(isset($_POST['datestart']) &&  $_POST['exportexcel'] != '1' ){
			$datestart = $_POST['datestart'];
			$_SESSION['datestart'] = $_POST['datestart'];
}elseif( $_SESSION['datestart'] != '' ){
			$datestart = $_SESSION['datestart'];
}else{
	$datasettings = json_decode(file_get_contents('data/Setting.json'), true);
	$aipvn = explode(',',$datasettings['ipvn']);
	$aipcn = explode(',',$datasettings['ipcn']);
	$aiptha = explode(',',$datasettings['iptha']);
	$aipmain = explode(',',$datasettings['ipmain']);
	$aipcontroller = explode(',',$datasettings['ipcontroller']);
	$ip = getenv('HTTP_CLIENT_IP')?:
	getenv('HTTP_X_FORWARDED_FOR')?:
	getenv('HTTP_X_FORWARDED')?:
	getenv('HTTP_FORWARDED_FOR')?:
	getenv('HTTP_FORWARDED')?:
	getenv('REMOTE_ADDR');
	//echo '<br/>ip='.$ip; echo '<pre>'; print_r($aipvn);
	$isouroffice = 1;
	if(in_array($ip,$aipvn) || in_array($ip,$aipcn) || in_array($ip,$aiptha) || in_array($ip,$aipmain) || in_array($ip,$aipcontroller)){
		$isouroffice = 0;
	}
	//echo '<br/>isouroffice='.$isouroffice;
	if($isouroffice){
		$datestart = date('Y.m.d',strtotime("-7 day"));
	}else{
		$datestart = date('Y.m.d',strtotime("-10 day"));
	}
}	
if(isset($_POST['dateto']) &&  $_POST['exportexcel'] != '1' ){
			$dateto = $_POST['dateto'];
			$_SESSION['dateto'] = $_POST['dateto'];
}elseif( $_SESSION['dateto'] != '' ){
			$dateto = $_SESSION['dateto'];
}else{
			$dateto = date('Y.m.d');
}

if($currentuser->gm != 1 && $currentuser->name != 'DANNA' && $currentuser->daytoseedata == '' ){
 if(strtotime(str_replace('.','-',$datestart)) < time() - 30*86400 && $datestart != ''){
	 $datestart = date('Y.m.d',strtotime("-30 day"));
 }	
 if(strtotime(str_replace('.','-',$dateto)) < time() - 30*86400 && $dateto != '' ){
	 $dateto = date('Y.m.d',strtotime("-30 day"));
 }	
}
//var_dump($currentuser);
//echo '<br/>datestart='.$datestart.'|dateto='.$dateto;
if($_POST['dateto'] && $_POST['datestart']){
    
    if($currentuser->daytoseedata > 0
            && ((strtotime(str_replace('.','-',$dateto)) - strtotime(str_replace('.','-',$datestart)))/86400  > $currentuser->daytoseedata 
            || (time() - strtotime(str_replace('.','-',$datestart)))/86400  > $currentuser->daytoseedata) ){
        
            $datestart = date('Y.m.d',strtotime("-".$currentuser->daytoseedata." day"));
            $_SESSION['datestart'] = $datestart;
            $dateto = date('Y.m.d');
            $_SESSION['dateto'] = $dateto;
    }
}

//echo '<br/>datestart='.$datestart.'|dateto='.$dateto;
if(isset($_POST['acctiveaccount'])){
			$acctiveaccount = $_POST['acctiveaccount'];
}else{
	$acctiveaccount = '1563435423';
}	
include 'tpl/header.php';
ob_end_flush();
//$ipcode = file_get_contents('http://ip-api.com/json/'.$ip);
//file_put_contents(__DIR__.'/ipcode.txt',$ipcode);					
//$ipcode = json_decode($ipcode);
$id_invoice = json_decode(file_get_contents('data/invoice.json'),true);
foreach ($id_invoice as $r){
	$id_invoice_a[$r['id']] = $r;
}
$id_invoice =  $id_invoice_a;
?>

<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">
<!--
<script type="text/javascript" src="tpl/js/tablesort.js"></script>
<script>
	jQuery(document).ready(function($){
        $("table.tablesorter").tablesort(); 
        $("table.tablesorter thead th.dateh").click(); 
		setTimeout(function() { 
        	$("table.tablesorter thead th.dateh").click(); 
		}, 1500);
	});
</script>-->
<style>  
    .tab-content.current {
    display: inline-table!important;
}
.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;    right: -55px; } .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'; }
.filtervendor svg { display:none; }
.dnoon { color:#fff; }
.iopd::after {
    display:none!important;
}
.ishighlight{
	border:3px solid #9e9b0a !important;
}
.ishighlight img{
filter: none!important;
display:block!important;
}
.navbar-fixed nav {
    overflow: unset;
}
.dasjdbask li{
background: none;    color: #222;    display: inline-block;    padding: 10px 15px;    cursor: pointer;    border-top: 3px solid #eeeeee;
}
.dasjdbask li:hover {
	    background: white;
    border-top: 3px solid #26a69a;

}
.dasjdbask li.current {
    background: #ffffff;
    color: #26a69a;
    border-top: 3px solid #26a69a;
}
</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($cannotedit != 1){ ?>
<div <?php if($_GET['onlyform'] != 1) { ?> class="badge grey lighten-3  show-table" style="padding:0.5em;    border-bottom: 2px solid rgb(221, 221, 221);    margin-left: -5px;" <?php } ?> >
        <?php if($_GET['onlyform'] != 1) { ?>
			<div class="ismoreadd" style="display:none;    border-bottom: 1px solid #ddd;" >
				<iframe hsrc="index_form.php?onlyform=1&adf=1" src="about:blank"   width="100%" style="height:130px;     background: transparent;     border: none;" ></iframe>
			</div>
			<div class="ismoreadd" style="display:none;    border-bottom: 1px solid #ddd;">
				<iframe hsrc="index_form.php?onlyform=1&adf=2" src="about:blank"   width="100%" style="height:130px;       background: transparent;   border: none;" ></iframe>
			</div>
			<div class="ismoreadd" style="display:none;    border-bottom: 1px solid #ddd;">
				<iframe hsrc="index_form.php?onlyform=1&adf=3" src="about:blank"   width="100%" style="height:130px;        background: transparent;   border: none;" ></iframe>
			</div>
			<div class="ismoreadd" style="display:none;    border-bottom: 1px solid #ddd;">
				<iframe hsrc="index_form.php?onlyform=1&adf=4" src="about:blank"   width="100%" style="height:130px;       background: transparent;    border: none;" ></iframe>
			</div>
			<script>
				$('.ismoreadd iframe').each(function(){
					$(this).attr('src',$(this).attr('hsrc'));
				});				
			</script>
		<?php } ?>
			
		<form method="POST" enctype="multipart/form-data" id="bifdnino" >
            <div class="row" style="padding-top:15px;" >
                <div class="input-field col s1 isdepartmentform" style="width:5%;" >
					<select name="department" id="department"   >  
							<option value="" selected >----------</option>       
							<option value="越南"><?php echo $i18n["越南"]; ?></option>    
							<option value="中国"><?php echo $i18n["中国"]; ?></option>  
							<option value="泰国"><?php echo $i18n["泰国"]; ?></option>  	
                                                        <option value="印尼"><?php echo $i18n["印尼"]; ?></option>  	
                                                        <option value="马来西亚"><?php echo $i18n["马来西亚"]; ?></option>  	
					</select>	
                    <label for="charge"><?php echo $i18n["部门"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Enter department
                    </span>
                </div>
                
				<?php if(( $currentuser->gm == 1 || $currentuser->name == 'DANNA' )&& $_GET['onlyform'] != 1 ){ ?>
					<div class="input-field col s1">
						<input 
							id="dkasndlkas"
							value="<?php echo date('Y.m.d'); ?>"
							name="date" 
							type="text" 
							class="datepicker"  
							/>
						<input type="text" class="timepicker" name="timepicker" style="width: 20px;    height: 20px;    cursor: pointer;    color: transparent;    border: none;    top: -13px;    right: 12px;    position: absolute;    z-index: 10000;      background-image: url(https://image.flaticon.com/icons/png/512/63/63355.png);    background-size: 100% 100%;" >
						<label style="    transform: translateY(-14px) scale(0.8);    transform-origin: 0 0;" for="dkasndlkas" class="active" ><?php echo $i18n["Date"]; ?></label>
						<span class="helper-text" data-error="Error" data-success="OK">
							Enter Charge Details
						</span>
						
					</div>	
				<?php }else{ ?>			
					<div class="input-field col s2">
						<select name="date" id="dkasndlkas" >						
							<option value="<?php echo date('Y.m.d'); ?>" selected ><?php echo date('Y.m.d'); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-1 day')); ?>" ><?php echo date('Y.m.d',strtotime('-1 day')); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-2 day')); ?>" ><?php echo date('Y.m.d',strtotime('-2 day')); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-3 day')); ?>" ><?php echo date('Y.m.d',strtotime('-3 day')); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-4 day')); ?>" ><?php echo date('Y.m.d',strtotime('-4 day')); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-5 day')); ?>" ><?php echo date('Y.m.d',strtotime('-5 day')); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-6 day')); ?>" ><?php echo date('Y.m.d',strtotime('-6 day')); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-7 day')); ?>" ><?php echo date('Y.m.d',strtotime('-7 day')); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-8 day')); ?>" ><?php echo date('Y.m.d',strtotime('-8 day')); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-9 day')); ?>" ><?php echo date('Y.m.d',strtotime('-9 day')); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-10 day')); ?>" ><?php echo date('Y.m.d',strtotime('-10 day')); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-11 day')); ?>" ><?php echo date('Y.m.d',strtotime('-11 day')); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-12 day')); ?>" ><?php echo date('Y.m.d',strtotime('-12 day')); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-13 day')); ?>" ><?php echo date('Y.m.d',strtotime('-13 day')); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-14 day')); ?>" ><?php echo date('Y.m.d',strtotime('-14 day')); ?></option>
						</select>
						<input type="text" class="timepicker" name="timepicker" style="width: 20px;    height: 20px;    cursor: pointer;    color: transparent;    border: none;    top: -13px;    right: 12px;    position: absolute;    z-index: 10000;      background-image: url(https://image.flaticon.com/icons/png/512/63/63355.png);    background-size: 100% 100%;" >
						<label for="dkasndlkas" style="    transform: translateY(-14px) scale(0.8);    transform-origin: 0 0;"  class="active" ><?php echo $i18n["Date"]; ?></label>
						<span class="helper-text" data-error="Error" data-success="OK">
							Enter Charge Details
						</span>
						 
					</div>	
				<?php } ?>
				<div class="input-field col s2">
                    <select name="tabs" id="tabs" class="sandjnas" required >						
                        <?php 
                            foreach($tabs as $tab){
								if( $currentuser->gm != 1 && $tab->iduser != $currentuser->id && !in_array($tab->id,$currentuser->account) ) { continue; } 
                                ?> 
                                    <option cur="<?php echo $tab->currency; ?>" location="<?php echo $tab->location; ?>" class="<?php if($tab->special3 == 1){?> isspeci3 <?php } ?> <?php if($tab->special == 1){?> isspeci <?php } ?> <?php if($tab->special2 == 1){?> isspeci2 <?php } ?>" value="<?php echo $tab->id ?>"><?php echo $tab->name ?></option>
                                <?php
                            }
                        ?>
                    </select>
                    <label for="tab"><?php echo $i18n["Accounting"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Select Accounting
                    </span>
                </div>	
                <div class="input-field col s1" style="width:5%;" >                  
					<select name="payment" id="idpayment"  tabindex="-1">         
							<option value="收"><?php if($i18n["收"] != ''){ echo $i18n["收"]; }else{ echo '收'; } ?></option>                  
                       		<option value="付"><?php if($i18n["付"] != ''){ echo $i18n["付"]; }else{ echo '付'; } ?></option>
					</select>
                    <label for="idpayment"><?php echo $i18n["收/付"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Enter Payment
                    </span>
                </div>
				<div class="input-field col s1 inputisspeci3 " style="display:none;" >
					<select name="currency" id="currencyisspeci3"  tabindex="-1">                           
                       		<?php foreach($currency as $r){ if($r['id'] !='1560829162' && $r['id'] !='1560829223'){continue;} ?>
								<option value="<?php echo $r['id']; ?>" <?php if($r['id'] =='1560829223'){ } ?>  ><?php echo $r['currency']; ?></option>
							<?php } ?>	
					</select>
                    <label for="wht"><?php echo $i18n["Currency"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                    </span>
					<input type="hidden" name="tygiausdtovnd" class="tygiausdtovnd" value=""  />
                </div>
				
				<div class="input-field col s1">
                    <select name="classification" id="classification"  tabindex="-1"  >           
							<option value="">----------</option>                
                       		<?php 
									$containers_op = $Setting->Container;
									$containers_op = explode(PHP_EOL,$containers_op );
                                    foreach($containers_op as $kk => $container_op ){
										$container_op = explode('|',$container_op );
										$container_op[0] = str_replace(array("\n","\r\n","\r",PHP_EOL,' '), '',$container_op[0]);										
										$container_op[1] = str_replace(array("\n","\r\n","\r",PHP_EOL,' '), '',$container_op[1]);
										$container_op[2] = str_replace(array("\n","\r\n","\r",PHP_EOL,' '), '',$container_op[2]);
										
										
										if( strpos($categoryf, $container_op[0] ) === false ){
											$category .= '<option value="'.$container_op[0].'" color="'.$container_op[1].'" freetext="'.$container_op[2].'" >'.(($i18n[$container_op[0]] != '')?$i18n[$container_op[0]]:$container_op[0] ).'</option>';
										}else{
											$category .= '<option value="'.$container_op[0].'" color="'.$container_op[1].'" freetext="'.$container_op[2].'" selected >'.(($i18n[$container_op[0]] != '')?$i18n[$container_op[0]]:$container_op[0] ).'</option>';
										}
                                        ?> 
                                            <option value="<?php echo $container_op[0]; ?>" color="<?php echo $container_op[1]; ?>" freetext="<?php echo $container_op[2]; ?>" ><?php echo ($kk+1).' '; if($i18n[$container_op[0]] != ''){ echo $i18n[$container_op[0]]; }else{ echo $container_op[0]; } ?></option>
                                        <?php
                                    }
                            ?>

					</select>
                    <label for="classification"><?php echo $i18n["费用归类"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Enter Cost classification
                    </span>
                </div>
				<div class="input-field col s2 charge" >
					<select name="charge" id="charge"  tabindex="-1" disabled >           
							<option value="">----------</option>                
                       		<?php 
									$subContainer = $Setting->subContainer;
									$subContainers = explode(PHP_EOL,$subContainer );
                                    foreach($subContainers as $subContainer ){
										$subContainer = explode('|',$subContainer );
										$subContainer[1] = str_replace(array("\n","\r\n","\r",PHP_EOL,' '), '',$subContainer[1]);
										if($subContainer[0] != $fgni){
											$fgni = $subContainer[0];
											$dhere = 1;
										}else{
											$dhere++;
										}
										$erjkik[$subContainer[1]] =  $dhere.'. ';
										if( strpos($subcategoryf, $subContainer[0] ) === false ){
											$subcategory .= '<option class="'.$subContainer[0].'" value="'.$subContainer[1].'">'.(($i18n[$subContainer[1]] != '')?$i18n[$subContainer[1]]:$subContainer[1]).'</option>';
										}else{
											$subcategory .= '<option selected class="'.$subContainer[0].'" value="'.$subContainer[1].'">'.(($i18n[$subContainer[1]] != '')?$i18n[$subContainer[1]]:$subContainer[1]).'</option>';
										}
                                        ?> 
                                            <option class="<?php echo $subContainer[0]; ?>" value="<?php echo $subContainer[1]; ?>"><?php echo $dhere; ?> <?php if($i18n[$subContainer[1]] != ''){ echo $i18n[$subContainer[1]]; }else{ echo $subContainer[1]; } ?></option>
                                        <?php
                                    }
                            ?>
							<option  class="novalue" value=""></option>                
					</select>	
                    <label for="charge"><?php echo $i18n["费用明细"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Enter Charge Details
                    </span>
                </div>
				
				<div class="input-field col s2 chargefreetext" style="display:none;" >
					 <input 
                        value="" 
                        id="chargefreetext" 
                        name="charge" 
                        type="text" 
                        class="validate"    
						disabled
                        />
                    <label for="chargefreetext"><?php echo $i18n["费用明细"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Enter Charge Details
                    </span>
                </div>
				
				<div class="input-field col s1 exchangeamout" style="display:none;" >
					<select name="currencyex" id="currencyex" tabindex="-1"  >     
							<option value="" selected >--货币--</option>
                                                        <option value="1560828928" >RMB</option>
							<option value="1560829162" >USD</option>
							<option value="1560829223" >VND</option>
							<option value="1560911884" >Baht</option>
                                                        <option value="1664953269" >HKD</option>
                                                        <option value="1734688747" >MYR</option>
					</select>
                    <label for="currencyex">Ex Cur/货币兑换</label>
                    <span class="helper-text" data-error="Error" data-success="OK"></span>
                </div>
				
				<div class="input-field col s1 exchangeamout" style="display:none;" >
					 <div style="font-size: 9px;width: 39%;float: left;padding-top: 26px;" >1(<span class="currentcur"></span>)=</div>
					 <input 
                        value="" 
                        id="exchangeamout" 
                        name="exchangeamout" 
                        type="text" 
                        class="validate"  style="width: 60%; float: right;"
                        />
                    <label for="exchangeamout" class="active" >Ex Rate/汇率</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Enter Charge Details
                    </span>
                </div>
				
			
				
				<div class="input-field col s2 inputisspeci2 " style="display:none;" >
					 <input 
                        value="" 
                        id="BillNo" 
                        name="billno" 
                        type="text" 
                        class="validate"    
						
                        />
                    <label for="BillNo"><?php echo $i18n["Bill No."]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                    </span>
                </div>
				
				<div class="input-field col s2 inputisspeci2 " style="display:none;" >
					
					<select name="billto" id="Billto"   >  
							<option value="">----------</option>       
							<option value="Vantrans">Vantrans</option>    
							<option value="Fubo-AV6207001">Fubo-AV6207001</option>  							
					</select>	
					
                    <label for="Billto"><?php echo $i18n["Bill To"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                    </span>
                </div>
				
				<div class="input-field col s2 inputisspeci2 " style="display:none;" >
					 <input 
						data-type='currency'
                        value="" 
                        id="vat" 
                        name="vat" 
                        type="text" 
                        class="validate"    
						placeholder="0.00"
                        />
                    <label for="vat"><?php echo $i18n["增值税"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                    </span>
                </div>
				<div class="input-field col s2 inputisspeci2 " style="display:none;" >
					 <input 
						data-type='currency'
                        value="" 
                        id="wht" 
                        name="wht" 
                        type="text" 
                        class="validate"    
						placeholder="0.00"
                        />
                    <label for="wht"><?php echo $i18n["预扣税"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                    </span>
                </div>
				
				<div class="input-field col s1" style="    margin: 0;    margin-top: -33px;    margin-left: 46px;display:none;" >
					<label class="pure-material-checkbox" style="margin-top: 16px;" >
						  <input type="checkbox"  value="1"  id="idbaddebt"   name="baddebt"  >
						  <span><?php echo $i18n["坏账损失"];  ?></span>
					</label>
				</div>
				<div class="input-field col s3 summarydiv">
                    <input 
                        value="" 
                        id="summary" 
                        name="summary" 
                        type="text" 
                        class="validate"                        
                        />
                    <label for="summary"><?php echo $i18n["摘要"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Enter Summary
                    </span>
                </div>
                <div class="input-field col s2 divpayin">
                    <input 
						data-type='currency'
                        value="" 
                        id="amountincome" 
                        name="amountincome" 
                        type="text" 
                        class="validate" 
                         placeholder="0.00"
                        />
                    <label for="amountincome"><?php echo $i18n["收入金额"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Amount of income
                    </span>
                </div>
                <div class="input-field col s2 divpayout" style="display:none;" >
                    <input 
						data-type='currency'
                        value="" 
                        id="amountpayout" 
                        name="amountpayout" 
                        type="text" 
                        class="validate" 
                         placeholder="0.00"
                        />
                    <label for="amountpayout"><?php echo $i18n["支出金额"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Amount of payout
                    </span>
                </div>
				<div class="input-field col s1 exchangeamout" style="display:none;" >
                    <input 
						data-type='currency'
                        value="" 
                        id="feeex" 
                        name="feeex" 
                        type="text" 
                        class="validate" 
                        placeholder="0.00"
						style="width:100%;float:left;" 
                        />
					<input 
						data-type='currency'
                        value="" 
                        id="feeexrate" 
                        name="feeexrate" 
                        type="text" 
                        class="validate" 
                        placeholder="USD/RMB = ?VND"
						style="width:48%;float:right;display:none;" 
                        />	
                    <label for="amountpayout">Fee/费用交换</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                    </span>
                </div>
				<div class="input-field col s2 exchangeamout" style="display:none;" >
                    <select name="tabsex[]" id="tabsex" class="exclude" multiple >						
                        <?php foreach($tabs as $tab){ ?> 
                              <option cur="<?php echo $tab->currency; ?>" name="<?php echo $tab->name ?>"  value="<?php echo $tab->id ?>" ><?php echo $tab->name ?></option>
                        <?php } ?>
                    </select>
                    <label for="tabsex"><?php echo $i18n["Accounting"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Select Accounting
                    </span>
                </div>	
				<div class="input-field col s2">
					<select name="corresponding[]" id="corresponding"  class="exclude" multiple >  
							<option value="">-----<?php echo $i18n["Corresponding"]; ?>-----</option>       
							<?php foreach ($corresponding as $rp){
                                                        if($rp->accept == 1){
                                                            ?>
							<option value="<?php echo $rp->id; ?>"><?php echo $rp->fullname; ?></option>  
                                                        <?php }} ?>	
					</select>	
					<label for="corresponding"><?php echo $i18n["Corresponding"]; ?></label>
				</div>	
				<div class="input-field col s2">
					<select name="payer[]" id="payer"  class="exclude" multiple >  
							<option value="">-----<?php echo $i18n["收付款人"]; ?>-----</option>       
							<option value="addmore">+ Add more</option>    
							<?php foreach ($receiver_payer as $rp){ ?>
							<option value="<?php echo $rp->id; ?>"><?php echo $rp->name; ?></option>  
							<?php } ?>	
					</select>	
                    <input 
                        value="" 
                        id="payer_more" 
                        name="payer_more" 
						placeholder="New <?php echo $i18n["收付款人"]; ?>"
                        type="text" 
                        class="validate"    
						style="display:none;"	
                        />
                    <label for="payer"></label>
					<label for="payer_more"><?php echo $i18n["Accounting"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Enter Payer
                    </span>
                </div>
                <div class="input-field col s2" >
                    <input 
                        value="" 
                        id="requestnumber" 
                        name="requestnumber" 
                        type="text" 
                        class="validate" 
                        />
                    <label for="requestnumber"><?php echo $i18n["催/请款单号"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                       Request number
                    </span>
                </div>
				<?php if(0 == 1){ ?>
                <div class="input-field col s3">
                    <input 
                        value="" 
                        id="jobnumber" 
                        name="jobnumber" 
                        type="text" 
                        class="validate"                        
                        />
                    <label for="jobnumber"><?php echo $i18n["工作号"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                       Job number
                    </span>
                </div>
				<?php } ?>				
				<div class="input-field col s1" style="min-width: 157px;">
                    <input 
                        value="" 
                        id="documentnumber" 
                        name="documentnumber" 
                        type="text" 
                        class=""     
						placeholder=" "				
                        />
                    <label for="documentnumber" class="makesimilarlabel" style="z-index: 1000!important;" >
						
						<span style="margin-right:2px;position:relative;z-index: 2;" ><?php echo $i18n["凭证号"]; ?></span> 
						<label class="pure-material-checkbox" style="position:relative;z-index: 2;" >
						  <input type="checkbox"  value="1"  id="iscontinue"    >
						  <span style="padding-left: 20px;    z-index: 100000;"><?php echo $i18n["继续?"]; ?></span>
						</label>
						<select class="makesimilar"  ></select> </label>
                    <span class="helper-text iopd"  data-success="OK" style="display: block!important;">
                       
                    </span>
					<style>
						@media only screen and (max-width: 1400px){
							.djbjd	{
								width:200px!important;
							}
						}
						.makesimilarlabel .select2 .selection .select2-selection--single{
							border:none;
						}
						.makesimilarlabel .select2-container--default .select2-selection--single .select2-selection__rendered ,.makesimilarlabel .select2-container--default .select2-selection--single .select2-selection__arrow{
							display:none;
						}
						.makesimilarlabel .select2  {
							position: absolute;
							top: -34px;
							right: -68px;
							width: 200px !important;
							z-index: 1;
						}
						.makesimilarlabel .dropdown-trigger {
							    border: none!important;
								position: absolute!important;
								width: 50px!important;
								color: transparent!important;
								top: -29px;
								height: 30px!important;
								left: 120px;
								background: rgba(0, 0, 0, 0.12)!important;
								opacity:0.4;
						}
						.makesimilarlabel .dropdown-content{
								min-width:190px;
								top: 10px!important;
								 
						}
					</style>
                </div>               
				<div class="input-field col s1 writtenoff" style="display:none;"  >
					<select name="writtenoff" id="writtenoff"   >  
							<option value="">----------</option>       
							<option value="是"><?php if($i18n["是"] != ''){ echo $i18n["是"]; }else{ echo '是'; } ?></option>    
							<option value="没有"><?php if($i18n["没有"] != ''){ echo $i18n["没有"]; }else{ echo '没有'; } ?></option>  							
					</select>	
                    <label for="charge"><?php echo $i18n["是否核销"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Is it written off?
                    </span>
                </div>
				
                <div class="input-field col s3 djbjd" style="    max-width: 20%;" >
                    <input 
                        value="" 
                        id="remarks" 
                        name="remarks" 
                        type="text" 
                        class="validate"                        
                        />
                    <label for="remarks"><?php echo $i18n["备注"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                       Remarks
                    </span>
                </div>
                			
				
				<div class="input-field col s2  ">
					<div class="file-field">
						<div class="btn btn-primary btn-sm float-left" style="padding: 3px;" >
							  <span><?php echo $i18n['Choose file']; ?></span>
							  <input style="    max-width: 85%;" type="file"  name="fileupload[]"  id="fileupload"  multiple="multiple" >
						</div>
						<div class="file-path-wrapper">
							  <textarea style="    max-width: 100%;    min-width: 100%;" class="file-path validate" type="text" placeholder="<?php echo $i18n['Upload your file']; ?>"></textarea> 
						</div>
					</div>
				</div>	
				<?php if($_GET['onlyform'] != 1) { ?>
                <div class="input-field col " style="  ">
                     <div class="input-field col  ">
                    <button class="colortoptran btn waves-effect waves-light" style="float: right;    padding: 0px 4px;" type="submit" name="action">
                        <?php echo $i18n['Save New Issue']; ?>
                        <i class="material-icons right">add_circle_outline</i>
                    </button>
                          </div>
                    <div class="input-field col   ">
                        <button onclick="jQuery('.formchiem').empty();jQuery('#documentnumber').val(''); $('.ismoreadd iframe').attr('src', function(index, attr){ return attr; });" type="button" class="btn waves-effect waves-light toggle" style="    padding: 0px 4px;background: #999999;" ><?php echo $i18n['Go Back']; ?></button>
                    </div>
					<?php if( $currentuser->gm == 1){ ?>
					<div class="input-field col  ">
						<button onclick="if(jQuery('.ismoreadd').hasClass('act')){ jQuery('.ismoreadd').removeClass('act');jQuery('.ismoreadd').hide(); }else{ jQuery('.ismoreadd').addClass('act');jQuery('.ismoreadd').fadeIn(); }"  class="colortoptran btn waves-effect waves-light" style="    padding: 0px 4px;" type="button" ><?php echo $i18n['Multi']; ?></button>
					</div>
					<?php } ?>
                </div>
				<?php } ?>
				<div class="input-field col s12 exchangeaccount " style="">
					
				</div>
            </div>
        </form>		
    </div>
<?php }else{ ?>	
<div <?php if($_GET['onlyform'] != 1) { ?> class="badge grey lighten-3  show-table" style="padding:0.5em;    border-bottom: 2px solid rgb(221, 221, 221);    margin-left: -5px;" <?php } ?> >
	This Ip Can't create. 
</div>       
<?php } ?>
<?php if($_GET['onlyform'] != 1) { ?>	
	<br>
<?php } ?>	
	<?php
		 foreach($tabs as $tab){
			 if($tab->tabsg != ''){
				$tabsg[$tab->tabsg] = $tab->tabsg;
			 }else{
				$havetabsge = 1;
			 }
		 }
		 if(count((array)$tabsg) > 0){
			 $distabsg = 'display:none;'; 
		 }
	if(count((array)$tabsg) > 0){	 
	?>
	 <ul style="    display: flex;    background: #f7f7f7;    align-items: center;    height: unset;    position: relative;  overflow-x: auto;    overflow-y: hidden;    height: 48px;    width: 100%;        margin: 0 auto;    white-space: nowrap;<?php if($_GET['none']) ?><?php if($_GET['onlyform'] == 1) { ?>display:none;<?php } ?>" class="dasjdbask"  >
		<?php foreach ($tabsg as $r){ ?>
                <li style="" onclick="$('.dasjdbask li').removeClass('current'); $(this).addClass('current'); $('.tabs li.tab-link ,.companyinformation ').hide();$('.tabs li.tab-link.<?php echo str_replace(' ','',$r ); ?>').css('display','inline-block');  $('.tabs').show();  " ><?php if(isset($i18n[$r])){echo $i18n[$r];}else{ echo $r;} ?></li>
		<?php } ?>
		<?php if($havetabsge != 1){ ?>
		<li style="display:none;" onclick="$('.dasjdbask li').removeClass('current'); $(this).addClass('current'); $('.tabs li.tab-link,.companyinformation').hide();$('.tabs li.tab-link.unknonwa , .tabs ').show();" >Uncategory</li>
		<?php } ?>
                <?php if ( $currentuser->gm == 1 || $currentuser->role == 'Controller' || $currentuser->mod26 == '1' ) {  ?>   
                	<li class="ckasnklcasnl"  onclick="$('.dasjdbask li').removeClass('current'); $('.excludethistable').removeClass('current');  $(this).addClass('current'); $('.excludethistable , .tabs ').hide();$('.companyinformation').show();" ><?php echo $i18n['公司资料资产登记']; ?></li>
                    
                        
               <?php } ?>         
                        <?php if ( $currentuser->gm == 1 || $currentuser->role == 'Controller' || $currentuser->companyinfo == '1' ) {  ?>   
             
                        <li class="ckasnklcasnl"  onclick=""  >
                            <select class="exclude" onchange=" if($(this).val() != ''){ $('.textnames').text('所显示的画面是'+$(this).val()+'公司的模块'); } if($(this).val() == ''){ $('.textnames').text('所显示的画面是公司公司的模块'); $('.nationfilter').removeClass('ishide'); }else if($(this).val() == '越南'){ $('.nationfilter').addClass('ishide'); $('.nationfilter越南').removeClass('ishide'); }else if($(this).val() == '中国'){ $('.nationfilter').addClass('ishide'); $('.nationfilter中国').removeClass('ishide'); }else if($(this).val() == '泰国'){ $('.nationfilter').addClass('ishide'); $('.nationfilter泰国').removeClass('ishide'); }else if($(this).val() == '印尼'){ $('.nationfilter').addClass('ishide'); $('.nationfilter印尼').removeClass('ishide'); }else if($(this).val() == '马来西亚'){ $('.nationfilter').addClass('ishide'); $('.nationfilter马来西亚').removeClass('ishide'); }" id="filteraccountlocation">
                                     <option value=""><?php if(isset($i18n['全部'])){echo $i18n['全部'];}else{ echo '全部';} ?></option>
                                    <option value="越南"><?php if(isset($i18n['越南'])){echo $i18n['越南'];}else{ echo '越南';} ?></option>
                                    <option value="中国"><?php if(isset($i18n['中国'])){echo $i18n['中国'];}else{ echo '中国';} ?></option>
                                    <option value="泰国"><?php if(isset($i18n['泰国'])){echo $i18n['泰国'];}else{ echo '泰国';} ?></option>
                                    <option value="印尼"><?php if(isset($i18n['印尼'])){echo $i18n['印尼'];}else{ echo '印尼';} ?></option>
                                    <option value="马来西亚"><?php if(isset($i18n['马来西亚'])){echo $i18n['马来西亚'];}else{ echo '马来西亚';} ?></option>
                                </select>          
                            <script>
                                <?php if($currentuser->location != '总公司'){ ?>
                                $('#filteraccountlocation').val('<?php echo $currentuser->location; ?>');
                                <?php } ?>
                            </script>
                          
                        </li>       
                       
               <?php } ?>    
                <li class="ckasnklcasnl textnames" style="    background: transparent !important;    border: none !important;"  >
                      所显示的画面是<?php if( $currentuser->location == '总公司' ){ echo '公司'; }elseif( $currentuser->location == '印尼' ){ echo '印度尼西亚'; }else{ echo $currentuser->location;} ?>公司的模块
                </li>
	 </ul>
      
	<?php } ?>
    <ul style="display:flex;background:#eeeeee;align-items:center;height:unset;<?php if($_GET['none']) ?><?php if($_GET['onlyform'] == 1) { ?>display:none;<?php } ?><?php echo $distabsg; ?>" class="tabs">
        <?php if ( $currentuser->gm == 1 || $currentuser->role == 'Finance' || $currentuser->name == 'LEX' ) {  ?>   
                <button data-target="addNewTab" onclick="$('#addNewTab #id_tabname,#addNewTab #tab,#addNewTab #tabinfo').val('')" class="btn modal-trigger sdastr" style="margin-left:10px;margin-right:10px;"><i class="material-icons right" style="line-height:1.5;font-size: 25px;margin: 0;padding: 0;">add_circle_outline</i></button>
        <?php } ?>     
            <?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(count((array)$tabsg) > 1 && $tab->tabsg == ''){
					  $rtabsgname = 'unknonwa';
				  }elseif(count((array)$tabsg) > 1 && $tab->tabsg != ''){
					  $rtabsgname = str_replace(' ','',$tab->tabsg );
				  }
				  
                  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; '.$distabsg.'   border-top: 3px solid #eeeeee;" class="nationfilter  nationfilter'.$tab->location.' tab-link '.$rtabsgname .'">'.$tab->name.'('.$currencyname.')</li>';
						}else{
							echo '<li data-tab="tab-'.$tab->id.'" data-id="'.$tab->id.'" style="'.$distabsg.'" class="nationfilter  nationfilter'.$tab->location.' tab-link '.$rtabsgname .'">'.$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.'" currencyname="'.$currencyname.'" currency="'.$tab->currency.'"  special="'.$tab->special.'"   special2="'.$tab->special2.'"  special3="'.$tab->special3.'"  class="nationfilter nationfilter'.$tab->location.' tab'.$tab->id.' tab-link '.$current.'  '.$rtabsgname .'" style="'.$distabsg.'" >'.$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($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((float)(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';
			$tygiausdtovnd = $rcurrency['exchangerate'];
		}elseif($rcurrency['currency'] == 'HKD'){
			$exchangeratetext2[] = '1 USD = '.number_format((float)$rcurrency['exchangerate'],2).' HKD';
			
		}elseif($rcurrency['currency'] == 'HKDVND'){
			$exchangeratetext2[] = '1 HKD = '.number_format((float)$rcurrency['exchangerate'],0).' VND';
			
		}
	}else{
		$exchangeratetext = ' '.$rcurrency['currency'];
	}
}		
		
	
	
foreach($tabs as $tab){ 
	 //ksort((array)${'data'.$tab->id});
	 ${'data'.$tab->id} = array_sort(${'data'.$tab->id}, 'settime', SORT_ASC);
	 ${'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($_GET['opti'] == 1){
				if($values['classification'] == '换汇' &&  $values['payment'] == '收'){
					$values['classification'] = '汇入';
				}elseif($values['classification'] == '换汇' &&  $values['payment'] == '付'){
					$values['classification'] = '汇出';
				}
				
				$values['tabs'] = $rt;
				$newdata[] = $values;
				$newtabdata[] = array(
					'iddoc' => $values['id'],      
					'idtab' => $values['tabs']
				);    
			}
			if( date('Y.m.d',(int)$values['settime']) >=  $datestart  ){
				 
			}else{
				if($tab->special3 == 1){
					if($values['amountpayoutusd'] > 0){
						$balance[$rt] += floatval($values['amountpayoutusd']*$values['exchangeusdtovnd']);
					}else{
						$balance[$rt] += floatval($values['amountincome']) - floatval($values['amountpayout']) ;
					}
				}else{
					$balance[$rt] += floatval($values['amountincome']) - floatval($values['amountpayout']) ;
				}
				$balanceusdtovnd[$rt] += floatval($values['amountincomeusd'])-floatval($values['amountpayoutusd']);
			}
			
			$groupdocumentnumber[] = $values['documentnumber'];
			if ( $values['documentnumber'] == '' || strpos($values['documentnumber'], '-') !== false || date('Ym') != date('Ym',$values['id']) ){
				 continue;
			}
			
			$tablocation = $tab->location;
		
			if($tab->special == 1){
				if(strpos($values['documentnumber'],'VN') !== false ){
					$tablocation = '越南';
				}
				if(strpos($values['documentnumber'],'CN') !== false ){
					$tablocation = '中国';
				}
				if(strpos($values['documentnumber'],'TH') !== false ){
					$tablocation = '泰国';
				}
			}
			
			if($values['classification'] == '管理费用'){
				
				if( $nextvalue1[$tablocation] < substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3)){
					$nextvalue1[$tablocation] = substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3);
				}
				if(strpos($values['documentnumber'],'VN') !== false){
				$missingvalue1['越南'][intval (substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3))] = 1 ;
				}
				if(strpos($values['documentnumber'],'CN') !== false){
				$missingvalue1['中国'][intval (substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3))] = 1 ;
				}
				if(strpos($values['documentnumber'],'TH') !== false){
				$missingvalue1['泰国'][intval (substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3))] = 1 ;
				}
			}
			if($values['classification'] == '应收账款'){
				
				if( $nextvalue2[$tablocation] < substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3)){
					$nextvalue2[$tablocation] = substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3);
				}
				if(strpos($values['documentnumber'],'VN') !== false){
				$missingvalue2['越南'][intval (substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3))] = 1 ;
				}
				if(strpos($values['documentnumber'],'CN') !== false){
				$missingvalue2['中国'][intval (substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3))] = 1 ;
				}
				if(strpos($values['documentnumber'],'TH') !== false){
				$missingvalue2['泰国'][intval (substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3))] = 1 ;
				}
			}
			if($values['classification'] == '应付账款'){
						
				if( $nextvalue3[$tablocation] < substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3)){
					$nextvalue3[$tablocation] = substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3);
				}
				if(strpos($values['documentnumber'],'VN') !== false){
				$missingvalue3['越南'][intval (substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3))] = 1 ;
				}
				if(strpos($values['documentnumber'],'CN') !== false){
				$missingvalue3['中国'][intval (substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3))] = 1 ;
				}
				if(strpos($values['documentnumber'],'TH') !== false){
				$missingvalue3['泰国'][intval (substr(filter_var($values['documentnumber'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), -3, 3))] = 1 ;
				}
			}			
	}
	
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; ";
  }elseif($tab->special3 == 1){
	  $isdho = "<style> #tab-".$tab->id." .havepecial3 { display:table-cell!important; } #tab-".$tab->id." .dbjiie span {display: initial!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 excludethistable '.$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;"><img onclick="if($(this).hasClass(\'dvyyyh\')){$(this).removeClass(\'dvyyyh\');$(\'.bsbkbbka\').hide(); }else{$(\'.bsbkbbka\').show();$(this).addClass(\'dvyyyh\');}" style="width:16px;filter: brightness(0) invert(1);" src="https://htlservice.net/Docs/tpl/img/50-512.png" /></th>';
  $table .= '<th style="width:65px;    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:65px;display:none;" class="sortdata dateh">settime</th> 
  <th style="width:65px;" >'.$i18n['Modified'].'</th> 	
  <th style="width:70px;" class="filtervendor" >'.$i18n['收/付'].' <select class="inorout" style="display:none;" id="inorout" multiple ><option value="clicktosearch" > Click to Show/Hide </option><option value="out" selected > 付 </option><option value="in" selected > 收 </option></select>  <i class="material-icons right" style="line-height:1.5;position:absolute;top:8px;right:5px;">search</i> </th> 
  <th style="width:100px; background-image: none;    z-index: 100;"  class="filtervendor"  >'.$i18n['费用归类'].'  <select class="shkabkasb" style="display:none;" id="category" multiple ><option value="clicktosearch" > << Click to Search >> </option>'.$category.'</select> <i class="material-icons right" style="line-height:1.5;position:absolute;top:8px;right:5px;">search</i> </th>
  <th style="width:100px; background-image: none;    z-index: 100;"  class="filtervendor"  >'.$i18n['费用明细'].'  <select class="shkabkasb" style="display:none;" id="subcategory" multiple ><option value="clicktosearch" > << Click to Search >> </option>'.$subcategory.'</select> <i class="material-icons right" style="line-height:1.5;position:absolute;top:8px;right:5px;">search</i> 
  </th>
  <th class="havepecial" style="display:none;width:50px;" ><input class="" type="text" placeholder="搜: '.$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;padding: 0 10px;" ><input class="dnoon" ref="1" type="text" placeholder="搜: '.$i18n['摘要'].'" /></th>
  <th style="width:105px;" class="dbjiie"  >'.$i18n['收入金额'].' <span  class="havepecial3" style="display:none;" >USD</span></th>
  <th style="width:105px;" class="dbjiie" >'.$i18n['支出金额'].' <span  class="havepecial3" style="display:none;" >USD</span></th>
  <th class="havepecial3" style="display:none;width: 125px;" >汇率 USD-VND</th>
  <th class="havepecial3" style="display:none;" >收入VND</th>
  <th class="havepecial3" style="display:none;" >支出VND</th>  
  <th style="width:105px;"  >'.$i18n['余额'].'</th>
  <th style="width:110px;padding: 0 10px;" class="" ><input class="dnoon" ref="4" type="text"       placeholder="搜: '.$i18n["Corresponding"].'" /></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;padding: 0 10px;" ><input class="dnoon" ref="2" type="text" placeholder="搜: '.$i18n['催/请款单号'].'" /></th>
  <th style="width:115px;padding: 0 10px;"  ><input class="dnoon" ref="3" type="text" placeholder="搜: '.$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="8" >'.$i18n["From"].':'.$datestart.' - '.$i18n["To"].':'.$dateto.'</td><td class="havepecial" style="display:none;"  >&nbsp;</td><td class="havepecial3" colspan="3" 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;" >'.$i18n["Balance Left"].' ('.$currencyname.')</td><td  style="    font-weight: normal;padding-left:6px!important;" >'.number_format((float)$balance[$rt],$decimal).'</td><td colspan="8"  style="text-align:right;" >汇买价 '.implode(', ',$exchangeratetext2).'</td></tr>';
  }else{
  $table .='<tr class="tr_total"><td colspan="8" >'.$i18n["From"].':'.$datestart.' - '.$i18n["To"].':'.$dateto.'</td><td class="havepecial" style="display:none;"  >&nbsp;</td><td class="havepecial3" colspan="3" 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;" >'.$i18n["Balance Left"].' ('.$currencyname.')</td><td  style="    font-weight: normal;padding-left:6px!important;" >'.number_format((float)$balance[$rt],$decimal).'</td><td  colspan="8"   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'){
             $totalrevision++;
        }
		if( date('Y.m.d',(int)$values['settime']) <  $datestart || date('Y.m.d',(int)$values['settime']) >  $dateto ){
			if( $values['documentnumber'] != '' && date('Ym',$values['id']) >= date('Ym', strtotime('first day of -3 month'))  ){

				if(strlen($values['documentnumber']) > 30){
file_put_contents(__DIR__.'/documentnumbers.txt', $values['documentnumber']);
$values['documentnumber'] = '';

}
				$phieubosung .= '<td style="display:none;" class="tddocumentnumber'.$values['classification'].$tab->location.' '.$values['documentnumber'].'" >' . $values['documentnumber'] .'</td>';
			}
			continue;
		}		
		
		if(!is_array($values['payer'])){
				$values['payer'] = array($values['payer']);
		}
		foreach($values['payer'] as $payer_cl ){
			if( strpos($vendor, $payer_cl) === false ){
				if(isset($receiver_payer_id[$payer_cl])){
					$payer[$rt][] = "<option value='".$payer_cl."' >".$receiver_payer_id[$payer_cl]->name."</option>";
				}elseif(isset($receiver_payer_name[$values['payer']])){
					$payer[$rt][] = "<option value='".$payer_cl."' >".$receiver_payer_name[$payer_cl]->name."</option>";
				}else{
					$payer[$rt][] = "<option value='".$payer_cl."' >".$payer_cl."</option>";
				}
			}else{
				if(isset($receiver_payer_id[$payer_cl])){
					$payer[$rt][] = "<option value='".$payer_cl."'  selected='' >".$receiver_payer_id[$payer_cl]->name."</option>";
				}elseif(isset($receiver_payer_name[$values['payer']])){
					$payer[$rt][] = "<option value='".$payer_cl."'  selected='' >".$receiver_payer_name[$payer_cl]->name."</option>";
				}else{
					$payer[$rt][] = "<option value='".$payer_cl."'  selected='' >".$payer_cl."</option>";
				}
			}
		}
		
		if($_POST['acctiveaccount'] == $values['tabs']){
			if( $vendor  != '' && $vendor != 'clicktosearch' && count(array_intersect(explode(',',$vendor), $values['payer'])) == 0 ){
				continue;
			}	
			if( $categoryf  != '' && $categoryf != 'clicktosearch' && strpos($categoryf, $values['classification']) === false ){
				continue;
			}	
			if( $subcategoryf != '' && $subcategoryf != 'clicktosearch' && strpos($subcategoryf, $values['charge']) === 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']);
		}elseif($tab->special3 == 1){
			
			
			if($values['amountpayoutusd'] > 0){
				$balance[$rt] += floatval($values['amountpayoutusd']*$values['exchangeusdtovnd']);
			}else{
				$balance[$rt] += floatval($values['amountincome']) - floatval($values['amountpayout']) ;
			}
			
			
		}else{
			$balance[$rt] += floatval($values['amountincome']) - floatval($values['amountpayout']) ;
		}
		$balanceusdtovnd[$rt] += (float)$values['amountincomeusd']-$values['amountpayoutusd'];
		$incomeusd[$rt] += floatval($values['amountincomeusd']);
		$expendusd[$rt] += floatval($values['amountpayoutusd']);
			
			$income[$rt] += floatval($values['amountincome']);
			$expend[$rt] += floatval($values['amountpayout']);
		if($values['payment'] == '收'){
			$rowclass = ' rowin row'.$tab->id.$values['id'];	
		}
		if($values['payment'] == '付'){
			$rowclass = ' rowout row'.$tab->id.$values['id'];	
		}
		
		
		$baddebt = '';
		if($values['baddebt'] == 1){
			$baddebt = 'border:2px solid red;';
		}
		if($values['highlight'] == 1){
			$rowclass .= ' ishighlight';
		}
		
		if($values['status'] == ''){
			$table .= '<tr class="'.$rowclass.'" style="'.$baddebt.'" >';
		}elseif($values['status'] == 'pending'){
			$table .= '<tr class="'.$rowclass.'" style="background-color: #dddddd;'.$baddebt.'" >';
		}elseif($values['status'] == 'approval'){
			$table .= '<tr class="'.$rowclass.'" style="background-color: #d1f9a9;'.$baddebt.'"  >';
		}elseif($values['status'] == 'notapproval'){
			$table .= '<tr class="'.$rowclass.'" style="background-color: #ffe5e5;'.$baddebt.'" >';
		}
		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 = ''; 
		
                if($values['id_invoice'] != ''){ 
                   
//                    for($i = 0; $i < 20 ; $i++){					
//                        if($id_invoice_a[$values['id_invoice']]['filename'.$i] > 0){
//                            
//                                
//                                $values['filename'][] = $id_invoice_a[$values['id_invoice']]['filename'.$i];
//                                $values['filepath'][] = $id_invoice_a[$values['id_invoice']]['filepath'.$i];
//                                $values['filetype'][] = $id_invoice_a[$values['id_invoice']]['filetype'.$i];
//
//					
//
//                                $values['filesize'][] = $id_invoice_a[$values['id_invoice']]['filesize'.$i];
//                                $values['filetimeupload'][] = $id_invoice_a[$values['id_invoice']]['filetimeupload'.$i];
//                                $values['filecreatebyid'][] = $id_invoice_a[$values['id_invoice']]['filecreatebyid'.$i];
//                                $values['filecreatebyname'][] = $id_invoice_a[$values['id_invoice']]['filecreatebyname'.$i];						
//                        }
//                }
                    
                }
		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\'));$(\'.iframereadfile\').load( function() { $(this).contents().find(\'img\').css(\'max-width\',\'100%\');$(this).contents().find(\'img\').css(\'display\',\'block\');$(this).contents().find(\'img\').css(\'margin\',\'0 auto\'); });"  ><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>';
				}
		}
		
		$ikey = '';
		foreach ($id_invoice[$values['id_invoice']]['veri'] as $verikey => $veri){
			if( $veri == $values['documentnumber'] && is_array($id_invoice[$values['id_invoice']]['filename'.$verikey]) ){
				$ikey = $verikey;
			}
		}
                if($ikey == ''){
                    if(!isset($valuesid_invoice[$values['id_invoice']])){
                        $ikey = $valuesid_invoice[$values['id_invoice']] = 0 ;  
                        $valuesid_invoice[$values['id_invoice']]++;
                    }else{
                        $ikey = $valuesid_invoice[$values['id_invoice']]++;
                    }
                }
               
		 if($values['id_invoice'] != ''){ 
                    
		foreach ($id_invoice[$values['id_invoice']]['filename'.$ikey] as $keyfile => $dataf){
				$fnjf++;
				if ( strpos($id_invoice[$values['id_invoice']]['filetype'.$ikey][$keyfile] , 'pdf')  !== false ) {
						if( $currentuser->location == '中国' ){
							$file .=  '<a ref="https://htlservice.net/expense/uploads/'.rawurlencode($id_invoice[$values['id_invoice']]['filepath'.$ikey][$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($id_invoice[$values['id_invoice']]['filepath'.$ikey][$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($id_invoice[$values['id_invoice']]['filetype'.$ikey][$keyfile] , 'sheet')  !== false || strpos($id_invoice[$values['id_invoice']]['filepath'.$ikey][$keyfile] , '.xls')  !== false ) { 
						$file .=  '<a ref="https://view.officeapps.live.com/op/embed.aspx?src=https://htlservice.net/expense/uploads/'.$id_invoice[$values['id_invoice']]['filepath'.$ikey][$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($id_invoice[$values['id_invoice']]['filetype'.$ikey][$keyfile] , 'zip')  !== false ) { 
						$file .=  '<a download href="https://htlservice.net/expense/uploads/'.$values['filepath'.$ikey][$keyfile].'" ><img src="https://htlservice.net/Docs/tpl/img/zip.png" style="width:24px;height:auto;" /></a>';
				} elseif ( strpos($id_invoice[$values['id_invoice']]['filetype'.$ikey][$keyfile] , 'doc')  !== false ) { 
						$file .=  '<a ref="https://view.officeapps.live.com/op/embed.aspx?src=https://htlservice.net/expense/uploads/'.$id_invoice[$values['id_invoice']]['filepath'.$ikey][$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($id_invoice[$values['id_invoice']]['filetype'.$ikey][$keyfile] , 'image')  !== false ) { 
						$file .=  '<a ref="https://htlservice.net/expense/uploads/'.$id_invoice[$values['id_invoice']]['filepath'.$ikey][$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\'));$(\'.iframereadfile\').load( function() { $(this).contents().find(\'img\').css(\'max-width\',\'100%\');$(this).contents().find(\'img\').css(\'display\',\'block\');$(this).contents().find(\'img\').css(\'margin\',\'0 auto\'); });"  ><img src="https://htlservice.net/Docs/tpl/img/png.png" style="width:24px;height:auto;" /></a>';
				} else{
						$file .=  '<a download href="https://htlservice.net/expense/uploads/'.$id_invoice[$values['id_invoice']]['filepath'.$ikey][$keyfile].'" ><img src="https://htlservice.net/Docs/tpl/img/file.png" style="width:24px;height:auto;" /></a>';
				}
		}
                 }
		if(  $cannotedit == 1 || ($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 == 'Finance' || $currentuser->name == 'LEX' ){
				$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>';
			}elseif ( ($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( $cannotedit == 1 || ( $currentuser->role == 'Operator' && !in_array($tab->id,$currentuser->account) && in_array($tab->id,$currentuser->accountreadonly))) {
			$table .= '<td style="text-align:center"><a href="index.php?highlight=1&id='.$values['id'].'" ><img style="width:16px;filter: sepia(1);display:none;" class="bsbkbbka" src="https://htlservice.net/Docs/tpl/img/50-512.png" /></a></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'].'" /><a href="index.php?highlight=1&id='.$values['id'].'" ><img style="display:none;width:16px;filter: sepia(1);" src="https://htlservice.net/Docs/tpl/img/50-512.png" class="bsbkbbka"  /></a></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 = '';
		}
		
		$tablocation = $tab->location;
		
			if($tab->special == 1){
				if(strpos($values['documentnumber'],'VN') !== false ){
					$tablocation = '越南';
				}
				if(strpos($values['documentnumber'],'CN') !== false ){
					$tablocation = '中国';
				}
				if(strpos($values['documentnumber'],'TH') !== false ){
					$tablocation = '泰国';
				}
			}
			
			
		if($cannotedit == 1){ $editmode = ''; } 
		
		$date = date('y.m.d',$values['id']);
		if(isset($values['settime'])){
			if($values['settime'] != ''){
				$date = date('y.m.d',$values['settime']);
			}
		}
		if($values['id'] == 1673317134){
			//echo '<pre>'; print_r($values);
		}
                if(stripos($values['documentnumber'],'<') !== false){
                    $valuesdocumentnumber = explode('<',$values['documentnumber']);
                    $valuesdocumentnumber1 = explode('>',$values['documentnumber']);
                    $values['documentnumber'] = $valuesdocumentnumber[0];//.$valuesdocumentnumber1[1];
                }
                
                
		$table .= '<td  style="padding-left:6px!important;"><span style="display:none;" >'.$values['id'].'</span><a href="#"  title="'.date('Y.m.d H:i:s',$values['id']).' '.$values['createbyname'].'" >' . $date .
	    '</a>'.$editmode.
		'</td><td class="sortdata" style="display:none;">'.date('Ymd',$values['settime']).'</td><td style="padding-left:6px!important;" ><a href="#"  title="'.date('Y.m.d H:i:s',$values['timemodify']).'" >' . $values['modifybyname']  .'</a>'.
		'</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;">' . (($tab->special3 == 1)?(($values['amountincomeusd'] > 0)?number_format((float)$values['amountincomeusd'],2):""):number_format((float)$values['amountincome'],$decimal)).
		'</td><td style="padding-left:6px!important;">' .(($tab->special3 == 1)?(($values['amountpayoutusd'] > 0)?number_format((float)$values['amountpayoutusd'],2):""):number_format((float)$values['amountpayout'],$decimal)).
		'</td><td class="havepecial3" style="padding-left:6px!important;display:none;">' . (($values['exchangeusdtovnd'] != '')?number_format((float)$values['exchangeusdtovnd'],0):'').
		'</td><td class="havepecial3" style="padding-left:6px!important;display:none;">' . (($values['exchangeusdtovnd'] != '')?number_format((float)($values['amountpayoutusd']*$values['exchangeusdtovnd']),$decimal): number_format((float)$values['amountincome'],$decimal) ) .
		'</td><td class="havepecial3" style="padding-left:6px!important;display:none;">' . number_format((float)$values['amountpayout'],$decimal) .
		'</td><td style="padding-left:6px!important;">' .(( $vendor  == '' ||  $_POST['acctiveaccount'] != $values['tabs']  )?number_format((float)$balance[$rt],$decimal):"") ;
		$table .= '</td><td style="padding-left:6px!important;"><div class="nofulltext" >';
		foreach ($values['corresponding'] as $rcorresponding){
			$table .= '<a data-target="modal8" class="modal-trigger " ref="'.$rcorresponding.'" title="Code/代码：'.$corresponding_id[$rcorresponding]->code.'&#010;Abbreviation/简称：'.$corresponding_id[$rcorresponding]->abbreviation.'&#010;Fullname/全名:：'.$corresponding_id[$rcorresponding]->fullname.' " >'.$corresponding_id[$rcorresponding]->fullname.'</a> ';
		}
		$table .= '</div>  <i class="fas fa-sort-down" style="color: #000;    font-size: 17px;"></i>  </td><td style="padding-left:6px!important;"><div class="nofulltext" >';
		foreach ($values['payer'] as $rpayer){
			if(isset($receiver_payer_id[$rpayer])){
				$table .= '<a data-target="modal8" class="modal-trigger payerdetail" ref="'.$rpayer.'" title="编号 Numbering：'.$receiver_payer_id[$rpayer]->name.'&#010;收付款人简称 Abbreviation：'.$receiver_payer_id[$rpayer]->abbreviation.'&#010;详细信息 Details:：'.$receiver_payer_id[$rpayer]->description.' " >'.$receiver_payer_id[$rpayer]->name.'</a>';
			}elseif(isset($receiver_payer_name[$rpayer])){
				$table .= '<a data-target="modal8" class="modal-trigger payerdetail" ref="'.$rpayer.'" title="编号 Numbering：'.$receiver_payer_name[$rpayer]->name.'&#010;收付款人简称 Abbreviation：'.$receiver_payer_name[$rpayer]->abbreviation.'&#010;详细信息 Details:：'.$receiver_payer_name[$rpayer]->description.' " >'.$receiver_payer_name[$rpayer]->name.'</a>';
			}else{
				$table .= $rpayer;
			}
			if(count((array)$values['payer']) > 1){
				$table .= ' | ';
			}
		}
		$table .= '</div><i class="fas fa-sort-down" style="color: #000;    font-size: 17px;"></i></td>'.
		'<td style="padding-left:6px!important;"><div class="nofulltext" >' . $values['requestnumber'].	
		'</div><i class="fas fa-sort-down" style="color: #000;    font-size: 17px;"></i></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'].$tablocation.' '.$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;" class="qwsda" ref="'.$values['id'].'" ><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( $cannotedit == 1 || ($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;" >'.$i18n['等待财务完成'].'</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']).'" >'.$i18n['待审核...'].'</a></td>';
					}elseif($values['status'] == 'approval'){
						$table .= '<td style="padding-left:6px!important;" ><a href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">'.$i18n['已审核'].' 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']).'">'.$i18n['未通过'].' 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 ">'.$i18n['发送'].'</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']).'" >'.$i18n['待审核...'].'</a></td>';
					}elseif($values['status'] == 'approval'){
						$table .= '<td style="padding-left:6px!important;" ><a href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">'.$i18n['已审核'].' 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']).'">'.$i18n['未通过'].' by '.$values['controlerapproval'].'</a></td>';
					}
				}
				
				if($currentuser->role == 'Finance'  || $currentuser->name == 'LEX'){
					if($values['status'] == ''){
						$table .= '<td style="padding-left:6px!important;" ><button style="width:100%;" id="'.$values['id'].'" class="btn waves-effect waves-light sendtoaproval ">'.$i18n['发送'].'</button></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',(int)$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']).'">'.$i18n['已审核'].' 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']).'">'.$i18n['未通过'].' 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'] == 'cancel'){
						$table .= '<td style="padding-left:6px!important;" ></td>';
					}
				}elseif($currentuser->gm == 1){
					if($values['status'] == ''){
						$table .= '<td style="padding-left:6px!important;" >'.$i18n['等待财务完成'].'</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',(int)$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:0px!important;" ><a href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">'.$i18n['已审核'].': '.$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:0px!important;" ><a style="color:red;" href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">'.$i18n['未通过'].': '.$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'] == 'cancel'){
						$table .= '<td style="padding-left:0px!important;" class="revision" >'.$values['controlerapproval'].' '.$i18n['请求返回'].' <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;" >'.$i18n['等待财务完成'].'</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']).'" >'.$i18n['待审核...'].'</a></td>';
					}elseif($values['status'] == 'approval'){
						$table .= '<td style="padding-left:6px!important;" ><a href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">'.$i18n['已审核'].': '.$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']).'">'.$i18n['未通过'].': '.$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'.$tab->id}[$key]);
    }
	
	if ($currentuser->role == 'Manager' || $currentuser->role == 'Operator') {
		if ($countNo > 0) {
        $table .= '</tbody><tfoot><tr class="tr_total"><td colspan="7"  style="padding-left: 5px;" >'.$i18n["From"].':'.$datestart.' - '.$i18n["To"].':'.$dateto.'</td><td class="havepecial" style="display:none;"  >&nbsp;</td><td class="havepecial3" style="display:none;"  ></td><td class="havepecial3" style="display:none;"  >'.number_format((float)$incomeusd[$rt],2).'(usd)</td><td class="havepecial3" style="display:none;"  >'.number_format((float)$expendusd[$rt],2).'(usd)</td><td class="havepecial2" colspan="4" style="display:none;"  >&nbsp;</td><td ><span style="display:none;" class="totalamountpayoutvnd" >'.$balance[$rt].'</span><span style="display:none;" class="totalamountpayoutusd" >'.$balanceusdtovnd[$rt].'</span>'.(($tab->special3 == 1)?number_format((float)$balanceusdtovnd[$rt],2).'(usd)':'')
		.(($balanceusdtovnd[$rt] >= 1)?'<button data-target="moneyexchange"  maxmonney="'.$balanceusdtovnd[$rt].'" curexchange="'.$tygiausdtovnd.'"  class="exchangemoney3 colortoptran modal-trigger btn waves-effect waves-light " ref="'.$tab->id.'" style="    padding: 0px 4px;" type="button">交换 VND</button>':'').'</td><td>'.(($tab->special3 != 1)?number_format((float)$income[$rt],$decimal):'').'</td><td  style="padding-left:6px!important;" >'.(($tab->special3 != 1)?number_format((float)$expend[$rt],$decimal):'').'</td><td  style="padding-left:6px!important;" >'.(( $vendor  == '' || $_POST['acctiveaccount'] != $values['tabs'])?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><td>&nbsp;</td></tr></tfoot>';
		}
	}else{
		if ($countNo > 0) {
        $table .= '</tbody><tfoot><tr class="tr_total"><td colspan="7"  style="padding-left: 5px;" >'.$i18n["From"].':'.$datestart.' - '.$i18n["To"].':'.$dateto.'</td><td class="havepecial" style="display:none;"  >&nbsp;</td><td class="havepecial3" style="display:none;"  ></td><td class="havepecial3" style="display:none;"  >'.number_format((float)$incomeusd[$rt],2).'(usd)</td><td class="havepecial3" style="display:none;"  >'.number_format((float)$expendusd[$rt],2).'(usd)</td><td class="havepecial2" colspan="4" style="display:none;"  >&nbsp;</td><td>'.(($tab->special3 != 1)?number_format((float)$income[$rt],$decimal):'').'</td><td style="padding-left:6px!important;" >'.(($tab->special3 != 1)?number_format((float)$expend[$rt],$decimal):'').'</td><td style="padding-left:6px!important;" >'.(( $vendor  == '' || $_POST['acctiveaccount'] != $values['tabs'])?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><td>&nbsp;</td></tr></tfoot>';
		}
	}
	
    echo $table . '</table>
		<script>
			jQuery("#vendorid'.$tab->id.'").append("'.implode('',array_unique((Array)$payer[$rt])).'");
		</script>
	';
}
if($currentuser->gm == 1 && $_GET['opti'] == 1){
	file_put_contents(__DIR__.'/dataopti.json', json_encode($newdata));
	file_put_contents(__DIR__.'/datatabopti.json', json_encode($newtabdata));
	
}
	$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 );
	
	
	
        if(is_countable($missingvalue1['越南'])){
        $a = $missingvalue1['越南'];    
	ksort($a);
        $missingvalue1['越南'] = $a;
        }
        if(is_countable($missingvalue1['中国'])){
        $a = $missingvalue1['中国'];    
	ksort($a);
        $missingvalue1['中国'] = $a;    
       
        }
        if(is_countable($missingvalue1['泰国'])){
        $a = $missingvalue1['泰国'];    
	ksort($a);
        $missingvalue1['泰国'] = $a;
        }
        if(is_countable($missingvalue2['越南'])){
	$a = $missingvalue2['越南'];    
	ksort($a);
        $missingvalue2['越南'] = $a;
        }
        if(is_countable($missingvalue2['中国'])){
        $a = $missingvalue2['中国'];    
	ksort($a);
        $missingvalue2['中国'] = $a;
        }
        if(is_countable($missingvalue2['泰国'])){
        $a = $missingvalue2['泰国'];    
	ksort($a);
        $missingvalue2['泰国'] = $a;
        }
        if(is_countable($missingvalue3['越南'])){
	$a = $missingvalue3['越南'];    
	ksort($a);
        $missingvalue3['越南'] = $a;
        }
        if(is_countable($missingvalue3['中国'])){
        $a = $missingvalue3['中国'];    
	ksort($a);
        $missingvalue3['中国'] = $a;
        }
        if(is_countable($missingvalue3['泰国'])){
        $a = $missingvalue3['泰国'];    
	ksort($a);
        $missingvalue3['泰国'] = $a;
        }
        
	for($s = 1 ;$s < 100 ; $s++){
		if(!$missingvalue1['越南'][$s] && is_array($missingvalue1['越南']) && count((array)$amissingvalue1['越南']) < 3){ $amissingvalue1['越南'][] = $s; }
		if(!$missingvalue1['中国'][$s] && is_array($missingvalue1['中国']) && count((array)$amissingvalue1['中国']) < 3){ $amissingvalue1['中国'][] = $s; }
		if(!$missingvalue1['泰国'][$s] && is_array($missingvalue1['泰国']) && count((array)$amissingvalue1['泰国']) < 3){ $amissingvalue1['泰国'][] = $s; }
		if(!$missingvalue2['越南'][$s] && is_array($missingvalue2['越南']) && count((array)$amissingvalue2['越南']) < 3){ $amissingvalue2['越南'][] = $s; }
		if(!$missingvalue2['中国'][$s] && is_array($missingvalue2['中国']) && count((array)$amissingvalue2['中国']) < 3){ $amissingvalue2['中国'][] = $s; }
		if(!$missingvalue2['泰国'][$s] && is_array($missingvalue2['泰国']) && count((array)$amissingvalue2['泰国']) < 3){ $amissingvalue2['泰国'][] = $s; }
		if(!$missingvalue3['越南'][$s] && is_array($missingvalue3['越南']) && count((array)$amissingvalue3['越南']) < 3){ $amissingvalue3['越南'][] = $s; }
		if(!$missingvalue3['中国'][$s] && is_array($missingvalue3['中国']) && count((array)$amissingvalue3['中国']) < 3){ $amissingvalue3['中国'][] = $s; }
		if(!$missingvalue3['泰国'][$s] && is_array($missingvalue3['泰国']) && count((array)$amissingvalue3['泰国']) < 3){ $amissingvalue3['泰国'][] = $s; }
	}
	$missingvalue1['越南'] =  substr( $amissingvalue1['越南'][0]+1000 , 1 , 3 );
	$missingvalue1['中国'] =  substr( $amissingvalue1['中国'][0]+1000 , 1 , 3 );
	$missingvalue1['泰国'] =  substr( $amissingvalue1['泰国'][0]+1000 , 1 , 3 );
	
	$missingvalue2['越南'] =  substr( $amissingvalue2['越南'][0]+1000 , 1 , 3 );
	$missingvalue2['中国'] =  substr( $amissingvalue2['中国'][0]+1000 , 1 , 3 );
	$missingvalue2['泰国'] =  substr( $amissingvalue2['泰国'][0]+1000 , 1 , 3 );
	
	$missingvalue3['越南'] =  substr( $amissingvalue3['越南'][0]+1000 , 1 , 3 );
	$missingvalue3['中国'] =  substr( $amissingvalue3['中国'][0]+1000 , 1 , 3 );	
	$missingvalue3['泰国'] =  substr( $amissingvalue3['泰国'][0]+1000 , 1 , 3 );
	
	
	$m2issingvalue1['越南'] =  substr( $amissingvalue1['越南'][1]+1000 , 1 , 3 );
	$m2issingvalue1['中国'] =  substr( $amissingvalue1['中国'][1]+1000 , 1 , 3 );
	$m2issingvalue1['泰国'] =  substr( $amissingvalue1['泰国'][1]+1000 , 1 , 3 );
	
	$m2issingvalue2['越南'] =  substr( $amissingvalue2['越南'][1]+1000 , 1 , 3 );
	$m2issingvalue2['中国'] =  substr( $amissingvalue2['中国'][1]+1000 , 1 , 3 );
	$m2issingvalue2['泰国'] =  substr( $amissingvalue2['泰国'][1]+1000 , 1 , 3 );
	
	$m2issingvalue3['越南'] =  substr( $amissingvalue3['越南'][1]+1000 , 1 , 3 );
	$m2issingvalue3['中国'] =  substr( $amissingvalue3['中国'][1]+1000 , 1 , 3 );	
	$m2issingvalue3['泰国'] =  substr( $amissingvalue3['泰国'][1]+1000 , 1 , 3 );
	
	
	echo '
	
		<input type="hidden" class="nextvalue1越南" miss="'.$missingvalue1['越南'].'" miss2="'.$m2issingvalue1['越南'].'" value="'.$nextvalue1['越南'].'" />
		<input type="hidden" class="nextvalue1中国" miss="'.$missingvalue1['中国'].'" miss2="'.$m2issingvalue1['中国'].'" value="'.$nextvalue1['中国'].'" />
		<input type="hidden" class="nextvalue1泰国" miss="'.$missingvalue1['泰国'].'" miss2="'.$m2issingvalue1['泰国'].'" value="'.$nextvalue1['泰国'].'" />
		
		<input type="hidden" class="nextvalue2越南" miss="'.$missingvalue2['越南'].'" miss2="'.$m2issingvalue2['越南'].'" value="'.$nextvalue2['越南'].'" />
		<input type="hidden" class="nextvalue2中国" miss="'.$missingvalue2['中国'].'" miss2="'.$m2issingvalue2['中国'].'" value="'.$nextvalue2['中国'].'" />
		<input type="hidden" class="nextvalue2泰国" miss="'.$missingvalue2['泰国'].'" miss2="'.$m2issingvalue2['泰国'].'" value="'.$nextvalue2['泰国'].'" />
		
		<input type="hidden" class="nextvalue3越南" miss="'.$missingvalue3['越南'].'" miss2="'.$m2issingvalue3['越南'].'" value="'.$nextvalue3['越南'].'" />
		<input type="hidden" class="nextvalue3中国" miss="'.$missingvalue3['中国'].'" miss2="'.$m2issingvalue3['中国'].'" value="'.$nextvalue3['中国'].'" />
		<input type="hidden" class="nextvalue3泰国" miss="'.$missingvalue3['泰国'].'" miss2="'.$m2issingvalue3['泰国'].'" 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="moneyexchange" class="modal modal-fixed "  enctype="multipart/form-data" >
			<div class="modal-content">
            <h4 style="margin-bottom: -20px;" >Exchange/交换 USD => USD</h4>
			 <form method="post" style="    margin-top: 53px;"  >
			 
				<?php if($currentuser->gm == 1){ ?>
					<div class=" col s12"  style="    height: 75px;"  >
						<input 
							value="<?php echo date('Y.m.d'); ?>"
							name="date" 
							type="text" 
							class="datepicker"  
							/>
						<label style="    transform: translateY(-14px) scale(0.8);    transform-origin: 0 0;" for="dkasndlkas" class="active" ><?php echo $i18n["Date"]; ?></label>
						<span class="helper-text" data-error="Error" data-success="OK">
							Enter Charge Details
						</span>
					</div>	
				<?php } else{ ?>			
					<div class=" col s12"  style="    height: 75px;"  >
						<select name="date" id="dkasndlkas" >						
							<option value="<?php echo date('Y.m.d'); ?>" selected ><?php echo date('Y.m.d'); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-1 day')); ?>" ><?php echo date('Y.m.d',strtotime('-1 day')); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-2 day')); ?>" ><?php echo date('Y.m.d',strtotime('-2 day')); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-3 day')); ?>" ><?php echo date('Y.m.d',strtotime('-3 day')); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-4 day')); ?>" ><?php echo date('Y.m.d',strtotime('-4 day')); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-5 day')); ?>" ><?php echo date('Y.m.d',strtotime('-5 day')); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-6 day')); ?>" ><?php echo date('Y.m.d',strtotime('-6 day')); ?></option>
							<option value="<?php echo date('Y.m.d',strtotime('-7 day')); ?>" ><?php echo date('Y.m.d',strtotime('-7 day')); ?></option>
						</select>
						<label for="dkasndlkas" style="    transform: translateY(-14px) scale(0.8);    transform-origin: 0 0;"  class="active" ><?php echo $i18n["Date"]; ?></label>
					</div>	
				<?php } ?>
				
				<div class=" col s12"  style="    height: 75px;"  >
					<span>Exchange rate/汇率</span>
                    <input id="monneyexchangerate" type="text" class="validate"  placeholder="Exchange rate/汇率" name="monneyexchangerate" value=""  />                  
                </div>				
				<div class="col s12"  style="    height: 75px;" >
					<span>Amount/量</span>
                    <input id="amountexchange" type="text" class="validate"   placeholder="Amount/量"  name="amountexchange"  value="" />                    
                </div>
				<div class="col s12"  style="    height: 75px;" >
					<span><?php echo $i18n["摘要"]; ?></span>
                    <input value="" id="summary" name="summary" type="text" class="validate">                   
                </div>
				<div class="col s12"  style="    height: 75px;" >
					<span><?php echo $i18n["备注"]; ?></span>
                    <input type="text" class="validate"     name="remark"  value="" />                    
                </div>
				<div class="col s12"  style="    height: 75px;" >
					<div class="file-field">
						<div class="btn btn-primary btn-sm float-left" style="padding: 3px;" >
							  <span><?php echo $i18n['Choose file']; ?></span>
							  <input style="    max-width: 85%;" type="file"  name="fileupload[]"  id="fileupload"  multiple="multiple" >
						</div>
						<div class="file-path-wrapper">
							  <textarea style="    max-width: 100%;    min-width: 100%;" class="file-path validate" type="text" placeholder="<?php echo $i18n['Upload your file']; ?>"></textarea> 
						</div>
					</div>
				</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 type="hidden" name="idaccount" id="idaccount" value=""  />
			 </form>	
			</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>
                                                <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: 30px;" >
						<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" style="    height: 60px;" >
						<label class="pure-material-checkbox">
						  <input type="checkbox"  value="1"  id="special3"   name="special3"  >
						  <span>Special Account work on 2 currency VND & USD ?</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" >
   <input class="typeapp" type="hidden"  name="typeapp" value="" >
</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" >
    <input class="typeapp" type="hidden"  name="typeapp" value="" >
</form>
<?php } ?>
<div id="modal5" class="modal">

  <iframe class="frameedit" src="" width="100%" style="height:auto;    min-height: 383px;" ></iframe>
</div>
<div id="modal8" class="modal">
  <iframe class="receiverpayer" 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 $categoryf; ?>" id="categoryf" name="categoryf" type="hidden" />
	<input value="<?php echo $subcategoryf; ?>" id="subcategoryf" name="subcategoryf" type="hidden" />
	
	<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' || $_SESSION['HTTP_ACCEPT_LANGUAGE'] == '' ){
			$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");

$("#idpayment").change(function(){
	if($(this).val() == '收'){
		$('.divpayin').show();
		$('.divpayout').hide();
		$('#amountpayout').val('');
		//$('#currencyisspeci3 option[value="1560829223"]').prop('disabled',true);
		//$('#currencyisspeci3').val('1560829162');
		//$('#currencyisspeci3').formSelect();
	}
	if($(this).val() == '付'){
		$('.divpayout').show();
		$('.divpayin').hide();
		$('#amountincome').val('');
		//$('#currencyisspeci3 option').prop('disabled',false);
		//$('#currencyisspeci3').formSelect();
	}
}); 
$("#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()],
           '十五天内': [moment().subtract(14, '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 
            if($currentuser->daytoseedata > 0 ){
                $currentuserdaytoseedata  = $currentuser->daytoseedata;
            }else{
                $currentuserdaytoseedata = 10000;
            }
           if($currentuserdaytoseedata > 0){  $currentuserdaytoseedata = $currentuserdaytoseedata - 30;?>
           '<?php echo $monthchinatext[(date('n', strtotime('first day of last month')) - 1 )].' '.date('Y',strtotime('first day of last month')); ?>': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
           <?php } if($currentuserdaytoseedata > 0){ $currentuserdaytoseedata = $currentuserdaytoseedata - 30; ?>        
           '<?php echo $monthchinatext[(date('n', strtotime('first day of -2 month')) - 1 )].' '.date('Y',strtotime('first day of -2 month')); ?>': [moment().subtract(2, 'month').startOf('month'), moment().subtract(2, 'month').endOf('month')],
           <?php } if($currentuserdaytoseedata > 0){ $currentuserdaytoseedata = $currentuserdaytoseedata - 30; ?>                
           '<?php echo $monthchinatext[(date('n', strtotime('first day of -3 month')) - 1 )].' '.date('Y',strtotime('first day of -3 month')); ?>': [moment().subtract(3, 'month').startOf('month'), moment().subtract(3, 'month').endOf('month')],
            <?php } if($currentuserdaytoseedata > 0){ $currentuserdaytoseedata = $currentuserdaytoseedata - 30; ?>                
           '<?php echo $monthchinatext[(date('n', strtotime('first day of -4 month')) - 1 )].' '.date('Y',strtotime('first day of -4 month')); ?>': [moment().subtract(4, 'month').startOf('month'), moment().subtract(4, 'month').endOf('month')],
                    <?php } if($currentuserdaytoseedata > 0){ $currentuserdaytoseedata = $currentuserdaytoseedata - 30; ?>        
           '<?php echo $monthchinatext[(date('n', strtotime('first day of -5 month')) - 1 )].' '.date('Y',strtotime('first day of -5 month')); ?>': [moment().subtract(5, 'month').startOf('month'), moment().subtract(5, 'month').endOf('month')],
                    <?php } if($currentuserdaytoseedata > 0){ $currentuserdaytoseedata = $currentuserdaytoseedata - 30; ?>        
           '<?php echo $monthchinatext[(date('n', strtotime('first day of -6 month')) - 1 )].' '.date('Y',strtotime('first day of -6 month')); ?>': [moment().subtract(6, 'month').startOf('month'), moment().subtract(6, 'month').endOf('month')],
                    <?php } if($currentuserdaytoseedata > 0){ $currentuserdaytoseedata = $currentuserdaytoseedata - 30; ?>        
           '<?php echo $monthchinatext[(date('n', strtotime('first day of -7 month')) - 1 )].' '.date('Y',strtotime('first day of -7 month')); ?>': [moment().subtract(7, 'month').startOf('month'), moment().subtract(7, 'month').endOf('month')],
                    <?php } if($currentuserdaytoseedata > 0){ $currentuserdaytoseedata = $currentuserdaytoseedata - 30; ?>        
           '<?php echo $monthchinatext[(date('n', strtotime('first day of -8 month')) - 1 )].' '.date('Y',strtotime('first day of -8 month')); ?>': [moment().subtract(8, 'month').startOf('month'), moment().subtract(8, 'month').endOf('month')],
                    <?php } if($currentuserdaytoseedata > 0){ $currentuserdaytoseedata = $currentuserdaytoseedata - 30; ?>        
           '<?php echo $monthchinatext[(date('n', strtotime('first day of -9 month')) - 1 )].' '.date('Y',strtotime('first day of -9 month')); ?>': [moment().subtract(9, 'month').startOf('month'), moment().subtract(9, 'month').endOf('month')],
                    <?php } if($currentuserdaytoseedata > 0){ $currentuserdaytoseedata = $currentuserdaytoseedata - 30; ?>        
           '<?php echo $monthchinatext[(date('n', strtotime('first day of -10 month')) - 1 )].' '.date('Y',strtotime('first day of -10 month')); ?>': [moment().subtract(10, 'month').startOf('month'), moment().subtract(10, 'month').endOf('month')],
                    <?php } if($currentuserdaytoseedata > 0){ $currentuserdaytoseedata = $currentuserdaytoseedata - 30; ?>        
           '<?php echo $monthchinatext[(date('n', strtotime('first day of -11 month')) - 1 )].' '.date('Y',strtotime('first day of -11 month')); ?>': [moment().subtract(11, 'month').startOf('month'), moment().subtract(11, 'month').endOf('month')]
                    <?php } ?>
        
        }
    }, 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('first day of last month')) - 1 )].' '.date('Y'); ?>': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -2 month')) - 1 )].' '.date('Y'); ?>': [moment().subtract(2, 'month').startOf('month'), moment().subtract(2, 'month').endOf('month')],
			'<?php echo $monthchinatext[(date('n', strtotime('first day of -3 month')) - 1 )].' '.date('Y',strtotime('first day of -3 month')); ?>': [moment().subtract(3, 'month').startOf('month'), moment().subtract(3, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -4 month')) - 1 )].' '.date('Y',strtotime('first day of -4 month')); ?>': [moment().subtract(4, 'month').startOf('month'), moment().subtract(4, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -5 month')) - 1 )].' '.date('Y',strtotime('first day of -5 month')); ?>': [moment().subtract(5, 'month').startOf('month'), moment().subtract(5, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -6 month')) - 1 )].' '.date('Y',strtotime('first day of -6 month')); ?>': [moment().subtract(6, 'month').startOf('month'), moment().subtract(6, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -7 month')) - 1 )].' '.date('Y',strtotime('first day of -7 month')); ?>': [moment().subtract(7, 'month').startOf('month'), moment().subtract(7, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -8 month')) - 1 )].' '.date('Y',strtotime('first day of -8 month')); ?>': [moment().subtract(8, 'month').startOf('month'), moment().subtract(8, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -9 month')) - 1 )].' '.date('Y',strtotime('first day of -9 month')); ?>': [moment().subtract(9, 'month').startOf('month'), moment().subtract(9, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -10 month')) - 1 )].' '.date('Y',strtotime('first day of -10 month')); ?>': [moment().subtract(10, 'month').startOf('month'), moment().subtract(10, 'month').endOf('month')],
		   '<?php echo $monthchinatext[(date('n', strtotime('first day of -11 month')) - 1 )].' '.date('Y',strtotime('first day of -11 month')); ?>': [moment().subtract(11, 'month').startOf('month'), moment().subtract(11, 'month').endOf('month')]
        
		}
    }, cb2);
    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">
 var d = new Date(); var days = (Date.parse(jQuery(this).text()) - Date.parse(d)) / 86400000;  if(days < 30){ jQuery(this).css("color","#f48024");}  if(days < 0){ jQuery(this).css("color","red"); }
$(function() {  	
	jQuery('.editmode').click(function(){
		jQuery('.frameedit').attr( 'src',jQuery(this).attr('ref'));
	});	
	jQuery('.payerdetail').click(function(){
		jQuery('.receiverpayer').attr( 'src','/expense/receiver_payer.php?payer='+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 () {
	 $("#payer").change(function(){
		  if($(this).val().indexOf("addmore") !== -1 ){	  
			  $(this).next('.select2').hide();
			  $('#payer_more').show();
		  }
	 });
	<?php if($currentuser->role == 'Finance'  || $currentuser->name == 'LEX' ){ ?>
		$('.qwsda').dblclick(function() {			
			$(this).append('<form method="POST" enctype="multipart/form-data"  ><input type="hidden" name="editremark" value="1"  /><input type="hidden" name="idorder" value="'+$(this).attr('ref')+'"  /><textarea style="width:100%; height:50px;" name="controlerremark" >'+$(this).find('.nofulltext').text()+'</textarea>  <button class="colortoptran btn waves-effect waves-light" style="float: right;    padding: 0px 4px;" type="submit" name="action"><?php echo $i18n['Save New Issue']; ?></button></form>');
			$(this).find('.nofulltext , i').remove();
		});
	<?php } ?>
	$(".asbdkbas").text('<?php if($totalrevision <= 0){ $totalrevision = 0; } echo $totalrevision; ?>');
	$(".asbdkbas").show();
	$(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);
		
	});

	<?php if($_GET['opentab']){ ?>
            setTimeout(function(){
            $('.tab<?php echo $_GET['opentab']; ?>').trigger('click');
            }, 2000);
        <?php } ?>
        <?php if($_GET['openid']){ ?>
           $('.row<?php echo $_GET['opentab'].$_GET['openid']; ?>').css('background','#c5d9ff');
            setTimeout(function(){
            $([document.documentElement, document.body]).animate({
                    scrollTop: $('.row<?php echo $_GET['opentab'].$_GET['openid']; ?>').offset().top - 100
            }, 2000); 
            }, 2500);
        <?php } ?>

	<?php if($_POST['rowclick'] != '' || $_POST['tabclick'] != ''){ ?>
		setTimeout(function(){
			$('.tab<?php echo $_POST['tabclick']; ?>').trigger('click');
			$('.<?php echo $_POST['rowclick']; ?>').css('background','#c5d9ff');
			$([document.documentElement, document.body]).animate({
				scrollTop: $('.<?php echo $_POST['rowclick']; ?>').offset().top - 100
			}, 2000);
			setTimeout(function(){
				$('.<?php echo $_POST['rowclick']; ?>').removeAttr('style');
			}, 7000);
		}, 1000);
	<?php } ?>
	
	$('.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('搜寻');
	
    $('.timepicker').timepicker({   twelveHour: false });
	
  
	$("#bifdnino").submit(function(e){	
		if(($('#classification').val() == "应收账款" || $('#classification').val() == "应付账款" || $('#classification').val() == "预收账款" || $('#classification').val() == "预付账款") && $('#writtenoff').val() == '' ){
			alert('是否核销 ?');
			return false;
		}	
		if($( ".sandjnas option:selected" ).hasClass('isspeci3') && $('#idpayment').val() == '付'){
			var amountpayout = parseFloat($("#amountpayout").val().replace(/\,/g, ''));
			if($("#currencyisspeci3").val() == '1560829162'){
				// usd
				if( amountpayout > parseFloat($('#tab-'+$(".sandjnas").val()).find('.totalamountpayoutusd').text())){
						$("#amountpayout").val('');
						alert('USD payments cannot exceed balance/美元付款不得超过余额');
						e.preventDefault();
						return;
				}
			}
			if($("#currencyisspeci3").val() == '1560829223'){
				// vnd
				if( amountpayout > parseFloat($('#tab-'+$(".sandjnas").val()).find('.totalamountpayoutvnd').text())){
						$("#amountpayout").val('');
						alert('VND payments cannot exceed balance/美元付款不得超过余额');
						e.preventDefault();
						return;
				}
			}
			
		}
		
	
		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();
		}
	});
	
	$("#currencyex").change(function(){		
		$('label[for="exchangeamout"]').addClass('active');
		if($(".tab-link.current").attr('currency') == '1560828928'){ // RMB
			if($("#currencyex").val() == '1560828928'){
				
			}else if($("#currencyex").val() == '1560829162'){
				$('#exchangeamout').val('1/<?php echo $currencyex['1560829162']['exchangerate']; ?>');
			}else if($("#currencyex").val() == '1560829223'){
				$('#exchangeamout').val('<?php echo round(1/$currencyex['1560829223']['exchangerate'],0); ?>');
			}else if($("#currencyex").val() == '1560911884'){
				$('#exchangeamout').val('<?php echo round(1/$currencyex['1560911884']['exchangerate'],2); ?>');
			}else if($("#currencyex").val() == '1664953269'){
                                $('#exchangeamout').val('0.92');
			}
			$('#feeexrate').val('<?php echo round(1/$currencyex['1560829223']['exchangerate'],0); ?>');	
		}else if($(".tab-link.current").attr('currency') == '1560829162'){  // USD
			if($("#currencyex").val() == '1560828928'){
				$('#exchangeamout').val('<?php echo $currencyex['1560829162']['exchangerate']; ?>');
			}else if($("#currencyex").val() == '1560829162'){
				
			}else if($("#currencyex").val() == '1560829223'){
				$('#exchangeamout').val('<?php echo $currencyex['1567070565']['exchangerate']; ?>');
			}else if($("#currencyex").val() == '1560911884'){
				$('#exchangeamout').val('29.96');
			}else if($("#currencyex").val() == '1664953269'){
                                $('#exchangeamout').val('<?php echo round($currencyex['1664953269']['exchangerate'],2); ?>');
			}
			$('#feeexrate').val('<?php echo $currencyex['1567070565']['exchangerate']; ?>');	
		}else if($(".tab-link.current").attr('currency') == '1560829223'){ // VND
			if($("#currencyex").val() == '1560828928'){
				$('#exchangeamout').val('1/<?php echo round(1/$currencyex['1560829223']['exchangerate'],0); ?>');
			}else if($("#currencyex").val() == '1560829162'){
				$('#exchangeamout').val('1/<?php echo $currencyex['1567070565']['exchangerate']; ?>');
			}else if($("#currencyex").val() == '1560829223'){
				
			}else if($("#currencyex").val() == '1560911884'){
				$('#exchangeamout').val('1/770');
			}else if($("#currencyex").val() == '1664953269'){
                                $('#exchangeamout').val('3043');
			}
			$('#feeexrate').val('1');
		}else if($(".tab-link.current").attr('currency') == '1560911884'){ // Baht
			if($("#currencyex").val() == '1560828928'){
				$('#exchangeamout').val('1/<?php echo round(1/$currencyex['1560911884']['exchangerate'],2); ?>');
			}else if($("#currencyex").val() == '1560829162'){
				$('#exchangeamout').val('1/29.96');
			}else if($("#currencyex").val() == '1560829223'){
				$('#exchangeamout').val('770');
			}else if($("#currencyex").val() == '1560911884'){
                            
			}else if($("#currencyex").val() == '1664953269'){
                                $('#exchangeamout').val('486');
			}
			$('#feeexrate').val('770');	
		}else if($(".tab-link.current").attr('currency') == '1664953269'){ // Baht
                
			if($("#currencyex").val() == '1560828928'){
				$('#exchangeamout').val('1/<?php echo round(1/$currencyex['1560911884']['exchangerate'],2); ?>');
			}else if($("#currencyex").val() == '1560829162'){
				$('#exchangeamout').val('1/29.96');
			}else if($("#currencyex").val() == '1560829223'){
				$('#exchangeamout').val('770');
			}else if($("#currencyex").val() == '1560911884'){
                            $('#exchangeamout').val('<?php echo round(1/$currencyex['1560911884']['exchangerate'],2); ?>');
			}else if($("#currencyex").val() == '1664953269'){
                            
			}
                        
			$('#feeexrate').val('770');	
		}
		
		
		$("#tabsex").val('');
		$("#tabsex option").prop('disabled',true);
		$("#tabsex option[cur='"+$(this).val()+"']").prop('disabled',false);
		$("#tabsex option[value='"+$("#tabs").val()+"']").prop('disabled',true);
		$("#tabsex").select2({width: "100%"});
	});
	
	$("#tabsex").change(function(){
		if($("#currencyex").val() == ''  ){
			alert('Select Currency exchange rate first/首先选择货币汇率');
			$("#tabsex").val('');
			$("#tabsex").select2({width: "100%"});
		}else if( $("#exchangeamout").val() == '' ){
			alert('Enter exchange rate first/首先输入汇率');
			$("#tabsex").val('');
			$("#tabsex").select2({width: "100%"});
		}else { 	
		
			var exchangeamout = $("#exchangeamout").val().replace(/\,/g, '');
			if(exchangeamout.indexOf('/') != -1){
				var aa = exchangeamout.split('/');
				exchangeamout = parseFloat(aa[0])/parseFloat(aa[1]);
			}
			
			var a = parseFloat($('#amountpayout').val().replace(/\,/g, '')) * parseFloat(exchangeamout);
			a = parseFloat(a).toFixed(2);
			$('.exchangeaccount table').remove();
			if($("#tabsex :selected").length > 1){
				$('.exchangeaccount').append( '<table  style="width: 500px;" class="fulamout" a="'+a+'" ><tr><td style="padding: 5px" >Full Amount/全额:</td><td style="padding: 5px;    text-align: right;" >'+a+' ('+$("#currencyex option:selected").text()+')</td></tr></table>');
			}
			$("#tabsex :selected").map(function(i, el) {
				if($("#tabsex :selected").length == 1){
					$('.exchangeaccount').append( '<table style="width: 500px;" ><tr><td style="padding: 5px" >IN/收: '+$(el).attr('name')+'</td><td style="padding: 5px;    text-align: right;"><input style="width:120px;" name="amountaccountex['+$(el).val()+']" value="'+a+'" /> ('+$("#currencyex option:selected").text()+')</td></tr></table>');
				}else{
					$('.exchangeaccount').append( '<table style="width: 500px;" ><tr><td style="padding: 5px" >IN/收: '+$(el).attr('name')+'</td><td style="padding: 5px;    text-align: right;"><input style="width:120px;" class="checkfulla" name="amountaccountex['+$(el).val()+']" value=""  /> ('+$("#currencyex option:selected").text()+')</td></tr></table>');
				}
			}).get();
			
		}
	});
	
	$( "body" ).on( "change", ".checkfulla", function() {	
		var check= 0;
		$('.checkfulla').each(function(){
			check += parseFloat($(this).val().replace(/\,/g, ''));
		});
		if( $('.fulamout').attr('a') < check || check == '' ){
			alert(' > Full Amount/全额 ');
			$('.checkfulla').val('');
		}
	});
	
	$("#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);
		}
	});
	
	$(".inorout").change(function(){
		var string = $(this).val()+'';
		
		if(string.indexOf("in") !== -1 ){
			$(this).parents('table').find('tr.rowin').show();
		}else{
			$(this).parents('table').find('tr.rowin').hide();
		}
		
		if(string.indexOf("out") !== -1 ){
			$(this).parents('table').find('tr.rowout').show();
		}else{
			$(this).parents('table').find('tr.rowout').hide();
		}
		
	});
	
	$(".shkabkasb").change(function(){
		if($(this).attr('id') == 'category'){
			jQuery('#categoryf').val($(this).val()); 
		}else if($(this).attr('id') == 'subcategory'){
			jQuery('#subcategoryf').val($(this).val()); 
		}else{
			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();
			$("#department").val('越南').change();
		}else{
			//$(".isdepartmentform").hide();
			$("#department").val('').change();
		}
		
		if($( ".sandjnas option:selected" ).hasClass('isspeci2')){
			$(".inputisspeci2").show();
		}else{
			$(".inputisspeci2").hide();
		}
		
		if($( ".sandjnas option:selected" ).hasClass('isspeci3')){
			$(".tygiausdtovnd").val('<?php echo $tygiausdtovnd; ?>');
			$(".inputisspeci3").show();
		}else{
			$(".inputisspeci3").hide();
			$(".tygiausdtovnd").val('');
		}
		
	});
	$(".sandjnas").change();

	
	$('.tab-link').on('click',function(){
		 $('.currentcur').text($(this).attr('currencyname'));	
		 $("#documentnumber").val('');$("#classification").val('');
		 $('.exchangeamout').hide();
		 $('.summarydiv').removeClass('s2').addClass('s3');
         $(".sandjnas").val($(this).attr("data-id")).change();
		 $("#acctiveaccount").val($(this).attr("data-id"));
		 $(".sandjnas").formSelect();
		 $("#classification").formSelect();
		 $(".formchiem").empty();
		 $(".exchangeaccount").empty();
		 $('#exchangeamout').val('');
		 $('#currencyex').val('').formSelect();
		 $("#tabsex").val('');
		 $("#tabsex").select2({width: "100%"});
		 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());
	});
	$(".exchangemoney3").click(function(){
		$(".exchangemoney3").removeClass('dnainpo');
		$("#monneyexchangerate").val($(this).attr('curexchange'));
		$("#amountexchange").val($(this).attr('maxmonney'));
		$("#idaccount").val($(this).attr('ref'));
		$(this).addClass('dnainpo');
	});
	$("#monneyexchangerate").blur(function(){
		if( parseFloat($(this).val()) <= 0  ){
			$(this).val('');
			alert("Exchange rate/汇率 > 0");
		}
	});
	$("#amountexchange").blur(function(){
		if( parseFloat($(this).val()) <= 0 || parseFloat($(this).val()) > parseFloat($('.dnainpo').attr('maxmonney'))){
			$(this).val('');
			alert("Amount/量 <= "+$('.dnainpo').attr('maxmonney') );
		}
	});
	
	
	$(".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);
		}
		
		if($(this).prev().attr('special3') == 1){
			$("#addNewTab #special3").prop('checked',true);
		}else{
			$("#addNewTab #special3").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;
	}

	function checkpad (str){
		 var a = '';	
		 $.get("index.php?checkveri=1&veri="+str, function(data, status){
			$("#documentnumber").val(str+data);
			a = data;
		 });	
		 return a;
	}
	
	$("#classification").change(function(){
		$('#charge').val('');$("#documentnumber").val('');$('.iopd').html("");
		jQuery('.makesimilar').empty();
		jQuery('.makesimilar').select2({width: "100%"});
		jQuery('#iscontinue').prop('checked',false);
		$("#documentnumber").removeAttr('readonly');
		$('.exchangeamout').hide();
		$('.summarydiv').removeClass('s2').addClass('s3');
		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');
		var cur = $( ".sandjnas option:selected" ).attr('cur');
		
		$('#currencyex option').prop('disabled',false);
		$('#currencyex option[value="'+cur+'"]').prop('disabled',true);
		
		$('#currencyex').formSelect();
		
		if( $( ".sandjnas option:selected" ).hasClass('isspeci') && $("#department").val() != '' ){
			location = $("#department").val();
		}
		location = '越南';
		var tabvalue = $( ".sandjnas" ).val();
		var date = "<?php echo date("ym"); ?>"+'';
		var date2 = $( "#dkasndlkas" ).val()+'';		
		date2 = date2.replace(/\./g, '');
		date2 = date2.substring(2, 10);
		
		if($(this).val() == "管理费用"){			
			if(location == '越南'){
				var num = $( ".nextvalue1越南" ).val();
				var miss = $( ".nextvalue1越南" ).attr('miss');
				var miss2 = $( ".nextvalue1越南" ).attr('miss2');
				if(num != miss && !$('.'+'VNG'+date+pad(miss, 3)).length && miss != 000 ){
					$('.iopd').html("<a href='#' onclick=\"$('#documentnumber').val('VNG"+date+pad(miss, 3)+"');\" >"+'VNG'+date+pad(miss, 3)+" is Missing. Click to use ?</a>");
					if(num != miss2 && !$('.'+'VNG'+date+pad(miss2, 3)).length && miss2 != 000 ){
						$('.iopd').append("<br><a href='#' onclick=\"$('#documentnumber').val('VNG"+date+pad(miss2, 3)+"');\" >"+'VNG'+date+pad(miss2, 3)+" is Missing. Click to use ?</a>");
					}
				}else{
					$('.iopd').html("");
				}
				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();
				var miss = $( ".nextvalue1中国" ).attr('miss');
				var miss2 = $( ".nextvalue1中国" ).attr('miss2');
				if(num != miss && !$('.'+'CNG'+date+pad(miss, 3)).length && miss != 000){
					$('.iopd').html("<a href='#' onclick=\"$('#documentnumber').val('CNG"+date+pad(miss, 3)+"');\" >"+'CNG'+date+pad(miss, 3)+" is Missing. Click to use ?</a>");
					if(num != miss2 && !$('.'+'CNG'+date+pad(miss2, 3)).length && miss2 != 000 ){
						$('.iopd').append("<br><a href='#' onclick=\"$('#documentnumber').val('CNG"+date+pad(miss2, 3)+"');\" >"+'CNG'+date+pad(miss2, 3)+" is Missing. Click to use ?</a>");
					}
				}else{
					$('.iopd').html("");
				}
				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();
				var miss = $( ".nextvalue1泰国" ).attr('miss');
				var miss2 = $( ".nextvalue1泰国" ).attr('miss2');
				if(num != miss && !$('.'+'THG'+date+pad(miss, 3)).length && miss != 000){
					$('.iopd').html("<a href='#' onclick=\"$('#documentnumber').val('THG"+date+pad(miss, 3)+"');\" >"+'THG'+date+pad(miss, 3)+" is Missing. Click to use ?</a>");
					if(num != miss2 && !$('.'+'THG'+date+pad(miss2, 3)).length && miss2 != 000){
						$('.iopd').append("<br><a href='#' onclick=\"$('#documentnumber').val('THG"+date+pad(miss2, 3)+"');\" >"+'THG'+date+pad(miss2, 3)+" is Missing. Click to use ?</a>");
					}
				}else{
					$('.iopd').html("");
				}
				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();
				var miss = $( ".nextvalue2越南" ).attr('miss');
				var miss2 = $( ".nextvalue2越南" ).attr('miss2');
				if(num != miss  && !$('.'+'VNS'+date+pad(miss, 3)).length && miss != 000){
					$('.iopd').html("<a href='#' onclick=\"$('#documentnumber').val('VNS"+date+pad(miss, 3)+"');\" >"+'VNS'+date+pad(miss, 3)+" is Missing. Click to use ?</a>");
					if(num != miss2  && !$('.'+'VNS'+date+pad(miss2, 3)).length && miss2 != 000){
						$('.iopd').append("<br><a href='#' onclick=\"$('#documentnumber').val('VNS"+date+pad(miss2, 3)+"');\" >"+'VNS'+date+pad(miss2, 3)+" is Missing. Click to use ?</a>");
					}
				}else{
					$('.iopd').html("");
				}
				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();
				var miss = $( ".nextvalue2中国" ).attr('miss');
				var miss2 = $( ".nextvalue2中国" ).attr('miss2');
				if(num != miss  && !$('.'+'CNS'+date+pad(miss, 3)).length && miss != 000){
					$('.iopd').html("<a href='#' onclick=\"$('#documentnumber').val('CNS"+date+pad(miss, 3)+"');\" >"+'CNS'+date+pad(miss, 3)+" is Missing. Click to use ?</a>");
					if(num != miss2  && !$('.'+'CNS'+date+pad(miss2, 3)).length && miss2 != 000){
						$('.iopd').append("<br><a href='#' onclick=\"$('#documentnumber').val('CNS"+date+pad(miss2, 3)+"');\" >"+'CNS'+date+pad(miss2, 3)+" is Missing. Click to use ?</a>");
					}
				}else{
					$('.iopd').html("");
				}
				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();
				var miss = $( ".nextvalue2泰国" ).attr('miss');
				var miss2 = $( ".nextvalue2泰国" ).attr('miss2');
				if(num != miss && !$('.'+'THS'+date+pad(miss, 3)).length && miss != 000){
					$('.iopd').html("<a href='#' onclick=\"$('#documentnumber').val('THS"+date+pad(miss, 3)+"');\" >"+'THS'+date+pad(miss, 3)+" is Missing. Click to use ?</a>");
					if(num != miss2 && !$('.'+'THS'+date+pad(miss2, 3)).length && miss2 != 000){
						$('.iopd').append("<br><a href='#' onclick=\"$('#documentnumber').val('THS"+date+pad(miss2, 3)+"');\" >"+'THS'+date+pad(miss2, 3)+" is Missing. Click to use ?</a>");
					}
				}else{
					$('.iopd').html("");
				}
				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();
				var miss = $( ".nextvalue3越南" ).attr('miss');
				var miss2 = $( ".nextvalue3越南" ).attr('miss2');
				if(num != miss && !$('.'+'VNF'+date+pad(miss, 3)).length && miss != 000){
					$('.iopd').html("<a href='#' onclick=\"$('#documentnumber').val('VNF"+date+pad(miss, 3)+"');\" >"+'VNF'+date+pad(miss, 3)+" is Missing. Click to use ?</a>");
					if(num != miss2 && !$('.'+'VNF'+date+pad(miss2, 3)).length && miss2 != 000){
						$('.iopd').append("<br><a href='#' onclick=\"$('#documentnumber').val('VNF"+date+pad(miss2, 3)+"');\" >"+'VNF'+date+pad(miss2, 3)+" is Missing. Click to use ?</a>");
					}
				}else{
					$('.iopd').html("");
				}
				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();
				var miss = $( ".nextvalue3中国" ).attr('miss');
				var miss2 = $( ".nextvalue3中国" ).attr('miss2');
				if(num != miss && !$('.'+'CNF'+date+pad(miss, 3)).length && miss != 000){
					$('.iopd').html("<a href='#' onclick=\"$('#documentnumber').val('CNF"+date+pad(miss, 3)+"');\" >"+'CNF'+date+pad(miss, 3)+" is Missing. Click to use ?</a>");
					if(num != miss2 && !$('.'+'CNF'+date+pad(miss2, 3)).length && miss2 != 000){
						$('.iopd').append("<br><a href='#' onclick=\"$('#documentnumber').val('CNF"+date+pad(miss2, 3)+"');\" >"+'CNF'+date+pad(miss2, 3)+" is Missing. Click to use ?</a>");
					}
				}else{
					$('.iopd').html("");
				}
				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();
				var miss = $( ".nextvalue3泰国" ).attr('miss');
				var miss2 = $( ".nextvalue3泰国" ).attr('miss2');
				if(num != miss && !$('.'+'THF'+date+pad(miss, 3)).length && miss != 000){
					$('.iopd').html("<a href='#' onclick=\"$('#documentnumber').val('THF"+date+pad(miss, 3)+"');\" >"+'THF'+date+pad(miss, 3)+" is Missing. Click to use ?</a>");
					if(num != miss2 && !$('.'+'THF'+date+pad(miss2, 3)).length && miss2 != 000){
						$('.iopd').html("<br><a href='#' onclick=\"$('#documentnumber').val('THF"+date+pad(miss2, 3)+"');\" >"+'THF'+date+pad(miss2, 3)+" is Missing. Click to use ?</a>");
					}
				}else{
					$('.iopd').html("");
				}
				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','');
		}	
		
		if($(this).val() == "汇入"){			
			
			if(location == '越南'){
				
				$("#documentnumber").val('VNI'+date2+checkpad('VNI'+date2));
				
			}
			if(location == '中国'){
				
				$("#documentnumber").val('CNI'+date2+checkpad('CNI'+date2));
				
			}
			if(location == '泰国'){
				
				$("#documentnumber").val('THI'+date2+checkpad('THI'+date2));
				
			}
			$("#documentnumber").attr('readonly','');
		}
		if(($('#classification').val() == "应收账款" || $('#classification').val() == "应付账款" || $('#classification').val() == "预收账款" || $('#classification').val() == "预付账款")){
			$('.writtenoff').show();
		}else{
			$('.writtenoff').hide();
		} 
		if($(this).val() == "汇出"){			
			//$('.chargefreetext').hide();
			$('.exchangeamout').show();
			if($('#idpayment').val() == '收'){
				$('.divpayout').show();
				$('.divpayin').hide();
				$('#amountincome').val('');	
				$('#idpayment').val('付').change();
				$('#idpayment').formSelect();
			}
			
			
			$('.summarydiv').removeClass('s3').addClass('s2');
			if(location == '越南'){
			
				$("#documentnumber").val('VNE'+date2+checkpad('VNE'+date2));
				
			}
			if(location == '中国'){
				
				$("#documentnumber").val('CNE'+date2+checkpad('CNE'+date2));
				
			}
			if(location == '泰国'){
				
				$("#documentnumber").val('THE'+date2+checkpad('THE'+date2));
				
			}
			$("#documentnumber").attr('readonly','');
		}
		
	});	
	<?php 	if ($currentuser->role == 'Finance' || $currentuser->gm == 1 || $currentuser->name == 'LEX') { ?>
		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 || $currentuser->name == 'LEX') { ?>
				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 }	?>
		}
	});
	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 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'  || $currentuser->name == 'LEX') {  ?>   
		$('.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').select2({width: "100%"});
			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').select2({width: "100%"});
			
			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').select2({width: "100%"});
		}
	});
	
	
	$( "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 } ?>	

	$(".dnoon").on('keyup change',function(){
		  var input, filter, table, tr, td, i, txtValue;
		  input = $(this).val();
		  filter = input.toUpperCase();
		  table = $(this).parents('table');
		  tr = table.find('tbody tr');
		  for (i = 0; i < tr.length; i++) {
				if($(this).attr('ref') == 1){
					td = tr[i].getElementsByTagName("td")[13];
				}
				if($(this).attr('ref') == 2){
					td = tr[i].getElementsByTagName("td")[22];
				}
				if($(this).attr('ref') == 3){
					td = tr[i].getElementsByTagName("td")[23];
				}
                                if($(this).attr('ref') == 4){
					td = tr[i].getElementsByTagName("td")[20];
				}
			   
			   if (td) {
				  txtValue = td.textContent || td.innerText;
                                  

				  if (txtValue.toUpperCase().indexOf(filter) > -1) {
					tr[i].style.display = "";
					tr[i].style.display = "";
				  } else {
					tr[i].style.display = "none";
				  }
				}
		  }
	});	
});
</script>
<div style="display:none;" class="companyinformation">
<form action="" method="POST" enctype="multipart/form-data" >
				<input value=""  id="id" name="id" type="hidden"  />
                <div class="row">                    
					
					<div class="input-field col s2" style="width: 20%;" >
                        <input 
                            value="<?php //echo $datacominfo['contractnumber']; ?>" 
                            id="contractnumber" 
                            name="contractnumber" 
                            type="text" 
                            class="validate"                           
                            required="required" 
							autocomplete="off" />
                        <label for="contractnumber">交接单/合同号</label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                           
                        </span>
                    </div>
					
					
					
					<div class="input-field col s2">
                           <input
                         value="" style="width:48%;float:left;"
                         id="validityperiod"
                         name="validityperiod"
                         type="text"
                         class="datepicker"
                         maxlength="<?php strlen($PICK); ?>"
                         data-length="<?php strlen($PICK); ?>" />
                           <span style="width:2%;float:left;padding-top: 13px;" >-</span>
                             <input
                         value="" style="width:45%;float:left;padding-left: 5px;"
                         id="validityperiod2"
                         name="validityperiod2"
                         type="text"
                         class="datepicker"
                         maxlength="<?php strlen($PICK); ?>"
                         data-length="<?php strlen($PICK); ?>" />
                           
                        <label for="validityperiod">有效期</label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                           
                        </span>
                    </div>
                    
                    
                    
                    <div class="input-field col s3 djbjd" style="    max-width: 20%;" >
                    <input 
                        value="" 
                        id="inforemarks" 
                        name="remarks" 
                        type="text" 
                        class="validate"                        
                        />
                    <label for="inforemarks"><?php echo $i18n["备注"]; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                       摘要
                    </span>
                </div>
                    
		<div class="input-field col s2">
                <?php //bank account ?>
                        <select name="corresponding[]" id="infocorresponding"  class="exclude" multiple >  
							<option value="">-----<?php echo $i18n["Corresponding"]; ?>-----</option>       
							<?php foreach ($corresponding as $rp){
                                                        if($rp->accept == 1){
                                                            ?>
							<option value="<?php echo $rp->id; ?>"><?php echo $rp->fullname; ?></option>  
                                                        <?php }} ?>	
					</select>	
                        <label for="infocorresponding"><?php echo $i18n["Corresponding"]; ?></label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                           
                        </span>
                    </div>
                    
                    <div class="input-field col s1">
                        <input 
                            value="" 
                            id="savepoint" 
                            name="savepoint" 
                            type="text" 
                            class="validate" 
                            maxlength="32" 
                            data-length="32" 
                            autocomplete="off" />
                        <label for="savepoint">保存点</label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                           
                        </span>
                    </div>
                    
                    <div class="input-field col s2  dhkasbdbas"  >
						<div class="file-field">
							<div class="btn btn-primary btn-sm float-left" style="padding: 3px;" >
								  <span><?php echo $i18n['Choose file']; ?></span>
								  <input type="file"  name="fileupload[]"  id="fileupload"  multiple="multiple" style="z-index: 1000;" >
							</div>
							<div class="file-path-wrapper">
							
							<div class="chips chips-initial input-field" style="    margin: 0;" >
								<input class="file-path validate" type="text" style="border-bottom: 0;" placeholder="<?php echo $i18n['Upload your file']; ?>">
							</div>
								 
							</div>
						</div>
					</div>
					
					
				
					
					<div class="input-field col s1" style="    text-align: right;    width: auto;    padding: 0;">
                        <button class="colortoptran btn waves-effect waves-light" type="submit" name="action">
                          Save
                        </button>
                    </div>		
                </div> 
                
                <input id="idcompanyinfo" name="id" type="hidden" value="">
                <input name="formcompanyinfo" type="hidden" value="1">
            </form>
    
    
    <table class="striped responsive-table  tablesorter" id="tab-table" style="border: 1px solid #000;" >
            <thead>
                <tr>
                    <th ></th>
                    <th >日期</th>
                    <th style="width: 15%" >交接单/合同号</th>
                    <th >有效期</th>
                    <th >摘要</th>
                    <th ><?php echo $i18n["Corresponding"]; ?></th>
                    <th >保存点</th>	
                    <th >附件</th>							
                    <th  style="border-right: 1px solid #1b278a;" >审核</th>
                </tr>			
            </thead>
            <tbody>
                <?php foreach ($companyinfo as $values){ 
                        $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>';
                                }
                        }
                    $date = date('y.m.d',$values['id']);
                    
                       $toast = 'M.toast({html: "<span>' . $values['requestnumber'] . '</span>' .
                '<a href=?formcompanyinfo_delete_id=' . $values['id']  . ' class=toast-action>' .
                $i18n['DELETE'] . '</a> &nbsp; &nbsp;"});';
				
                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 = '';
		}  
                       
                    ?>
                <tr>
                    <td>
                    <?php if ( $currentuser->gm == 1 || $values['status'] == '') { ?>
                        <a class="tooltipped" data-position="top" data-tooltip="<?= $i18n['EDIT'] ?>" href="#" onclick='editc("<?php echo addslashes(json_encode($values)); ?>")'><i class="grey-text small material-icons">mode_edit</i></a>
                    <?php
                    echo '<a href="#" onclick=\'' . $toast . '\'><i class="red-text text-darken-4 small ' .
                    'material-icons">delete_forever</i></a>'.$logsmode.'';
                    }
		 ?></td>
                    <td><?php echo '<span style="display:none;" >'.$values['id'].'</span><a href="#"  title="'.date('Y.m.d H:i:s',$values['id']).' '.$values['createby'].'" >' . $date .  '</a>'; ?></td>
                    <td><?php echo $values['contractnumber']; ?></td>
                    <td><?php echo $values['validityperiod']; ?><?php if($values['validityperiod2']){echo '-'.$values['validityperiod2'];} ?></td>
                    <td><?php echo $values['remarks']; ?></td>
                    <td><?php foreach ($values['corresponding'] as $rcorresponding){
			echo  '<a data-target="modal8" class="modal-trigger " ref="'.$rcorresponding.'" title="Code/代码：'.$corresponding_id[$rcorresponding]->code.'&#010;Abbreviation/简称：'.$corresponding_id[$rcorresponding]->abbreviation.'&#010;Fullname/全名:：'.$corresponding_id[$rcorresponding]->fullname.' " >'.$corresponding_id[$rcorresponding]->fullname.'</a> ';
		} 
                ?></td>
                    <td><?php echo $values['savepoint']; ?></td>	
                    <td><?php echo $file; ?></td>							
                    <?php 
                    if( $cannotedit == 1 || ($currentuser->role == 'Operator' && !in_array($tab->id,$currentuser->account) && in_array($tab->id,$currentuser->accountreadonly))){
					if($values['status'] == ''){
						echo  '<td style="padding-left:6px!important;" >'.$i18n['等待财务完成'].'</td>';
					}elseif($values['status'] == 'pending'){
						echo  '<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'){
						echo  '<td style="padding-left:6px!important;" ><a href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">'.$i18n['已审核'].' by '.$values['controlerapproval'].'</a></td>';
					}elseif($values['status'] == 'notapproval'){
						echo  '<td style="padding-left:6px!important;" ><a style="color:red;" href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">'.$i18n['未通过'].' by '.$values['controlerapproval'].'</a></td>';
					}
			}else{
				if($currentuser->role == 'Operator'){
					if($values['status'] == ''){
						echo  '<td><button style="width:100%;" id="'.$values['id'].'" onclick="$(\'.typeapp\').val(1);" class="btn waves-effect waves-light sendtoaproval ">发送</button></td>';
					}elseif($values['status'] == 'pending'){
						echo  '<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'){
						echo  '<td style="padding-left:6px!important;" ><a href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">'.$i18n['已审核'].' by '.$values['controlerapproval'].'</a></td>';
					}elseif($values['status'] == 'notapproval'){
						echo  '<td style="padding-left:6px!important;" ><a href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">'.$i18n['未通过'].' by '.$values['controlerapproval'].'</a></td>';
					}
				}
				
				if($currentuser->role == 'Finance'  || $currentuser->name == 'LEX' ){
					if($values['status'] == ''){
						echo  '<td style="padding-left:6px!important;" ><button style="width:100%;" onclick="$(\'.typeapp\').val(1);" id="'.$values['id'].'" class="btn waves-effect waves-light sendtoaproval ">发送</button></td>';
					}elseif($values['status'] == 'pending'){
						echo  '<td><button id="'.$values['id'].'" title="'.$values['financeclicktoapproval'].' - '.date('Y.m.d H:i',$values['financeclicktoapprovaltime']).'" onclick="$(\'.typeapp\').val(1);" id="'.$values['id'].'" class="btn waves-effect waves-light approval">Yes</button><button  id="'.$values['id'].'" title="'.$values['financeclicktoapproval'].' - '.date('Y.m.d',(int)$values['financeclicktoapprovaltime']).'" id="'.$values['id'].'"  onclick="$(\'.typeapp\').val(1);" class="btn red waves-effect waves-light deny">No</button></td>';				
					}elseif($values['status'] == 'approval'){
						echo  '<td style="padding-left:6px!important;" ><a href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">'.$i18n['已审核'].' by '.$values['controlerapproval'].'</a><button style="width:100%;    background: #a0a0a0;" id="'.$values['id'].'" onclick="$(\'.typeapp\').val(1);" class="btn btn-danger waves-effect waves-light sendtoaproval ">'.$i18n['rollback'].'</button></td>';
					}elseif($values['status'] == 'notapproval'){
						echo  '<td style="padding-left:6px!important;" ><a style="color:red;" href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">'.$i18n['未通过'].' by '.$values['controlerapproval'].'</a><button style="width:100%;    background: #a0a0a0;" id="'.$values['id'].'" onclick="$(\'.typeapp\').val(1);" class="btn btn-danger waves-effect waves-light sendtoaproval ">'.$i18n['rollback'].'</button></td>';
					}elseif($values['status'] == 'cancel'){
						echo  '<td style="padding-left:6px!important;" ></td>';
					}
				}elseif($currentuser->gm == 1){
					if($values['status'] == ''){
						echo  '<td style="padding-left:6px!important;" >'.$i18n['等待财务完成'].'</td>';
                                                
					}elseif($values['status'] == 'pending'){
						echo  '<td><button id="'.$values['id'].'" title="'.$values['financeclicktoapproval'].' - '.date('Y.m.d H:i',$values['financeclicktoapprovaltime']).'" id="'.$values['id'].'" onclick="$(\'.typeapp\').val(1);" class="btn waves-effect waves-light approval">Yes</button><button  id="'.$values['id'].'" title="'.$values['financeclicktoapproval'].' - '.date('Y.m.d',(int)$values['financeclicktoapprovaltime']).'" id="'.$values['id'].'" onclick="$(\'.typeapp\').val(1);" class="btn red waves-effect waves-light deny">No</button></td>';				
					}elseif($values['status'] == 'approval'){
						echo  '<td style="padding-left:0px!important;" ><a href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">'.$i18n['已审核'].': '.$values['controlerapproval'].'</a><button style="width:100%;    background: #a0a0a0;" id="'.$values['id'].'" onclick="$(\'.typeapp\').val(1);" class="btn btn-danger waves-effect waves-light sendtoaproval ">'.$i18n['rollback'].'</button></td>';
					}elseif($values['status'] == 'notapproval'){
						echo  '<td style="padding-left:0px!important;" ><a style="color:red;" href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">'.$i18n['未通过'].': '.$values['controlerapproval'].'</a><button style="width:100%;    background: #a0a0a0;" id="'.$values['id'].'" onclick="$(\'.typeapp\').val(1);" class="btn btn-danger waves-effect waves-light sendtoaproval ">'.$i18n['rollback'].'</button></td>';
					}elseif($values['status'] == 'cancel'){
						echo  '<td style="padding-left:0px!important;" onclick="$(\'.typeapp\').val(1);" class="revision" >'.$values['controlerapproval'].' 请求返回 <button style="width:80%;    background: #ffee58;    color: #000;" id="'.$values['id'].'" onclick="$(\'.typeapp\').val(1);" class="btn waves-effect waves-light pulse  sendtoaproval darken-2 ">是</button></td>';
					}
				}elseif($currentuser->role == 'Manager'){
					if($values['status'] == ''){
						echo  '<td style="padding-left:6px!important;" >'.$i18n['等待财务完成'].'</td>';
					}elseif($values['status'] == 'pending'){
						echo  '<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'){
						echo  '<td style="padding-left:6px!important;" ><a href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">'.$i18n['已审核'].': '.$values['controlerapproval'].'</a></td>';
					}elseif($values['status'] == 'notapproval'){
						echo  '<td style="padding-left:6px!important;" ><a style="color:red;" href="#" title="'.date('y.m.d H:i',$values['controlerapprovaltime']).'">'.$i18n['未通过'].': '.$values['controlerapproval'].'</a></td>';
					}elseif($values['status'] == 'cancel'){
						echo  '<td style="padding-left:6px!important;" ><button style="width:100%;" id="'.$values['id'].'" onclick="$(\'.typeapp\').val(1);" class="btn waves-effect waves-light sendtoaproval ">'.$i18n['Go Back'].'</button></td>';
					}
				}
			}
                    
                    ?>
                <?php } ?>
            </tbody>
    </table>        
</div>


<script>
$(document).ready(function(){
    <?php if($_GET['typeapp'] == 1 || $_POST['formcompanyinfo'] == 1 || $_POST['formcompanyinfo_delete_id'] == 1){ ?>
    $('.ckasnklcasnl').trigger('click');
    <?php } ?>        
    $('.chips').chips();
});         
function editc(id) {

var obj = jQuery.parseJSON(id);
$('#idcompanyinfo, #contractnumber, #validityperiod , #validityperiod2 , #inforemarks, #savepoint').next().addClass('active');
$('#idcompanyinfo').val(obj.id);
$('#contractnumber').val(obj.contractnumber);
$('#validityperiod').val(obj.validityperiod);
$('#validityperiod2').val(obj.validityperiod2);
$('#inforemarks').val(obj.remarks);
$('#savepoint').val(obj.savepoint);
$('.chip').remove();
$('.file-path').addClass('isacctive');
if (typeof obj.filename != 'undefined'){
$.each( obj.filename, function( key, value ) {
  $('.chips').prepend('<div class="chip" tabindex="0"><input type="hidden" name="filename[]" value="'+value+'" /><i style="cursor: pointer;" class="fas fa-times"></i> '+value+'</div>');
});
}

$('#infocorresponding').val(obj.corresponding);
$('select:not(.exclude):not(#status)').formSelect();
						
}

$( "body" ).delegate( '.chips i' , "click", function() {

    $(this).parents().eq(0).remove();
});
</script>
<style>
.chip {
    z-index: 1001;
    position: relative;
    max-width: 130px;
    overflow: hidden;
    margin-bottom: -9px;
}
.chip i{
	    color: red;
}
ul.tabs li.ishide{
    display:none!important;
}    
.select2-container--open .select2-dropdown--below {   
    min-width: 100px;
}
.ui-widget-header {
  
    background: #ba0000;
      color: #fff;
    border-radius: 5px;
}
</style>
<div style="display:none" class="asbkdbsak" ></div>
<?php if($_GET['onlyform'] != 1) { ?>
<table style="display:none" ><tr class="formchiem" > <tr><table>
<br>

<?php } ?>

<?php if($_SESSION['showlogin'] == '') { 
    $_SESSION['showlogin'] = '1';
    
    ?>
<div id="notification" style="display: none;background: #fffee3;font-size: 16px;"  title="注意力/Attention" >
  <span class="dismiss">
    <b>1.</b> 日记账的原则：实事求是（实际的时间，真实的“往来单位”实际的“收/付款人”实际的单据，实际进出账笔数，实际的金额，每笔交易单独录入，不允许将交易合并录入或合并账单）。
    <br>
    <b>2.</b> 每日17：00点之前发生的交易必须在当天完成录入，17:00点后发生的交易必须在次日上午9:00点前完成录入。
    <br>
    <b>3.</b> 在财务系统上录入时，必须明确选择“往来单位” 它代表的是我们往来的“对象”“往来单位”和“收/付款人”可以是同一个人/公司，也可以不是同一个人/公司。
    <br>
    <b>4.</b> 当日最后一笔交易必须附上账户余额的图片。
    <br>
   <b> 5.</b> 公司使用的个人越南盾账户余额必须控制在10亿越南盾以下。如果账户余额超过10亿越盾，主管将被罚款，罚款金额为超出限额的金额0.5%。如果下属员工未经过部门负责人确认就转入款项，该员工将承担上述罚款责任。
    <br>
    <b>6.</b> 所有的收付交易必须在“Zalo财务收付款”群里进行，不允许私聊，以便接受监督。对于现金支出，必须在收支账簿上签字确认，并在当天下班前拍照发送到“Zalo财务收付款”群里。
    <br>
    <b>7.</b> 日记账上业务操作完成发送及审核时限如下：
    - 管理费用、财务费用、应收账款、结汇产生代收、代付、借款收入、内部转账、汇出、汇入取现等业务必须在当天内录齐（如果是当天下班后产生的，可以放在第二天完成），隔天内完成发送及审核工作；例如：周一当天的日记账当天录齐，周三审核完毕。<br>
    - 付税金、报关费、车队业务由于供应商对账单处理时间影响需在5工作日内完成发送，7个工作日内完成审核。
</div>
<script>
  $("#notification").dialog({
   
   width: "1024px",
   maxWidth: "1024px"
});
</script>

<?php } ?>

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