<?php

namespace App\Controllers;

use App\Models\User\UserModel;

class Home extends BaseController
{
    public function index()
    {
        return view('login');
    }

    public function login()
    {
        if (session()->get('is_logged')) {
            return redirect()->to('/dashboard');
        }

        return view('login');
    }

    public function signin()
    {
        $validationRules = [
            'usuario'    => 'required|valid_email',
            'contrasena' => 'required'
        ];

        if (!$this->validate($validationRules)) {
            return redirect()
                ->to('/login')
                ->with('errors', $this->validator->getErrors())
                ->withInput();
        }

        $email      = trim($this->request->getVar('usuario'));
        $contrasena = trim($this->request->getVar('contrasena'));

        $userModel = new UserModel();

        // Buscar usuario por email
        $user = $userModel
            ->where('Email', $email)
            ->first();

        if (!$user) {
            return redirect()
                ->to('/login')
                ->with('error', 'El usuario no está registrado.');
        }

        // Verificar contraseña
        if (!password_verify($contrasena, $user['Password'])) {
            return redirect()
                ->to('/login')
                ->with('error', 'Contraseña incorrecta.');
        }

        // Crear sesión
        session()->set([
            'PK_User'   => $user['PK_User'],
            'nombre'    => $user['Name'],
            'email'     => $user['Email'],
            'rol'       => $user['Rol'],
            'is_logged' => true
        ]);

        return redirect()
            ->to('/dashboard')
            ->with('success-login', 'Inicio de sesión exitoso.');
    }

    public function logout()
    {
        session()->destroy();

        return redirect()
            ->to('/login')
            ->with('success', 'Sesión cerrada correctamente.');
    }
}
