<?php

require_once '../../../core/api_bootstrap.php';
require_once '../../../core/jwt.php';

$data = Request::post();

try {

Validator::required($data,[
'email',
'password'
]);

$db = new Database();
$conn = $db->connect();

$stmt = $conn->prepare("

SELECT id,name,email,password,status,role_id

FROM employees

WHERE email=:email

LIMIT 1

");

$stmt->execute([
':email'=>$data['email']
]);

$employee = $stmt->fetch();

if(!$employee){
Response::error("Invalid credentials",401);
}

if(!password_verify($data['password'],$employee['password'])){
Response::error("Invalid credentials",401);
}

if($employee['status']!='active'){
Response::error("Account suspended",403);
}

/*
Update last login
*/

$conn->prepare("

UPDATE employees

SET last_login=NOW()

WHERE id=:id

")->execute([
':id'=>$employee['id']
]);

$token = JWTAuth::generate($employee['id']);

Response::success([

"token"=>$token,
"employee"=>$employee

]);

}
catch(Exception $e){

Logger::log("system.log",$e->getMessage());

Response::error("Server error",500);

}