<?php

namespace App\Models;

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

class WalletTransaction extends Model
{
    use HasFactory;

    protected $fillable = [
        'pm_type',
        'type',
        'status',
        'amount',
        'stripe_pm_id',
        'wallet_id',
        'user_id',
    ];

    protected function casts(): array
    {
        return [
            'id'        => 'integer',
            'wallet_id'=> 'integer',
            'user_id'  => 'integer',
   

        ];
    }

    /**
     * Event handling
     */
    protected static function booted()
    {
        static::created(function (WalletTransaction $transaction) {

            if ($transaction->status !== 'completed') {
                return;
            }

            $wallet = $transaction->wallet;

            if ($wallet && $wallet->is_active) {
                $wallet->applyTransaction($transaction);
            }
        });

        /**
         * اگر status بعداً از pending → completed تغییر کرد
         */
        static::updated(function (WalletTransaction $transaction) {

            if (
                $transaction->status === 'completed' &&
                $transaction->wasChanged('status')
            ) {
                $wallet = $transaction->wallet;

                if ($wallet && $wallet->is_active) {
                    $wallet->applyTransaction($transaction);
                }
            }
        });
    }

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

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