<?php
	require_once('source/session.php');
	require_once('source/error.php');
	require_once('source/dbconfig.php');
	require_once('source/function.php');
	
	if(isset($_POST['signin']))
	{
		try {
			// INSERT RECORD
			$email	   		= strip_tags($_POST['username']);
			$pass	   		= strip_tags($_POST['password']);
			$password  		= md5(md5($salt . md5($pass)) . $salt);

			
			//Get Duplicate Username OR Email
			$STH = $DBH->prepare("SELECT * FROM tbl_user WHERE email = :email");
			$STH->bindParam(':email', $email);
			$STH->execute();
			$row = $STH->fetch(PDO::FETCH_ASSOC);
			
			
			if($STH->rowCount() == 1)
			{
				
				if($password == $row['password'])
				{
					
					$rows2 = sql($DBH, "SELECT * FROM tbl_user WHERE email = ?", array($email), "rows");							
					foreach($rows2 as $row2)
					{	
						$user_status 	  		= $row2['status'];
						$user_t 	  		= $row2['teacher'];
						if($user_status == "Inactive"){
							redirect('index.php?msg=inactive');
						}else if($user_t == "true"){
							redirect('index.php?msg=st_failed');
						}
					}
					
					switch($row['access_level'])
					#1) User
					{
						###########Case No:1
						#1) User
						case "User":
												
						#Redirect
						$_SESSION['msg'] = "signin";
						redirect('main.php');
						break;

						###########Default Case:
						default:
						#Redirect
						$_SESSION['msg'] = "failed";
						redirect('index.php');
						break;
					}
					//Switch Close
				}
				else
				{
					#Redirect
					$_SESSION['msg'] = "failed";
					redirect('index.php');
					//echo "Not Verify";
				}
			}
			else
			{
					$_SESSION['msg'] = "failed";
					redirect('index.php');
					//echo "No Record Found";
			}
		}
		catch(PDOException $e) { 
			file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND); # Errors Log File
				redirect('index.php?msg=failed');
		}
	}
	else
	{
				redirect('index.php?msg=failed');
	}
?>