<?php
date_default_timezone_set('Asia/Bangkok');
session_start();
ob_start();
require 'setup/config.php';
$currency = json_decode(file_get_contents('../Docs/data/Currency.json'), true);
// SET LANGUAGE

$LANG =  'cn';
// SET LANGUAGE
if (isset($_GET['lang'])){	
	$_SESSION['HTTP_ACCEPT_LANGUAGE'] = $_GET['lang'];
}
if (isset($_SESSION['HTTP_ACCEPT_LANGUAGE']) and file_exists('lang/' . $_SESSION['HTTP_ACCEPT_LANGUAGE'] . '.php')) {	
	if((@include 'lang/' . $_SESSION['HTTP_ACCEPT_LANGUAGE'] . '.php') === false){
		echo 'Caught exception: Translate file is wrong';
	}else{
		@include_once('lang/' . $_SESSION['HTTP_ACCEPT_LANGUAGE'] . '.php');
	}
} else {
	if((@include 'lang/' . $LANG . '.php') === false){
		echo 'Caught exception: Translate file is wrong';
	}else{
		@include_once('lang/' . $LANG . '.php');
	}
}

// INI VARs
$file = 'data/' . $TYPE . '.json'; // DATA FILE NAME
// LOGIN CHECK
session_start();
$login = check_current_user_login($ARR_USERS, $SALT);
$currentuser = $login['user'];
//var_dump($login);
if($login['status'] == 200){
//    if($currentuser->role != 'Ma'){        
//        header('location: index.php');
//        exit;
//    }
    //var_dump($login);
}else{
    header('location: login.php');
    exit;
}
$tabs = json_decode(file_get_contents('data/Tabs.json'));
$tabdoc = json_decode(file_get_contents('data/TabDoc.json'));
$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'));
/*$sessionname = md5($USER . $SALT);
if (!@$_SESSION[$sessionname]) {
    header('location: login.php');
    exit;
}*/
// READ DATA


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

