<?php

namespace App\Controllers;

use App\Models\User;
use App\Utils\View;

class AuthController
{
    public function login()
    {
        if (isset($_SESSION['user_id'])) {
            $user = (new User())->find($_SESSION['user_id']);
            if ($user['role'] === 'admin') {
                View::redirect('/admin/dashboard');
            } else {
                View::redirect('/client/dashboard');
            }
        }
        View::render('auth.login');
    }

    public function authenticate()
    {
        $email = $_POST['email'] ?? '';
        $password = $_POST['password'] ?? '';

        $userModel = new User();
        $user = $userModel->first('email', $email);

        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_role'] = $user['role'];
            $_SESSION['user_name'] = $user['name'];

            if ($user['role'] === 'admin') {
                View::redirect('/admin/dashboard');
            } else {
                View::redirect('/client/dashboard');
            }
        } else {
            View::render('auth.login', ['error' => 'Credenciais inválidas']);
        }
    }

    public function logout()
    {
        session_destroy();
        View::redirect('/login');
    }
}
