<?php

namespace App\Models;

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

class Invoice extends Model
{
    use HasFactory;

    protected $fillable = [
        'invoice_number', 'user_id', 'package_id', 'amount', 'currency',
        'status', 'payment_method', 'transaction_id', 'notes',
        'due_date', 'paid_at',
    ];

    protected $casts = [
        'amount'   => 'decimal:2',
        'due_date' => 'date',
        'paid_at'  => 'datetime',
    ];

    protected static function booted(): void
    {
        static::creating(function ($invoice) {
            if (empty($invoice->invoice_number)) {
                $invoice->invoice_number = 'INV-' . date('Ymd') . '-' . str_pad((string)(self::max('id') + 1), 5, '0', STR_PAD_LEFT);
            }
        });
    }

    public function user()     { return $this->belongsTo(User::class); }
    public function package()  { return $this->belongsTo(Package::class); }
    public function payments() { return $this->hasMany(Payment::class); }

    public function isPaid(): bool   { return $this->status === 'paid'; }
    public function isUnpaid(): bool { return $this->status === 'unpaid'; }

    public function statusBadgeClass(): string
    {
        return match($this->status) {
            'paid'      => 'bg-success',
            'unpaid'    => 'bg-warning text-dark',
            'cancelled' => 'bg-secondary',
            'refunded'  => 'bg-info',
            default     => 'bg-light text-dark',
        };
    }
}