if ($_SERVER['REQUEST_METHOD'] == 'POST' and @ $_POST['payment'] != '' ) {
    $jsonString = file_get_contents($file);
    $data = json_decode($jsonString, true);
    foreach ($data as $key => $entry) {
        if ($entry['id'] == $_GET['id']) {
			if($currentuser->role == 'Operator' && ( $data[$key]['status'] == 'approval' || $data[$key]['status'] == 'pending' )){
				continue;
			}
			$_POST['amountincome'] = str_replace(',','',$_POST['amountincome']);
			$_POST['amountpayout'] = str_replace(',','',$_POST['amountpayout']);
			// write logs
			foreach ($data[$key] as $keylog => $logs ){
				if($keylog == 'filename' || $keylog == 'filetype' || $keylog == 'filesize' || $keylog == 'filetimeupload' || $keylog == 'filecreatebyid' 
				|| $keylog == 'filecreatebyid' || $keylog == 'filecreatebyname' || $keylog == 'filepath' || $keylog == 'modifybyid' 
				|| $keylog == 'modifybyname' || $keylog == 'timemodify' || $keylog == 'id' || $keylog == 'createbyname' || $keylog == 'createbyid' 
				|| $keylog == 'controlerapprovaltime' || $keylog == 'financeclicktoapprovaltime' || $keylog == 'financeclicktoapproval' || $keylog == 'controlerapproval'				){
					continue;
				}elseif( $_POST[$keylog] != $logs){
					if($_POST[$keylog] == ''){ 
						$textlog = date('Y-m-d H:i:s').' - '.$currentuser->name.': changed '.$keylog.' from '.$logs.' to empty'  ;
					}else{
						$textlog = date('Y-m-d H:i:s').' - '.$currentuser->name.': changed '.$keylog.' from '.$logs.' to '.$_POST[$keylog]  ;
					}
					file_put_contents('logs/'.$entry['id'],file_get_contents('logs/'.$entry['id']).$textlog.PHP_EOL);
				}
			}
			foreach ( $data[$key]['filepath']  as $filekey => $fileu ){
				
			if(!in_array($fileu, $_POST['filepath'])){
					 
					 unset($data[$key]['filename'][$filekey]);
					 unset($data[$key]['filetype'][$filekey]);
					 unset($data[$key]['filesize'][$filekey]);
					 unset($data[$key]['filetimeupload'][$filekey]);
					 unset($data[$key]['filecreatebyid'][$filekey]);
					 unset($data[$key]['filecreatebyname'][$filekey]);
					 unset($data[$key]['filepath'][$filekey]);
					 
					 $data[$key]['filename'] = array_values($data[$key]['filename']);
					 $data[$key]['filetype'] = array_values($data[$key]['filetype']);
					 $data[$key]['filesize'] = array_values($data[$key]['filesize']);
					 $data[$key]['filetimeupload'] = array_values($data[$key]['filetimeupload']);
					 $data[$key]['filecreatebyid'] = array_values($data[$key]['filecreatebyid']);
					 $data[$key]['filecreatebyname'] = array_values($data[$key]['filecreatebyname']);
					 $data[$key]['filepath'] = array_values($data[$key]['filepath']);
				 }
			 }
		
			 if(count((array)$_FILES['fileupload']['name']) > 0 && $_FILES['fileupload']['error'][0] == 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 ){ continue; }
					
					 $filename = time().'_'.$fileu;
					 $data[$key]['filename'][] = $fileu;
					 $data[$key]['filetype'][] = $_FILES['fileupload']['type'][$filekey];
					 $data[$key]['filesize'][] =  $_FILES['fileupload']['size'][$filekey];
					 $data[$key]['filetimeupload'][] = time();
					 $data[$key]['filecreatebyid'][] = $currentuser->id;
					 $data[$key]['filecreatebyname'][] = $currentuser->name;
					 $data[$key]['filepath'][] = $filename;
					 copy( $_FILES['fileupload']['tmp_name'][$filekey] , __DIR__.'/uploads/'.$filename );
				 }
			 }else{				
				$data[$key]['filepath'] = array_values($_POST['filepath']);			
				$data[$key]['filename'] = array_values($_POST['filename']);
				$data[$key]['filetype'] = array_values($_POST['filetype']);
				$data[$key]['filesize'] = array_values($_POST['filesize']);
				$data[$key]['filetimeupload'] = array_values($_POST['filetimeupload']);
				$data[$key]['filecreatebyid'] = array_values($_POST['filecreatebyid']);
				$data[$key]['filecreatebyname'] = array_values($_POST['filecreatebyname']);
			}		 
			
            //$data[$key]['date'] = $_POST['date'];
            $data[$key]['payment'] = $_POST['payment'];
            $data[$key]['settime'] = $_POST['settime'];
            
            $data[$key]['account'] = $_POST['account'];
            //$data[$key]['currency'] = $_POST['currency'];
			$data[$key]['baddebt'] =  $_POST['baddebt'];
            $data[$key]['department'] =  $_POST['department'];
			$data[$key]['classification'] =  $_POST['classification'];
			$data[$key]['charge'] =  $_POST['charge'];
			
			
			
			$data[$key]['exchangeusdtovnd'] =  $_POST['exchangeusdtovnd'];
			$data[$key]['amountincomeusd'] =  $_POST['amountincomeusd'];
			$data[$key]['amountpayoutusd'] =  $_POST['amountpayoutusd'];
			
			$data[$key]['summary'] =  $_POST['summary'];
			$data[$key]['amountincome'] =  str_replace(',','',$_POST['amountincome']);
			$data[$key]['amountpayout'] =  str_replace(',','',$_POST['amountpayout']);
			$data[$key]['corresponding'] =  $_POST['corresponding'];
			if($_POST['payer_more'] == ''){
				$data[$key]['payer'] =  $_POST['payer'];
			}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) );
				$data[$key]['payer'] = array($idre)	;
			}
			
			$data[$key]['requestnumber'] =  $_POST['requestnumber'];
			$data[$key]['documentnumber'] =  $_POST['documentnumber'];
			$data[$key]['jobnumber'] =  $_POST['jobnumber'];
			$data[$key]['fee'] =  $_POST['fee'];
			
			if($data[$key]['tabs'] != $_POST['tabs']){
				mail("rimbah@iexodus.com","Toptrans Changed account balance id:".$entry['id'],file_get_contents('logs/'.$entry['id']));
			}
			
			if($_POST['tabs'] > 0){
				$data[$key]['tabs'] =  $_POST['tabs'];
			}
			
			if($currentuser->role != 'Operator' ){
				$data[$key]['remarks'] =  $_POST['remarks'];
			}else{
				if($_POST['remarks'] != ''){
					$data[$key]['remarks'] .= $data[$key]['remarks'].PHP_EOL.$_POST['remarks'];
				}
			}
			$data[$key]['writtenoff'] =  $_POST['writtenoff'];
			$data[$key]['location'] =  $_POST['location'];
			$data[$key]['modifybyid'] =  $currentuser->id;
			$data[$key]['modifybyname'] =  $currentuser->name;
			$data[$key]['timemodify'] =  time();
			if($currentuser->role == 'Operator' && $data[$key]['status'] == 'notapproval' ){
				$data[$key]['status'] = '';
			}
			
			if( $currentuser->gm == 1 || ( $currentuser->name == 'LEX' &&  time() - $_POST['idreplace'] < 86400*30 &&  time() - $_POST['idreplace'] > 0 )  || ( $currentuser->name == 'DANNA' &&  time() - $_POST['idreplace'] < 86400*60 &&  time() - $_POST['idreplace'] > 0 ) ) {
                                if($_POST['id_invoice'] != '' ){
				$data[$key]['id_invoice'] = $_POST['id_invoice'];
                                }
				if($_POST['idreplace'] != '' && $_POST['idreplace'] != $data[$key]['id']){
                                    $data[$key]['id'] = $_POST['idreplace'];
                                }
			}
			
			//if($entry['id'] == '1610425013'){
			//	$data[$key]['id_invoice'] =  '1610426043';
			//}
          
        }
    }
    
    $tabdocfull =  json_decode(file_get_contents('data/TabDoc.json'),true);
    
    foreach ($tabdocfull as $vt => $tb) {
        if($tb->iddoc == $_POST['id']){
             unset($tabdocfull[$vt]);
        }
    }
    
    $tabdocfull = array_values($tabdocfull);
    if ($_POST['tabs']){
        $tabdocfull[] = array(
            'iddoc' => $_POST['id'],      
            'idtab' => $_POST['tabs'],
        );    
    }
    file_put_contents('data/TabDoc.json', json_encode($tabdocfull)); 

    
    
    $newJsonString = json_encode($data);
	copy(__DIR__.'/data/Documents.json',__DIR__.'/data/Documents_bk.json');
    file_put_contents($file, $newJsonString);
    //header('location: index.php?msg=' . $i18n['Entry successfully edited!']);
