<?php 
require('config.php');
session_start();
$show_password_error = 0;
if (isset($_POST['username'])){
	
        // removes backslashes
	$username = stripslashes($_REQUEST['username']);
        //escapes special characters in a string
	$username = mysqli_real_escape_string($con,$username);
	$password = stripslashes($_REQUEST['password']);
	$password_encoded = urlencode($password);	
	

	$curl = curl_init();
	$cur_url= $domainname . "login/token.php?username=".$username."&service=moodle_mobile_app&password=".$password_encoded;
	
	curl_setopt_array($curl, array(
		CURLOPT_RETURNTRANSFER => 1,
		CURLOPT_URL => $cur_url,
    
	));
	// Send the request & save response to $resp
	$resp = curl_exec($curl);
	// Close request to clear up some resources
	curl_close($curl);

	$respjson=json_decode($resp);	
	if(isset($respjson->token)){
		//valid user
		$query = "SELECT * FROM ".$database_prefix."user WHERE username='$username'";
		//echo $query;exit;
		$result = mysqli_query($con,$query) or die(mysqli_error($con));
		$rows = mysqli_num_rows($result);
		//var_dump($rows);exit;
		if($rows==1){
			$result_data = mysqli_fetch_array($result,MYSQLI_ASSOC);
			$userid = $result_data['id'];
			$check_adminquery = "SELECT * FROM ".$database_prefix."config WHERE name='siteadmins'";
			$result_admin = mysqli_query($con,$check_adminquery) or die(mysqli_error($con));
			$rows_admin = mysqli_num_rows($result_admin);
			
			if($rows_admin == 1){
				$result_admin_data = mysqli_fetch_array($result_admin,MYSQLI_ASSOC);
				$result_admin_array = explode(',',$result_admin_data['value']);
				$admin = false;
				foreach($result_admin_array AS $admin_users){
					if($admin_users == $userid){
						$_SESSION['moodle_admin'] = 'true';		
						$admin = true;
						break;
					}					
				}
				if($admin){
					$_SESSION['username'] = $result_data['username'];
					$_SESSION['id'] = $userid;
					$_SESSION['firstname'] = $result_data['firstname'];
					$_SESSION['lastname'] = $result_data['lastname'];
					// Redirect user to index.php
					header("Location: index.php");
				}else{
					$show_password_error = 2;
				}
			}else{
				$show_password_error = 2;
			}				
		}else{
			$show_password_error = 1;
	 }
	}else{
		$external_login = trim(file_get_contents($txt_filename), "\xEF\xBB\xBF"); 

		// Convert JSON string to Array
		$external_array = json_decode($external_login);
				
		if($external_array){
		
			$data_xml = $external_array->data;
			$xml = $data_xml->row;
			
			$matched_department = false;
			$departmentname = '';
			$divisionname = '';
			foreach($xml As $row_data){
				$xml_username  = (string)($row_data->username);
				$xml_password = (string)($row_data->password);
				if($xml_username == $username){					
					if($xml_password == $password){
						$matched_department = true;
						if(isset($row_data->department)){
							$departmentname = (string)$row_data->department;
						}
						if(isset($row_data->division)){
							$divisionname = (string)$row_data->division;
						}
						break;
					}
				}
			}
			if($matched_department){				
				$_SESSION['username'] = $username;
				if($departmentname){
					$_SESSION['department'] = $departmentname;				
				}
				if($divisionname){
					$_SESSION['division'] = $divisionname;				
				}		
				// Redirect user to index.php
				header("Location: index.php");
			}else{
				//not valid user
				$show_password_error = 1;
			}			
		}else{
			//not valid user
			$show_password_error = 1;
		}
		/*
		$xml=simplexml_load_file($xml_filename) or die("Error: Cannot create object");
		if($xml){
			//$xml_data = $xml->row;
			$matched_department = false;
			$departmentname = '';
			foreach($xml As $row_data){
				$xml_username  = (string)($row_data->username);
				$xml_password = (string)($row_data->password);
				if($xml_username == $username){					
					if($xml_password == $password){
						$matched_department = true;
						$departmentname = (string)$row_data->department;
						break;
					}
				}
			}			
			if($matched_department){				
				$_SESSION['username'] = $username;
				$_SESSION['department'] = $departmentname;				
				// Redirect user to index.php
				header("Location: index.php");
			}else{
				//not valid user
				$show_password_error = 1;
			}			
		}else{
			//not valid user
			$show_password_error = 1;
		}*/
	}
}
?>
<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>Comlearn Reporting - Course Completion Report</title>
	<link rel="shortcut icon" href="images/Comlearn Logo_Navy500.png">
	<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
	<link rel="stylesheet" type="text/css" href="css/style.css">
	<link rel="stylesheet" type="text/css" href="css/responsive.css">
	<link rel="stylesheet" type="text/css" href="css/datatables.min.css">
	<link rel="stylesheet" type="text/css" href="css/font-awesome.min.css"> 
</head>
<body style="background-color: #EFF2F0 ">
	<div class="container-fluid">
		<center>
			<div id="login"> 
			<img src="images/Comlearn Logo_Navy500.png" class="loginimg img-responsive">
			<div class="col-sm-4 login">
				
			<h1 class="loginheading">Comlearn Australia<br />Reporting Tool Login</h1>
			<?php if($show_password_error > 0){
				if($show_password_error == 1){
					echo '<h6 style="color:red;text-align:left;" class="">Username and password is not valid</h6>';
				}elseif($show_password_error == 2){
					echo '<h6 style="color:red;text-align:left;" class="">You are not authorized admin user to access system</h6>';
				}				
			} ?>
			<form id="form" method="post" data-fv-message="This value is not valid" data-fv-icon-valid="fa fa-check" data-fv-icon-invalid="fa fa-times" data-fv-icon-validating="fa fa-refresh" action="login.php">
              <div class="row">
                <div class="col-md-12">
                  <div class="form-group">
                  <label>Username</label>                    
                      <input type="text" name="username" value=""  class="form-control" required data-fv-notempty-message="Please fill out this field." />
					</div>
                </div>
                <div class="col-md-12">
                  <div class="form-group">
                  <label>Password</label>
                      <input type="password" class="form-control" value="" name="password"
                              required data-fv-notempty-message="The password is required and cannot be empty"
                                   data-fv-identical="true" data-fv-identical-field="password"   />                    
                             </div>
                </div>
              </div>
              <button class="btn btn-primary" type="submit">Login</button>
            </form>			
		</div>	
		</div>
	</center>
	<footer>
    <p>Developed by Wallace Web Design and Development, any queries please email <a href="mailto:richard@wwdad.com.au">richard@wwdad.com.au</a>
</p>
  </footer>
	</div>
</body>
	<script type="text/javascript" src="js/bootstrap.min.js"></script>	
	<script type="text/javascript" src="js/jquery.min.js"></script>
	<script type="text/javascript" src="js/datatables.min.js"></script>
	<script type="text/javascript" src="js/formValidation.js"></script>
	<script type="text/javascript" src="js/bootstrap-validation.js"></script>
	<script type="text/javascript" src="js/custom-validation.js"></script>
	<script type="text/javascript" src="js/jquery.datatables.min.js"></script>
	<script>
	
	$(document).ready(function() {
    $('#form').formValidation({
            
        .on('err.field.fv', function(e, data) {
            if (data.fv.getSubmitButton()) {
                data.fv.disableSubmitButtons(false);
            }
        })
        .on('success.field.fv', function(e, data) {
            if (data.fv.getSubmitButton()) {
                data.fv.disableSubmitButtons(false);
            }
        });
    });
});
		
	</script>

</html>