<?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/Product.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: product.php?msg=' . $i18n['Entry successfully deleted.']);
    
}


if (@$_GET['approve'] != '') {
    $data = json_decode(file_get_contents($file), true);
    
    foreach ( $data as $key => $r  ){
        if($r['id'] == @$_GET['approve']){
           $data[$key]['notapprove'] = 0;
        }
    }
    
    $convert_array_to_json = array_values($data);
    $write_json = json_encode($convert_array_to_json);
    file_put_contents($file, $write_json);
    header('location: product.php');
    
}

// 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['name'] != ''  ) {
	$id = time();
	if($_POST['id'] == ''){	
		if ($_POST['productid'] == ''){
			$_POST['productid'] = count(json_decode(file_get_contents($file),true));
		}
        $formdata = array(
        'id' => $id	
		, 'productid' => $_POST['productid']
        , 'name' => $_POST['name']
        , 'description' => $_POST['description']
		, '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']){
				
				foreach ($data[$key] as $keylog => $logs ){
					if($keylog == 'modifieddate' || $keylog == 'modifiedby' || $keylog == 'createdby' || $keylog == 'createddate' ){
						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/'.$r['id'],file_get_contents('logs/'.$r['id']).$textlog.PHP_EOL);
					
					}
				}	
				
				$arr_data[$key]['productid'] = $_POST['productid'];
				$arr_data[$key]['name'] = $_POST['name'];
				$arr_data[$key]['description'] = $_POST['description'];		
				$arr_data[$key]['modifieddate'] = $id;
				$arr_data[$key]['notapprove'] =  1;
                                $arr_data[$key]['createddate'] =  $arr_data[$key]['id'];
                                $arr_data[$key]['createdby'] =  "GM";
                        }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: product.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
if(@$_GET['q'] == ''){
?>
<?php       
if($_GET['nocontrol'] == 1){	
?>
<style>
.navbar-fixed {
	display:none;
}
</style>
<script>

</script>
<?php } ?>
<script>

$(document).ready(function(){
   // $('select').formSelect();
	$(".cllogcontent").click(function(){
		$(".logcontent").html($(this).find('span').html());
	});
});

function editc(id) {

var obj = jQuery.parseJSON(id);
$('#name,#acronym,#contracttermsstart,#contracttermsend,#productid,#description').next().addClass('active');

$('#id').val(obj.id);

$('#contracttermsstart').val(obj.contracttermsstart);
$('#contracttermsend').val(obj.contracttermsend);

$('#productid').val(obj.productid);
$('#name').val(obj.name);
$('#acronym').val(obj.acronym);
$('#type').val(obj.type);
$('#description').val(obj.description);

$('select').formSelect();


}
        
</script>            

        <div class="badge grey lighten-3 hoverable create-user">
            <form action="product.php?nocontrol=<?php echo $_GET['nocontrol']; ?>" method="POST">
				<input value=""  id="id" name="id" type="hidden"  />
                <div class="row">
					<div class="input-field col s2" style="display:none;" >
                        <input 
                            value="<?php echo @$_POST['productid']; ?>" 
                            id="productid" 
                            name="productid" 
                            type="text" 
                            class="validate" 
                            maxlength="32" 
                            data-length="32" 
                            autocomplete="off"  />
                        <label for="productid">ID</label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                           Product ID
                        </span>
                    </div> 
                    <div class="input-field col s2">
                        <input 
                            value="<?php echo @$_POST['name']; ?>" 
                            id="name" 
                            name="name" 
                            type="text" 
                            class="validate" 
                            maxlength="32" 
                            data-length="32" 
                            required="required"  autocomplete="off"  />
                        <label for="name">产品名称</label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                           Name
                        </span>
                    </div> 			
					<div class="input-field col s4" style="display:none;" >
                        <input 
                            value="<?php echo @$_POST['description']; ?>" 
                            id="description" 
                            name="description" 
                            type="text" 
                            class="validate" 
                            maxlength="32" 
                            data-length="32" 
                           autocomplete="off"  />
                        <label for="description">描述</label>
                        <span class="helper-text" data-error="Error" data-success="OK">
                          Commodity
                        </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 Product
                        </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 style="display:none;" >Product ID</th>
                    <th>Commodity Name</th>
                    <th style="display:none;" >Commodity</th>                  
					<th>Create By</th>
					<th>Date Create</th>
					<th>Modified Date</th>
					<th style="width: 100px;" ></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;"});';
					
					if ($currentuser->role == 'Manager' ) {
				   
						if (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 style=" font-size: 24px;    margin-left: 3px;    float: left; " class="grey-text small material-icons">content_paste</i></a>';
						}else{
							$logsmode = '';
						}
				
					}
					
	            ?>    
                <tr style="<?php if($values['notapprove'] == 1){ ?> background:#ffcaca; <?php } ?>" >

                  <td style="padding-left:6px;display:none;"><?= $values['productid']?></td>
                    <td style="padding-left:6px"><?= $values['name']?></td>
                    <td style="padding-left:6px;display:none;"><?= $values['description']?></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"><?= date('d/m/y h:i',$values['modifieddate']); ?></td>
                    <td style="">
						<?php  if($currentuser->role == 'Manager'  ) {  echo $logsmode ; ?>
                        <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>	
						<?php  if( ( $currentuser->role == 'Manager' || $currentuser->managergroup  == 1 ) && $values['notapprove'] == 1 ) { ?>
						<a href="?approve=<?php echo $values['id']; ?>'"  >
							<button style="margin-right: 10px;width:100%;" class="btn waves-effect waves-light mapproval">Approval</button>
						</a>
						<?php } ?>	
						
                    </td>
                </tr>
            <?php  }  ?>
        </tbody>
        </table>
<div id="modal6" class="modal">
  <div class="logcontent" style="padding: 15px;" ></div>
</div>			
    <?php
}
// ENDIF no data    
// ECHO PROGRESS-BAR (only if there is no search performed) SEE tpl/css/progress.css
if (@$_GET['q'] == '') {
    echo '<div class="progress tooltipped" data-position="top"' .
    ' data-tooltip="' . $done . '/' . count((array)$data) . ' ' . $TYPE .
    '" title="' . $done . '/' . count((array)$data) . ' ' . $TYPE . '">' .
    '<div class="progress-bar green" data-width="' . ($done / count((array)$data) * 100) .
    '" style="width:' . ($done / count((array)$data) * 100) . '%"></div></div>';
}
?>
<?php
// var_dump($sortdate); die;
// FOOTER
include 'tpl/footer.php';
?>
