<?php 
     require_once 'db.connect.php';
     require_once 'helpers/func/helper.php';

     $errorMessage = '';
     $charLimit = 3;
     $errors = array('email' => '', 'password' => '');
 
     if(isset($_SESSION['username'])){
         redirect('index.php');
     }

     if(isset($_POST['submit'])){
        if($_POST['email'] === ''){
            $errors['email'] = 'Email must be Specified';
        }
        if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
            $errors['email'] = 'Invalid Email format';
        }
    
        
        if($_POST['password'] === ''){
            $errors['password'] = 'Password must be Specified';
        }
        if($_POST['password'] < $charLimit){
            $errors['password'] = 'Password not strong enough!';
        }

        $email = $_POST['email'];
        $password = $_POST['password'];

        $sql = "SELECT * FROM users WHERE email = '".$email."'";

        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            // output data of each row
            $row = $result->fetch_assoc();
                $id = $row['id'];
                $username = $row['username'];
                $email = $row['email'];
                $result_password = $row['password'];
                $role = $row['role'];
                $avatar = $row['avatar'];

                if ($password !== $result_password){
                    $errors['password'] = "Incorrect password.";
                }else{
                    $_SESSION['id'] = $id;
                    $_SESSION['username'] = $username;
                    $_SESSION['avatar'] = $avatar;
                    $_SESSION['signed_in'] = true;

                    if($_SERVER['HTTP_REFERER'] === "/eduask/signin"){
                        redirect("index.php");
                    }else{
                        redirect($_SERVER['HTTP_REFERER']);
                    }
                }
        } else {
            $errorMessage = 'User does not exist. Please sign in';
        }
    }

?>

<form class="col s12" method="post" action="">
    <?php print $errorMessage; ?>
    <div class="row">
        <div class="input-field col s12">
            <input id="email" type="email" name="email" class="validate">
            <label for="email" data-error="wrong" data-success="right">Email</label>
            <?php print $errors['email'] ?>
        </div>
    </div>
    <div class="row">
        <div class="input-field col s12">
            <input id="password" type="password" name="password" class="validate">
            <label for="password" data-error="wrong" data-success="right">Password</label>
            <?php print $errors['password'] ?>
        </div>
    </div>
    <div class="row">
        <div class="input-field">
            <input id="submitBtn" type="submit" name="submit" class="waves-effect waves-light btn black col s12">
        </div>
    </div>
</form>