<?php

namespace App\Models;

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

class Supplier extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'tenant_id',
        'name',
        'company_name',
        'contact_person',
        'phone',
        'email',
        'address',
        'supplier_type',
        'credit_limit',
        'current_credit_balance',
        'payment_terms_days',
        'opening_balance',
        'tax_number',
        'license_number',
        'notes',
        'is_active',
    ];

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

    public const TYPE_MANUFACTURER  = 'manufacturer';
    public const TYPE_DISTRIBUTOR   = 'distributor';
    public const TYPE_WHOLESALER    = 'wholesaler';
    public const TYPE_LOCAL         = 'local';

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

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

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

    public function ledger(): HasMany
    {
        return $this->hasMany(SupplierLedger::class)->orderBy('transaction_date')->orderBy('id');
    }

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

    public function scopeOverLimit($query)
    {
        return $query->whereColumn('current_credit_balance', '>=', 'credit_limit')
                     ->where('credit_limit', '>', 0);
    }

    public function getRemainingCreditAttribute(): float
    {
        return max(0, (float) $this->credit_limit - (float) $this->current_credit_balance);
    }

    public function isOverCreditLimit(float $additionalAmount = 0): bool
    {
        if ($this->credit_limit <= 0) return false;
        return ($this->current_credit_balance + $additionalAmount) > $this->credit_limit;
    }

    public function hasOverdueInvoices(): bool
    {
        return $this->invoices()->where('status', 'overdue')->exists();
    }

    public static function generateReference(): string
    {
        return 'SUP-' . strtoupper(substr(uniqid(), -6));
    }
}
