<?php

namespace App\Http\Controllers;

use App\Http\Requests\StorePayoutRequest;
use App\Models\PayoutRequest;
use App\Models\Wallet;
use Illuminate\Support\Facades\DB;

class PayoutRequestController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:request payout', ['only' => ['index', 'store']]);
    }

    public function index()
    {
        $wallet = Wallet::firstOrCreate(
            ['user_id' => auth()->id()],
            ['balance' => 0, 'currency' => 'USD']
        );

        $payoutRequests = PayoutRequest::query()
            ->where('user_id', auth()->id())
            ->latest()
            ->paginate(10);

        return view('payout_requests.index', compact('wallet', 'payoutRequests'));
    }

    public function store(StorePayoutRequest $request)
    {
        $wallet = Wallet::firstOrCreate(
            ['user_id' => auth()->id()],
            ['balance' => 0, 'currency' => 'USD']
        );

        $amount = (float) $request->validated('amount');
        if ($amount > (float) $wallet->balance) {
            return back()->withErrors(['amount' => 'Insufficient wallet balance.'])->withInput();
        }

        DB::transaction(function () use ($request, $wallet, $amount) {
            PayoutRequest::create([
                'user_id' => auth()->id(),
                'amount' => $amount,
                'currency' => $request->validated('currency') ?? 'USD',
                'bank_name' => $request->validated('bank_name'),
                'account_name' => $request->validated('account_name'),
                'account_number' => $request->validated('account_number'),
                'iban' => $request->validated('iban'),
                'swift_code' => $request->validated('swift_code'),
                'status' => 'pending',
            ]);

            $wallet->decrement('balance', $amount);
            $request->user()->decrement('balance', $amount);
        });

        return redirect()->route('payout-requests.index')->with('status', 'Payout request submitted.');
    }
}