?>
	<script type="text/javascript">
		window.parent.closeiframereload();
	</script>
<?php 
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $_GET['msg'] = $i18n['All fields are required!'];
}


$jsonString = file_get_contents($file);
$data = json_decode($jsonString, true);

// GENERATE LIST FOR DATA-LIST IN NAME INPUT FIELD
foreach ($data as $key => $values) {
    //$list .= '<option value="' . $values['name'] . '">';
}

// HEADER
ob_end_flush();
include 'tpl/header.php';


foreach ($tabdoc as $r){
      if (  $data[@$_GET['id']]['id'] == $r->iddoc ) {
			foreach($tabs as $tab){
				 if($tab->id == $r->idtab){
					 break;
				 }
			}
            if( $currentuser->gm != 1 && $tab->iduser != $currentuser->id && !in_array($r->idtab,$currentuser->account) ) { 			
				?>
				<script type="text/javascript">
					window.parent.closeiframereload();
				</script>
				<?php
				exit();
			}    
      }
}

// FORM FOR EDIT ENTRY


?>
<style>
.navbar-fixed , .page-footer {
	display:none;
}
body {
    background: #eeeeee;
}
main {
    padding: 0px;
}
.helper-text {
    display: none!important;
}
td, th {
    padding: 5px 5px;
   
}
.row {
	margin:0px;
}
.disabled {
	display:none;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<?php
	foreach ($data as $r ){
		$data2[$r['id']] = $r;
	}
	$data = $data2;
	
if( $currentuser->name != 'DANNA' && ($currentuser->role == 'Operator' || $currentuser->role == 'Finance') && $data[@$_GET['id']]['status'] != '' && $data[@$_GET['id']]['status'] != 'notapproval' ){
	echo 'Status '.$data[@$_GET['id']]['status'].' Order Can\'t edit';die;
}		
 ?>
<div class="badge grey lighten-3 " style="padding: 0px 1em;">
       <form method="POST" enctype="multipart/form-data" >
<input type="text" style="display:none;" name="idreplace"  id="idreplace" value="<?php echo $_GET['id']; ?>" />   
<input type="text" style="display:none;" name="settime" id="settime" value="<?php echo $data[@$_GET['id']]['settime']; ?>" />   
        <div class="row">
                               
				<div class="input-field col s1">                  
					<select name="payment" id="idpayment"  tabindex="-1">         
							<option <?php if($data[@$_GET['id']]['payment'] == '收' ){ echo 'selected=""';} ?> value="收">收</option>                  
                       		<option <?php if($data[@$_GET['id']]['payment'] == '付' ){ echo 'selected=""';} ?> value="付">付</option>
					</select>
                    <label for="idpayment">收付</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                         Payment
                    </span>
					
                </div>
				<div class="input-field col s1 isdepartmentform"  >
					<select name="department" id="department"   >  
							<option value="">----------</option>       
							<option <?php if($data[@$_GET['id']]['department'] == '越南' ){ echo 'selected=""';} ?>  value="越南">越南</option>    
							<option <?php if($data[@$_GET['id']]['department'] == '中国' || $data[@$_GET['id']]['department'] == '国内' ){ echo 'selected=""';} ?>  value="中国">中国</option>  
							<option <?php if($data[@$_GET['id']]['department'] == '泰国' ){ echo 'selected=""';} ?>  value="泰国">泰国</option>  						
                                                        <option <?php if($data[@$_GET['id']]['department'] == '印尼' ){ echo 'selected=""';} ?>  value="印尼">印尼</option>  						
                                                        <option <?php if($data[@$_GET['id']]['department'] == '马来西亚' ){ echo 'selected=""';} ?>  value="马来西亚">马来西亚</option>  						
					</select>	
                    <label for="charge">部门</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Enter department
                    </span>
                </div>
                <div class="input-field col s2">
                    <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 $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]);
										$data[@$_GET['id']]['classification'] = str_replace(array("\n","\r\n","\r",PHP_EOL,' '), '',$data[@$_GET['id']]['classification']);
                                        ?> 
                                            <option <?php if(strpos($container_op[0],$data[@$_GET['id']]['classification']) !== false ){ echo 'selected="selected"';} ?> value="<?php echo $container_op[0]; ?>"  freetext="<?php echo $container_op[2]; ?>" color="<?php echo $container_op[1]; ?>" ><?php echo $container_op[0]; ?></option>
                                        <?php
                                    }
                            ?>

					</select>
                    <label for="classification">费用归类 </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"  >           
							<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>';
										}
										
										if($data[@$_GET['id']]['charge'] == $subContainer[1]){
											$selected = "selected";
										}else{
											$selected = "";
										}
                                        ?> 
                                            <option <?php echo $selected; ?> 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">费用明细 </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="<?php echo $data[@$_GET['id']]['charge']; ?>" 
                        id="chargefreetext" 
                        name="charge" 
                        type="text" 
                        class="validate"    
						disabled
                        />
                    <label for="chargefreetext">费用明细 </label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Enter Charge Details
                    </span>
                </div>
			

		


		

		<div class="input-field col s2">
                    <input 
                        value="<?php echo $data[@$_GET['id']]['summary']; ?>" 
                        id="summary" 
                        name="summary" 
                        type="text" 
                        class="validate" 
                       
                        />
                    <label for="summary">摘要</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Enter Summary
                    </span>
                </div>
              
				<?php if( $data[@$_GET['id']]['exchangeusdtovnd'] > 0 ){ ?>
				
				 <div class="input-field col s2">
                    <input 
						
                        value="<?php echo $data[@$_GET['id']]['exchangeusdtovnd']; ?>" 
                        id="exchangeusdtovnd" 
                        name="exchangeusdtovnd" 
                        type="text" 
                        class="validate" 
                       placeholder="0.00"
                        />
                    <label for="exchangeusdtovnd">usd to vnd</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Amount of income
                    </span>
                </div>
				
				<?php } ?>
				<?php if( $data[@$_GET['id']]['amountincomeusd'] > 0 ){ ?>
				
				 <div class="input-field col s2">
                    <input 
						
                        value="<?php echo $data[@$_GET['id']]['amountincomeusd']; ?>" 
                        id="amountincomeusd" 
                        name="amountincomeusd" 
                        type="text" 
                        class="validate" 
                       placeholder="0.00"
                        />
                    <label for="amountincomeusd">收入金额 USD</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Amount of income
                    </span>
                </div>
				
				<?php } ?>
				<?php if( $data[@$_GET['id']]['amountpayoutusd'] > 0 ){ ?>
				
				 <div class="input-field col s2">
                    <input 
						
                        value="<?php echo $data[@$_GET['id']]['amountpayoutusd']; ?>" 
                        id="amountpayoutusd" 
                        name="amountpayoutusd" 
                        type="text" 
                        class="validate" 
                       placeholder="0.00"
                        />
                    <label for="amountpayoutusd">支出金额 VND</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Amount of payout
                    </span>
                </div>
				
				<?php } ?>

                <div class="input-field col s2">
                    <input 
						
                        value="<?php echo $data[@$_GET['id']]['amountincome']; ?>" 
                        id="amountincome" 
                        name="amountincome" 
                        type="text" 
                        class="validate" 
                       placeholder="0.00"
                        />
                    <label for="amountincome">收入金额</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Amount of income
                    </span>
                </div>
                <div class="input-field col s2">
                    <input 
						data-type='currency'
                        value="<?php echo $data[@$_GET['id']]['amountpayout']; ?>" 
                        id="amountpayout" 
                        name="amountpayout" 
                        type="text" 
                        class="validate" 
                        placeholder="0.00"
                        />
                    <label for="amountpayout">支出金额</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Amount of payout
                    </span>
                </div>
               <div class="input-field col s2" style=" width: 23%;height: 75px;overflow: auto;" >
					<select name="corresponding[]" id="corresponding"  class="exclude" multiple  >  
							<option value="">-----往来单位-----</option>       
							<?php 
							if(!is_array($data[@$_GET['id']]['corresponding'])){ $data[@$_GET['id']]['corresponding'] =  array($data[@$_GET['id']]['corresponding']); }
							foreach ($corresponding as $rp){ if( $rp->id == '' || $rp->code == '' ) { continue; }
							if( in_array($rp->id,$data[@$_GET['id']]['corresponding']) ){ $select='selected';} else{ $select='';}  ?>
							<option <?php echo $select; ?> value="<?php echo $rp->id; ?>"><?php echo $rp->code; ?>-<?php echo $rp->abbreviation; ?></option>  
							<?php } ?>	
					</select>	
				</div>	
				<div class="input-field col s2" style=" width: 23%;margin-top: -16px;height: 75px;overflow: auto;" >
					<select name="payer[]" id="payer"  class="exclude" multiple  >  
							<option value="">-----<?php echo $i18n["收付款人"]; ?>-----</option>       
							<option value="addmore">+ Add more</option>    
							<?php 
							if(!is_array($data[@$_GET['id']]['payer'])){ $data[@$_GET['id']]['payer'] =  array($data[@$_GET['id']]['payer']); }
							foreach ($receiver_payer as $rp){ if( $rp->id == '' || $rp->name == '' ) { continue; }
							if( in_array($rp->name,$data[@$_GET['id']]['payer']) || in_array($rp->id,$data[@$_GET['id']]['payer']) ){ $select='selected';} else{ $select='';}  ?>
							<option <?php echo $select; ?> 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>
                    <span class="helper-text" data-error="Error" data-success="OK">
                         Payer
                    </span>
                </div>

            
                 <div class="input-field col s3" >
                    <input 
                        value="<?php echo $data[@$_GET['id']]['requestnumber']; ?>" 
                        id="requestnumber" 
                        name="requestnumber" 
                        type="text" 
                        class="validate" 
                      
                        />
                    <label for="requestnumber">请款单号</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="<?php echo $data[@$_GET['id']]['jobnumber']; ?>" 
                        id="jobnumber" 
                        name="jobnumber" 
                        type="text" 
                        class="validate" 
                       
                        />
                    <label for="jobnumber">工作号</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                       Job number
                    </span>
                </div>
				<?php } ?>
                    <div class="input-field col s2">
                    <input 
                        value="<?php echo $data[@$_GET['id']]['documentnumber']; ?>" 
                        id="documentnumber" 
                        name="documentnumber" 
                        type="text" 
                        class="validate" <?php if ($currentuser->gm != '1' && $currentuser->name != 'DANNA' ) {  ?> readonly <?php } ?>
                       
                        />
                    <label for="documentnumber">凭证号</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                       Document number
                    </span>
                </div>


				<div class="input-field col s1"  >
					<select name="writtenoff" id="writtenoff"   >  
							<option value="">----------</option>       
							<option <?php if($data[@$_GET['id']]['writtenoff'] == '是' ){ echo 'selected=""';} ?> value="是">是</option>    
							<option <?php if($data[@$_GET['id']]['writtenoff'] == '没有' ){ echo 'selected=""';} ?> value="没有">没有</option>  							
					</select>	
                    <label for="charge">是否核销</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Is it written off?
                    </span>
                </div>
				<div class="input-field col s1" style="  min-width: 120px;  margin: 0;" >
					<label class="pure-material-checkbox" style="margin-top: 16px;" >
						  <input type="checkbox"  value="1"  id="idbaddebt"  <?php if( $data[@$_GET['id']]['baddebt'] == 1){ echo 'checked'; } ?>  name="baddebt"  >
						  <span><?php echo $i18n["坏账损失"];  ?></span>
					</label>
				</div>
                   
				<?php if($currentuser->role != 'Operator' ){ ?>
                    <div class="input-field col s2" >
                    <textarea 
                        id="remarks" 
                        name="remarks" 
                        type="text" 
                        class="validate" 
                     
                        ><?php echo $data[@$_GET['id']]['remarks']; ?></textarea>
                    <label for="remarks">备注</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                       Remarks
                    </span>
                </div>
				<?php }else{ ?>
					 <div class="input-field col s3" >
						<input 
							id="remarks" 
							name="remarks" 
							type="text" 
							class="validate" 
							value=""
							/>
						<label for="remarks">备注</label>
						<span class="helper-text" data-error="Error" data-success="OK">
						   Remarks
						</span>
					</div>
				<?php } ?>

            <div class="input-field col s2">
                    <select name="tabs" id="tabs"  class="sandjnas" onchange="alert('Please! Your change will affect balance of 2 accounts/您的更改将影响2个帐户的余额')" >
                        <option value="">-- Select Account --</option>';
                        <?php                         
                            foreach($tabs as $tab){
								$selected = '';
								if( $currentuser->gm != 1 && $tab->iduser != $currentuser->id && !in_array($tab->id,$currentuser->account) ) { continue; } 
                                
                                  foreach ($tabdoc as $r){
                                        if (  ($data[@$_GET['id']]['id'] == $r->iddoc && $tab->id == $r->idtab) ||  $data[@$_GET['id']]['tabs'] ==  $tab->id  ) {
                                                    $selected = 'selected=""';                                                    break;
                                        }
                                    }

        
                                ?> 
                        <option <?php if($tab->special == 1){?> class="isspeci" <?php } ?>  value="<?php echo $tab->id ?>" <?php echo $selected; ?>  ><?php echo $tab->name ?></option>';
                                <?php
                            }
                        ?>
                    </select>
                    <label for="status">选择</label>
                   <span class="helper-text" data-error="Error" data-success="OK">
                       Select Account
                   </span>
                </div>
				<?php if( $currentuser->gm == 1 ) { ?> 
				 <div class="input-field col s1" >
                   <input 
							id="id_invoice" 
							name="id_invoice" 
							type="text" 
							class="validate" 
							value="<?php echo $data[@$_GET['id']]['id_invoice']; ?>"
							/>
                    <label for="id_invoice">Id invoice</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                       
                    </span>
                </div>
				<?php } ?>
				 
             <?php if($currentuser->gm == 1 || $currentuser->name == 'LEX' || $currentuser->name == 'DANNA'){ ?>
					<div class="input-field col s1">
						<input 
							id="dkasndlkas"
							value="<?php echo date('Y.m.d',$_GET['id']); ?>"
							
							type="text" 
							class="datepicker"  
                                                        onchange="var myDate = jQuery(this).val(); myDate = myDate.split('.'); var newDate = new Date( myDate[0], myDate[1] - 1, myDate[2],<?php echo date('H'); ?>,<?php echo date('i'); ?>,<?php echo date('s'); ?>); jQuery('#idreplace').val(parseInt(newDate.getTime()/ 1000)); jQuery('#settime').val(parseInt(newDate.getTime()/ 1000));"
							/>
						<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 }elseif($currentuser->name == 'LEX'){ ?>
                                    
                                <?php } ?>

				<div class="input-field col s12  " style="    padding: 0;    margin: 0;">
					<div class="file-field">
								<div class="btn btn-primary btn-sm float-left">
								  <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>
         <input type="hidden" name="id" value="<?php echo $data[@$_GET['id']]['id']; ?>"   />
		 
				<?php if(count((array)$data[@$_GET['id']]['filename']) > 0){ ?>	
				<script type="text/javascript">
					window.parent.changewidthframe();
				</script>
				<table class="striped responsive-table tablesorter " >
				<thead>
					<tr>
						<th  style="background: #004ea2;    color: #fff;"  ></th>
						<th  style="background: #004ea2;    color: #fff;" >File Name (click to download)</th>
						<th  style="background: #004ea2;    color: #fff;" >File Size</th>
						<th style="background: #004ea2;    color: #fff;" >Date Created</th>
						<th style="background: #004ea2;    color: #fff;" >User Created</th>
						<th style="background: #004ea2;    color: #fff;" ></th>
					</tr>
				</thead>
				<tbody class="sortable" >
					<?php foreach ($data[@$_GET['id']]['filepath'] as $keyfile => $file ){ ?>
					<tr style="cursor: all-scroll;" >
						<td style="width:30px;" ><?php


						if ( strpos($data[@$_GET['id']]['filetype'][$keyfile] , 'pdf')  !== false ) { 
							echo '<img src="https://htlservice.net/Docs/tpl/img/pdf.png" style="width:24px;height:auto;" />';
						} elseif ( strpos($data[@$_GET['id']]['filetype'][$keyfile] , 'sheet')  !== false ) { 
							echo '<img src="https://htlservice.net/Docs/tpl/img/excel.png" style="width:24px;height:auto;" />';
						} elseif ( strpos($data[@$_GET['id']]['filetype'][$keyfile] , 'zip')  !== false ) { 
							echo '<img src="https://htlservice.net/Docs/tpl/img/zip.png" style="width:24px;height:auto;" />';
						} elseif ( strpos($data[@$_GET['id']]['filetype'][$keyfile] , 'doc')  !== false ) { 
							echo '<img src="https://htlservice.net/Docs/tpl/img/word.png" style="width:24px;height:auto;" />';
						} elseif ( strpos($data[@$_GET['id']]['filetype'][$keyfile] , 'image')  !== false ) { 
							echo '<img src="https://htlservice.net/Docs/tpl/img/png.png" style="width:24px;height:auto;" />';
						} else{
							echo '<img src="https://htlservice.net/Docs/tpl/img/file.png" style="width:24px;height:auto;" />';
						}
						?></td>
						<td><a download href="uploads/<?php echo $data[@$_GET['id']]['filepath'][$keyfile]; ?>" ><?php echo $data[@$_GET['id']]['filename'][$keyfile]; ?><a></td>
						<td><?php echo $data[@$_GET['id']]['filesize'][$keyfile]; ?></td>
						<td><?php echo date('y.m.d h:i',$data[@$_GET['id']]['filetimeupload'][$keyfile]); ?></td>
						<td><?php echo $data[@$_GET['id']]['filecreatebyname'][$keyfile]; ?></td>
						<td style="    text-align: center;    border: none;"> 
								<div style="display:none;">
								    <input value="<?php echo $data[@$_GET['id']]['filepath'][$keyfile]; ?>" name="filepath[]" type="hidden" >	
									<input value="<?php echo $data[@$_GET['id']]['filename'][$keyfile]; ?>" name="filename[]" type="hidden" >	
									<input value="<?php echo $data[@$_GET['id']]['filetype'][$keyfile]; ?>" name="filetype[]" type="hidden" >	
									<input value="<?php echo $data[@$_GET['id']]['filesize'][$keyfile]; ?>" name="filesize[]" type="hidden" >	
									<input value="<?php echo $data[@$_GET['id']]['filetimeupload'][$keyfile]; ?>" name="filetimeupload[]" type="hidden" >	
									<input value="<?php echo $data[@$_GET['id']]['filecreatebyid'][$keyfile]; ?>" name="filecreatebyid[]" type="hidden" >	
									<input value="<?php echo $data[@$_GET['id']]['filecreatebyname'][$keyfile]; ?>" name="filecreatebyname[]" type="hidden" >									   
								</div>
								<i class="removeproduct material-icons " style="   color: red; padding-top: 0px; cursor: pointer;">indeterminate_check_box</i>
						</td>
					</tr>
					<?php } ?>
				</tbody>
			</table>
			<?php } ?>
			<div class="row" style="background: #ddd;position: fixed;width: 100%;left: 0px;bottom: 0;">
			<div class="input-field col right s2" style="    margin: 5px;    width: auto;" >
                <button class="colortoptran btn waves-effect waves-light" style="float: right;" type="submit" name="action">
                    <?php echo $i18n['Save Issue']; ?>
                    <i class="material-icons right">save</i>
                </button>
            </div>
            <div class="input-field col s1 right  "  style="    margin: 5px;    width: auto;" >
                    <a class="colortoptran btn waves-effect waves-light" href="#" onclick="window.parent.closeiframe();"  >
                        <?php echo $i18n['Go Back']; ?>
                    </a>
            </div>
			</div>	
    </form>
	<?php $Borrower = json_decode(file_get_contents('data/Borrower.json'), true); 
	
		if($data[@$_GET['id']]['classification'] == '借款-支出') { 
	?>
	<h3 style="font-size: 15px;    margin-bottom: 4px;    border-top: 1px solid #fff;    padding-top: 6px;">借款-收入</h3>
	<table class="striped responsive-table tablesorter " >
				<thead>
					<tr>
						<th style="background: #004ea2;    color: #fff;" >日期</th>
						<th style="background: #004ea2;    color: #fff;" >地点</th>
						<th style="background: #004ea2;    color: #fff;" >帐户</th>
						<th style="background: #004ea2;    color: #fff;" >费用明细</th>
						<th style="background: #004ea2;    color: #fff;" >摘要</th>
						<th style="background: #004ea2;    color: #fff;" >收入金额</th>
						<th style="background: #004ea2;    color: #fff;" >收/付款人</th>
					</tr>
				</thead>
				<tbody>
					<?php 
							
						foreach ($Borrower as $keyb => $r){				
							$inputbenchovay =  explode(',',$r['inputbenchovay']);
							$inputbennhantien = '';
							if( in_array(@$_GET['id'],$inputbenchovay) ){ 
								$inputbennhantien =  explode(',',$r['inputbennhantien']);
							}
							foreach ($inputbennhantien as $k){
								foreach($tabs as $tab){
									if($data[$k]['tabs'] == $tab->id){
										foreach($currency as $rcurrency){
												if($rcurrency['id'] == $tab->currency ){
													$currencynamesub =  $rcurrency['currency'];
												} 	
										}	
										$tabname = $tab->name;	
										$tablocation = $tab->location;				
									}
								}
								if($data[$k]['amountincome'] > 0){
									?>
									<tr>
										<td><?php echo date('Y.m.d',$data[$k]['id']); ?></td>
										<td><?php echo $tablocation; ?></td>
										<td><?php echo $tabname; ?></td>
										<td><?php echo $data[$k]['charge']; ?></td>
										<td><?php echo $data[$k]['summary']; ?></td>
										<td><?php echo number_format((float)$data[$k]['amountincome']).' '.$currencynamesub; ?></td>
										<td><?php echo $data[$k]['payer']; ?></td>
									</tr>
									<?php 
									//$marching[] = ''.number_format((float)$data3[$k]['amountincome']).' '.$currencynamesub.' ('.date('Y.m.d',$data3[$k]['id']).')'; 
								}
							}
						}
					
					?>
					
				</tbody>
	</table>
		<?php } ?>
