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

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

class VendorWithdrawController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $withdrawals = WithdrawRequest::where('vendor_id', $request->user()->vendor->id)->latest()->paginate(10);
        return response()->json($withdrawals);
    }
    public function store(Request $request): JsonResponse
    {
        $vendor = $request->user()->vendor;
        $data = $request->validate([
            'amount'          => 'required|numeric|min:' . config('vendorflow.withdraw_min_amount'),
            'method'          => 'required|in:bank_transfer,paypal,stripe',
            'payment_details' => 'nullable|array',
        ]);
        if ($data['amount'] > $vendor->balance) {
            return response()->json(['message' => 'Insufficient balance.'], 422);
        }
        $vendor->decrement('balance', $data['amount']);
        $withdrawal = WithdrawRequest::create(['vendor_id' => $vendor->id, ...$data]);
        return response()->json(['message' => 'Withdrawal request submitted.', 'withdrawal' => $withdrawal], 201);
    }
    public function show(Request $request, int $id): JsonResponse
    {
        $withdrawal = WithdrawRequest::where('vendor_id', $request->user()->vendor->id)->findOrFail($id);
        return response()->json(['withdrawal' => $withdrawal]);
    }
}
