<?php

namespace App\Core;

/**
 * ITSWEBER CMS – Authentication
 */
class Auth
{
    private Database $db;
    private Session $session;

    public function __construct(Database $db, Session $session)
    {
        $this->db = $db;
        $this->session = $session;
    }

    /**
     * Attempt to log in a user.
     */
    public function attempt(string $username, string $password): bool
    {
        $user = $this->db->fetch(
            "SELECT * FROM iw_users WHERE (username = :username OR email = :email) AND is_active = 1 LIMIT 1",
            [
                'username' => $username,
                'email' => $username,
            ]
        );

        if (!$user || !password_verify($password, $user['password_hash'])) {
            return false;
        }

        $this->session->regenerate();
        $this->session->set('user_id', $user['id']);
        $this->session->set('user_role', $user['role']);
        $this->session->set('user_name', $user['username']);

        return true;
    }

    /**
     * Log out the current user.
     */
    public function logout(): void
    {
        $this->session->remove('user_id');
        $this->session->remove('user_role');
        $this->session->remove('user_name');
        $this->session->regenerate();
    }

    /**
     * Check if a user is logged in.
     */
    public function check(): bool
    {
        return $this->session->has('user_id');
    }

    /**
     * Get the current user ID.
     */
    public function userId(): ?int
    {
        return $this->session->get('user_id');
    }

    /**
     * Get the current user role.
     */
    public function role(): ?string
    {
        return $this->session->get('user_role');
    }

    /**
     * Check if the current user is an admin.
     */
    public function isAdmin(): bool
    {
        return $this->session->get('user_role') === 'admin';
    }

    /**
     * Get the current user's name.
     */
    public function userName(): ?string
    {
        return $this->session->get('user_name');
    }
}