<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\{Order, OrderItem};
use App\Services\Payments\GatewayFactory;

class PaymentController extends Controller
{
    public function checkout(Request $r, GatewayFactory $factory)
    {
        $data = $r->validate([
            'amount'=>'required|integer|min:100',
            'item_type'=>'required|string',
            'return_url'=>'nullable|url'
        ]);

        $order = Order::create([
            'company_id' => auth()->user()->company_id,
            'user_id'    => auth()->id(),
            'amount'     => $data['amount'],
            'currency'   => config('bluebando.currency','TZS'),
            'gateway'    => $r->string('gateway', 'azam_pay'),
            'status'     => 'pending',
            'reference'  => uniqid('BB-')
        ]);

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

        return redirect()->away($intent->url ?? $r->input('return_url','/'));
    }

    public function orders() {
        $orders = Order::latest()->paginate(30);
        return view('payments.index', compact('orders'));
    }
}
