<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ProductVariant extends Model
{
    protected $guarded = [];

    protected function casts(): array
    {
        return [
            'dynamic_fields' => 'array',
            'is_featured' => 'boolean',
            'is_best_seller' => 'boolean',
        ];
    }

    public function game()
    {
        return $this->belongsTo(Game::class);
    }

    public function stockCodes()
    {
        return $this->hasMany(StockCode::class);
    }

    public function orderItems()
    {
        return $this->hasMany(OrderItem::class);
    }

    public function providerMappings()
    {
        return $this->hasMany(ProviderProductMapping::class);
    }

    public function displayPrice(): string
    {
        $amountEgp = ($this->sale_price_minor ?? $this->price_minor) / 100;
        $currencyCode = session('store_currency', $this->currency_code ?: 'EGP');
        $currency = Currency::where('code', $currencyCode)->first();

        if (! $currency || $currency->code === $this->currency_code) {
            return number_format($amountEgp, 2).' '.$this->currency_code;
        }

        $exchangeRate = max((float) $currency->exchange_rate, 0.0001);
        $converted = $amountEgp / $exchangeRate;
        $formatted = number_format($converted, 2);

        return $currency->symbol_position === 'before'
            ? $currency->symbol.$formatted
            : $formatted.' '.$currency->symbol;
    }
}
