<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\WithdrawRequest;
use Illuminate\Http\Request;

class WithdrawRequestController extends Controller
{
    /** সব withdraw list + filter */
    public function index(Request $request)
    {
        $status = $request->get('status');

        $query = WithdrawRequest::with('user')
            ->orderByDesc('created_at');

        if ($status && in_array($status, ['pending', 'approved', 'rejected'])) {
            $query->where('status', $status);
        }

        $withdraws = $query->paginate(25);

        return view('admin.withdraw_requests.index', compact('withdraws', 'status'));
    }

    /** একটার edit form */
    public function edit(WithdrawRequest $withdraw)
    {
        return view('admin.withdraw_requests.edit', compact('withdraw'));
    }

    /** status / trx_id আপডেট */
    public function update(Request $request, WithdrawRequest $withdraw)
    {
        $data = $request->validate([
            'status' => ['required', 'in:pending,approved,rejected'],
            'trx_id' => ['nullable', 'string', 'max:255'],
        ]);

        $oldStatus = $withdraw->status;

        $withdraw->update($data);

        // চাইলে: pending → rejected হলে user এর balance এ টাকা ফেরত
        if ($oldStatus === 'pending' && $data['status'] === 'rejected') {
            $user = $withdraw->user;
            if ($user) {
                $user->balance = ($user->balance ?? 0) + $withdraw->amount;
                $user->save();
            }
        }

        return redirect()
            ->route('admin.withdraw.index')
            ->with('success', 'Withdraw request আপডেট হয়েছে।');
    }
}
