<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Order;
use App\Services\Payments\GatewayFactory;

class AzamPayTestController extends Controller
{
    public function form()
    {
        return view('payments.azampay_test');
    }

    public function start(Request $r, GatewayFactory $factory)
    {
        $data = $r->validate(['amount'=>'required|integer|min:100','return_url'=>'nullable|url']);
        $order = Order::create([
            'company_id' => auth()->user()->company_id ?? 1,
            'user_id'    => auth()->id(),
            'amount'     => $data['amount'],
            'currency'   => 'TZS',
            'gateway'    => 'azam_pay',
            'status'     => 'pending',
            'reference'  => uniqid('BB-'),
        ]);

        $gw = $factory->for('azam_pay');
        $intent = $gw->createCheckout([
            'amount'=>$order->amount,
            'currency'=>$order->currency,
            'reference'=>$order->reference,
            'description'=>'BlueBando Test Payment',
            'return_url'=>$r->input('return_url') ?? url('/'),
            'webhook_url'=>url('/api/webhooks/payments/azam_pay'),
        ]);

        return redirect()->away($intent->url ?? url('/'));
    }
}
