<?php

namespace App\Models;

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

class Supplier extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'email',
        'phone',
        'whatsapp',
        'tax_id',
        'address',
        'notes',
        'is_active',
        'currency_id',
        'opening_balance',
        'balance',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'opening_balance' => 'decimal:2',
        'balance' => 'decimal:2',
    ];

    public function currency()
    {
        return $this->belongsTo(Currency::class);
    }

    public function bills()
    {
        return $this->hasMany(Bill::class);
    }

    public function transactions()
    {
        return $this->morphMany(FinancialTransaction::class, 'model');
    }

    /**
     * Get Total Due from Unpaid Bills.
     */
    public function getTotalDueAttribute()
    {
        return $this->bills()
            ->whereIn('status', ['unpaid', 'partial', 'sent'])
            ->get()
            ->sum(function ($bill) {
                return $bill->total - $bill->paid_amount;
            });
    }

    /**
     * Get Advance Credit (Balance field).
     */
    public function getAdvanceBalanceAttribute()
    {
        return $this->balance;
    }

    /**
     * Get Net Balance (Total Due - Advance).
     * Positive: We owe them. Negative: We have credit with them.
     */
    public function getNetBalanceAttribute()
    {
        return $this->total_due - $this->advance_balance;
    }
}
