<?php

namespace Modules\CashRegister\Observers;

use Modules\CashRegister\Entities\CashRegisterTransaction;
use Modules\CashRegister\Services\CashRegisterCacheService;

class CashRegisterTransactionObserver
{
    /**
     * Handle the CashRegisterTransaction "created" event.
     */
    public function created(CashRegisterTransaction $transaction): void
    {
        // Clear session totals cache when transaction is created
        CashRegisterCacheService::clearSessionTotalsCache($transaction->cash_register_session_id);
        
        // Also clear session cache to refresh active session data
        $session = $transaction->session;
        if ($session) {
            CashRegisterCacheService::clearSessionCache($session->opened_by, $session->branch_id);
        }
    }

    /**
     * Handle the CashRegisterTransaction "updated" event.
     */
    public function updated(CashRegisterTransaction $transaction): void
    {
        // Clear session totals cache when transaction is updated
        CashRegisterCacheService::clearSessionTotalsCache($transaction->cash_register_session_id);
        
        // Also clear if session changed
        if ($transaction->isDirty('cash_register_session_id')) {
            CashRegisterCacheService::clearSessionTotalsCache($transaction->getOriginal('cash_register_session_id'));
        }
    }

    /**
     * Handle the CashRegisterTransaction "deleted" event.
     */
    public function deleted(CashRegisterTransaction $transaction): void
    {
        // Clear session totals cache when transaction is deleted
        CashRegisterCacheService::clearSessionTotalsCache($transaction->cash_register_session_id);
    }
}

