<?php

namespace App\Observers;

use App\Models\Invoice;
use App\Models\TaxRate;

class InvoiceObserver
{
    /**
     * Handle the Invoice "creating" event.
     */
    public function creating(Invoice $invoice): void
    {
        $invoice->pst_rate = TaxRate::where('name', 'PST')->value('value') ?? 0;
        $invoice->gst_rate = TaxRate::where('name', 'GST')->value('value') ?? 0;
        $invoice->hst_rate = TaxRate::where('name', 'HST')->value('value') ?? 0;
    }

    /**
     * Handle the Invoice "created" event.
     */
    public function created(Invoice $invoice): void
    {

        $invoice->internal_id = 'TN4'.str_pad($invoice->id, 4, '0', STR_PAD_LEFT);
        $invoice->saveQuietly();

        $invoice->calculateTotals();

    }

    public function saved(Invoice $invoice) {}

    /**
     * Handle the Invoice "updated" event.
     */
    public function updated(Invoice $invoice): void
    {
        $invoice->calculateTotals();
    }
}
