<?php
namespace App\Http\Controllers\Admin;

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

class AdminWithdrawalController extends Controller
{
    public function index(Request $request)
    {
        $query = Withdrawal::with('user');

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        $withdrawals = $query->latest()->paginate(25)->withQueryString();

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

    public function approve(Request $request, $id)
    {
        $withdrawal = Withdrawal::findOrFail($id);

        if (!in_array($withdrawal->status, ['pending', 'processing'])) {
            return back()->with('error', 'Only pending/processing withdrawals can be approved.');
        }

        $withdrawal->approve(session('admin_id'), $request->note);

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

    public function reject(Request $request, $id)
    {
        $withdrawal = Withdrawal::findOrFail($id);

        if (!in_array($withdrawal->status, ['pending', 'processing'])) {
            return back()->with('error', 'Only pending/processing withdrawals can be rejected.');
        }

        $withdrawal->reject(session('admin_id'), $request->note);

        $withdrawal->user->increment('real_balance', $withdrawal->amount);

        return back()->with('success', 'Withdrawal rejected and amount refunded.');
    }
}
