<?php

namespace Modules\Inventory\Observers;

use App\Helper\Files;
use Modules\Inventory\Entities\InventoryItem;

class InventoryItemObserver
{

    public function creating(InventoryItem $inventoryitem)
    {
        if (branch()) {
            $inventoryitem->branch_id = branch()->id;
        }
    }

    public function created(InventoryItem $inventoryitem): void
    {
        // Clear branch cache when item is created
        \Modules\Inventory\Services\InventoryCacheService::clearBranchCache($inventoryitem->branch_id);
    }

    public function updated(InventoryItem $inventoryitem): void
    {
        // Clear branch cache when item is updated
        \Modules\Inventory\Services\InventoryCacheService::clearBranchCache($inventoryitem->branch_id);
        
        // Also clear if branch changed
        if ($inventoryitem->isDirty('branch_id')) {
            \Modules\Inventory\Services\InventoryCacheService::clearBranchCache($inventoryitem->getOriginal('branch_id'));
        }
    }

    public function deleted(InventoryItem $inventoryitem): void
    {
        if ($inventoryitem->photo_path) {
            $folder = trim(dirname($inventoryitem->photo_path), './') ?: InventoryItem::PHOTO_DIRECTORY;

            Files::deleteFile(
                basename($inventoryitem->photo_path),
                $folder
            );
        }
        
        // Clear branch cache when item is deleted
        \Modules\Inventory\Services\InventoryCacheService::clearBranchCache($inventoryitem->branch_id);
    }
}
