
<?php

require_once __DIR__.'/jwt.php';

class EmployeeAuth {

    public static function id(){

        $headers = getallheaders();

        if(!isset($headers['Authorization'])){
            Response::error("Authorization token missing",401);
        }

        $token = str_replace("Bearer ","",$headers['Authorization']);

        $payload = JWTAuth::verify($token);

        return $payload->provider_id;

    }

    public static function check($permission_key){

        $employee_id = self::id();

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

        $stmt = $conn->prepare("

        SELECT p.permission_key

        FROM employees e

        JOIN role_permissions rp
        ON e.role_id = rp.role_id

        JOIN permissions p
        ON rp.permission_id = p.id

        WHERE e.id = :employee
        AND p.permission_key = :permission

        LIMIT 1

        ");

        $stmt->execute([
        ':employee'=>$employee_id,
        ':permission'=>$permission_key
        ]);

        if(!$stmt->fetch()){
            Response::error("Permission denied",403);
        }

    }

}