<?php

namespace App\Http\Controllers;

use App\Models\Brand;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;

class FundsController extends Controller
{
    /**
     * Handle the submission of the add funds form and redirect to the payment page.
     *
     * @param Request $request
     * @return RedirectResponse
     */
    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'amount' => 'required|numeric|min:1',
            'brand_id' => 'required|exists:brands,id',  // Changed to required
            'terms' => 'required|accepted',
        ]);

        $amount = $validated['amount'];
        $brandId = $validated['brand_id'];
        
        // Get the complete brand information
        $brand = Brand::where('id', $brandId)
                     ->where('status', 1)
                     ->firstOrFail();

        $brandKey = $brand->brand_key;

        // Redirect to the payment page with the correct parameters.
        // Pass brand_id as a query parameter so the payment page can load brand-specific gateways.
        // Create the URL with all parameters as query parameters for consistency.
        $url = route('payment') . '?' . http_build_query([
            'brand_key' => $brandKey,
            'amount' => $amount,
            'brand_id' => $brandId,
        ]);

        return redirect($url);
    }
}
