<?php

namespace Modules\Roles\Controllers;

use App\Controllers\BaseController;
use App\Models\PermissionModel;
use Modules\Roles\Services\PermissionService;

class PermissionController extends BaseController
{
    protected PermissionModel $permissions;
    protected PermissionService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->permissions = new PermissionModel();
        $this->service      = new PermissionService();
    }

    public function index()
    {
        return view('Modules\Roles\Views\permissions_index', array_merge($this->baseViewData(), [
            'title'       => 'Permissions',
            'breadcrumbs' => ['Dashboard' => base_url('dashboard'), 'Permissions'],
            'grouped'     => $this->permissions->grouped(),
        ]));
    }

    public function store()
    {
        $rules = [
            'group'  => 'required|alpha_dash|max_length[100]',
            'action' => 'required|alpha_dash|max_length[50]',
        ];

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

        $result = $this->service->createCustom($this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/permissions')->with('success', 'Permission created.');
    }

    public function destroy(int $id)
    {
        $result = $this->service->delete($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->to('/permissions')->with('error', $result['error']);
        }

        return redirect()->to('/permissions')->with('success', 'Permission deleted.');
    }
}
