<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Supplier extends Model
{
    protected $fillable = ['name', 'phone', 'address', 'balance'];

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

    public function payments()
    {
        return $this->hasMany(SupplierPayment::class);
    }

    // Recalculate balance from purchases and payments
    public function recalculateBalance(): void
    {
        $totalPurchases = $this->purchases()->sum('total_amount');
        $totalPayments = $this->payments()->sum('amount');
        $this->update(['balance' => $totalPurchases - $totalPayments]);
    }
}
