<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\User;
use Illuminate\Database\Eloquent\Relations\HasMany;
use App\Support\OfferAudience;
use App\Support\GeoLocation;
use Carbon\Carbon;

class Offerwall extends Model
{
    use HasFactory;

    protected $guarded = [];

    protected $casts = [
        'show_rate' => 'boolean',
        'is_mobile' => 'boolean',
        'sdk_data' => 'array',
    ];

    public function launchUrlFor(User $user): string
    {
        $replacements = [
            '{user_id}' => $user->id,
            '{USER_ID}' => $user->id,
            '[user_id]' => $user->id,
            '[USER_ID]' => $user->id,
            '{uid}' => $user->id,
            '{UID}' => $user->id,
            '[uid]' => $user->id,
            '[UID]' => $user->id,
            '{subid}' => $user->id,
            '{SUBID}' => $user->id,
            '[subid]' => $user->id,
            '[SUBID]' => $user->id,
            '{username}' => rawurlencode($user->username),
            '{USERNAME}' => rawurlencode($user->username),
            '[username]' => rawurlencode($user->username),
            '[USERNAME]' => rawurlencode($user->username),
            '{email}' => rawurlencode($user->email),
            '{EMAIL}' => rawurlencode($user->email),
            '[email]' => rawurlencode($user->email),
            '[EMAIL]' => rawurlencode($user->email),
            '{country}' => rawurlencode((string) GeoLocation::countryForRequest()),
            '{country_code}' => rawurlencode((string) GeoLocation::countryForRequest()),
            '{os}' => OfferAudience::deviceForRequest(),
            '{device}' => OfferAudience::deviceForRequest(),
        ];

        return str_replace(array_keys($replacements), array_values($replacements), $this->iframe_url);
    }

    public function clicks(): HasMany
    {
        return $this->hasMany(OfferwallClick::class);
    }

    public function providerOffers(): HasMany
    {
        return $this->hasMany(ProviderOffer::class);
    }

    public function apiFeedEnabled(): bool
    {
        $config = $this->sdk_data ?: [];

        if (array_key_exists('offer_feed_enabled', $config)) {
            return filter_var($config['offer_feed_enabled'], FILTER_VALIDATE_BOOLEAN);
        }

        return filled($config['offer_feed_url'] ?? null)
            || str_contains(strtolower($this->name), 'upwall');
    }

    public function hasLiveApiFeed(): bool
    {
        $config = $this->sdk_data ?: [];
        $lastCheckedAt = $config['offer_feed_last_checked_at'] ?? null;

        if (!$this->apiFeedEnabled()
            || !filter_var($config['offer_feed_last_success'] ?? false, FILTER_VALIDATE_BOOLEAN)
            || (int) ($config['offer_feed_last_count'] ?? 0) < 1
            || !$lastCheckedAt) {
            return false;
        }

        try {
            $freshMinutes = max(1, (int) config('rewards.provider_offer_fresh_minutes', 10));

            return Carbon::parse($lastCheckedAt)->gte(now()->subMinutes($freshMinutes));
        } catch (\Throwable) {
            return false;
        }
    }
}
