<?php

namespace App\Observers;

use App\Models\ProductService;

class ProductServiceObserver
{
    /**
     * Handle the ProductService "created" event.
     */
    public function created(ProductService $productService): void
    {
        $this->calculateInvoiceTotalsIfExists($productService);
    }

    /**
     * Handle the ProductService "updated" event.
     */
    public function updated(ProductService $productService): void
    {
        $this->calculateInvoiceTotalsIfExists($productService);
    }

    public function saved(ProductService $productService): void
    {
        $this->calculateInvoiceTotalsIfExists($productService);
    }

    /**
     * Handle the ProductService "deleted" event.
     */
    public function deleted(ProductService $productService): void
    {
        $this->calculateInvoiceTotalsIfExists($productService);
    }

    /**
     * Handle the ProductService "restored" event.
     */
    public function restored(ProductService $productService): void
    {
        $this->calculateInvoiceTotalsIfExists($productService);

    }

    /**
     * Handle the ProductService "force deleted" event.
     */
    public function forceDeleted(ProductService $productService): void
    {
        $this->calculateInvoiceTotalsIfExists($productService);
    }

    private function calculateInvoiceTotalsIfExists(ProductService $productService): void
    {
        if ($productService->order()->exists()) {
            if ($productService->order->invoice()->exists()) {

                $productService->order->invoice->calculateTotals();
            }
        }
    }
}
