<?php namespace App\Controllers\Configuracion;

use App\Entities\Usuarios\UserEntity;
use App\Models\Chat\ChatDeparmentModel;
use App\Models\Chat\ChatDeparmentUserModel;
use App\Models\Usuarios\GroupModel;

use App\Models\Usuarios\UserModel;
use App\Models\Usuarios\GroupsUsersModel;
use App\Models\Collection;


class Users extends \App\Controllers\GoBaseController
{

    private $group_model;
    private $group_user_model;
    private $user_model;
    private ChatDeparmentModel $chat_department_model;
    private ChatDeparmentUserModel $chat_department_user_model;


    use \CodeIgniter\API\ResponseTrait;

    protected static $primaryModelName = UserModel::class;
    protected $modelName = ClientePlantillaPreciosLineasModel::class;

    protected static $singularObjectNameCc = 'user';
    protected static $singularObjectName = 'User';
    protected static $pluralObjectName = 'Users';
    protected static $controllerSlug = 'users';

    protected static $viewPath = 'themes/vuexy/form/user/';

    protected $indexRoute = 'userList';


    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {

        $this->group_model = new GroupModel();
        $this->group_user_model = new GroupsUsersModel();
        $this->user_model = new UserModel();
        $this->chat_department_model = model(ChatDeparmentModel::class);
        $this->chat_department_user_model = model(ChatDeparmentUserModel::class);


        $this->viewData['pageTitle'] = lang('Users.moduleTitle');

        // Breadcrumbs (IMN)
        $this->viewData['breadcrumb'] = [
            ['title' => lang("App.menu_configuration"), 'route' => "javascript:void(0);", 'active' => false],
            ['title' => lang("App.menu_users"), 'route' => route_to('userList'), 'active' => true]
        ];

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

    }

    public function index()
    {
        $this->viewData['usingServerSideDataTable'] = true;
        $this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Users.user')]);

        parent::index();
    }

