<?php
declare(strict_types=1);

namespace App\Controller\Admin;

use App\Controller\AppController;
use Cake\Event\EventInterface;
use App\Text\Messages;

/**
 * Usuarios Controller
 *
 * @property \App\Model\Table\UsuariosTable $Usuarios
 */
class UsuariosController extends AppController
{
    public $texts;
    public function beforeFilter( EventInterface $event ) {
        parent::beforeFilter( $event );
        $this->viewBuilder()->setLayout('admin/default');
        $this->Authentication->addUnauthenticatedActions(['login']);
        $this->texts = [
            'article' => __('El'),
            'entity' => __('usuario'),
            'article_lower' => __('el'),
        ];
    }
    /**
     * Index method
     *
     * @return \Cake\Http\Response|null|void Renders view
     */
    public function index()
    {

    }
    public function list(){
        $this->viewBuilder()->setLayout("ajax");
        $users = [];
        if($this->request->is("ajax"))
        {
            $conditions = [];
            $users = $this->Usuarios->find('all',
                [
                    'fields' => [
                        'id',
                        'nombre',
                        'apellido',
                        'email',
                        'activo',
                        'rol_id',
                        'empresa_id',
                    ],
                    'conditions' => $conditions,
                    'contain' => [
                        'Empresas' => [
                            'fields' => [
                                'id',
                                'nombre',
                            ]
                        ],
                        'Rols' => [
                            'fields' => [
                                'id',
                                'nombre'
                            ]
                        ]
                    ]
                ]
            );
        }
        $users = array_map(function ($user){
            $company = null;
            if(!empty($user->empresa->nombre))
            {
                $company = $user->empresa->nombre;
            }
            return [
                'id' =>  $user->id,
                'name' => $user->getFullName(),
                'email' => $user->email,
                'rol' => $user->rol->nombre,
                'role_id' => 'role_id_'.$user->rol_id,
                'company' => $company,
                'active' => $user->activo,
            ];
        }, $users->toArray());
        $this->response = $this->response->withType('json');
        $this->response = $this->response->withStringBody(json_encode(["data" => $users]));
        return $this->response;
    }

    /**
     * View method
     *
     * @param string|null $id Usuario id.
     * @return \Cake\Http\Response|null|void Renders view
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $usuario = $this->Usuarios->get($id, contain: ['Rols', 'Empresas']);
        $this->set(compact('usuario'));
    }

    /**
     * Add method
     *
     * @return \Cake\Http\Response|null|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $this->viewBuilder()->setClassName('Ajax.Ajax');
        $user = $this->Usuarios->newEmptyEntity();
        $user->activo = 1;
        if ($this->request->is('post')) {
            $user = $this->Usuarios->patchEntity($user, $this->request->getData());
            if ($this->Usuarios->save($user)) {
                $this->Flash->success(Messages::success('add', $this->texts['article'], $this->texts['entity']));
            }
            else
            {
                $this->Flash->error(Messages::error('add', $this->texts['article_lower'], $this->texts['entity']));
            }
        }
        $roles = $this->Usuarios->Rols->find('list', limit: 200)->all();
        $companies = $this->Usuarios->Empresas->find('list', limit: 200)->all();
        $this->set(compact('user', 'roles', 'companies'));
    }

    /**
     * Edit method
     *
     * @param string|null $id Usuario id.
     * @return \Cake\Http\Response|null|void Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $this->viewBuilder()->setClassName('Ajax.Ajax');
        $user = $this->Usuarios->get($id, contain: []);
        unset($user->clave);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $data = $this->request->getData();
            if(!isset($data['clave']) || empty($data['clave']))
            {
                unset($data['clave']);
            }
            $user = $this->Usuarios->patchEntity($user, $data);
            if ($this->Usuarios->save($user)) {
                $this->Flash->success(Messages::success('edit', $this->texts['article'], $this->texts['entity']));
            }
            else
            {
                $this->Flash->error(Messages::error('edit', $this->texts['article_lower'], $this->texts['entity']));
            }
        }
        $roles = $this->Usuarios->Rols->find('list', limit: 200)->all();
        $companies = $this->Usuarios->Empresas->find('list', limit: 200)->all();
        $this->set(compact('user', 'roles', 'companies'));
    }

    /**
     * Delete method
     *
     * @param string|null $id Usuario id.
     * @return \Cake\Http\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($id = null)
    {
        $success = null;
        $this->viewBuilder()->setClassName('Ajax.Ajax');
        $this->request->allowMethod(['post', 'delete']);
        $user = $this->Usuarios->get($id);
        if ($this->Usuarios->delete($user)) {
            $this->Flash->success(Messages::success('delete', $this->texts['article'], $this->texts['entity']));
            $success = true;
        } else {
            $this->Flash->error(Messages::error('delete', $this->texts['article_lower'], $this->texts['entity']));
            $success = false;
        }
        $this->set(compact('success'));
    }

    public function login()
    {
        $this->viewBuilder()->setLayout( 'admin/login' );
        $this->request->allowMethod(['get', 'post']);
        $result = $this->Authentication->getResult();
        // Sin importar si es POST o GET, redirige si el usuario esta autenticado
        if ($result->isValid()) {
            $user = $this->Authentication->getIdentity();
            if(!empty($this->menus[$user->rol_id][0]['links'][0]['full_url']))
            {
                $redirect = $this->request->getQuery('redirect',$this->menus[$user->rol_id][0]['links'][0]['full_url']);
                return $this->redirect($redirect);
            }
            $this->Flash->error(__('El Rol de usuario no ha sido configurado.'));
            return $this->logout();
        }
        // Muestra los errors si el usuario envió el formulario y fallo la autenticación
        if ($this->request->is('post') && !$result->isValid()) {
            $this->Flash->error(__('Usuario y/o contraseña no válida.'));
        }
    }

    public function logout()
    {
        $result = $this->Authentication->getResult();
        // Sin importar si es POST o GET, redirige si el usuario esta autenticado
        if ($result->isValid()) {
            $user = $this->Authentication->getIdentity();
            $url = ['controller' => 'Usuarios', 'action' => 'login'];
            $this->Authentication->logout();
            return $this->redirect($url);
        }
    }
}
