<?php
	include("config.php");
	session_start();
	$error = "";
	//fetch usertype from database
	include("ChatApp/php/config.php"); 
	$sql_campus = mysqli_query($db, "SELECT * FROM campus WHERE `Status`='inactive'");
	
	
	if($_SERVER["REQUEST_METHOD"] == "POST") {

		$lname = mysqli_real_escape_string($db,$_POST['lname']);
		$fname = mysqli_real_escape_string($db,$_POST['fname']);
		$middle_in = mysqli_real_escape_string($db,$_POST['middle_in']);
		$email = mysqli_real_escape_string($db,$_POST['email']);
		$password = mysqli_real_escape_string($db,$_POST['pass']);
	    $my_campus = mysqli_real_escape_string($db,$_POST['campus']);
		$dept_off = "admin";
		$usertype = "admin";
		
		//Encrypt the password of the user
		$encrypted_pwd = md5($password);

		$date = new DateTime($birthdate);
		$now = new DateTime();
		$age = $now->diff($date);
		$age_now = $age->y;

		if (ctype_alpha($middle_in)) {
					if(isset($_FILES['image'])){
						$img_name = $_FILES['image']['name'];
						$img_type = $_FILES['image']['type'];
						$tmp_name = $_FILES['image']['tmp_name'];
						
						$img_explode = explode('.',$img_name);
						$img_ext = end($img_explode);
		
						$extensions = ["jpeg", "png", "jpg"];
						if(in_array($img_ext, $extensions) === true){
							$types = ["image/jpeg", "image/jpg", "image/png"];
							if(in_array($img_type, $types) === true){
								$time = time();
								$new_img_name = $time.$img_name;
								if(move_uploaded_file($tmp_name,"profile_pic/".$new_img_name)){
                                    
                                    // INSERT user
									$sql = "INSERT INTO members (`Last_Name`, `First_Name`, `Middle_Initial`, `Email`, `Password`, `Campus`, `Department/Office`, `Usertype`, `Profile_Picture`)
									VALUES ('$lname', '$fname', '$middle_in', '$email', '$encrypted_pwd', '$my_campus', '$dept_off', '$usertype', '$new_img_name')";
								   
								    //UPDATE Campus Status   
								    $sql_upd = "UPDATE campus Set `Status` = 'active' WHERE Campus='$my_campus'"; 
                					$result_upd = mysqli_query($db,$sql_upd);
								    
								    // $ran_id = rand(time(), 100000000);
            //                         $status = "Active now";
								    // $insert_query = mysqli_query($conn, "INSERT INTO users (unique_id, fname, lname, usertype, email, password, img, status)
            //                         VALUES ({$ran_id}, '{$fname}','{$lname}', '{$dept_off}', '{$email}', '{$encrypted_pwd}', '{$new_img_name}', '{$status}')");
								}
								if (mysqli_query($db, $sql) == true && $result_upd == true) {
								    // ==========================EMAIL VERIFICATION====================================
								    $to = $email;
								    $from = "minsupmeoffice@gmail.com";
                                    $subject = "MINDORO STATE UNIVERSITY - PME OFFICE";
                                    $full_name = "".$fname. " " .$middle_in. " " .$lname."";
                                    
                                    $message = 'Good Day! '.$full_name.',<br>';
                                    $message .= "Here is your account for MINSU-PME Website<br><br>";
                                    $message .= "===============================<br>";
                                    $message .= "Email: ".$email."<br>";
                                    $message .= "Password: ".$password."<br>";
                                    $message .= "===============================<br><br>";
                                    $message .= "You may now login through this website link:<br>";
                                    $message .= "http://www.minsu-pme-office.store/<br>";
                                    
                                    
                                    // Always set content-type when sending HTML email
                                    $headers = "";
                                    $headers .= 'From: ' . $from . "\r\n";
                                    $headers .= "MIME-Version: 1.0" . "\r\n";
                                    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
                                    
                                    mail($to,$subject,$message,$headers);
                                    
                                    // ============================END=================================
                                    
								    echo '<script>alert("Admin was registered succesfully!")</script>';
									echo "<script>top.window.location = '/register-su.php'</script>";
								} else {
									$error = "Invalid";
									echo "Error: " . $sql . "<br>" . mysqli_error($db);
								}
							}
							else{
								echo "Please upload an image file - jpeg, png, jpg";
							}
						}
						else{
							echo "Please upload an image file - jpeg, png, jpg";
						}
					}
		} 
		else {
			$error = "Invalid Middle Initial! It only accepts letters";
		}
	}
	else{
		$error = "";
	}

?>

<!DOCTYPE html>
<html lang="en">
<head>
	<title>Sign up</title>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
<!--===============================================================================================-->	
	<link rel="icon" type="image/png" href="images/icons/minsu-icon.ico"/>
<!--===============================================================================================-->
	<link rel="stylesheet" type="text/css" href="vendor/bootstrap/css/bootstrap.min.css">
<!--===============================================================================================-->
	<link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css">
<!--===============================================================================================-->
	<link rel="stylesheet" type="text/css" href="fonts/iconic/css/material-design-iconic-font.min.css">
<!--===============================================================================================-->
	<link rel="stylesheet" type="text/css" href="vendor/animate/animate.css">
