<?php
include 'connect/cms-config.php' ;
include 'requires/function.php' ;

// check session exsits
if ($_SESSION["system_id"] != "" && $_SESSION["system_name"] != "" && $_SESSION["system_branch"] != "" && $_SESSION["system_permission"] != ""){
	header("Location: main.php") ;
	exit ;
}else{
	// check cookie login
	checkCookieLogin() ;
}

// user - login
if ($_POST['user_hide'] == 1){
	$user_hide_status = $_POST['user_hide_status'] ;
	$user_verification = escapeString($_POST['user_verification']) ;
	$boolean_status = ($user_hide_status == 'login' ? true : false) ;
	$boolean_statement = false ;
	if ($boolean_status){
		$user = escapeString($_POST['user_name']) ; // name
		$password = $_POST['user_password'] ; // password
		$password2 = $password ;
		$remember = $_POST['remeber'] ; // remember me
		$boolean_statement = true ;
	}else{
		$user = $_SESSION['system_temp_user_name'] ; // name
		$password = $_SESSION['system_temp_password'] ; // password
		$remember = $_SESSION['system_temp_remember'] ; // remember me
		$access = $_SESSION['system_temp_access'] ; // access time
		if ($user_verification != '' && strlen($user_verification) == 6){
			$query = "AND user_verification = '".$user_verification."'" ;
			$boolean_statement = true ;
		}else{
			$warning_verfication = 'error_verifcation' ;
		}
	}
	if ($user != '' && $password != '' && $boolean_statement){
		$mysqli_user = $mysqli->query("SELECT user_code, user_login_cookies FROM system_user 
										WHERE user_name = '".$user."' AND user_trash = '0' LIMIT 1") ;
		// check if username exists
		if ($mysqli_user->num_rows > 0){
			// set query in variable
			$row_user = $mysqli_user->fetch_array(MYSQLI_ASSOC) ;
			// encode password with md5 + code
			$code = $row_user['user_code'] ;
			$password = md5(md5($password).$code) ;
			$login_cookies = $row_user['user_login_cookies'] ;
			$login_cookies = (trim($login_cookies) != '' ? $login_cookies : rand(100000,999999)) ;
			if ($system_login_cookies == $login_cookies && trim($system_login_cookies) != ''){
				$query = '' ;
				$boolean_status = false ;
			}
			// check user login
			$mysqli_user = $mysqli->query("SELECT user_id, user_name, user_fullname, user_code, user_permission, user_branch, user_verification_type, user_visit_count FROM system_user 
										WHERE user_name = '".$user."' AND user_password = '".$password."' ".$query." AND user_trash = '0' LIMIT 1") ;
			// check if username exists
			if ($mysqli_user->num_rows > 0){
				// set query in variable
				$row_user = $mysqli_user->fetch_array(MYSQLI_ASSOC) ;
				// user id
				$user_id = $row_user['user_id'] ;
				$user_code = $row_user['user_code'] ;
				$visit_count = $row_user['user_visit_count'] ;
				$user_verification_type = $row_user['user_verification_type'] ;
				$visit_count++ ;
				$get_client_ip = get_client_ip() ;
				$get_user_agent = userAgent($_SERVER['HTTP_USER_AGENT']) ;
				// get user last login coordinates
				$latitude = escapeString($_POST['latitude']) ;
				$longtitude = escapeString($_POST['longtitude']) ;
					
				// check status
				if ($boolean_status){
					$_SESSION['system_temp_user_name'] = $user ; // name
					$_SESSION['system_temp_password'] = $password2 ; // password
					$_SESSION['system_temp_remember'] = $remember ; // remember me
					$_SESSION['system_temp_access'] = 3 ; // verification access times | 3
					$_SESSION['system_temp_bool_verify'] = $user_verification_type ; // verification boolean

					if( $user_verification_type == 'yes' ){
						// generate rand number
						$rand = rand(100000,999999) ;

						// update login form
						$mysqli->query( "UPDATE system_user SET
										 user_verification = '".$rand."',
										 user_verification_date = '".TODAYDATE."'
										 WHERE user_id = '".$user_id."'") ;

						// send verifcation code to owner
						emailVerifcationCode($mysqli, system_user, COMPANY, EMAILSYSTEM, $row_user, $rand) ;
					}else{
						// update login form
						$mysqli->query("UPDATE system_user SET
										user_login_cookies = '".$login_cookies."',
										user_visit_count = '".$visit_count."',
										user_last_latitude = '".$latitude."',
										user_last_longtitude = '".$longtitude."',
										user_last_device = '".$get_user_agent."',
										user_last_ip = '".$get_client_ip."',
										user_last_login = '".TODAYDATE."'
										WHERE user_id = '".$user_id."'") ;		
						// unset temporary session
						unset($_SESSION['system_temp_user_name']) ;
						unset($_SESSION['system_temp_password']) ;
						unset($_SESSION['system_temp_remember']) ;
						unset($_SESSION['system_temp_access']) ;
						unset($_SESSION['system_temp_bool_verify']) ;
						// get the customer information
						$_SESSION['system_id'] = $user_id ;
						$_SESSION['system_name'] = $row_user['user_name'] ;
						$_SESSION['system_branch'] = $row_user['user_branch'] ;
						$_SESSION['system_permission'] = $row_user['user_permission'] ;
						// set cookies
						$expired_time = (time() + 60 * 60 * 24 * 365 * 5) ;
						setcookie("system_login_cookies", $login_cookies, $expired_time, "/") ;
						if ($remember){
							setcookie("system_id", $_SESSION['system_id'], $expired_time, "/") ;
							setcookie("system_name", $_SESSION['system_name'], $expired_time, "/") ;
							setcookie("system_branch", $_SESSION['system_branch'], $expired_time, "/") ;
							setcookie("system_permission", $_SESSION['system_permission'], $expired_time, "/") ;
						}else{
							$expired_time = (time() - 3600) ;
							setcookie("system_id", $_SESSION['system_id'], $expired_time, "/") ;
							setcookie("system_name", $_SESSION['system_name'], $expired_time, "/") ;
							setcookie("system_branch", $_SESSION['system_branch'], $expired_time, "/") ;
							setcookie("system_permission", $_SESSION['system_permission'], $expired_time, "/") ;
						}
						// redirect page
						header('Location: main.php') ;
						exit ;
					}
				}else{
					// update login form
					$mysqli->query("UPDATE system_user SET
									user_verification = '',
									user_login_cookies = '".$login_cookies."',
									user_visit_count = '".$visit_count."',
									user_last_latitude = '".$latitude."',
									user_last_longtitude = '".$longtitude."',
									user_last_device = '".$get_user_agent."',
									user_last_ip = '".$get_client_ip."',
									user_last_login = '".TODAYDATE."'
									WHERE user_id = '".$user_id."'") ;		
					// unset temporary session
					unset($_SESSION['system_temp_user_name']) ;
					unset($_SESSION['system_temp_password']) ;
					unset($_SESSION['system_temp_remember']) ;
					unset($_SESSION['system_temp_access']) ;
					unset($_SESSION['system_temp_bool_verify']) ;
					// get the customer information
					$_SESSION['system_id'] = $user_id ;
					$_SESSION['system_name'] = $row_user['user_name'] ;
					$_SESSION['system_branch'] = $row_user['user_branch'] ;
					$_SESSION['system_permission'] = $row_user['user_permission'] ;
					// set cookies
					$expired_time = (time() + 60 * 60 * 24 * 365 * 5) ;
					setcookie("system_login_cookies", $login_cookies, $expired_time, "/") ;
					if ($remember){
						setcookie("system_id", $_SESSION['system_id'], $expired_time, "/") ;
						setcookie("system_name", $_SESSION['system_name'], $expired_time, "/") ;
						setcookie("system_branch", $_SESSION['system_branch'], $expired_time, "/") ;
						setcookie("system_permission", $_SESSION['system_permission'], $expired_time, "/") ;
					}else{
						$expired_time = (time() - 3600) ;
						setcookie("system_id", $_SESSION['system_id'], $expired_time, "/") ;
						setcookie("system_name", $_SESSION['system_name'], $expired_time, "/") ;
						setcookie("system_branch", $_SESSION['system_branch'], $expired_time, "/") ;
						setcookie("system_permission", $_SESSION['system_permission'], $expired_time, "/") ;
					}
					
					// redirect page
					header('Location: main.php') ;
					exit ;
				}
			}else{
				$warning_verfication = 'error_verifcation' ;
				$access-- ;
				if ($access == 0){
					// unset temporary session
					unset($_SESSION['system_temp_user_name']) ;
					unset($_SESSION['system_temp_password']) ;
					unset($_SESSION['system_temp_remember']) ;
					unset($_SESSION['system_temp_access']) ;
					unset($_SESSION['system_temp_bool_verify']) ;
				}else{
					$_SESSION['system_temp_access'] = $access-- ;
				}
			}
		}
	}
}

// check status
if ($_SESSION['system_temp_user_name'] != '' && $_SESSION['system_temp_password'] != ''){
	if( $_SESSION['system_temp_bool_verify'] == 'yes' ){
		$boolean_verifcation = true ;	
	}else{
		$boolean_verifcation = false ;	
	}
}else{
	$boolean_verifcation = false ;	
}

// token session
$_SESSION['system_token'] = md5(uniqid()) ;

// body onload script
$show_map_library = true ;
$show_map_script = true ;
$body_onload = true ;

// start header here
include 'requires/page_header.php' ;

?>
<div class="container">
	<div class="row" style="margin:50px 0;">
        <div class="col-lg-4 col-lg-offset-4">
        	<h3 class="text-center login_logo">
        		<img src="<?= PATH ?>images/logo_full.png" style="width:150px;" />
        	</h3>
			<!--
				<h3 class="text-center" style="font-size:20px; margin-bottom:40px; color:#000;"><b><?= COMPANY ?></b></h3>
			-->
            <hr class="clean">
            <p id="email_error"><?= $lang['please_get_the_verification_code_from_the_owner']?></a></p>
            <p id="block_error"><?= $lang['sorry_your_account_was_in_our_block_list']?></p>
            <form method="post" role="form" id="<?= ($boolean_verifcation ? 'quotationForm' : 'login_form') ?>" novalidate>
				<?php
                if ($boolean_verifcation){
                    echo '
					<p>'.$lang['please_get_the_verification_code_from_the_owner'].'</p>
					'.($warning_verfication == 'error_verifcation' ? '<p id="block_error" style="display:block;">'.$lang['sorry_please_provide_a_correct_verification_code'].$lang['you_still_can_try'].$_SESSION['system_temp_access'].$lang['times'].'</p>' : '').'
					<div class="form-group input-group">
						<span class="input-group-addon"><i class="fa fa-key"></i></span>
						<input type="text" name="user_verification" class="form-control" minlength="6" maxlength="6" placeholder="'.$lang['verification_code_6_digits_only'].'" required />
					</div>' ;
                }else{
                    echo '
					<div class="form-group input-group">
						<span class="input-group-addon"><i class="fa fa-user"></i></span>
						<input type="text" name="user_name" class="form-control"  placeholder="'.$lang['username'].'" required="required" />
					</div>
					<div class="form-group input-group">
						<span class="input-group-addon"><i class="fa fa-key"></i></span>
						<input type="password" name="user_password" class="form-control"  placeholder="'.$lang['password'].'" required="required" />
					</div>
					<div class="form-group">
						<label class="cr-styled">
							<input type="checkbox" name="remeber" value="remeber" ng-model="todo.done">
							<i class="fa"></i> 
						</label>
						'.$lang['remember_me'].'
					</div>' ;
                }
                ?>
                <!-- last login coordinates use -->
                <input type="hidden" name="latitude" id="current_lat_input" />
                <input type="hidden" name="longtitude" id="current_lot_input" />
                <!-- end last login coordinates use -->
            	<input type="hidden" name="user_hide" value="1" />
                <input type="hidden" name="user_hide_status" value="<?= ($boolean_verifcation ? 'verification' : 'login') ?>" />
                <input type="hidden" name="user_token" value="<?= $_SESSION['system_token'] ?>" />
                <button type="submit" class="btn btn-purple btn-block"><?= $lang['sign_in']?></button>
            </form>

            <div class="language index_language">
            	<?php
            	if ( arrayCheck($app_download_link) ){
            		$new_download = [] ;
	            	foreach ( $app_download_link as $k => $v ){
	            		$new_download[] = '<a href="https://ips.com.my/apk/apk/'.$k.'.apk" download>'.$v.'</a>' ;
	            	}
	            	echo implode( ' / ', $new_download ) ;
            	}
            	?>
            </div>

            <hr />
            
            <div class="language index_language">
            	<a href="language.php?lang=en&link=//<?= $_SERVER['HTTP_HOST'].urlencode($_SERVER['REQUEST_URI']) ?>" class="<?= $get_lang == 'en' ? 'active' :'' ?>">ENG</a>
            	<a href="language.php?lang=cn&link=//<?= $_SERVER['HTTP_HOST'].urlencode($_SERVER['REQUEST_URI']) ?>" class="<?= $get_lang == 'cn' ? 'active' :'' ?>">中文</a>
            </div>

            <hr />

			<p class="text-center text-gray"><?= $lang['developed_by_eng']?><a href="http://ips.com.my" target="_blank">IPS Software Sdn. Bhd.</a><?= $lang['developed_by_cn']?></p>
        </div>
    </div>
</div>
<script>
$("#login_form").validate({
	submitHandler: function (form) {
		$('#ajax_button').addClass('button_disabled').attr('disabled', 'disabled');
		$('#email_error').hide();
		$('#block_error').hide();
		// form validates so do the ajax
		var parent = $('#login_form');
			data = parent.serialize();
		$.ajax({
			type: 'POST',
			url: 'requires/validate_login.php',
			data: data,
			success: function (result) {
				if (result == 4){
					form.submit();
				}
				else if (result == 2){
					$('#email_error').show();
				}
				else if (result == 3){
					$('#block_error').show();
				}
				else{
					//alert("Token error, system will auto reload the page!");	
					//location.reload();
				}
				$('#ajax_button').removeClass('button_disabled').removeAttr('disabled');
			}
		});
		return false; // ajax used, block the normal submit
	}
});
</script>
</body>
</html>