<?php

namespace apexl\Io\modules\user\controllers;

use apexl\Io\includes\Controller;
use apexl\Io\includes\System;
use apexl\Io\modules\user\entities\roleEntity;
use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\modules\user\services\currentUser;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

class rolesController extends Controller
{
    /** @var userEntity */
    protected $currentUser;

    public function __construct(currentUser $currentUser)
    {
        parent::__construct();
        $this->currentUser = $currentUser;
    }

    /**
     * @param Request $request
     * @param Response $response
     * @param $args
     * @return String | Response
     * @throws \Exception Automatic install method. Runs the core IO installation process, requires Database user and pass as a minimum to run.
     * @method POST
     */
    public function createUpdate(Request $request, Response $response, $args)
    {
        $body = $request->getParsedBody();

        $role = new roleEntity();
        //check if this is an update or create.
        if ($id = $args["id"] ?? false) {
            $role->load($id);
            if ($role->id === null) {
                $this->output::addResponse($request, [], false); //added so we can hook into this elsewhere.
                return $this->throw404($response);
            }
        }

        $role->name = $body->name;
        unset($body->name);

        $perms = [];
        foreach ($body as $perm => $set) {
            if ($set) {
                $perms[] = $perm;
            }
        }
        $role->permissions = $perms;
        $role->store();
        $this->output::addMessage($this->path->getRouteName($request).'.validation', 'success', $role->name.' '. ($id ? 'updated' : 'created'));
        $this->output::addResponse($request); //added so we can hook into this elsewhere.
        return System::asJson($response);
    }

    public function getRoles($request, $response, $args)
    {
        return $this->getEntityData($request, $response, $args, (new roleEntity()));
    }
}
