<?php
namespace App\Http\Controllers;

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

class CheckoutController extends Controller
{

    public function index()
    {
        return view('checkout.index');
    }
    public function form()
    {
        $routers = Router::where('is_active',true)->get();
        $plans   = Plan::orderBy('price_tzs')->get();
        return view('checkout.form', compact('routers','plans'));
    }

    public function start(Request $r, GatewayFactory $factory)
    {
        $data = $r->validate([
            'router_id'=>'required|integer|exists:routers,id',
            'plan_id'  =>'required|integer|exists:plans,id',
            'qty'      =>'required|integer|min:1|max:50',
            'gateway'  =>'required|string|in:azam_pay,flutterwave,zenopay_tz,selcom,clickpesa,pesapal',
            'return_url'=>'nullable|url'
        ]);

        $plan   = Plan::findOrFail($data['plan_id']);
        $amount = $plan->price_tzs * $data['qty'];

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

        OrderItem::create([
            'order_id'  => $order->id,
            'type'      => 'voucher',
            'plan_id'   => $plan->id,
            'qty'       => $data['qty'],
            'unit_price'=> $plan->price_tzs
        ]);

        $gw = $factory->for($order->gateway);
        $intent = $gw->createCheckout([
            'amount'=>$order->amount,
            'currency'=>$order->currency,
            'reference'=>$order->reference,
            'description'=>"BlueBando {$data['qty']}x {$plan->name}",
            'return_url'=>$r->input('return_url') ?? url('/'),
            'webhook_url'=>url('/api/webhooks/payments/'.$order->gateway),
        ]);

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