<?php

use App\Models\Usuarios\GroupModel;
use App\Models\Usuarios\PermisosModel;
use CodeIgniter\HTTP\RedirectResponse;

if (!function_exists('generate_php_roles_constant')) {
    function generate_php_roles_constant()
    {
        // Generate the array of keys
        $array = (new GroupModel())->getRolesList();

        // Start of the file
        $phpCode = "<?php\n\n";

        // Add constant name
        $phpCode .= "const SK_ROLES = [\n";

        // Loop through the array and create constant
        // Loop through the array and create constant
        foreach ($array as $key => $values) {
            $phpCode .= "    '{$key}' => [\n";
            foreach ($values as $subkey => $value) {
                $phpCode .= "        '{$subkey}' => '{$value}',\n";
            }
            $phpCode .= "    ],\n";
        }

        // Close the array
        $phpCode .= "];\n";

        $dirPath = APPPATH . "Config/RBAC";
        if (!is_dir($dirPath)) {
            mkdir($dirPath, 0775, true); // true permite crear carpetas anidadas
        }

        $filePath = $dirPath . "/roles.php";
        file_put_contents($filePath, $phpCode);

    }
}


if (!function_exists('generate_php_permissions_constant')) {
    function generate_php_permissions_constant()
    {
        // Generate the array of keys
        $array = (new PermisosModel())->getPermissionsList();

        // Start of the file
        $phpCode = "<?php\n\n";

        // Add constant name
        $phpCode .= "const SK_PERMISSIONS = [\n";

        // Loop through the array and create constant
        foreach ($array as $key => $value) {
            // Using single quotes to ensure keys/values are emitted as literals
            $phpCode .= "\t'{$key}' => '{$value}',\n";
        }

        // Close the array
        $phpCode .= "];\n";

        $dirPath = APPPATH . "Config/RBAC";
        if (!is_dir($dirPath)) {
            mkdir($dirPath, 0775, true); // true permite crear carpetas anidadas
        }

        $filePath = $dirPath . "/permissions.php";
        file_put_contents($filePath, $phpCode);

    }
}

if (!function_exists('generate_php_permissions_matrix_constant')) {
    function generate_php_permissions_matrix_constant()
    {
        $matrix = (new GroupModel())->getRolesPermissionMatrix();


        // Start of the file
        $phpCode = "<?php\n";

        // Add constant name
        $phpCode .= "const SK_PERMISSION_MATRIX = [\n";

        // Loop through the array and create constant
        foreach ($matrix as $role => $permissions) {
            $phpCode .= "\t\"{$role}\" => [\n";
            foreach ($permissions as $permission) {
                $phpCode .= "\t\t\"{$permission}\",\n";
            }
            $phpCode .= "\t],\n";
        }
        // Close the array
        $phpCode .= "];\n";

        $dirPath = APPPATH . "Config/RBAC";
        if (!is_dir($dirPath)) {
            mkdir($dirPath, 0775, true); // true permite crear carpetas anidadas
        }

        $filePath = $dirPath . "/permissionMatrix.php";
        file_put_contents($filePath, $phpCode);
    }
}




if (!function_exists('checkPermission')) {
    /**
     * Checks if the user has the required permission and redirects accordingly.
     *
     * @param string $sectionPermission The permission to check.
     * @param string|null $redirectRoute The route to redirect to if the permission is not granted.
     * @return RedirectResponse|null Redirect response if the user does not have permission, null otherwise.
     */
    function checkPermission(string $sectionPermission, string $redirectRoute = null)
    {
        $session = \Config\Services::session();
        $response = \Config\Services::response();

        if (!auth()->user()->can($sectionPermission)) {
            $session->setFlashdata('errorMessage', "No tiene permisos de acceso");

            $route = $redirectRoute ?? 'home';
            return $response->redirect(route_to($route));
        }

        return null;
    }
}

if (!function_exists('checkGroups')) {
    /**
     * Verifica si el usuario pertenece a alguno de los grupos especificados.
     *
     * @param array $groups Lista de grupos permitidos.
     * @param string|null $redirectRoute Ruta de redirección si no pertenece a ningún grupo.
     * @return \CodeIgniter\HTTP\RedirectResponse|null
     */
    function checkGroups(array $groups, string $redirectRoute = null)
    {
        $session = \Config\Services::session();
        $response = \Config\Services::response();
        $auth = auth(); // Shield auth service

        $user = $auth->user();

        $inGroup = false;
        foreach ($groups as $group) {
            if ($user->inGroup($group)) {
                $inGroup = true;
                break;
            }
        }

        if (!$inGroup) {
            $session->setFlashdata('errorMessage', 'No tiene permisos de acceso.');
            $route = $redirectRoute ?? 'home';
            return $response->redirect(route_to($route));
        }

        return null;
    }
}

