<?php

declare(strict_types=1);

namespace App\Modules\Administration\Services;

use PDO;
use System\Contracts\DatabaseInterface;

final class AuthenticationService
{
    private PDO $pdo;

    public function __construct(
        DatabaseInterface $database
    ) {
        $this->pdo = $database->getConnection();
    }

    public function attempt(
        string $username,
        string $password
    ): bool {
        $statement = $this->pdo->prepare(
            'SELECT *
             FROM users
             WHERE username = ?
             AND active = 1
             LIMIT 1'
        );

        $statement->execute([
            $username
        ]);

        $user = $statement->fetch(
            PDO::FETCH_ASSOC
        );

        if (!$user) {
            return false;
        }

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

        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        session_regenerate_id(true);

        $_SESSION['user_id'] = $user['id'];

        $_SESSION['username'] = $user['username'];

        $_SESSION['full_name'] = $user['full_name'];

        $_SESSION['authenticated'] = true;

        return true;
    }

    public function check(): bool
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        return isset($_SESSION['authenticated'])
            && $_SESSION['authenticated'] === true;
    }

    public function logout(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        $_SESSION = [];

        if (ini_get('session.use_cookies')) {

            $params = session_get_cookie_params();

            setcookie(
                session_name(),
                '',
                time() - 42000,
                $params['path'],
                $params['domain'],
                $params['secure'],
                $params['httponly']
            );
        }

        session_destroy();
    }
}