<?php

namespace App\Core\Roles\Controllers;

use App\Controllers\BaseController;
use App\Core\Audit\Services\AuditService;
use App\Core\Auth\Models\PermissionModel;
use App\Core\Auth\Models\RoleModel;
use Config\Database;

class RoleController extends BaseController
{
    public function index()
    {
        $roleModel = new RoleModel();
        $roles = $roleModel->orderBy('label')->findAll();
        $permissions = (new PermissionModel())->orderBy('group_name')->orderBy('label')->findAll();

        $rolePermissions = [];
        foreach ($roles as $role) {
            $rolePermissions[(int) $role['id']] = array_column($roleModel->permissions((int) $role['id']), 'id');
        }

        $permissionsByGroup = [];
        foreach ($permissions as $permission) {
            $permissionsByGroup[$permission['group_name']][] = $permission;
        }

        return view('core/roles/index', [
            'title' => 'Rôles et permissions',
            'roles' => $roles,
            'permissionsByGroup' => $permissionsByGroup,
            'rolePermissions' => $rolePermissions,
        ]);
    }

    public function updatePermissions(int $roleId)
    {
        $role = (new RoleModel())->find($roleId);
        if (! $role) {
            return redirect()->back()->with('error', 'Rôle introuvable.');
        }

        if ($role['name'] === 'super_admin') {
            return redirect()->back()->with('error', 'Le rôle Super Admin conserve toujours toutes les permissions.');
        }

        $permissionIds = array_map('intval', (array) $this->request->getPost('permissions'));
        $validIds = array_column((new PermissionModel())->findAll(), 'id');
        $permissionIds = array_values(array_intersect($permissionIds, array_map('intval', $validIds)));

        $db = Database::connect();
        $db->transStart();
        $db->table('core_role_permissions')->where('role_id', $roleId)->delete();
        foreach ($permissionIds as $permissionId) {
            $db->table('core_role_permissions')->ignore(true)->insert([
                'role_id' => $roleId,
                'permission_id' => $permissionId,
            ]);
        }
        $db->transComplete();

        (new AuditService())->log('role.permissions.update', 'role', (string) $roleId, 'Mise à jour des permissions du rôle ' . $role['label']);

        return redirect()->back()->with('success', 'Permissions du rôle mises à jour.');
    }
}
