<?php
	include("config.php");
	session_start();
	$error = "";
	
	//fetch members from database 	
	$sql_members = mysqli_query($db, "SELECT * FROM members");
	
	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']);
		$contact = mysqli_real_escape_string($db,$_POST['contact']);
		$email = mysqli_real_escape_string($db,$_POST['email']);
		$password = mysqli_real_escape_string($db,$_POST['pass']);
	    $usertype = "user";
		
		//Encrypt the password of the user
		$encrypted_pwd = md5($password);
		
		        // Generate emails and check duplicates
        $email_existed = false;
        while($row_mem = mysqli_fetch_array($sql_members)) {
            $members_email = $row_mem['Email'];
            if($members_email == $email){
                $email_existed = true;
            }
        }
        
            if($email_existed == false){
		        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'];
						
                        if(isset($_FILES['image'])){
                            $img_name = $_FILES['image']['name'];
                            $tmp_name = $_FILES['image']['tmp_name'];
                        
                            // Check if the file is an image
                            $image_info = getimagesize($tmp_name);
                            if($image_info !== false){
                                $time = time();
                                $new_img_name = $time.$img_name;
                        
                                // Move the uploaded file to the desired location
                                if(move_uploaded_file($tmp_name, "profile_pic/".$new_img_name)){
                                    // Insert user data into the database
                                    $sql = "INSERT INTO members (`Last_Name`, `First_Name`, `Middle_Initial`, `Contact_Number`, `Email`, `Password`, `Profile_Picture`, `Usertype`)
                                            VALUES ('$lname', '$fname', '$middle_in', '$contact', '$email', '$encrypted_pwd', '$new_img_name', '$usertype')";
                        
                                    if(mysqli_query($db, $sql)){
                                        echo '<script>alert("User was registered successfully!")</script>';
                                        echo "<script>top.window.location = 'accounts.php'</script>";
                                    } else {
                                        $error = "Database Error: " . mysqli_error($db);
                                        echo $error;
                                    }
                                } else {
                                    echo "Failed to upload image file.";
                                }
                            } else {
                                echo "The uploaded file is not a valid image.";
                            }
                        }

					}
        		} 
        		else {
        			$error = "Invalid Middle Initial! It only accepts letters";
        		}
            }
            else{
                echo '<script>alert("Email already in use!")</script>';
                $error = "Email already in use!";
            }
	}
	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/brgy_logo.png"/>
<!--===============================================================================================-->
	<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="util.css">
	<link rel="stylesheet" type="text/css" href="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/blue_bg.jfif'); 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/header_1.png" alt="" width="510px" height="120px" style="margin-top: -65px; margin-left: -59px; background-color: black;">
				<br><br>
				<center><h3 style="font-weight: bold;">SIGN-UP</h3></center>
		        <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 = "Contact Number is required">
						<span class="label-input100">Contact Number</span>
						<input class="input100" type="text" name="contact" placeholder="Type your contact number" maxlength = "50">
						<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>
					
					<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: #242e42;">
								REGISTER
							</button>
						</div>
					</div>
				</form>
				<center>
				<p style="font-size: 16px; font-weight: ;">or</p>
				<a href="login-admin.php" style="background-color: ; width: 100%; padding: 12px; border-radius: 25px; color: ; font-size: 16px;">LOGIN</a></center>
				</center>
			</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>