<?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;
use Illuminate\Notifications\Notifiable;

class Supplier extends Model
{
    use HasFactory, Notifiable;

    protected $fillable = [
        'user_id',
        'name',
        'phone',
        'email',
        'address',
        'current_balance',
        'is_active',
        'is_company_warehouse',
    ];

    protected function casts(): array
    {
        return [
            'current_balance' => 'decimal:2',
            'is_active' => 'boolean',
            'is_company_warehouse' => 'boolean',
        ];
    }

    /**
     * المورد الافتراضي للأصناف بدون مورد (مخزن الشركة).
     */
    public static function getCompanyWarehouseId(): ?int
    {
        return (int) static::where('is_company_warehouse', true)->value('id');
    }

    /**
     * مسار الإشعارات البريدية للمورد.
     */
    public function routeNotificationForMail(): ?string
    {
        return $this->email;
    }

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

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

    public function productVariants(): HasMany
    {
        return $this->hasMany(ProductVariant::class, 'default_supplier_id');
    }

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