<?php
// DISPLAY ALL ERRORS
//error_reporting(E_ALL);
ini_set('display_errors', 0);

// FOR DEBUG ONLY
if (isset($_GET['php']) and $_GET['php'] == 'info') {
    die(phpinfo());
}
// 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
ob_start();
require 'setup/config.php';

$LANG =  'cn';
// SET LANGUAGE
if (isset($_GET['lang'])){	
	$_SESSION['HTTP_ACCEPT_LANGUAGE'] = $_GET['lang'];
}
if (isset($_SESSION['HTTP_ACCEPT_LANGUAGE']) and file_exists('lang/' . $_SESSION['HTTP_ACCEPT_LANGUAGE'] . '.php')) {	
	if((@include 'lang/' . $_SESSION['HTTP_ACCEPT_LANGUAGE'] . '.php') === false){
		echo 'Caught exception: Translate file is wrong';
	}else{
		@include_once('lang/' . $_SESSION['HTTP_ACCEPT_LANGUAGE'] . '.php');
	}
} else {
	if((@include 'lang/' . $LANG . '.php') === false){
		echo 'Caught exception: Translate file is wrong';
	}else{
		@include_once('lang/' . $LANG . '.php');
	}
}
// INI VARs
$found = 0;                     // MARKER HOW MANY HITS FOUND A SEARCH
$done = 0;                     // MARKER HOW MANY ENTRYs ARE DONE
$msg = '';                    // TOAST MESSAGE
$file = 'data/Departure.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) {
    //var_dump($login);
} else {
    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']){
            unset($data[$key]);
        }
    }    
    $convert_array_to_json = array_values($data);
    $write_json = json_encode($convert_array_to_json);
    file_put_contents($file, $write_json);
    header('location: departure.php?msg=' . $i18n['Entry successfully deleted.']);
    
}

// READ DATA
$user = json_decode(file_get_contents('data/User.json'));
$data = json_decode(file_get_contents($file), true);



if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['idport'] != ''  ) {
	$id = time();
	if($_POST['id'] == ''){	   	
        $formdata = array(
        'id' => $id	
		, 'idport' => $_POST['idport']
        , 'port' => $_POST['port']
        , 'location' => $_POST['location']
		, 'createdby' => $currentuser->name
		, 'createddate' => $id
		, 'modifieddate' => ''  
  	);
  	$arr_data = array();
    	if (file_exists($file)) {
        	$jsondata = file_get_contents($file);
        	$arr_data = json_decode($jsondata, true);
    	}
   	$arr_data[] = $formdata;

	}else{
		$arr_data = array();
    		if (file_exists($file)) {
        		$jsondata = file_get_contents($file);
        		$arr_data = json_decode($jsondata, true);
    		}
		foreach ($arr_data as $key => $r){
			if($r['id'] == $_POST['id']){
				$arr_data[$key]['idport'] = $_POST['idport'];
				$arr_data[$key]['port'] = $_POST['port'];
				$arr_data[$key]['location'] = $_POST['location'];		
				$arr_data[$key]['modifieddate'] = $id;
				$arr_data[$key]['modifiedby'] = $currentuser->name;
                                //$arr_data[$key]['createdby'] =  "GM";
                                //$arr_data[$key]['createddate'] =  $arr_data[$key]['id'];

                        }else{
//                            $arr_data[$key]['createdby'] =  "GM";
//                            $arr_data[$key]['createddate'] =  $arr_data[$key]['id'];
//                            $arr_data[$key]['modifieddate'] = '';
                        }
		}
	}
  
    $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: departure.php?msg=' . $msg);
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $_GET['msg'] = $i18n['All fields are required!'];
}
// CREATE DATA FILE IF NOT EXISTS
if (!is_file($file)) {
    file_put_contents($file, '');
}

// HEADER
ob_end_flush();
include 'tpl/header.php';
// FORM FOR NEW ENTRY

?>

<script>

function editc(id) {

var obj = jQuery.parseJSON(id);
$('#idport,#port').next().addClass('active');
$('#id').val(obj.id);
$('#idport').val(obj.idport);
$('#port').val(obj.port);
$('#location').val(obj.location);
$('select').formSelect();

}
        