<!--===============================================================================================-->	
	<link rel="stylesheet" type="text/css" href="vendor/css-hamburgers/hamburgers.min.css">
<!--===============================================================================================-->
	<link rel="stylesheet" type="text/css" href="vendor/animsition/css/animsition.min.css">
<!--===============================================================================================-->
	<link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css">
<!--===============================================================================================-->	
	<link rel="stylesheet" type="text/css" href="vendor/daterangepicker/daterangepicker.css">
<!--===============================================================================================-->
	<link rel="stylesheet" type="text/css" href="css/util.css">
	<link rel="stylesheet" type="text/css" href="css/main.css">
<!--===============================================================================================-->
</head>
<body>
	
	<div class="limiter">
		<div class="container-login100" style="background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('images/minsu2.jpg'); background-size: cover;">
			<div class="wrap-login100 p-l-55 p-r-55 p-t-65 p-b-54">

				<form class="login100-form validate-form" action="" method="POST" enctype="multipart/form-data">
				<img src="images/mcc_pme_cover1.jpg" alt="Minsu-Logo" width="510px" height="200px" style="margin-top: -65px; margin-left: -57px;">
				<br><br>
		
					<div class="wrap-input100 validate-input m-b-23" data-validate = "Lastname is required" >
						<span class="label-input100">Lastname</span>
						<input class="input100" type="text" name="lname" placeholder="Type your last name" maxlength = "50">
						<span class="focus-input100"></span>
					</div>

                    <div class="wrap-input100 validate-input m-b-23" data-validate = "First Name is required">
						<span class="label-input100">First Name</span>
						<input class="input100" type="text" name="fname" placeholder="Type your first name" maxlength = "50">
						<span class="focus-input100"></span>
					</div>

                    <div class="wrap-input100 m-b-23">
						<span class="label-input100">Middle Initial</span>
						<input class="input100" type="text" name="middle_in" placeholder="Type your middle initial" maxlength = "1" >
						<span class="focus-input100"></span>
					</div>

                    <div class="wrap-input100 validate-input m-b-23" data-validate = "Email is required">
						<span class="label-input100">Email</span>
						<input class="input100" type="email" name="email" placeholder="Type your email">
						<span class="focus-input100" data-symbol="&#xf206;"></span>
					</div>

					<div class="wrap-input100 validate-input" data-validate="Password is required">
						<span class="label-input100">Password</span>
						<input class="input100" type="password" name="pass" placeholder="Type your password">
						<span class="focus-input100" data-symbol="&#xf190;"></span>
					</div>
					<br>
						
					<select name="campus" class="field input" style="color: black; width: 392px; border-color: white; border-radius: 5px; border: 2px solid #e8e8e8; height: 40px; font-size: 17px; margin-top: 20px; padding:5px;" required>
							<option value="">Select Campus :</option>
								<!-- Fetch the list of usertype in usertype table from database -->
								<?php
									$i=0;
									while($DB_ROW = mysqli_fetch_array($sql_campus)) {
									?>
									<option>
									<?php echo $DB_ROW["Campus"]; ?></option>
									<?php
									$i++;
									}
									?>
					</select>
					
					<div class="wrap-input100 validate-input" data-validate="Profile picture is required">
					<br><span class="label-input100">Upload Profile Picture</span><br>
						<input type="file" name="image" accept="image/x-png,image/gif,image/jpeg,image/jpg" style="margin-top: 10px;" required>
					</div>

					<div class="container-login100-form-btn m-t-20" style="color:red;">
						<?php echo $error?> <hr>
					</div>
					
					<div class="container-login100-form-btn">
						<div class="wrap-login100-form-btn">
							<div class="login100-form-bgbtn"></div>
							<button class="login100-form-btn" style="background-color: #e65c00;">
								REGISTER ADMIN
							</button>
						</div>
					</div>
				</form>
			</div>
		</div>
	</div>
	

	<div id="dropDownSelect1"></div>

	<!--<script> 
	function add(bd){ 
    //calculate month difference from current date in time  
    var month_diff = Date.now() - dob.getTime();  
    //convert the calculated difference in date format  
    var age_dt = new Date(month_diff);   
    //extract year from date      
    var year = age_dt.getUTCFullYear();
	var my_year = dob.getUTCFullYear();  
    //now calculate the age of the user  
    var age = Math.abs(year - my_year);
	
	if(age < 18)
	{
		alert("Invalid birthdate!");
	}
	} 

</script> -->  

<!--===============================================================================================-->
	<script src="vendor/jquery/jquery-3.2.1.min.js"></script>
<!--===============================================================================================-->
	<script src="vendor/animsition/js/animsition.min.js"></script>
<!--===============================================================================================-->
	<script src="vendor/bootstrap/js/popper.js"></script>
	<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<!--===============================================================================================-->
	<script src="vendor/select2/select2.min.js"></script>
<!--===============================================================================================-->
	<script src="vendor/daterangepicker/moment.min.js"></script>
	<script src="vendor/daterangepicker/daterangepicker.js"></script>
<!--===============================================================================================-->
	<script src="vendor/countdowntime/countdowntime.js"></script>
<!--===============================================================================================-->
	<script src="js/main.js"></script>

</body>
</html>