<?php 
    namespace App\Controllers;

    use CodeIgniter\Exceptions\PageNotFoundException;
    use App\Models\UsuarioModel;
    
    class MiPerfil extends BaseController
    {

        protected $usuarioModel;
        public function __construct()
        {
            $this->usuarioModel= new UsuarioModel();
        }
        

        public function index()
        {
            $usuario=$this->usuarioModel->where('id',session()->get('usuario')["id"])->first();
            return view('miperfil/miperfil',["usuario"=>$usuario]);
        }

        public function update(){
            $data = $this->request->getPost();
            $id=session()->get('usuario')["id"];

            $existeEmail = $this->usuarioModel->where('email', $data['email'])->where('id !=',$id)->where('deleted_at',null)->first();
            $existeRut = $this->usuarioModel->where('rut', $data['rut'])->where('id !=',$id)->where('deleted_at',null)->first();
            
            if ($existeEmail) {
                return $this->response->setJSON([
                    'success' => false,
                    'message' => 'El email ya está registrado.'
                ]);
                die();
            }
            if ($existeRut) {
                return $this->response->setJSON([
                    'success' => false,
                    'message' => 'El RUT ya está registrado.'
                ]);
                die();
            }
            
            $usuario=[
                "email"=>$data['email'],
                "nombre"=>$data['nombre'],
                "rut"=>$data['rut'],
            ];

            if (!empty($data['password'])) {
                $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            }

            $this->usuarioModel->update($id, $usuario);

            return $this->response->setJSON([
                'success' => true,
                'message' => 'Perfil modificado correctamente.',
                'data' => [
                    'user' => $data
                ]
            ]);
        }
    }
    
?>