    public function add()
    {

        if ($this->request->getPost()) :

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

            // Obtener contraseña nueva si se ha introducido en texto plano
            if (empty($postData['new_pwd'])) {
                $postData['password'] = 'Safekat2024';  // Contraseña por defecto
            } else {
                $postData['password'] = $postData['new_pwd'];
            }

            // Obtener los grupos a los que pertenece
            $currentGroups = $postData['group'] ?? [];
            $chatDepartments = $postData['chatDepartments'] ?? [];
            unset($postData['group']);
            unset($postData['chatDepartments']);

            // Marcar el username como NULL
            $sanitizedData = $this->sanitized($postData, true);
            
            $noException = true;

            // Obtener proveedor de usuarios
            $users = auth()->getProvider();

            if ($successfulResult = $this->canValidate()) :
                if ($this->canValidate()) :
                    try {

                        // The Email is unique
                        if ($this->user_model->isEmailUnique($sanitizedData['email'])) {

                            // Crear el usuario si pasa la validación
                            $user = new \CodeIgniter\Shield\Entities\User([
                                'username' => null, // If you don't have a username, be sure to set the value to null anyway, so that it passes CodeIgniter's empty data check
                                'first_name' => $sanitizedData['first_name'],
                                'last_name' => $sanitizedData['last_name'],
                                'cliente_id' => $sanitizedData['cliente_id'],
                                'comments' => $sanitizedData['comments'],
                                'email' => $sanitizedData['email'],
                                'password' => $sanitizedData['password'],
                                'status' => $sanitizedData['status'] ?? 0,
                                'active' => $sanitizedData['active'] ?? 0,
                            ]);
                            // Add the user to the system
                            $users->save($user);
                            $successfulResult = true;   // Hacked

                        } // Email is not unique!
                        else {
                            $this->viewData['errorMessage'] = "El correo '". $sanitizedData['email'] ."' ya está registrado en el sistema";
                            $this->session->setFlashdata('formErrors', $this->model->errors());
                            $successfulResult = false;   // Hacked
                        }

                    } catch (\Exception $e) {
                        $noException = false;
                        $this->viewData['errorMessage'] = $e->getMessage();
                    }
                else:
                    $this->viewData['errorMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Users.user'))]);
                    $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 = $users->getInsertID();
                $this->group_user_model->where('user_id', $id)->delete();
                foreach ($currentGroups as $group) {
                    $group_user_data = [
                        'user_id' => $id,
                        'group' => $group
                    ];
                    $this->group_user_model->insert($group_user_data);
                }
                $this->chat_department_user_model->where("user_id", $id)->delete();
                foreach ($chatDepartments as $chatDepartment) {
                    $this->chat_department_user_model->insert([
                        "user_id" => $id,
                        "chat_department_id" => $this->chat_department_model->where("name", $chatDepartment)->first()->id
                    ]);
                }

                $message = lang('Basic.global.saveSuccess', [mb_strtolower(lang('Users.user'))]) . '.';
                $message = ucfirst(str_replace("'", "\'", $message));

                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['user'] = isset($sanitizedData) ? new UserEntity($sanitizedData) : new UserEntity();
        $this->viewData['clienteList'] = $this->getClienteListItems();
        $this->viewData['formAction'] = route_to('createUser');
        $this->viewData['groups'] = $this->group_model->select('keyword, title')->findAll();
        $this->viewData['chatDepartments'] = $this->chat_department_model->findAll();
        $this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('Users.user') . ' ' . lang('Basic.global.addNewSuffix');


        return $this->displayForm(__METHOD__);
    } // end function add()

    public function edit($requestedId = null)
    {
        if ($requestedId == null) {
            return $this->redirect2listView();
        }

        $id = filter_var($requestedId, FILTER_SANITIZE_URL);
        $users = auth()->getProvider();
        $user = $users->findById($id);

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

        if ($this->request->getPost()) :

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

            $currentGroups = $postData['group'] ?? [];
            $chatDepartments = $postData['chatDepartments'] ?? [];

            unset($postData['group']);
            unset($postData['chatDepartments']);

            // Obtener contraseña nueva si se ha introducido en texto plano
            if (!empty($postData['new_pwd'])) {
                $postData['password'] = $postData['new_pwd'];
            }

            $sanitizedData = $this->sanitized($postData, true);

            if ($this->request->getPost('status') == 0) {
                $sanitizedData['status'] = null;
            }

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

                if ($this->canValidate()) :
                    try {

                        if (in_array('cliente-editor', $currentGroups) || in_array('cliente-administrador', $currentGroups)) {
                            if (!array_key_exists('cliente_id', $sanitizedData) || is_null($sanitizedData['cliente_id'])) {
                                $this->viewData['errorMessage'] = lang('Users.errors.cliente_sin_clienteID');
                                $this->session->setFlashdata('formErrors', $this->model->errors());
                                $successfulResult = false;
                            } else {
                                $successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
                            }
                        } else {
                            $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('Users.user'))]);
                    $this->session->setFlashdata('formErrors', $this->model->errors());

                endif;

                $user->fill($sanitizedData);
                $users->save($user);
                $thenRedirect = false;

            endif;
            if ($noException && $successfulResult) :

                $this->group_user_model->where('user_id', $user->id)->delete();
                foreach ($currentGroups as $group) {
                    $group_user_data = [
                        'user_id' => $user->id,
                        'group' => $group
                    ];
                    $this->group_user_model->insert($group_user_data);
                }
                $this->chat_department_user_model->where("user_id", $id)->delete();
                foreach ($chatDepartments as $chatDepartment) {
                    $this->chat_department_user_model->insert([
                        "user_id" => $id,
                        "chat_department_id" => $this->chat_department_model->where("name", $chatDepartment)->first()->id
                    ]);
                }
                $id = $user->id ?? $id;
                $message = lang('Basic.global.updateSuccess', [mb_strtolower(lang('Users.user'))]) . '.';
                $message = ucfirst(str_replace("'", "\'", $message));

                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->session->setFlashData('sweet-success', $message);
                endif;

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

        $this->viewData['user'] = $user;
        $this->viewData['clienteList'] = $this->getClienteListItems($user->cliente_id);
        $this->viewData['formAction'] = route_to('updateUser', $id);
        $this->viewData['selectedGroups'] = $this->group_model->getUsersRoles($requestedId);
        $this->viewData['groups'] = $this->group_model->select('keyword, title')->findAll();
        $this->viewData['chatDepartments'] = $this->chat_department_model->select(["display", "name", "id as chatDepartmentId"])->findAll();
        $this->viewData['chatDepartmentUser'] = $this->chat_department_user_model->getChatDepartmentUser($user->id);
        $this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Users.user') . ' ' . lang('Basic.global.edit3');

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


    public function delete($requestedId = null, bool $deletePermanently = true)
    {

        if ($requestedId == null) :
            return $this->redirect2listView();
        endif;

        $id = filter_var($requestedId, FILTER_SANITIZE_URL);
        $user = $this->model->find($id);

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

        $this->chat_department_user_model->where("user_id", $id)->delete();

        $users = auth()->getProvider();
        $users->delete($user->id);

        $message = "Usuario eliminado correctamente";
        return $this->redirect2listView('successMessage', $message);


    } // end function delete(...)


    public function allItemsSelect()
    {
        if ($this->request->isAJAX()) {
            $onlyActiveOnes = true;
            $reqVal = $this->request->getPost('val') ?? 'id_user';
            $menu = $this->model->getAllForMenu($reqVal . ', first_name', 'first_name', $onlyActiveOnes, false);
            $nonItem = new \stdClass;
            $nonItem->id_user = '';
            $nonItem->first_name = '- ' . 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_user', $reqText ?? 'first_name'];
            $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);
        }
    }

    public function datatable(){

        if($this->request->isAJAX()){

            $reqData = $this->request->getPost();
            if (!isset($reqData['draw']) || !isset($reqData['columns'])) {
                $errstr = 'No data available in response to this specific request.';
                $response = $this->respond(Collection::datatable([], 0, 0, $errstr), 400, $errstr);
                return $response;
            }
            $start = $reqData['start'] ?? 0;
            $length = $reqData['length'] ?? 5;
            $searchValues = get_filter_datatables_columns($reqData);
            $requestedOrder = $reqData['order'] ?? [];

            $resourceData = $this->model->getResource($searchValues);
            foreach ($requestedOrder as $order) {
                $column = $order['column'] ?? 0;
                $dir = $order['dir'] ?? 'asc';
                $orderColumn = UserModel::SORTABLE[$column] ?? null;
                if ($orderColumn) {
                    $resourceData->orderBy($orderColumn, $dir);
                }
            }
            $resourceData = $resourceData->limit($length, $start)->get()->getResultObject();

            return $this->respond(Collection::datatable(
                $resourceData,
                $this->model->getResource([])->countAllResults(),
                $this->model->getResource($searchValues)->countAllResults()
            ));

        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }

    public function getMenuComerciales()
    {
        if ($this->request->isAJAX()) {
            $comerciales = $this->model->getComerciales();

            return $this->respond($comerciales);
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }


    protected function getPaisListItems()
    {
        $data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Pais.pais'))])];
        $paisModel = model('App\Models\Configuracion\PaisModel');

        $registers = $paisModel->findAll();

        return $registers;
    }

    protected function getClienteListItems($selId = null)
    {
        $data = ['' => ""];
        if (!empty($selId)) :
            $clienteModel = model('App\Models\Clientes\ClienteModel');

            $selOption = $clienteModel->where('id', $selId)->findColumn('nombre');
            if (!empty($selOption)) :
                $data[$selId] = $selOption[0];
            endif;
        endif;
        return $data;
    }

}
