<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Vendor extends Model
{
    protected $fillable = [
        'name', 'contact_person', 'phone', 'email', 'address', 'ledger_balance',
    ];

    protected function casts(): array
    {
        return ['ledger_balance' => 'decimal:2'];
    }

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

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

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

    public function getTotalPurchasesAttribute(): float
    {
        return (float) $this->materialStocks()
            ->selectRaw('COALESCE(SUM(quantity_received * unit_price), 0) as total')
            ->value('total');
    }

    public function getTotalPaidAttribute(): float
    {
        return (float) $this->payments()->sum('amount');
    }

    public function getOutstandingBalanceAttribute(): float
    {
        return max(0, $this->total_purchases - $this->total_paid);
    }

    public function refreshLedgerBalance(): void
    {
        $totalBilled = (float) $this->materialStocks()
            ->selectRaw('COALESCE(SUM(quantity_received * unit_price), 0) as total')
            ->value('total');

        $totalPaid = (float) $this->payments()->sum('amount');

        $this->updateQuietly([
            'ledger_balance' => max(0, $totalBilled - $totalPaid),
        ]);
    }
}
