<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\Plan;
use App\Models\Router;
use App\Services\Payments\AzamPayGateway;
use App\Services\Sms\BeemSms;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class CheckoutController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function form(Request $request)
    {
        $routers = Router::orderBy('name')->get();
        $plans   = Plan::where('is_active', 1)->orderBy('price')->get();

        return view('payments.checkout', compact('routers', 'plans'));
    }

    public function create(Request $request)
    {
        $data = $request->validate([
            'router_id' => ['required', 'exists:routers,id'],
            'plan_id'   => ['required', 'exists:plans,id'],
            'phone'     => ['required', 'string', 'max:32'],
            'gateway'   => ['required', 'string', 'max:32'],
        ]);

        $plan   = Plan::findOrFail($data['plan_id']);
        $router = Router::findOrFail($data['router_id']);

        $reference = 'BB' . now()->format('ymdHis') . Str::random(4);

        $order = Order::create([
            'company_id' => 1,
            'router_id'  => $router->id,
            'plan_id'    => $plan->id,
            'user_id'    => Auth::id(),
            'channel'    => 'web',
            'gateway'    => $data['gateway'], // 'azam_pay'
            'reference'  => $reference,
            'phone'      => $data['phone'],
            'amount'     => $plan->price,
            'currency'   => $plan->currency ?? 'TZS',
            'status'     => 'pending',
            'meta'       => [
                'plan_name'   => $plan->name,
                'router_name' => $router->name,
            ],
        ]);

        if ($order->gateway === 'azam_pay') {
            $azam = new AzamPayGateway();
            $url  = $azam->createCheckout($order);

            if ($url) {
                return redirect()->away($url);
            }

            // Fallback if Azam API fails – keep order pending
            return redirect()
                ->route('payments.pending')
                ->with('status', 'Could not contact AzamPay. Order created in pending status.');
        }

        // Other gateways (Selcom, etc.) can be added later
        return redirect()->route('payments.pending')
            ->with('status', 'Order created with gateway ' . $order->gateway);
    }

    /**
     * AzamPay callback handler.
     * Map fields according to AzamPay docs.
     */
    public function azamCallback(Request $request)
    {
        // Example mapping – adjust based on real payload
        $externalId = $request->input('externalId') ?: $request->input('reference');
        $status     = strtolower($request->input('status', 'pending'));
        $paidAmount = $request->input('amount');

        if (!$externalId) {
            return response('Missing reference', 400);
        }

        $order = Order::where('reference', $externalId)->first();
        if (!$order) {
            return response('Order not found', 404);
        }

        $order->meta = array_merge($order->meta ?? [], [
            'azam_callback' => $request->all(),
        ]);

        if (in_array($status, ['success', 'completed', 'succeeded'])) {
            $order->status  = 'success';
            $order->paid_at = now();
            if ($paidAmount) {
                $order->amount = $paidAmount;
            }

            $order->save();

            // Send SMS via Beem
            $msg = "BlueBando: Your payment for plan {$order->plan->name} ({$order->amount} {$order->currency}) was received. Reference: {$order->reference}.";
            BeemSms::send($order->phone, $msg);
        } elseif (in_array($status, ['failed', 'cancelled'])) {
            $order->status = 'failed';
            $order->save();
        } else {
            $order->status = 'pending';
            $order->save();
        }

        // AzamPay expects some text response
        return response('OK', 200);
    }
}
