<?php

namespace App\Models;

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

class BankInvoice extends Model
{
    use HasFactory;

    protected $fillable = [
        'buyer_id',
        'order_confirmation_id',
        'invoice_number',
        'invoice_date',
        'due_date',
        'amount',
        'tax_amount',
        'total_amount',
        'description',
        'status',
        'bank_document_path',
        'bank_remarks',
        'created_by'
    ];

    protected $casts = [
        'invoice_date' => 'date',
        'due_date' => 'date',
        'amount' => 'decimal:2',
        'tax_amount' => 'decimal:2',
        'total_amount' => 'decimal:2',
    ];

 

protected static function boot()
    {
        parent::boot();

        static::creating(function ($invoice) {
            if (empty($invoice->invoice_number)) {
                $invoice->invoice_number = static::generateInvoiceNumber();
            }
            // Total amount calculate karo
            $invoice->total_amount = $invoice->amount + $invoice->tax_amount;
        });

        // ✅ YEH ADD KARO - Update ke time bhi total amount calculate hoga
        static::updating(function ($invoice) {
            $invoice->total_amount = $invoice->amount + $invoice->tax_amount;
        });

        // ✅ YEH BHI ADD KARO - Saving ke time bhi
        static::saving(function ($invoice) {
            $invoice->total_amount = $invoice->amount + $invoice->tax_amount;
        });
    }
    public static function generateInvoiceNumber(): string
    {
        $lastInvoice = static::latest('id')->first();
        $nextNumber = $lastInvoice ? $lastInvoice->id + 1 : 1;
        return 'INV-' . date('Y') . '-' . str_pad($nextNumber, 5, '0', STR_PAD_LEFT);
    }

  public function calculateTotalAmount(): void
    {
        $this->total_amount = $this->amount + $this->tax_amount;
    }
    public function buyer(): BelongsTo
    {
        return $this->belongsTo(Buyer::class);
    }

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

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function getStatusBadgeColorAttribute(): string
    {
        return match($this->status) {
            'draft' => 'secondary',
            'sent' => 'primary',
            'paid' => 'success',
            'cancelled' => 'danger',
            default => 'secondary',
        };
    }

    public function getIsOverdueAttribute(): bool
    {
        return $this->due_date->isPast() && $this->status !== 'paid';
    }

    public function getDaysUntilDueAttribute(): int
    {
        return now()->diffInDays($this->due_date, false);
    }
}