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

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

class AdminWithdrawController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $withdrawals = WithdrawRequest::with('vendor:id,store_name,user_id')
            ->when($request->status, fn($q) => $q->where('status', $request->status))
            ->latest()->paginate(15);
        return response()->json($withdrawals);
    }

    public function show(int $id): JsonResponse
    {
        $withdrawal = WithdrawRequest::with('vendor.user')->findOrFail($id);
        return response()->json(['withdrawal' => $withdrawal]);
    }

    public function process(Request $request, int $id): JsonResponse
    {
        $withdrawal = WithdrawRequest::findOrFail($id);
        $data = $request->validate([
            'status'      => 'required|in:processing,completed,rejected',
            'admin_notes' => 'nullable|string',
        ]);

        if ($data['status'] === 'rejected') {
            $withdrawal->vendor->increment('balance', $withdrawal->amount);
        }

        $withdrawal->update([
            'status'       => $data['status'],
            'admin_notes'  => $data['admin_notes'] ?? null,
            'processed_at' => now(),
        ]);

        return response()->json(['message' => 'Withdrawal processed.', 'withdrawal' => $withdrawal]);
    }
}
