<?php

namespace App\Controllers\Admin;

use App\Models\RoleModel;
use App\Models\PermissionModel;
use App\Models\UserRoleModel;

class Roles extends \App\Controllers\BaseController
{
    protected RoleModel $roleModel;
    protected PermissionModel $permissionModel;
    protected UserRoleModel $userRoleModel;

    public function __construct()
    {
        $this->roleModel = new RoleModel();
        $this->permissionModel = new PermissionModel();
        $this->userRoleModel = new UserRoleModel();
    }

    public function index()
    {
        $data = [
            'roles' => $this->applyExclusions($this->roleModel->findAll(), 'roles_list'),
            'title' => 'Rôles & Permissions',
        ];

        return view('admin/roles/index', $data);
    }

    public function create()
    {
        $data = [
            'permissions' => $this->permissionModel->findAll(),
            'title'       => 'Nouveau rôle',
        ];

        return view('admin/roles/create', $data);
    }

    public function store()
    {
        $rules = [
            'name' => 'required|max_length[100]',
            'slug' => 'required|max_length[100]|is_unique[roles.slug]',
        ];

        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $roleId = $this->roleModel->insert([
            'name'        => $this->request->getPost('name'),
            'slug'        => $this->request->getPost('slug'),
            'description' => $this->request->getPost('description'),
        ]);

        $permissionIds = $this->request->getPost('permissions') ?? [];
        $this->roleModel->assignPermissions($roleId, $permissionIds);

        return redirect()->to('/admin/roles')->with('message', 'Rôle créé avec succès.');
    }

    public function edit($id)
    {
        $role = $this->roleModel->find($id);

        if (! $role) {
            return redirect()->to('/admin/roles')->with('error', 'Rôle non trouvé.');
        }

        $data = [
            'role'        => $role,
            'permissions' => $this->permissionModel->findAll(),
            'rolePermissions' => array_column($this->roleModel->getPermissions($id), 'id'),
            'title'       => 'Modifier rôle',
        ];

        return view('admin/roles/edit', $data);
    }

    public function update($id)
    {
        $role = $this->roleModel->find($id);

        if (! $role) {
            return redirect()->to('/admin/roles')->with('error', 'Rôle non trouvé.');
        }

        $rules = [
            'name' => 'required|max_length[100]',
            'slug' => "required|max_length[100]|is_unique[roles.slug,id,{$id}]",
        ];

        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $this->roleModel->update($id, [
            'name'        => $this->request->getPost('name'),
            'slug'        => $this->request->getPost('slug'),
            'description' => $this->request->getPost('description'),
        ]);

        $permissionIds = $this->request->getPost('permissions') ?? [];
        $this->roleModel->assignPermissions($id, $permissionIds);

        return redirect()->to('/admin/roles')->with('message', 'Rôle mis à jour.');
    }

    public function delete($id)
    {
        $this->roleModel->delete($id);
        return redirect()->to('/admin/roles')->with('message', 'Rôle supprimé.');
    }

    // Permissions
    public function permissions()
    {
        $data = [
            'permissions' => $this->permissionModel->findAll(),
            'title'       => 'Permissions',
        ];

        return view('admin/roles/permissions', $data);
    }

    public function storePermission()
    {
        $rules = [
            'name' => 'required|max_length[100]',
            'slug' => 'required|max_length[100]|is_unique[permissions.slug]',
        ];

        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $this->permissionModel->insert([
            'name'        => $this->request->getPost('name'),
            'slug'        => $this->request->getPost('slug'),
            'description' => $this->request->getPost('description'),
        ]);

        return redirect()->to('/admin/roles/permissions')->with('message', 'Permission créée.');
    }

    public function deletePermission($id)
    {
        $this->permissionModel->delete($id);
        return redirect()->to('/admin/roles/permissions')->with('message', 'Permission supprimée.');
    }
}
