<?php

namespace App\Models;

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

class Supplier extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'email',
        'phone',
        'address',
        'contact_person',
        'website',
        'tax_id',
        'payment_terms',
        'notes',
        'status',
        'credit_limit', // Add this
        'current_balance', // Add this
        'credit_terms', // Add this
    ];

    protected $casts = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
        'credit_limit' => 'decimal:2',
        'current_balance' => 'decimal:2',
    ];

    protected $appends = [
        'credit_available',
        'credit_utilization',
        'is_over_limit',
    ];

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

    /**
     * Accessors
     */
    public function getCreditAvailableAttribute()
    {
        $limit = $this->credit_limit ?? 0;
        $balance = $this->current_balance ?? 0;
        
        return max(0, $limit - $balance);
    }

    public function getCreditUtilizationAttribute()
    {
        if ($this->credit_limit <= 0) {
            return 0;
        }
        
        $balance = $this->current_balance ?? 0;
        return min(100, ($balance / $this->credit_limit) * 100);
    }

    public function getIsOverLimitAttribute()
    {
        if ($this->credit_limit <= 0) {
            return false;
        }
        
        return $this->current_balance > $this->credit_limit;
    }

    /**
     * Update balance when purchase is made
     */
    public function updateBalance(float $amount)
    {
        $this->increment('current_balance', $amount);
        $this->save();
    }

    /**
     * Reduce balance when payment is made
     */
    public function reduceBalance(float $amount)
    {
        $this->decrement('current_balance', $amount);
        $this->save();
    }

    /**
     * Check if purchase can be made with current credit
     */
    public function canMakePurchase(float $amount): bool
    {
        if ($this->credit_limit <= 0) {
            return true; // No credit limit set
        }
        
        $newBalance = ($this->current_balance ?? 0) + $amount;
        return $newBalance <= $this->credit_limit;
    }

    /**
     * Scope a query to only include active suppliers.
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * Scope a query to only include suppliers with credit limit.
     */
    public function scopeWithCreditLimit($query)
    {
        return $query->where('credit_limit', '>', 0);
    }

    /**
     * Scope a query to include suppliers over credit limit.
     */
    public function scopeOverCreditLimit($query)
    {
        return $query->whereRaw('current_balance > credit_limit');
    }

    /**
     * Get the total amount spent with this supplier.
     */
    public function getTotalSpentAttribute()
    {
        return $this->purchases()->sum('grand_total');
    }

    /**
     * Get the total amount paid to this supplier.
     */
    public function getTotalPaidAttribute()
    {
        return $this->purchases()->sum('paid_amount');
    }

    /**
     * Get the total outstanding balance.
     */
    public function getTotalOutstandingAttribute()
    {
        return $this->purchases()->sum(DB::raw('grand_total - paid_amount'));
    }

    /**
     * Get purchase statistics
     */
    public function getPurchaseStatsAttribute()
    {
        return [
            'total_purchases' => $this->purchases()->count(),
            'total_amount' => $this->total_spent,
            'total_paid' => $this->total_paid,
            'outstanding' => $this->total_outstanding,
            'avg_order_value' => $this->purchases()->avg('grand_total') ?? 0,
        ];
    }
}