<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\WithdrawRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AdminWithdrawController extends Controller
{
    // সব withdraw দেখানোর পেজ
    public function index()
    {
        $withdraws = WithdrawRequest::with('user')
            ->latest()
            ->paginate(20);

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

    // single withdraw details page
    public function show(WithdrawRequest $withdraw)
    {
        $withdraw->load('user');

        return view('admin.withdraws.show', compact('withdraw'));
    }

    // ✅ APPROVE
    public function approve(Request $request, WithdrawRequest $withdraw)
    {
        // যদি আগেই approved/rejected হয়, আবার কিছু না করি
        if (in_array($withdraw->status, ['approved', 'rejected'])) {
            return back()->with('success', 'This withdraw is already processed.');
        }

        $request->validate([
            'trx_id' => ['nullable', 'string', 'max:255'],
        ]);

        $withdraw->status = 'approved';
        if ($request->filled('trx_id')) {
            $withdraw->trx_id = $request->trx_id;
        }
        $withdraw->save();

        return back()->with('success', 'Withdraw approved successfully.');
    }

    // ❌ REJECT (এখানে ইউজারের balance ফেরত দেব)
    public function reject(WithdrawRequest $withdraw)
    {
        if (in_array($withdraw->status, ['approved', 'rejected'])) {
            return back()->with('success', 'This withdraw is already processed.');
        }

        DB::transaction(function () use ($withdraw) {
            $withdraw->status = 'rejected';
            $withdraw->save();

            // ইউজারের balance এ amount ফিরিয়ে দেই
            $user = $withdraw->user;
            if ($user) {
                $user->balance = ($user->balance ?? 0) + $withdraw->amount;
                $user->save();
            }
        });

        return back()->with('success', 'Withdraw rejected & amount returned to user balance.');
    }
}
