<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class CustomerWalletTransaction extends Model
{
    protected $fillable = [
        'customer_id',
        'type',
        'amount',
        'payment_method',
        'date',
        'notes',
        'user_id',
        'model_id',
        'model_type',
    ];

    protected $casts = [
        'date' => 'date',
        'amount' => 'decimal:2',
    ];

    public function customer(): BelongsTo
    {
        return $this->belongsTo(Customer::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function model()
    {
        return $this->morphTo();
    }

    protected static function booted()
    {
        static::created(function ($transaction) {
            $customer = $transaction->customer;
            if ($transaction->type === 'deposit' || $transaction->type === 'adjustment' && $transaction->amount > 0) {
                $customer->increment('balance', abs($transaction->amount));
            } else {
                $customer->decrement('balance', abs($transaction->amount));
            }
        });

        static::deleted(function ($transaction) {
            $customer = $transaction->customer;
            if ($transaction->type === 'deposit' || $transaction->type === 'adjustment' && $transaction->amount > 0) {
                $customer->decrement('balance', abs($transaction->amount));
            } else {
                $customer->increment('balance', abs($transaction->amount));
            }
        });

        static::updated(function ($transaction) {
            // Revert original amount/type effect
            $originalAmount = $transaction->getOriginal('amount');
            $originalType = $transaction->getOriginal('type');
            $originalCustomer = $transaction->customer; // Assuming customer doesn't change

            if ($originalType === 'deposit' || $originalType === 'adjustment' && $originalAmount > 0) {
                $originalCustomer->decrement('balance', abs($originalAmount));
            } else {
                $originalCustomer->increment('balance', abs($originalAmount));
            }

            // Apply new amount/type effect
            if ($transaction->type === 'deposit' || $transaction->type === 'adjustment' && $transaction->amount > 0) {
                $originalCustomer->increment('balance', abs($transaction->amount));
            } else {
                $originalCustomer->decrement('balance', abs($transaction->amount));
            }
        });
    }
}
