<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Traits\Auditable;

class Invoice extends Model
{
    use HasFactory, Auditable;

    protected $fillable = [
        'invoice_no', 'user_id', 'customer_id', 'date',
        'subtotal', 'tax', 'discount', 'total', 'paid', 'due',
        'status', 'notes'
    ];

    protected $casts = [
        'date' => 'date',
        'subtotal' => 'decimal:2',
        'tax' => 'decimal:2',
        'discount' => 'decimal:2',
        'total' => 'decimal:2',
        'paid' => 'decimal:2',
        'due' => 'decimal:2'
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

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

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

    public function salesDashboard()
    {
        return $this->hasOne(SalesDashboard::class, 'invoice_id');
    }

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

        static::creating(function ($invoice) {
            // $invoice->invoice_no = 'INV-' . date('Ymd') . '-' . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
            $invoice->invoice_no = 'Startup-'. '-' . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        });
    }
}
