<?php

namespace App\Models;

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

class Party extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'type', 'name', 'code', 'contact_person', 'phone', 'email',
        'address', 'city', 'country', 'opening_balance', 'balance_type',
        'credit_limit', 'notes', 'is_active',
    ];

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

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

    public function sales()
    {
        return $this->hasMany(Sale::class);
    }

    public function vouchers()
    {
        return $this->hasMany(Voucher::class);
    }

    public function challans()
    {
        return $this->hasMany(Challan::class);
    }

    // Scopes
    public function scopeSuppliers($query)
    {
        return $query->whereIn('type', ['supplier', 'both']);
    }

    public function scopeCustomers($query)
    {
        return $query->whereIn('type', ['customer', 'both']);
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    // Computed: total purchase amount
    public function getTotalPurchaseAttribute()
    {
        return $this->purchases()->sum('grand_total');
    }

    public function getTotalSalesAttribute()
    {
        return $this->sales()->sum('grand_total');
    }

    public function getTotalPaidAttribute()
    {
        return $this->purchases()->sum('paid_amount')
             + $this->vouchers()->where('type', 'receipt')->sum('amount');
    }

    public function getCurrentDueAttribute()
    {
        return ($this->purchases()->sum('due_amount'))
             + ($this->sales()->sum('due_amount'))
             - ($this->vouchers()->where('type', 'receipt')->sum('amount'));
    }

    public function getBalanceAttribute()
    {
        $purchase = $this->purchases()->sum('grand_total');
        $sales    = $this->sales()->sum('grand_total');
        $paid     = $this->vouchers()->where('type', 'receipt')->sum('amount');
        $given    = $this->vouchers()->where('type', 'payment')->sum('amount');

        return [
            'purchase'  => $purchase,
            'sales'     => $sales,
            'paid'      => $paid,
            'given'     => $given,
            'net'       => ($purchase + $given) - ($sales + $paid),
        ];
    }
}
