<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Variation extends Model
{
    use HasFactory;

    protected $fillable = [
        'product_id',
        'title',
        'price',
        'buy_rate',
        'stock',
        'reseller_price', 
        'automatic',
        'provider',
        'provider_product_id',
    ];

    protected $casts = [
        'automatic' => 'boolean',
        'status'    => 'boolean',
    ];
    
    public function getPriceAttribute($value)
    {
        if (auth()->check() && auth()->user()->is_reseller) {
            
            if ($this->reseller_price > 0) {
                return $this->reseller_price;
            }
        }
        return $value;
    }
    

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

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

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

    public function isAutomatic(): bool
    {
        return $this->automatic;
    }

    public function providerType(Order $order)
    {
        $provider = "App\\Services\\TopupProvider\\{$this->provider}";
        return new $provider($order);
    }
}
