<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ResellerWithdrawRequest extends Model
{
    protected $fillable = ['user_id', 'amount', 'payment_method', 'account_number', 'status', 'admin_notes'];

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

    public function walletTransactions()
    {
        return $this->hasMany(ResellerWalletTransaction::class, 'withdraw_request_id');
    }

    protected static function boot()
    {
        parent::boot();

        static::updated(function ($request) {
            if ($request->wasChanged('status')) {
                $oldStatus = $request->getOriginal('status');
                $newStatus = $request->status;

                if ($newStatus === 'approved' && $oldStatus !== 'approved') {
                    // Create debit wallet transaction
                    ResellerWalletTransaction::create([
                        'user_id' => $request->user_id,
                        'amount' => $request->amount,
                        'type' => 'debit',
                        'status' => 'completed',
                        'description' => "Payment withdrawal approved (Method: " . ucfirst($request->payment_method) . ")",
                        'withdraw_request_id' => $request->id,
                    ]);
                } elseif ($oldStatus === 'approved' && $newStatus !== 'approved') {
                    // Delete or reverse the debit transaction
                    ResellerWalletTransaction::where('withdraw_request_id', $request->id)
                        ->where('type', 'debit')
                        ->delete();
                }
            }
        });
    }
}
