<?php
namespace EasyChat\Library\Support;

 
final class OfficialSupportRolloutPolicy {
    private $percent;
    private $secret;

    public function __construct(string $raw_percent, string $secret) {
        $raw_percent = trim($raw_percent);
         
         
        $this->percent = $raw_percent === ''
            ? 100
            : (preg_match('/^\d{1,3}$/D', $raw_percent) === 1 ? (int)$raw_percent : 0);
        if ($this->percent < 0 || $this->percent > 100) $this->percent = 0;
        $this->secret = $secret;
    }

    public function hasAudience(): bool {
        return $this->percent > 0;
    }

    public function allows(int $chat_id): bool {
        if ($chat_id <= 0 || $this->percent <= 0) return false;
        if ($this->percent >= 100) return true;
        if ($this->secret === '') return false;

         
         
        $hash = hash_hmac('sha256', 'official-support-chat|' . $chat_id, $this->secret);
        return (hexdec(substr($hash, 0, 4)) % 100) < $this->percent;
    }
}
