<?php  namespace App\Controllers\Configuracion;


use App\Entities\Usuarios\UserEntity;

use App\Models\Usuarios\UserGroupModel;
use App\Models\Usuarios\GroupUserModel;
use App\Models\Usuarios\UserModel;

use App\Libraries\PasswordHash;

class Users extends \App\Controllers\GoBaseController { 

    private $group_model;
    private $group_user_model;
    private $user_model;


	use \CodeIgniter\API\ResponseTrait;

    protected static $primaryModelName = 'App\Models\Usuarios\UserModel';

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

    protected static $viewPath = 'themes/backend/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 UserGroupModel();
        $this->group_user_model = new GroupUserModel();
        $this->user_model = new UserModel();

        $this->viewData['pageTitle'] = lang('Users.moduleTitle');
        parent::initController($request, $response, $logger);
        
    }

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

        parent::index();

    }

    public function add() { 
        
        $requestMethod = $this->request->getMethod();

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

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

            $postData = $this->request->getPost();
            
            if(!empty($postData['password'])){
                $phpass = new PasswordHash(8, true);
                $postData['password'] = $phpass->HashPassword($this->request->getPost('password'));
            }
            
            $currentGroups = $postData['group'];
            unset($postData['group']);

			$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
            
            if ($this->request->getPost('last_ip') == null ) {
                $sanitizedData['last_ip'] = '::1';
            }

            $sanitizedData['token'] = md5(uniqid(rand(), true));

            $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', [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 = $this->model->db->insertID();
                foreach($currentGroups as $group){
                    $group_user_data = [
                        'token_user' => $sanitizedData['token'],
                        'token_group' => $group
                    ];
                    $this->group_user_model->insert($group_user_data);
                }

                $message = lang('Basic.global.saveSuccess', [mb_strtolower(lang('Users.user'))]) . 'Downloads';
                $message .= anchor(route_to('editUser', $id), lang('Basic.global.continueEditing').'?');
                $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['paisList'] = $this->getPaisListItems();

        $this->viewData['formAction'] = route_to('createUser');
        $this->viewData['groups'] = $this->group_model->select('token,title')->findAll();
        
        $this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' Users.php' .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();
        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;

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

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

            $nullIfEmpty = true; // !(phpversion() >= '8.1');
        
            $postData = $this->request->getPost();
            $currentGroups = $postData['group'];
            unset($postData['group']);

            if(!empty($postData['password'])){
                $phpass = new PasswordHash(8, true);
                $postData['password'] = $phpass->HashPassword($this->request->getPost('password'));
            }

            $sanitizedData = $this->sanitized($postData, $nullIfEmpty);
            if ($this->request->getPost('tfa') == null ) {
                $sanitizedData['tfa'] = false;
            }
            if ($this->request->getPost('blocked') == null ) {
                $sanitizedData['blocked'] = false;
            }
            if ($this->request->getPost('last_ip') == null ) {
                $sanitizedData['last_ip'] = '::1';
            }

            $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('Users.user'))]);
            	    $this->session->setFlashdata('formErrors', $this->model->errors());
            	
            	endif;

            	$user->fill($sanitizedData);

            	$thenRedirect = false;
            endif;
            if ($noException && $successfulResult) :
                $postData = $this->request->getPost();
                
                $this->group_user_model->where('token_user', $user->token)->delete();
                foreach($currentGroups as $group){
                    $group_user_data = [
                        'token_user' => $user->token,
                        'token_group' => $group
                    ];
                    $this->group_user_model->insert($group_user_data);
                }
                
                $id = $user->id_user ?? $id;
                $message = lang('Basic.global.updateSuccess', [mb_strtolower(lang('Users.user'))]) . 'Downloads';
                $message .= anchor(route_to('editUser', $id), lang('Basic.global.continueEditing').'?');
                $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['paisList'] = $this->getPaisListItems();
        
        $this->viewData['formAction'] = route_to('updateUser', $id);

        $this->viewData['selectedGroups'] = $this->group_user_model->select('token_group')->where('token_user', $user->token)->findAll();
        $this->viewData['groups'] = $this->group_model->select('token,title')->findAll();

        $this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' Users.php' .lang('Users.user').' '.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_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);
        }
    }

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

        $registers = $paisModel->findAll();

		return $registers;
	}
        
}
