<?php

namespace App\Support;

use App\Models\ProviderOffer;
use Illuminate\Http\Request;

class OfferAudience
{
    public static function deviceForRequest(?Request $request = null): string
    {
        $request ??= request();
        $agent = strtolower((string) $request->userAgent());

        if (str_contains($agent, 'android')) {
            return 'android';
        }

        if (preg_match('/iphone|ipad|ipod/', $agent)) {
            return 'ios';
        }

        return 'desktop';
    }

    public static function allows(ProviderOffer $offer, ?string $country = null, ?string $device = null): bool
    {
        $country = strtoupper(trim((string) $country));
        $device = strtolower(trim((string) ($device ?: self::deviceForRequest())));
        $countries = self::countries($offer);

        if ($country !== '' && $countries && !in_array($country, $countries, true)) {
            return false;
        }

        return in_array($device, $offer->normalizedDevices(), true);
    }

    public static function countries(ProviderOffer $offer): array
    {
        return collect(preg_split('/[,|]/', (string) $offer->countries))
            ->map(fn ($country) => strtoupper(trim((string) $country)))
            ->filter(fn ($country) => $country !== '' && !in_array($country, ['ALL', 'WORLDWIDE', 'GLOBAL', '*'], true))
            ->unique()
            ->values()
            ->all();
    }
}
