<?php namespace App\Controllers\Configuracion;

use App\Entities\Usuarios\UserGroupEntity;

use App\Controllers\GoBaseResourceController;
use App\Models\Usuarios\UserGroupModel;
use App\Models\Usuarios\GroupUserModel;

class Group extends \App\Controllers\GoBaseController
{
    use \CodeIgniter\API\ResponseTrait;

    protected static $primaryModelName = 'App\Models\Usuarios\UserGroupModel';
    protected $modelName = UserGroupModel::class;

    protected static $singularObjectNameCc = 'userGroup';
    protected static $singularObjectName = 'Group';
    protected static $pluralObjectName = 'Groups';
    protected static $controllerSlug = 'groups';

    static $viewPath = '';

    protected $indexRoute = 'userGroupList';

    private $group_user_model;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        $this->viewData['pageTitle'] = lang('Group.moduleTitle');
        self::$viewPath = getenv('theme.path') . 'form/group/';

        parent::initController($request, $response, $logger);

    }

    public function index()
    {
        $this->viewData['usingClientSideDataTable'] = true;
        $this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Groups.group')]);
        // IMN
        $this->group_user_model = new GroupUserModel();
        $this->viewData['model'] = $this->group_user_model;

        parent::index();
    }

    public function add()
    {

        $requestMethod = $this->request->getMethod();

        if ($requestMethod === 'post') :

            $nullIfEmpty = true; // !(phpversion() >= '8.1');

            $postData = $this->request->getPost();


            $title = $postData['title'];
            $dashboard = $postData['dashboard'];
            unset($postData['title']);
            unset($postData['dashboard']);
            unset($postData['id_group']);
            unset($postData['save']);

            $controller = null;
            $rules_access = null;

            foreach ($postData as $key => $value) {
                $exp = explode('_', $key);
                $controller[] = $exp[0];
            }

            if ($controller != null) {
                foreach (array_unique($controller) as $item) {
                    $rules_access[$item] = [];

                    foreach ($postData as $key => $value) {
                        $exp = explode('_', $key);
                        if ($exp[0] == $item) {
                            array_push($rules_access[$item], str_replace($exp[0] . '_', '', $key));
                        }
                    }
                }
            }


            $temp_data['rules'] = json_encode($rules_access ?? '{}');
            $temp_data['token'] = md5(uniqid(rand(), true));;
            $temp_data['title'] = $title;
            $temp_data['dashboard'] = $dashboard;

            $sanitizedData = $this->sanitized($temp_data, $nullIfEmpty);

            $noException = true;
            if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :


                if ($this->canValidate()) :
                    try {
                        $successfulResult = $this->model->skipValidation(true)->save($sanitizedData);
                    } catch (\Exception $e) {
                        $noException = false;
                        $this->dealWithException($e);
                    }
                else:
                    $this->viewData['errorMessage'] = lang('Basic.global.formErr1', [lang('Basic.global.record')]);
                    $this->session->setFlashdata('formErrors', $this->model->errors());
                endif;

                $thenRedirect = true;  // Change this to false if you want your user to stay on the form after submission
            endif;
            if ($noException && $successfulResult) :

                $id = $this->model->db->insertID();

                $message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.';

                if ($thenRedirect) :
                    if (!empty($this->indexRoute)) :
                        return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
                    else:
                        return $this->redirect2listView('sweet-success', $message);
                    endif;
                else:
                    $this->viewData['successMessage'] = $message;
                endif;

            endif; // $noException && $successfulResult

        endif; // ($requestMethod === 'post')

        $this->viewData['group'] = isset($sanitizedData) ? new UserGroupModel($sanitizedData) : new UserGroupModel();

        $this->viewData['formAction'] = route_to('createGroup');

        $this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('Group.moduleTitle') . ' ' . lang('Basic.global.addNewSuffix');


        return $this->displayForm(__METHOD__);
    }


    public function edit($requestedId = null)
    {

        helper('general');
        $session = session();

        if ($requestedId == null) :
            return $this->redirect2listView();
        endif;
        $id = filter_var($requestedId, FILTER_SANITIZE_URL);
        $groupEntity = $this->model->find($id);

        if ($groupEntity == false) :
            $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Group.userGroup')), $id]);
            return $this->redirect2listView('errorMessage', $message);
        endif;

        $requestMethod = $this->request->getMethod();

        if ($requestMethod === 'post') :

            $nullIfEmpty = true; // !(phpversion() >= '8.1');

            $postData = $this->request->getPost();

            $id_group = $groupEntity->id_group;
            $token = $groupEntity->token;
            $title = $postData['title'];
            $dashboard = $postData['dashboard'];

            unset($postData['id_group']);
            unset($postData['title']);
            unset($postData['dashboard']);

            $controller = null;
            $rules_access = null;

            foreach ($postData as $key => $value) {
                $exp = explode('_', $key);
                $controller[] = $exp[0];
            }

            if ($controller != null) {
                foreach (array_unique($controller) as $item) {
                    $rules_access[$item] = [];

                    foreach ($postData as $key => $value) {
                        $exp = explode('_', $key);
                        if ($exp[0] == $item) {
                            array_push($rules_access[$item], str_replace($exp[0] . '_', '', $key));
                        }
                    }
                }
            }

            $temp_data['id_group'] = $id_group;
            $temp_data['rules'] = json_encode($rules_access ?? '{}');
            $temp_data['token'] = $token;
            $temp_data['title'] = $title;
            $temp_data['dashboard'] = $dashboard;

            $sanitizedData = $this->sanitized($temp_data, $nullIfEmpty);


            $noException = true;
            if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :


                if ($this->canValidate()) :
                    try {
                        $successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
                    } catch (\Exception $e) {
                        $noException = false;
                        $this->dealWithException($e);
                    }
                else:
                    $this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Group.userGroup'))]);
                    $this->session->setFlashdata('formErrors', $this->model->errors());

                endif;

                $groupEntity->fill($sanitizedData);

                $thenRedirect = false;
            endif;
            if ($noException && $successfulResult) :
                $id = $groupEntity->id ?? $id;
                $message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';

                if ($session->get('group') == $this->request->getPost('token')) {
                    $session->set('rules', $temp_data['rules']);
                }
                if ($thenRedirect) :
                    if (!empty($this->indexRoute)) :
                        return redirect()->to(route_to($this->indexRoute))->with('successMessage', $message);
                    else:
                        return $this->redirect2listView('successMessage', $message);
                    endif;
                else:
                    $this->viewData['successMessage'] = $message;
                endif;

            endif; // $noException && $successfulResult
        endif; // ($requestMethod === 'post')

        $this->viewData['group'] = $groupEntity;

        $this->viewData['formAction'] = route_to('updateGroup', $id);

        $this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Group.userGroup') . ' ' . lang('Basic.global.edit3');


        return $this->displayForm(__METHOD__, $id);
    } // end function edit(...)


    public function allItemsSelect()
    {
        if ($this->request->isAJAX()) {
            $onlyActiveOnes = true;
            $reqVal = $this->request->getPost('val') ?? 'id';
            $menu = $this->model->getAllForMenu($reqVal . ', nombre', 'nombre', $onlyActiveOnes, false);
            $nonItem = new \stdClass;
            $nonItem->id = '';
            $nonItem->nombre = '- ' . lang('Basic.global.None') . ' -';
            array_unshift($menu, $nonItem);

            $newTokenHash = csrf_hash();
            $csrfTokenName = csrf_token();
            $data = [
                'menu' => $menu,
                $csrfTokenName => $newTokenHash
            ];
            return $this->respond($data);
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }

    public function menuItems()
    {
        if ($this->request->isAJAX()) {
            $searchStr = goSanitize($this->request->getPost('searchTerm'))[0];
            $reqId = goSanitize($this->request->getPost('id'))[0];
            $reqText = goSanitize($this->request->getPost('text'))[0];
            $onlyActiveOnes = false;
            $columns2select = [$reqId ?? 'id', $reqText ?? 'nombre'];
            $onlyActiveOnes = false;
            $menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr);
            $nonItem = new \stdClass;
            $nonItem->id = '';
            $nonItem->text = '- ' . lang('Basic.global.None') . ' -';
            array_unshift($menu, $nonItem);

            $newTokenHash = csrf_hash();
            $csrfTokenName = csrf_token();
            $data = [
                'menu' => $menu,
                $csrfTokenName => $newTokenHash
            ];
            return $this->respond($data);
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }
}
