<?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);
            makeAdminLogin($userName);
        }else{
            session_destroy();
            http_response_code(401);
            echo json_encode(["message" => "wrong password"]);
        }

    }else{
        session_destroy();
        http_response_code(401);
        echo json_encode(["message" => "admin don't exist"]);
    }
}else{
    http_response_code(400);
}