<?php
declare(strict_types=1);

namespace App\Core;

use App\Core\Database;

final class Auth
{
    public static function check(): bool
    {
        return is_array(Session::get('auth_user'));
    }

    public static function user(): ?array
    {
        $user = Session::get('auth_user');

        return is_array($user) ? $user : null;
    }

    public static function id(): ?int
    {
        $user = self::user();

        return isset($user['id']) ? (int) $user['id'] : null;
    }

    public static function role(): ?string
    {
        $user = self::user();

        return isset($user['role']) ? (string) $user['role'] : null;
    }

    public static function login(array $user): void
    {
        Session::regenerate(true);
        Session::put('auth_user', [
            'id' => (int) $user['id'],
            'nama' => (string) $user['nama'],
            'email' => (string) $user['email'],
            'whatsapp' => (string) $user['whatsapp'],
            'role' => (string) $user['role'],
        ]);
        Session::put('last_activity', time());
    }

    public static function logout(): void
    {
        Session::forget('auth_user');
        Session::forget('last_activity');
        Session::regenerate(true);
    }

    public static function attempt(string $identifier, string $password): ?array
    {
        $user = Database::query(
            'SELECT * FROM users WHERE email = :identifier OR whatsapp = :identifier LIMIT 1',
            ['identifier' => $identifier]
        )->fetch();

        if (! is_array($user) || ! password_verify($password, (string) $user['password'])) {
            return null;
        }

        return $user;
    }

    public static function enforceTimeout(int $lifetime): void
    {
        if (! self::check()) {
            return;
        }

        $lastActivity = (int) Session::get('last_activity', time());
        if ((time() - $lastActivity) > $lifetime) {
            self::logout();
            Session::flash('status', 'Sesi berakhir, silakan login kembali.');
            redirect('/login');
        }

        Session::put('last_activity', time());
    }
}
