<?php

namespace WowLive\Controllers;

use WowLive\Models\User;

class AuthController {
    private $db;
    private $user;

    public function __construct($db) {
        $this->db = $db;
        $this->user = new User($db);
    }

    public function showLogin() {
        if (isset($_SESSION['user_id'])) {
            header('Location: /dashboard');
            exit();
        }
        
        $error = $_SESSION['login_error'] ?? '';
        unset($_SESSION['login_error']);
        
        include '../src/Views/auth/login.php';
    }

    public function login() {
        $username = $_POST['username'] ?? '';
        $password = $_POST['password'] ?? '';

        if (empty($username) || empty($password)) {
            $_SESSION['login_error'] = 'Por favor, preencha todos os campos.';
            header('Location: /login');
            exit();
        }

        if ($this->user->authenticate($username, $password)) {
            $_SESSION['user_id'] = $this->user->id;
            $_SESSION['username'] = $this->user->username;
            $_SESSION['nome'] = $this->user->nome;
            
            header('Location: /dashboard');
            exit();
        } else {
            $_SESSION['login_error'] = 'Usuário ou senha inválidos.';
            header('Location: /login');
            exit();
        }
    }

    public function logout() {
        session_destroy();
        header('Location: /login');
        exit();
    }

    public function requireAuth() {
        if (!isset($_SESSION['user_id'])) {
            header('Location: /login');
            exit();
        }
    }

    public function isAuthenticated() {
        return isset($_SESSION['user_id']);
    }

    public function getCurrentUser() {
        if ($this->isAuthenticated()) {
            $user = new User($this->db);
            if ($user->findById($_SESSION['user_id'])) {
                return $user;
            }
        }
        return null;
    }
}

