<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;

class AuthController extends Controller
{
    public function showLogin()
    {
        if (!empty($_SESSION['admin_logged_in'])) {
            $this->redirect('/admin');
        }
        $this->view('admin.login');
    }

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

        $db = Database::getInstance()->getConnection();
        $stmt = $db->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->execute([$user]);
        $userData = $stmt->fetch();

        if ($userData && password_verify($pass, $userData['password'])) {
            $_SESSION['admin_logged_in'] = true;
            $_SESSION['user_id'] = $userData['id'];
            $_SESSION['user_name'] = $userData['name'];
            $_SESSION['user_role'] = $userData['role'];
            $_SESSION['user_permissions'] = json_decode($userData['permissions'] ?? '[]', true);
            
            $this->redirect('/admin');
        } else {
            $this->view('admin.login', ['error' => 'Usuário ou senha inválidos']);
        }
    }

    public function logout()
    {
        unset($_SESSION['admin_logged_in']);
        $this->redirect('/');
    }
}

