<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use App\Models\User;

class Campaign extends Model
{
    use HasFactory, SoftDeletes;

    protected $guarded = [];

    protected $casts = [
        'featured' => 'boolean',
        'is_hot' => 'boolean',
        'curation_locked' => 'boolean',
        'starts_at' => 'datetime',
        'ends_at' => 'datetime',
    ];

    public function launchUrlFor(User $user): string
    {
        $url = $this->direct_url ?: optional($this->offerwall)->iframe_url ?: '';
        $replacements = [
            '{user_id}' => $user->id,
            '{USER_ID}' => $user->id,
            '{uid}' => $user->id,
            '{UID}' => $user->id,
            '{subid}' => $user->id,
            '{SUBID}' => $user->id,
            '{username}' => rawurlencode($user->username),
            '{USERNAME}' => rawurlencode($user->username),
            '{email}' => rawurlencode($user->email),
            '{EMAIL}' => rawurlencode($user->email),
        ];

        return str_replace(array_keys($replacements), array_values($replacements), $url);
    }

    public function offerwall(): BelongsTo
    {
        return $this->belongsTo(Offerwall::class);
    }

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