<?php

namespace App\Observers;

use App\Models\PurchaseOrder;
use App\Services\SupplierSyncService;

class PurchaseOrderObserver
{
    protected SupplierSyncService $supplierSyncService;

    public function __construct(SupplierSyncService $supplierSyncService)
    {
        $this->supplierSyncService = $supplierSyncService;
    }

    public function updating(PurchaseOrder $po): void
    {
        if (! $po->isDirty('status')) {
            return;
        }

        $newStatus = $po->status;
        $oldStatus = $po->getOriginal('status');

        if ($oldStatus === $newStatus) {
            return;
        }

        $po->load('items', 'sourceOrder.items');

        if ($newStatus === PurchaseOrder::STATUS_CONFIRMED) {
            $this->supplierSyncService->onPurchaseOrderConfirmed($po);
        }

        if ($newStatus === PurchaseOrder::STATUS_RECEIVED) {
            $this->supplierSyncService->onPurchaseOrderReceived($po);
        }
    }
}
