<?php

namespace App\Models;

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

class PaymentLedger extends Model
{
    use HasFactory;

    protected $fillable = [
        'buyer_id',
        'total_in',
        'total_out',
        'current_balance',
        'last_updated'
    ];

    protected $casts = [
        'total_in' => 'decimal:2',
        'total_out' => 'decimal:2',
        'current_balance' => 'decimal:2',
        'last_updated' => 'datetime',
    ];

    public function buyer(): BelongsTo
    {
        return $this->belongsTo(Buyer::class);
    }

    /**
     * Update ledger balance for a buyer
     */
    public function updateBalance(): void
    {
        $totalIn = AdvancePayment::where('buyer_id', $this->buyer_id)
            ->where('status', 'received')
            ->sum('amount');

        $totalOut = PaymentAllocation::whereHas('advancePayment', function ($query) {
            $query->where('buyer_id', $this->buyer_id);
        })->sum('amount');

        $this->update([
            'total_in' => $totalIn,
            'total_out' => $totalOut,
            'current_balance' => $totalIn - $totalOut,
            'last_updated' => now(),
        ]);
    }

    /**
     * Get or create ledger for a buyer
     */
    public static function getOrCreateForBuyer($buyerId): self
    {
        $ledger = static::where('buyer_id', $buyerId)->first();

        if (!$ledger) {
            $ledger = static::create([
                'buyer_id' => $buyerId,
                'total_in' => 0,
                'total_out' => 0,
                'current_balance' => 0,
                'last_updated' => now(),
            ]);
        }

        return $ledger;
    }

    /**
     * Update all ledgers (for maintenance)
     */
    public static function updateAllLedgers(): void
    {
        $buyers = Buyer::has('advancePayments')->get();
        
        foreach ($buyers as $buyer) {
            $ledger = static::getOrCreateForBuyer($buyer->id);
            $ledger->updateBalance();
        }
    }

    /**
     * Get formatted balance with color
     */
    public function getFormattedBalanceAttribute(): string
    {
        $color = $this->current_balance >= 0 ? 'success' : 'danger';
        return '<span class="text-' . $color . ' fw-bold">₹' . number_format($this->current_balance, 2) . '</span>';
    }

    /**
     * Check if ledger has positive balance
     */
    public function getHasPositiveBalanceAttribute(): bool
    {
        return $this->current_balance > 0;
    }

    /**
     * Check if ledger has negative balance (over-allocated)
     */
    public function getHasNegativeBalanceAttribute(): bool
    {
        return $this->current_balance < 0;
    }
}