<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Supplier extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'supplier_code', 'name_en', 'name_ar',
        'vat_registered', 'vat_number', 'cr_number',
        'contact_person', 'mobile', 'phone', 'email',
        'building_number', 'street', 'district', 'city',
        'postal_code', 'additional_number', 'country',
        'payment_terms', 'credit_days', 'credit_limit',
        'opening_balance', 'opening_balance_type',
        'bank_name', 'iban', 'notes', 'status',
    ];

    protected $casts = [
        'credit_limit'    => 'decimal:2',
        'opening_balance' => 'decimal:2',
        'vat_registered'  => 'boolean',
    ];

    public function openingBalances()
    {
        return $this->hasMany(SupplierOpeningBalance::class);
    }

    public function ledgerEntries()
    {
        return $this->hasMany(SupplierLedger::class);
    }

    public function purchases()
    {
        return $this->hasMany(Purchase::class);
    }

    public function getOutstandingBalanceAttribute()
    {
        $opening = $this->openingBalances()->where('status', 'approved')
            ->selectRaw("SUM(CASE WHEN type='payable' THEN amount ELSE -amount END) as balance")
            ->value('balance') ?? 0;
        $activity = $this->ledgerEntries()->selectRaw('COALESCE(SUM(credit - debit), 0) as balance')->value('balance') ?? 0;
        return bcadd((string) $opening, (string) $activity, 2);
    }
}
