<?php
namespace App\Controllers;

use App\Models\UserModel;

class UserController extends BaseController
{
    public function index()
    {
        $userModel = new UserModel();
        $data['users'] = $userModel->getUsersWithRole();
        $data['title'] = 'Gestion de Usuarios';
        return view('users/index', $data);
    }

    public function create()
    {
        $data['title'] = 'Registrar Usuario';
        return view('users/create', $data);
    }

    public function store()
    {
        $validation = \Config\Services::validation();
        $validation->setRules([
            'username' => 'required|is_unique[usuarios.username]|min_length[3]',
            'password' => 'required|min_length[6]',
            'email'    => 'required|valid_email|is_unique[usuarios.email]',
            'id_rol'   => 'required|numeric'
        ]);

        if (!$validation->withRequest($this->request)->run()) {
            return redirect()->back()->withInput()->with('errors', $validation->getErrors());
        }

        $userModel = new UserModel();
        $data = [
            'username' => $this->request->getPost('username'),
            'password' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
            'email'    => $this->request->getPost('email'),
            'id_rol'   => $this->request->getPost('id_rol')
        ];

        if ($userModel->save($data)) {
            return redirect()->to('/users')->with('success', 'Usuario registrado correctamente');
        }
        return redirect()->back()->withInput()->with('error', 'Error al registrar usuario');
    }

    public function edit($id)
    {
        $userModel = new UserModel();
        $data['user'] = $userModel->find($id);
        if (!$data['user']) {
            return redirect()->to('/users')->with('error', 'Usuario no encontrado');
        }
        $data['title'] = 'Editar Usuario';
        return view('users/edit', $data);
    }

    public function update($id)
    {
        $userModel = new UserModel();
        $user = $userModel->find($id);
        if (!$user) {
            return redirect()->to('/users')->with('error', 'Usuario no encontrado');
        }

        $rules = [
            'username' => "required|is_unique[usuarios.username,id_usuario,$id]|min_length[3]",
            'email'    => "required|valid_email|is_unique[usuarios.email,id_usuario,$id]",
            'id_rol'   => 'required|numeric'
        ];
        if ($this->request->getPost('password')) {
            $rules['password'] = 'min_length[6]';
        }

        $validation = \Config\Services::validation();
        $validation->setRules($rules);

        if (!$validation->withRequest($this->request)->run()) {
            return redirect()->back()->withInput()->with('errors', $validation->getErrors());
        }

        $data = [
            'username' => $this->request->getPost('username'),
            'email'    => $this->request->getPost('email'),
            'id_rol'   => $this->request->getPost('id_rol')
        ];
        if ($this->request->getPost('password')) {
            $data['password'] = password_hash($this->request->getPost('password'), PASSWORD_DEFAULT);
        }

        if ($userModel->update($id, $data)) {
            return redirect()->to('/users')->with('success', 'Usuario actualizado correctamente');
        }
        return redirect()->back()->withInput()->with('error', 'Error al actualizar usuario');
    }

    public function delete($id)
    {
        $userModel = new UserModel();
        $user = $userModel->find($id);
        if (!$user) {
            return redirect()->to('/users')->with('error', 'Usuario no encontrado');
        }
        if ($userModel->delete($id)) {
            return redirect()->to('/users')->with('success', 'Usuario eliminado correctamente');
        }
        return redirect()->back()->with('error', 'Error al eliminar usuario');
    }
}

