<?php

namespace App\Models;

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

class Supplier extends Model
{
    use HasFactory;

    protected $fillable = ['user_id','name','phone','address','opening_balance','status'];
    protected $casts = ['opening_balance' => 'decimal:2'];

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

    public function getCurrentDueAttribute()
    {
        $sum = $this->transactions()->selectRaw('COALESCE(SUM(debit),0) as d, COALESCE(SUM(credit),0) as c')->first();
        return (float)$this->opening_balance + ((float)$sum->d - (float)$sum->c);
    }
}