<?php
require_once "../../../bootstrap.php";
require_once "Admin.php";

use Backend\Models\AdminUser;

//Start the php session
session_start();

if(isset($_POST['aLogin'])){

    $userName = $_POST["userName"];
    $password = $_POST["password"];

    $user = AdminUser::firstWhere('user_name', $userName );
    if($user){
        $hashedPassword = $user->password;
        if(password_verify($password, $hashedPassword )){
            $_SESSION['userName'] = $userName;
            $_SESSION['admin'] = true;
            $_SESSION['success'] = "You are now logged in";
            http_response_code(200);
        }else{
            session_destroy();
            echo "Fail to verify password";
            http_response_code(401);
        }

    }else{
        session_destroy();
        echo "No user";
        http_response_code(401);
    }
}else{
    http_response_code(400);
}