<?php
declare(strict_types=1);

namespace App;

use App\Repositories\Container;

class Pin
{
    public static function hash(string $pin): string
    {
        return password_hash($pin, PASSWORD_DEFAULT);
    }

    public static function verify(string $pin, string $hash): bool
    {
        return password_verify($pin, $hash);
    }

    /**
     * Verify a username + PIN combo and return the matching active staff user.
     * Admins may enter their password instead of a PIN (they aren't forced to set one).
     * Returns null if invalid.
     */
    public static function authenticate(string $username, string $secret): ?array
    {
        $users = Container::users();
        $user = $users->findByUsername($username);
        if (!$user) return null;
        if (empty($user['is_active'])) return null;
        if (!in_array($user['role'] ?? '', ['STAFF', 'ADMIN', 'ARTIST'], true)) return null;

        // Primary: PIN if set
        if (!empty($user['pin_hash']) && self::verify($secret, $user['pin_hash'])) {
            return $user;
        }
        // Fallback for admins: accept password
        if (($user['role'] ?? '') === 'ADMIN' && !empty($user['password_hash']) && password_verify($secret, $user['password_hash'])) {
            return $user;
        }
        return null;
    }
}