</script>      
<?php       
if($_GET['nocontrol'] == 1){	
?>
<style>
.navbar-fixed {
	display:none;
}
</style>
<script>

</script>
<?php } ?>
        <div class="badge grey lighten-3 hoverable create-user">
            <form action="" method="POST">

				<input value=""  id="id" name="id" type="hidden"  />
                <div class="row">
					<div class="input-field col s2">
                        <input 
                            value="<?php echo @$_POST['receiverid']; ?>" 
                            id="idport" 
                            name="idport" 
                            type="text" 
                            class="validate"                           
                            autocomplete="off"  />
                        <label for="idport">Port</label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                          
                        </span>
                    </div> 


                    <div class="input-field col s2">
                        <input 
                            value="<?php echo @$_POST['name']; ?>" 
                            id="port" 
                            name="port" 
                            type="text" 
                            class="validate"                            
                            required="required"  autocomplete="off"  />
                        <label for="port">Short Name</label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                           
                        </span>
                    </div> 
			
					<div class="input-field col s2">
						<select name="location" id="location"  tabindex="-1">
										<option value="VietNam">VietNam</option>
										<option value="ThaiLands">ThaiLands</option>
                                                                                <option value="Indonesia">Indonesia</option>
                                                                                <option value="Malaysia">Malaysia</option>
										<option value="China">China</option>
										<option value="Usa">Usa</option>
										<option value="Japan">Japan</option>
										<option value="Europe">Europe</option>
                                                                                <option value="Cambodia">Cambodia</option>
										<option value="order">Orders</option>
						</select>
						<label for="name">Location</label>
                        <span class="helper-text" data-error="Error" data-success="OK">
								
                        </span>
                    </div> 



                    <div class="input-field col s1" style="    text-align: right;">
                        <button class="colortoptran btn waves-effect waves-light" type="submit" name="action">
                            Save
                        </button>
                    </div>
                    <div class="input-field col s1 ">
                        <a style="    background: #4e4e4e;" class="btn  btn-default waves-effect waves-light" href="./index.php">
                            <?php echo $i18n['Go Back']; ?>
                        </a> 
                    </div>
                </div>
            </form>
        </div>
    <?php
// DATA TABLE
if (!empty($data)) {
    // LOOP EACH ENTRY
    ?>
        <table class="striped responsive-table hoverable tablesorter" id="tab-table">
            <thead>
                <tr>
					<th>ID</th>
                    <th>Port</th>
                    <th>Short Name</th> 
					<th>Location</th>					
					<th>Create By</th>
					<th>Date Create</th>
					<th>Modified By </th>
					<th>Modified Date</th>
					<th></th>
                </tr>
            </thead>
        <tbody>
   <?php 
     $total_receivable = $total_amount = $total_profit = 0;
     $countNo = 0;
        foreach ($data as $key => $values) {   
		     $toast = 'M.toast({html: "<span>' . $values['name'] . '</span>' .
                    '<a href=\"?delete_id=' . $values['id'] . '\" class=\"toast-action\">' .
                    $i18n['DELETE'] . '</a> &nbsp; &nbsp;"});';
	            ?>    
                <tr>
					<td style="padding-left: 6px;"><?= ++$i; ?></td>
                  	<td style="padding-left: 6px;"><?= $values['idport']?></td>
                    <td style="padding-left: 6px;"><?= $values['port']?></td>
                   	<td style="padding-left: 6px;"><?= $values['location']; ?></td>                   
					<td style="padding-left: 6px;"><?= $values['createdby']?></td>
					<td style="padding-left: 6px;"><?= date('d/m/y h:i',$values['createddate']); ?></td>
					<td style="padding-left: 6px;"><?= $values['modifiedby']?></td>
					<td style="padding-left: 6px;"><?= date('d/m/y h:i',$values['modifieddate']); ?></td>
                    <td style="padding-left: 6px;">
						<?php  if($currentuser->role == 'Manager'  ) {  ?>
                        <a class="tooltipped" data-position="top" data-tooltip="<?= $i18n['Click alert link for delete!']?>" href="#" onclick='<?php echo $toast; ?>' >
                            <i class="red-text text-darken-4 small material-icons">delete_forever</i>
                        </a>
						<?php } ?>
                        <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>
			
                    </td>
                </tr>
            <?php  }  ?>
        </tbody>
    </table>
    <?php
}

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