<?php

namespace App\Models;

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

class Invoice extends Model
{
    use HasFactory;

    protected $fillable = [
        'business_id',
        'customer_id',
        'invoice_number',
        'issue_date',
        'due_date',
        'status',
        'subtotal',
        'discount',
        'tax',
        'total',
        'notes',
        'payment_terms',
    ];

    protected $casts = [
        'issue_date' => 'date',
        'due_date' => 'date',
    ];

    protected static function booted(): void
    {
        static::addGlobalScope('business', function ($query) {
            if (auth()->check() && ! auth()->user()->isSuperAdmin() && auth()->user()->business) {
                $query->where('business_id', auth()->user()->business->id);
            }
        });

        static::creating(function (Invoice $invoice) {
            if (auth()->check() && auth()->user()->business) {
                $invoice->business_id = auth()->user()->business->id;

                if (empty($invoice->invoice_number)) {
                    $invoice->invoice_number = auth()->user()->business->nextInvoiceNumber();
                }
            }
        });
    }

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

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

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

    public function recalculateTotals(): void
    {
        $subtotal = $this->items->sum(fn(InvoiceItem $item) => $item->quantity * $item->unit_price);
        $discount = $this->items->sum('discount');
        $tax = $this->items->sum('tax_amount');

        $this->subtotal = (int) round($subtotal);
        $this->discount = (int) $discount;
        $this->tax = (int) $tax;
        $this->total = (int) ($this->subtotal - $this->discount + $this->tax);
        $this->save();
    }

    public function getDisplayStatusAttribute(): string
    {
        if ($this->status === 'sent' && $this->due_date->isPast()) {
            return 'overdue';
        }

        return $this->status;
    }
}