<?php

namespace forms;

use classes\authentication;
use Exception;
use objects\users_o;

abstract class form_restrictions_helper_c
{
    protected users_o $users_o;

    /**
     * @throws Exception
     */
    public function __construct()
    {
        // Initialize the users_o object
        $tmp_users_o = (new authentication())->get_user();
        if (!!$tmp_users_o) {
            $this->users_o = $tmp_users_o;
        }
    }

    /**
     * Restrict access, if the user does not have access to the department
     * @throws Exception If the user does not have access to the department
     */
    public function restrictAccessDepartment($department_id): void
    {
        self::requirePermission(
            'department_access_' . $department_id,
            'User does not have access to the department',
        );
    }

    /**
     * Require permission to continue
     * @param string $permission The permission to check
     * @param string $message The error message to throw, if the user does not have permission
     * @throws Exception If the user does not have permission
     */
    public function requirePermission(string $permission, string $message): void
    {
        self::requireAuth();
        // Check if the user has permission
        if (!$this->users_o->hasPermission($permission)) {
            throw new Exception($message);
        }
    }

    /**
     * @throws Exception
     */
    protected function requireAuth(): void
    {
        // Check if the user is authenticated
        if (!isset($this->users_o)) {
            throw new Exception('User not authenticated');
        }
    }
}