</div>
<?php if($data[@$_GET['id']]['id_invoice'] != ''){ ?>

<iframe id="ifr" src="https://htlservice.net/expense/invoice.php?gmbypass=1&idinvoice=<?php echo $data[@$_GET['id']]['id_invoice']; ?>" width="100%" height="300" frameBorder="0" style="overflow: auto;" >Browser not compatible.</iframe>

<?php } ?>
<br>
<script>
                            
                          jQuery(document).ready(function ($) {
						
  $(".sortable").sortable({
    revert: true
  });
  
  $("#payer").change(function(){
	  if($(this).val() == 'addmore'){
		  $(this).next('.select2').hide();
		  $('#payer_more').show();
	  }
  });

	$("#classification").change(function(){
		//$('#charge').val('');//$("#documentnumber").val('');
		if($(this).val() != ''){
			$('#charge').prop('disabled',false);
			$('#charge option').prop('disabled',true);
			if( $("#classification option:selected").attr('freetext') == 'freetext' ){
				$('.charge').hide();
				$('#charge').prop('disabled',true);
				$('#chargefreetext,.chargefreetext').show();
				//$('#chargefreetext').val('');
				$('#chargefreetext').prop('disabled',false);
			}else{
				$('.charge').show();
				$('#charge').prop('disabled',false);
				$('#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 tabvalue = $( ".sandjnas" ).val();
		var date = "<?php echo date("ym"); ?>"+'';		
		/*
		if($(this).val() == "管理费用"){
			var num = $( ".nextvalue1_"+tabvalue ).val();
			if(location == '越南'){
				$("#documentnumber").val('VNG'+date+num);
			}
			if(location == '中国'){
				$("#documentnumber").val('CNG'+date+num);
			}
			if(location == '泰国'){
				$("#documentnumber").val('THG'+date+num);
			}
		}
		if($(this).val() == "应收账款"){ 
			var num = $( ".nextvalue2_"+tabvalue ).val();
			if(location == '越南'){
				$("#documentnumber").val('VNS'+date+num);
			}
			if(location == '中国'){
				$("#documentnumber").val('CNS'+date+num);
			}
			if(location == '泰国'){
				$("#documentnumber").val('THS'+date+num);
			}
		}		
		if($(this).val() == "应付账款"){			
			var num = $( ".nextvalue3_"+tabvalue ).val();
			if(location == '越南'){
				$("#documentnumber").val('VNF'+date+num);
			}
			if(location == '中国'){
				$("#documentnumber").val('CNF'+date+num);
			}
			if(location == '泰国'){
				$("#documentnumber").val('THF'+date+num);
			}
		}	
		*/		
	});	
	
	$("#classification").change();
	
							jQuery( "body" ).delegate( ".removeproduct", "click", function() {
							 jQuery( this ).parents().eq('1').remove();
						    });	  
							$(".sandjnas").change(function(){
								if($( ".sandjnas option:selected" ).hasClass('isspeci')){
									$(".isdepartmentform").show();
								}else{
									$(".isdepartmentform").hide();
								}
							});
	
							$("input[data-type='currency']").each(function(){
								 formatCurrency($(this)); 
							});
							  
                           
							
                            $("input[data-type='currency']").on({
                                keyup: function() {
                                  formatCurrency($(this));
                                },
                                blur: function() { 
                                  formatCurrency($(this), "blur");
                                }
                            });
                            
                            
                          

                            function formatNumber(n) {
                              return n.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")
                            }


                            function formatCurrency(input, blur) {
                             
                              var input_val = input.val(); 
                              if (input_val === "" || input_val == "0.00") { return; }
                              var original_len = input_val.length;
                              var caret_pos = input.prop("selectionStart");
                              if (input_val.indexOf(".") >= 0) {
                                var decimal_pos = input_val.indexOf(".");
                                var left_side = input_val.substring(0, decimal_pos);
                                var right_side = input_val.substring(decimal_pos);
                                left_side = formatNumber(left_side);

                                right_side = formatNumber(right_side);
                                if (blur === "blur") {
                                 // right_side += "00";
                                }

                                right_side = right_side.substring(0, 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);
                            }
                           });
                           
                        </script>

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