<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class Site extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'logo_path',
        'redirect_url',
        'sid',
        'api_key',
        'secret_key',
        'withdraw_url',
        'notify_url',
        'deposit_callback_url',
        'is_active',
        'created_by',
    ];

    protected $casts = [
        'is_active' => 'boolean',
    ];

    public function transactions()
    {
        return $this->hasMany(Transaction::class);
    }

    public function financeGroupLimits()
    {
        return $this->hasMany(FinanceGroupSiteLimit::class);
    }

    public function bankAccountStatuses()
    {
        return $this->hasMany(BankAccountSiteStatus::class);
    }

    public function financeGroupStatuses()
    {
        return $this->hasMany(FinanceGroupSiteStatus::class);
    }

    public function financeGroupCryptoLimits()
    {
        return $this->hasMany(FinanceGroupSiteCryptoLimit::class);
    }

    public function paymentPopup()
    {
        return $this->hasOne(SitePaymentPopup::class);
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public static function generateUniqueSid(): string
    {
        do {
            $sid = 'pg_sid_' . Str::lower(Str::random(32));
        } while (static::where('sid', $sid)->exists());

        return $sid;
    }

    public static function generateUniqueApiKey(): string
    {
        do {
            $apiKey = 'pg_key_' . Str::lower(Str::random(32));
        } while (static::where('api_key', $apiKey)->exists());

        return $apiKey;
    }

    public function getLogoUrlAttribute(): ?string
    {
        if (!$this->logo_path) {
            return null;
        }

        if (preg_match('/^https?:\/\//i', $this->logo_path)) {
            return $this->logo_path;
        }

        if ($this->id) {
            $version = md5((string) $this->logo_path . '|' . (string) optional($this->updated_at)->timestamp);
            return route('site.logo', ['id' => $this->id, 'v' => $version], false);
        }

        return Storage::disk('public')->url($this->logo_path);
    }
}
