<?php

namespace App\Controllers;

use App\Models\UsuarioModel;
use App\Entities\Usuario;

class Auth extends BaseController
{
    public function login()
    {
        if (session()->get('isLoggedIn')) {
            if ((int)session()->get('user_id_rol') === 1) {
                return redirect()->to(base_url('admin/peliculas'));
            }
            return redirect()->to(base_url('/'));
        }
        return view('auth/login');
    }

    public function loginProcess()
    {
        $session = session();
        $email = $this->request->getPost('email');
        $password = $this->request->getPost('password');

        if (empty($email) || empty($password)) {
            return redirect()->back()->withInput()->with('error', 'Por favor, complete todos los campos.');
        }

        $model = new UsuarioModel();
        $user = $model->where('email', $email)->where('estado', 1)->first();

        if ($user && password_verify($password, $user->password)) {
            $sessionData = [
                'isLoggedIn'     => true,
                'user_id'        => $user->id_usuario,
                'user_nombres'   => $user->nombres,
                'user_apellidos' => $user->apellidos,
                'user_email'     => $user->email,
                'user_id_rol'    => (int)$user->id_rol,
            ];
            $session->set($sessionData);

            if ($user->esAdmin()) {
                return redirect()->to(base_url('admin/peliculas'));
            }
            return redirect()->to(base_url('/'))->with('success', '¡Bienvenido, ' . htmlspecialchars($user->nombres) . '!');
        }

        return redirect()->back()->withInput()->with('error', 'Credenciales incorrectas o usuario inactivo.');
    }

    public function register()
    {
        if (session()->get('isLoggedIn')) {
            return redirect()->to(base_url('/'));
        }
        return view('auth/register');
    }

    public function registerProcess()
    {
        $nombres = $this->request->getPost('nombres');
        $apellidos = $this->request->getPost('apellidos');
        $email = $this->request->getPost('email');
        $password = $this->request->getPost('password');
        $telefono = $this->request->getPost('telefono');

        $model = new UsuarioModel();

        // Validaciones manuales
        $rules = [
            'nombres'   => 'required|min_length[2]|max_length[100]',
            'apellidos' => 'required|min_length[2]|max_length[100]',
            'email'     => 'required|valid_email|is_unique[usuario.email]',
            'password'  => 'required|min_length[6]',
            'telefono'  => 'permit_empty|numeric|min_length[7]|max_length[20]'
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        // Crear instancia de la Entidad Usuario
        $user = new Usuario();
        $user->id_rol = 3; // Cliente
        $user->nombres = $nombres;
        $user->apellidos = $apellidos;
        $user->email = $email;
        $user->password = password_hash($password, PASSWORD_BCRYPT);
        $user->telefono = $telefono;
        $user->estado = 1; // Activo

        if ($model->save($user)) {
            return redirect()->to(base_url('login'))->with('success', 'Registro exitoso. Ya puedes iniciar sesión.');
        }

        return redirect()->back()->withInput()->with('error', 'Ocurrió un error en el registro. Inténtelo de nuevo.');
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to(base_url('login'))->with('success', 'Sesión cerrada correctamente.');
    }
}
