<?php

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

EmployeeAuth::check('manage_employees');

$data = Request::post();

try {

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

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

/* verify role */

$stmt = $conn->prepare("
SELECT id
FROM roles
WHERE id=:role
LIMIT 1
");

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

if(!$stmt->fetch()){
Response::error("Invalid role");
}

/* hash password */

$password = password_hash($data['password'],PASSWORD_BCRYPT);

/* create employee */

$stmt = $conn->prepare("

INSERT INTO employees
(name,email,phone,password,role_id,status)

VALUES
(:name,:email,:phone,:password,:role,'active')

");

$stmt->execute([

':name'=>$data['name'],
':email'=>$data['email'],
':phone'=>$data['phone'] ?? null,
':password'=>$password,
':role'=>$data['role_id']

]);

$id = $conn->lastInsertId();

Response::success([
'id'=>$id
],"Employee created");

}
catch(Exception $e){

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

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

}
