<?php

namespace App\Controllers;

use App\Models\UsuarioModel;
use CodeIgniter\Controller;

class AuthController extends Controller
{
    public function login()
    {
        return view('auth/login'); // Certifique-se de que esta view existe
    }

    public function authenticate()
    {
        $session = session();
        $model = new UsuarioModel();
        $email = $this->request->getVar('email');
        $senha = $this->request->getVar('senha');
        $user = $model->getUserByEmail($email);

        // Verifica a senha usando password_verify
        if ($user && password_verify($senha, $user['senha'])) {
            $session->set([
                'id' => $user['id'],
                'nome' => $user['nome'],
                'email' => $user['email'],
                'logged_in' => true,
            ]);
            return redirect()->to('/dashboard');
        } else {
            $session->setFlashdata('error', 'Credenciais inválidas.');
            return redirect()->to('/login');
        }
    }

    public function logout()
    {
        $session = session();
        $session->destroy();
        return redirect()->to('/login');
    }
}
