<?php

use App\Models\Order;
use App\Models\Network;
use App\Models\AFAPackage;
use App\Models\AFAPricing;
use App\Models\IshareOrder;
use App\Models\OrderPayment;
use App\Models\SiteSettings;
use App\Models\UserBusiness;
use Livewire\Volt\Component;
use App\Models\AFARegistration;
use App\Models\PaymentProvider;
use App\Rules\GhanaPhoneNumber;
use App\Services\MoorleService;
use App\Services\BulkClixService;
use App\Http\Integrations\Imake\MoorlePay;
use App\Http\Integrations\Imake\BulkClixAPI;
use App\Http\Integrations\Imake\Requests\BulkClix\MomoPay;
use App\Http\Integrations\Imake\Requests\BulkClix\SendOTP;
use App\Http\Integrations\Imake\Requests\BulkClix\VerifyOTP;
use App\Http\Integrations\Imake\Requests\BulkClix\CheckTStatus;
use App\Http\Integrations\Imake\Requests\MoorlePay\MakePayment;
use App\Http\Integrations\Imake\Requests\MoorlePay\InitiatePayment;

new class extends Component {
    public $activeNetwork = null;
    public $networks;

    // Modal and Payment Properties
    public $showBundleModal = false;
    public $selectedBundle = null;
    public $selectedNetwork = null;
    public $recipientNumber = '';
    public $paymentNumber = '';
    public $paymentChannel = '';
    public $paymentNetwork = '';
    public $currentStep = 1;
    public $otp = '';
    public $otpSent = false;
    public $verificationComplete = false;
    public $uniqueRef = null;
    public $paymentSummary = [];
    public $isProcessing = false;
    public $showPaymentPrompt = false;
    public $bundlePrice = 0;

    public $agent;
    public $business;

    public $canOrder = false;
    public $isLinkEnabled = false;

    public $canAfaOrder = false;
    public $isAfaLinkEnabled = false;
    public $applySystemLevy = false;

    // AFA Registration properties
    public $showRegistrationModal = false;
    public $activeTab = 'bundles'; // Add this to manage tabs

    public $realPricing;

    public $requestId;
    public $ussdCodeForOTP;

    private $paymentProvider;
    private $bulkClixService;
    private $moorleService;

    public function mount($id /*BulkClixService $bulkClixService, MoorleService $moorleService*/)
    {
        //$this->bulkClixService = $bulkClixService;
        //   $this->moorleService = $moorleService;

        // Ensure services are properly initialized
        // $this->initializeServices();

        //get user from business slug passed as id
        $bus = UserBusiness::where('slug', $id)->first();

        if (!$bus) {
            return redirect()->route('home');
        }

        $this->business = $bus;
        $this->agent = $bus->user;
        $this->getSettings();

        $this->networks = Network::active()
            ->with([
                'bundles' => function ($query) {
                    $query->withAgentPricingOrCustomerPricing($this->agent->id);
                    $query->active();
                },
            ])
            ->get();

        if ($this->networks->isNotEmpty()) {
            $this->activeNetwork = $this->networks->first()->id;
        }
    }

    public function getSettings()
    {
        $allSettings = SiteSettings::all();
        $this->canOrder = $allSettings->where('shortname', 'orders')->first()->toggler;
        $this->isLinkEnabled = $allSettings->where('shortname', 'allow-link-orders')->first()->toggler;
        $this->isAfaLinkEnabled = $allSettings->where('shortname', 'allow-link-afa-orders')->first()->toggler;
        $this->applySystemLevy = $allSettings->where('shortname', 'apply-levy')->first()->toggler;
    }

    public function setActiveNetwork($networkId)
    {
        $this->activeNetwork = $networkId;

        // Refresh the bundles for the selected network with agent pricing
        $network = Network::where('id', $networkId)
            ->with([
                'bundles' => function ($query) {
                    $query->withAgentPricingOrCustomerPricing($this->agent->id);
                    $query->orderBy('capacity', 'asc')->active();
                },
            ])
            ->first();

        // Update the bundles in the networks collection
        if ($network) {
            $this->networks = $this->networks->map(function ($n) use ($network, $networkId) {
                return $n->id == $networkId ? $network : $n;
            });
        }
    }

    public function getColorScheme($networkKeyname)
    {
        $colorSchemes = [
            'mtn' => [
                'badge' => 'bg-yellow-100 text-yellow-800',
                'price' => 'text-white',
                'tag' => 'bg-yellow-100 text-yellow-500',
                'hover' => 'hover:border-yellow-200 hover:shadow-yellow-100',
                'color' => 'bg-yellow-400',
                'data' => 'text-white',
                'tab' => 'bg-yellow-400 hover:bg-yellow-500',
            ],
            'telecel' => [
                'badge' => 'bg-red-100 text-red-500',
                'price' => 'text-red-50',
                'tag' => 'bg-red-100 text-red-500',
                'hover' => 'hover:border-red-200 hover:shadow-red-100',
                'color' => 'bg-red-500',
                'data' => 'text-red-50',
                'tab' => 'bg-red-500 hover:bg-red-600',
            ],
            'airteltigo' => [
                'badge' => 'bg-blue-100 text-blue-500',
                'price' => 'text-blue-50',
                'tag' => 'bg-blue-100 text-blue-500',
                'hover' => 'hover:border-blue-200 hover:shadow-blue-100',
                'color' => 'bg-blue-500',
                'data' => 'text-blue-50',
                'tab' => 'bg-blue-500 hover:bg-blue-600',
            ],
        ];

        $keyname = strtolower($networkKeyname);
        return $colorSchemes[$keyname] ?? $colorSchemes['airteltigo'];
    }

    public function getBusinessDetails()
    {
        return [
            'name' => $this->agent->userBusiness->name ?? '',
            'phone' => $this->agent->phone ?? '',
            'owner' => $this->agent->username ?? '',
            'tagline' => $this->agent->userBusiness->tagline ?? '',
            'background' => $this->agent->userBusiness->background_image ?? '',
            'logo' => 'https://affiliates.imakestrading.com/storage/' . $this->agent->userBusiness->image ?? '',
        ];
    }

    public function getBundlePrice($bundle)
    {
        $agentPrice = $bundle->pricing->where('user_id', $this->agent->id)->where('network_id', $bundle->network_id)->first();
        $bundlePrice = $agentPrice ? $agentPrice->price : $bundle->customerPricing();

        $finalPrice = $this->getFinalPrice($bundle, $bundlePrice);

        if ($this->applySystemLevy) {
            $finalPrice += $bundle->levyOnBundle($bundlePrice);
        }

        return $finalPrice; /*+ $levy*/
    }

    public function getFinalPrice($bundle, $price)
    {
        $maxPrice = $bundle->maxPrice();
        $minPrice = $bundle->minPrice($this->agent);

        $generalPrice = $bundle->customerPricing();

        if ($price <= $maxPrice && $price >= $minPrice) {
            return $price;
        }

        return $generalPrice;
    }

    public function selectBundle($bundleId, $networkId)
    {
        $this->getSettings();

        if (!$this->isLinkEnabled) {
            toastr('Online orders are currently disabled. Please contact the business owner directly.', 'error');
            return;
        }

        if (!$this->canOrder) {
            toastr('Orders are currently disabled! Try again later.', 'error');
            return;
        }

        $this->selectedNetwork = $this->networks->find($networkId);
        // Ensure we're only selecting from bundles with agent pricing
        $this->selectedBundle = $this->selectedNetwork->bundles->where('id', $bundleId)->first();

        if (!$this->selectedBundle) {
            // Handle case where bundle is not found or not priced by agent
            toastr('Bundle not available', 'error');
            return;
        }

        // if ($this->selectedNetwork->keyname == 'ishare') {
        //     // Convert bundle capacity from GB to MB for comparison
        //     $requiredMB = $this->selectedBundle->capacity * 1000;

        //     // Check if agent has enough ishare balance
        //     if ($this->agent->ishareWallet->balance < $requiredMB) {
        //         toastr('Insufficient ishare balance. Required: ' . $requiredMB / 1000 . 'GB, Available: ' . $this->agent->ishareWallet->balance / 1000 . 'GB', 'error');
        //         return;
        //     }
        // }

        $this->realPricing = $this->selectedBundle->minPrice($this->agent);
        $this->bundlePrice = $this->getBundlePrice($this->selectedBundle);

        //make sure that the real pricing is not higher than the bundle price
        if ($this->realPricing > $this->bundlePrice) {
            toastr('Bundle price is lower than the agent price. Please contact the business owner directly.', 'error');
            return;
        }

        $this->showBundleModal = true;
        $this->currentStep = 1;
        $this->resetPaymentFields();

        // Ensure services are available
        $this->initializeServices();
    }

    private function initializeServices()
    {
        // Re-initialize services if they're null
        if (!$this->bulkClixService) {
            $this->bulkClixService = app(BulkClixService::class);
        }

        if (!$this->moorleService) {
            $this->moorleService = app(MoorleService::class);
        }

        $this->paymentProvider = PaymentProvider::activeProvider();

        Log::info('Services initialized', [
            'moorleService' => $this->moorleService ? get_class($this->moorleService) : 'null',
            'bulkClixService' => $this->bulkClixService ? get_class($this->bulkClixService) : 'null',
        ]);
    }

    public function resetPaymentFields()
    {
        $this->recipientNumber = '';
        $this->paymentNumber = '';
        $this->paymentNetwork = '';
        $this->otp = '';
        $this->otpSent = false;
        $this->verificationComplete = false;
        $this->showPaymentPrompt = false;
        $this->paymentSummary = [];
        $this->uniqueRef = 'OP-' . (string) Str::uuid();
    }

    public function initiatePayment()
    {
        // Ensure services are available
        $this->initializeServices();

        $this->uniqueRef = $this->generateUniqueRef();

        $this->validate([
            'paymentNumber' => 'required|digits:10',
            'paymentNetwork' => 'required',
            'recipientNumber' => 'required|digits:10',
            'bundlePrice' => 'required|numeric',
        ]);

        //check if the bundle price is higher than the agent price
        if ($this->realPricing > $this->bundlePrice) {
            toastr('Bundle price is lower than the agent price. Please contact the business owner directly.', 'error');
            return;
        }

        $this->isProcessing = true;

        try {
            if (!$this->isValidPhoneNumber($this->paymentNumber)) {
                toastr()->error('Invalid payment number. Please try again.');
                return;
            }

            //check if phone number is valid
            if (!$this->isValidPhoneNumber($this->recipientNumber)) {
                toastr()->error('Invalid recipient phone number. Please try again.');
                return;
            }

            $this->paymentSummary = [
                'amount' => $this->bundlePrice,
                'payment_number' => $this->paymentNumber,
                'channel' => $this->paymentNetwork,
            ];

            match ($this->paymentProvider->name) {
                'bulkclix' => (function () {
                    //check if payment number is valid and has been used before
                    $paymentDetails = OrderPayment::where('contact', $this->paymentNumber)->where('status', 'completed')->first();
                    if ($paymentDetails) {
                        $this->currentStep = 3;
                        return;
                    }

                    $response = $this->bulkClixService->initiatePaymentWithOTP($this->paymentNumber);

                    if ($response) {
                        $this->requestId = $response['data']['otp']['requestId'];
                        $this->ussdCodeForOTP = $response['data']['otp']['ussd_code'];

                        $this->otpSent = true;
                        $this->currentStep = 2;
                    } else {
                        toastr()->error('Failed to initiate BulkClix payment. Please try again.');
                        return;
                    }
                })(),

                default => (function () {
                    $response = $this->moorleService->initiatePayment($this->bundlePrice, $this->paymentNumber, $this->paymentNetwork, $this->uniqueRef);

                    if ($response) {
                        $this->otpSent = true;
                        $this->currentStep = 2;
                    } else {
                        toastr()->error('Failed to initiate Moorle payment. Please try again.');
                        return;
                    }
                })(),
            };

            // $connector = new BulkClixAPI();
            // $request = new SendOTP($this->paymentNumber);
            // $response = $connector->send($request);

            // if ($response->ok()) {
            //     $this->requestId = $response->json()['data']['otp']['requestId'];
            //     $this->ussdCodeForOTP = $response->json()['data']['otp']['ussd_code'];

            //     $this->paymentSummary = [
            //         'amount' => $this->bundlePrice,
            //         'payment_number' => $this->paymentNumber,
            //         'channel' => $this->paymentNetwork,
            //     ];

            //     $this->otpSent = true;
            //     $this->currentStep = 2;
            // } else {
            //     toastr()->error('Failed to initiate payment. Please try again.' . $response->json()['message']);
            // }

            // $connector = new MoorlePay();
            // $request = new InitiatePayment($this->bundlePrice, $this->paymentNumber, '', $this->paymentNetwork, $this->uniqueRef);
            // $response = $connector->send($request);

            // if ($response->ok() && $response->json()['status'] == 1) {
            //     $this->otpSent = true;
            //     $this->currentStep = 2;
            // } else {
            //     $this->addError('payment', 'Failed to initiate payment. Please try again.');
            // }
        } catch (\Exception $e) {
            toastr('An error occurred: ' . $e->getMessage(), 'error');
            $this->addError('payment', 'An error occurred. Please try again.');
        } finally {
            $this->isProcessing = false;
        }
    }

    private function generateUniqueRef()
    {
        $uuid = (string) Str::uuid();
        $prefix = $this->selectedNetwork->keyname == 'ishare' ? 'AT-' : 'OP-';
        $maxLength = 30;
        $remainingLength = $maxLength - strlen($prefix);
        return $prefix . substr($uuid, 0, $remainingLength);
    }

    public function verifyOTP()
    {
        // Ensure services are available
        $this->initializeServices();

        $this->validate([
            'otp' => 'required|digits:6',
        ]);

        $this->isProcessing = true;

        try {
            $response = match ($this->paymentProvider->name) {
                'bulkclix' => $this->bulkClixService->verifyOTP($this->paymentNumber, $this->requestId, $this->otp),
                'moorle' => $this->moorleService->verifyOTP($this->bundlePrice, $this->paymentNumber, $this->otp, $this->paymentNetwork, $this->uniqueRef),
                default => null,
            };

            if ($response) {
                $this->verificationComplete = true;
                $this->currentStep = 3;
            } else {
                $this->addError('payment', 'Invalid OTP. Please try again.');
            }
            // $connector = new MoorlePay();
            // $request = new VerifyOTP($this->bundlePrice, $this->paymentNumber, $this->otp, $this->paymentNetwork, $this->uniqueRef);
            // $response = $connector->send($request);

            // $connector = new BulkClixAPI();
            // $request = new VerifyOTP($this->paymentNumber, $this->requestId, $this->otp);
            // $response = $connector->send($request);

            // if ($response->ok()) {
            //     $this->verificationComplete = true;
            //     $this->currentStep = 3;
            // } else {
            //     $this->addError('payment', 'Invalid OTP. Please try again.');
            // }
        } catch (\Exception $e) {
            $this->addError('payment', 'An error occurred. Please try again.');
        } finally {
            $this->isProcessing = false;
        }
    }

    public function processPayment()
    {
        // Ensure services are available
        $this->initializeServices();

        $this->isProcessing = true;

        try {
            //start transaction
            DB::beginTransaction();

            $realPricing = $this->selectedBundle->realPricing->where('role_id', $this->agent->userRole())->first();

            $order = Order::create([
                'user_id' => $this->agent->id,
                'recipient_phone' => $this->recipientNumber,
                'bundle_id' => $this->selectedBundle->id,
                'network_id' => $this->selectedNetwork->id,
                'cost' => $this->selectedBundle->cost,
                'price' => $realPricing->price,
                'profit' => $realPricing->price - $this->selectedBundle->cost,
                'status' => 'pending',
                'payment_mode' => 'momo',
                'payment_status' => 'pending',
                'is_customer' => true,
            ]);

            // Create API record
            $order->api()->create([
                'status' => 'pending',
            ]);

            $profit = $this->applySystemLevy ? $this->bundlePrice - $this->selectedBundle->levyOnBundle($this->bundlePrice) - $realPricing->price : $this->bundlePrice - $realPricing->price;

            $order->payment()->create([
                'contact' => $this->paymentNumber,
                'amount' => $this->bundlePrice,
                'profit' => $profit,
                'transaction_id' => $this->uniqueRef,
                'payment_provider_id' => $this->paymentProvider->id,
                'status' => 'pending',
            ]);

            if ($this->applySystemLevy) {
                $order->systemLevy()->create([
                    'levy' => $this->selectedBundle->levyOnBundle($this->bundlePrice),
                    'status' => 'pending',
                ]);
            }
            //make api call to send payment prompt
            $response = match ($this->paymentProvider->name) {
                'bulkclix' => $this->bulkClixService->sendPaymentPrompt($this->paymentNumber, $this->bundlePrice, $this->paymentNetwork, $this->uniqueRef),
                'moorle' => $this->moorleService->sendPaymentPrompt($this->bundlePrice, $this->paymentNumber, $this->otp, $this->paymentNetwork, $this->uniqueRef),
                default => null,
            };

            // $payload = [
            //     'amount' => $this->bundlePrice,
            //     'phone_number' => $this->paymentNumber,
            //     'network' => $this->paymentNetwork,
            //     'transaction_id' => $this->uniqueRef,
            // ];

            if ($response) {
                DB::commit();
                toastr()->success('Order placed successfully! Kindly approve the payment request sent to your phone number.');
                $this->showPaymentPrompt = true;
            } else {
                DB::rollBack();
                $this->addError('payment', 'Payment failed. Please try again.');
            }
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Payment failed: ' . $e->getMessage());
            $this->addError('payment', 'An error occurred. Please try again.' . $e->getMessage());
        } finally {
            $this->isProcessing = false;
        }
    }

    public function previousStep()
    {
        $this->currentStep--;
    }

    private function isValidPhoneNumber($phoneNumber)
    {
        $isValid = true;
        $ghanaPhoneNumber = new GhanaPhoneNumber();
        $ghanaPhoneNumber->validate('phone', $phoneNumber, function ($message) use (&$isValid) {
            $isValid = false;
        });
        return $isValid;
    }

    public function checkTransactionStatus()
    {
        $isSuccess = match ($this->paymentProvider->name) {
            'bulkclix' => $this->bulkClixService->checkTransactionStatus($this->uniqueRef),
            'moorle' => $this->moorleService->checkTransactionStatus($this->uniqueRef),
            default => null,
        };

        if ($isSuccess) {
            toastr()->success('Transaction successful');

            $orderPayment = OrderPayment::where('transaction_id', $this->uniqueRef)->first();

            if ($orderPayment && $orderPayment->status != 'completed') {
                $orderPayment->update([
                    'status' => 'completed',
                ]);

                $orderPayment->order()->update([
                    'payment_status' => 'completed',
                ]);
            }
            return redirect()->route('orders');
        } else {
            toastr()->error('Transaction failed');
            return redirect()->route('home');
        }
    }

    public function processIshareOrder($realPricing)
    {
        $usernameInCaps = strtoupper($this->agent->username);
        $capacityInMb = $this->selectedBundle->capacity * 1000;
        $referenceId = $usernameInCaps . '-' . $capacityInMb . '-' . now()->timestamp;

        $createdOrder = IshareOrder::create([
            'user_id' => $this->agent->id,
            'recipient' => $this->recipientNumber,
            'capacity' => $capacityInMb,
            'status' => 'pending',
            'api_status' => 'pending',
            'reference' => $referenceId,
            'is_customer' => true,
        ]);

        $profit = $this->applySystemLevy ? $this->bundlePrice - $this->selectedBundle->levyOnBundle($this->bundlePrice) - $realPricing->price : $this->bundlePrice - $realPricing->price;

        $createdOrder->payment()->create([
            'contact' => $this->paymentNumber,
            'amount' => $this->bundlePrice,
            'profit' => $profit,
            'transaction_id' => $this->uniqueRef,
            'status' => 'pending',
        ]);

        $this->showPaymentPrompt = true;
    }
}; ?>

<div class="w-full min-h-screen bg-gray-50" x-data="{
    showBundleModal: @entangle('showBundleModal'),
    showRegistrationModal: @entangle('showRegistrationModal'),
    init() {
        Livewire.on('registration-completed', () => {
            this.showRegistrationModal = false;
        });
        Livewire.on('close-modal', () => {
            this.showRegistrationModal = false;
        });
    }
}">
    <x-loading />

    <!-- Link Disabled Notice -->
    @if (!$isLinkEnabled)
        <div class="bg-red-50 border-l-4 border-red-400 p-4 fixed top-0 left-0 right-0 z-50">
            <div class="flex items-center justify-center">
                <div class="flex-shrink-0">
                    <svg class="h-5 w-5 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                </div>
                <div class="ml-3">
                    <p class="text-sm text-red-700">
                        Online orders are currently disabled. Please contact the business owner directly.
                    </p>
                </div>
            </div>
        </div>
    @endif

    <!-- Hero Section with Business Profile -->
    @php
        $business = $this->getBusinessDetails();
    @endphp
    <div class="relative bg-gradient-to-br from-primary/5 via-primary/10 to-transparent">
        <div class="absolute inset-0 bg-grid-pattern opacity-5"></div>
        <div class="container mx-auto px-4 py-12">
            <div
                class="flex flex-col md:flex-row items-center gap-8 bg-white/80 backdrop-blur-sm rounded-2xl p-8 shadow-xl">
                <!-- Business Logo & Info -->
                <div class="flex-shrink-0">
                    <div class="relative group">
                        <div
                            class="absolute inset-0 bg-gradient-to-br from-primary to-primary/60 rounded-full blur-lg opacity-20 group-hover:opacity-30 transition-opacity">
                        </div>
                        <div class="relative h-28 w-28 rounded-full border-4 border-white shadow-2xl overflow-hidden">
                            <img src="{{ $business['logo'] }}" alt="{{ $business['name'] }}"
                                class="w-full h-full object-cover transform group-hover:scale-110 transition-transform duration-300">
                        </div>
                    </div>
                </div>

                <div class="flex-grow text-center md:text-left">
                    <h1 class="text-3xl md:text-4xl font-bold text-gray-800 mb-2">{{ $business['name'] }}</h1>
                    <p class="text-primary/80 font-medium mb-1">Buying from: {{ $business['owner'] }}</p>
                    <p class="text-gray-600 text-sm">Contact: {{ $business['phone'] }}</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="container mx-auto px-4 py-8">
        <!-- Tabs -->
        <div class="flex justify-center mb-8">
            <div class="inline-flex rounded-lg bg-gray-100 p-1">
                <button wire:click="$set('activeTab', 'bundles')"
                    class="px-4 py-2 rounded-md {{ $activeTab === 'bundles' ? 'bg-white shadow-sm text-primary' : 'text-gray-600' }}">
                    Data Bundles
                </button>
                <button wire:click="$set('activeTab', 'afa')"
                    class="px-4 py-2 rounded-md {{ $activeTab === 'afa' ? 'bg-white shadow-sm text-primary' : 'text-gray-600' }}">
                    AFA Registration
                </button>
            </div>
        </div>

        <!-- Bundles Content -->
        <div class="{{ $activeTab === 'bundles' ? 'block' : 'hidden' }}">
            <!-- Network Selection -->
            <div class="mb-12">
                <h2 class="text-2xl font-bold text-center text-gray-800 mb-8">Choose Your Network</h2>

                <div class="flex gap-4 md:justify-center justify-start overflow-x-auto no-scrollbar py-3">
                    @foreach ($networks as $network)
                        @php
                            $colors = $this->getColorScheme($network->keyname);
                        @endphp
                        <button wire:click="setActiveNetwork({{ $network->id }})"
                            class="flex items-center gap-3 px-6 py-4 rounded-xl transition-all duration-300 {{ $activeNetwork === $network->id
                                ? $colors['tab'] . ' text-white shadow-lg scale-105'
                                : 'bg-white hover:bg-gray-50 text-gray-700 shadow-sm hover:shadow' }}">
                            @if ($network->thumbnail)
                                <div class="w-8 h-8 rounded-full bg-white/90 p-1 shadow-sm">
                                    <img src="{{ asset('images/' . $network->thumbnail) }}" alt="{{ $network->name }}"
                                        class="w-full h-full object-contain">
                                </div>
                            @endif
                            <span class="font-semibold">{{ $network->name }}</span>
                        </button>
                    @endforeach
                </div>
            </div>

            <!-- Bundles Grid -->
            @foreach ($networks as $network)
                <div class="{{ $activeNetwork === $network->id ? 'block' : 'hidden' }}">
                    @php
                        $colors = $this->getColorScheme($network->keyname);
                    @endphp
                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
                        @forelse ($network->bundles as $bundle)
                            @php
                                $networkBundlePrice = $this->getBundlePrice($bundle);
                                // $maxPrice = $bundle->maxPrice();
                                // $minPrice = $bundle->minPrice($this->agent);
                            @endphp
                            @if ($networkBundlePrice)
                                <div wire:click="{{ $isLinkEnabled ? "selectBundle($bundle->id, $network->id)" : '' }}"
                                    class="group relative bg-white rounded-2xl p-6 shadow-sm hover:shadow-xl transition-all duration-300 {{ $isLinkEnabled ? 'cursor-pointer' : 'cursor-not-allowed opacity-75' }} overflow-hidden">
                                    <!-- Add disabled overlay when link is disabled -->
                                    @if (!$isLinkEnabled)
                                        <div
                                            class="absolute inset-0 bg-gray-900/10 backdrop-blur-sm flex items-center justify-center z-10">
                                            <div class="bg-white/90 rounded-lg px-4 py-2 shadow-lg">
                                                <p class="text-sm text-gray-600">Orders Disabled</p>
                                            </div>
                                        </div>
                                    @endif

                                    <!-- Existing bundle card content -->
                                    <div
                                        class="absolute inset-0 bg-gradient-to-br {{ $colors['color'] }} group-hover:opacity-70 transition-opacity">
                                    </div>

                                    <div class="relative">
                                        <!-- Bundle Header -->
                                        <div class="flex justify-between items-start mb-6">
                                            <div>
                                                <p class="text-4xl font-bold {{ $colors['data'] }}">
                                                    {{ $bundle->capacity }}<span class="text-2xl">GB</span>
                                                </p>
                                                <p class="text-sm {{ $colors['data'] }}">Data Bundle</p>
                                            </div>
                                            <div
                                                class="px-3 py-1 rounded-full text-sm {{ $colors['badge'] }} shadow-sm">
                                                {{ $network->name }}
                                            </div>
                                        </div>

                                        <!-- Price Section -->
                                        <div class="flex items-center justify-between pt-4 border-t border-gray-100">
                                            <div class="flex flex-col">
                                                <div
                                                    class="text-3xl font-bold {{ str_replace('text-yellow-50', 'text-black', $colors['price']) }}">
                                                    &#8373;{{ number_format($networkBundlePrice, 2) }}
                                                </div>
                                            </div>
                                            <div
                                                class="px-4 py-2 rounded-lg text-sm {{ $colors['badge'] }} font-medium">
                                                Non Expiry
                                            </div>
                                        </div>

                                        <!-- Hover Effect Button -->
                                        <div
                                            class="absolute inset-x-0 bottom-0 h-1 bg-primary transform scale-x-0 group-hover:scale-x-100 transition-transform duration-300">
                                        </div>
                                    </div>
                                </div>
                            @endif
                        @empty
                            <div
                                class="col-span-full flex flex-col items-center justify-center p-12 bg-white rounded-2xl">
                                <div class="text-gray-400 mb-3">
                                    <svg class="w-16 h-16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                            d="M20 12H4">
                                        </path>
                                    </svg>
                                </div>
                                <p class="text-gray-500 text-lg">No bundles available for this network</p>
                                @if (!$isLinkEnabled)
                                    <p class="text-sm text-gray-400 mt-2">Online ordering is currently disabled</p>
                                @endif
                            </div>
                        @endforelse
                    </div>
                </div>
            @endforeach
        </div>

        <!-- AFA Registration Content -->
        <div class="{{ $activeTab === 'afa' ? 'block' : 'hidden' }}">
            <div class="max-w-3xl mx-auto">
                <div class="bg-white rounded-xl shadow-sm p-6">
                    <div class="text-center mb-8">
                        <h2 class="text-2xl font-bold text-gray-800">AFA Registration</h2>
                        <p class="text-gray-600 mt-2">Register for AFA services</p>
                    </div>

                    @if (!$isAfaLinkEnabled)
                        <div class="bg-gray-50 rounded-lg p-4 text-center">
                            <p class="text-gray-600">AFA registration is currently disabled. Please contact the business
                                owner directly.</p>
                            <p class="text-sm text-gray-500 mt-2">Contact: {{ $business['phone'] }}</p>
                        </div>
                    @else
                        <x-material-button wire:click="$set('showRegistrationModal', true)" name="Start Registration"
                            icon="ri-user-add-line" class="w-full bg-primary text-white hover:bg-primary-dark" />
                    @endif
                </div>
            </div>
        </div>
    </div>

    <!-- Registration Modal -->
    <x-modal x-show="showRegistrationModal" title="AFA Registration">
        <livewire:include.afa-registration :agent="$agent" :isAfaLinkEnabled="$isAfaLinkEnabled" />
    </x-modal>

    <!-- Purchase Modal - Keep existing modal code but update styling -->
    <x-modal x-show="showBundleModal" max-width="md" title="Purchase Bundle">
        <div class="p-6">
            <!-- Step 1: Bundle Details & Payment Info -->
            <div x-show="$wire.currentStep === 1">
                <!-- Bundle Summary -->
                <div class="bg-gray-50 rounded-lg p-4 mb-6">
                    <div class="flex justify-between items-center mb-2">
                        <span class="text-gray-600">Network</span>
                        <span class="font-medium">{{ $selectedNetwork?->name }}</span>
                    </div>
                    <div class="flex justify-between items-center mb-2">
                        <span class="text-gray-600">Capacity</span>
                        <span class="font-medium">{{ $selectedBundle?->capacity }}GB</span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-gray-600">Price</span>
                        <div class="text-right">
                            <span class="font-medium">&#8373; {{ number_format($bundlePrice ?? 0, 2) }}</span>

                        </div>
                    </div>
                </div>

                <!-- Payment Form -->
                <form class="space-y-4">
                    <x-input type="text" wire:model="recipientNumber" label="Recipient Number"
                        placeholder="Enter recipient number" maxlength="10" name="recipientNumber" />

                    <x-select wire:model="paymentNetwork" label="Payment Network" name="paymentNetwork">
                        <option value="">Select network</option>
                        <option value="MTN">MTN</option>
                        <option value="TELECEL">Telecel</option>
                        <option value="AIRTELTIGO">AT</option>
                    </x-select>

                    <x-input type="text" wire:model="paymentNumber" label="Payment Number"
                        placeholder="Enter payment number" maxlength="10" name="paymentNumber" />

                    <div class="flex justify-end mt-6">

                        <x-button wire:click="initiatePayment" wire:loading.attr="disabled">
                            <span wire:loading wire:target="initiatePayment">Processing...</span>
                            <span wire:loading.remove wire:target="initiatePayment">Continue</span>
                        </x-button>
                    </div>
                </form>
            </div>

            <!-- Step 2: OTP Verification -->
            <div x-show="$wire.currentStep === 2">
                <!-- Step 2: OTP Verification -->
                <div class="space-y-4 sm:space-y-6">
                    <div class="p-4 sm:p-6 bg-gray-50 rounded-lg text-center">
                        <i class="ri-message-2-line text-3xl sm:text-4xl text-primary mb-3 sm:mb-4"></i>
                        <p class="text-sm sm:text-base text-gray-600">
                            Enter the 6-digit code sent to <span class="font-bold">{{ $paymentNumber }}</span>
                        </p>
                    </div>

                    <!-- USSD Code Display for OTP (with different style) -->
                    @if ($ussdCodeForOTP)
                        <div
                            class="flex flex-col items-center bg-gradient-to-r from-blue-100 to-blue-50 border-l-4 border-blue-400 rounded-md py-4 px-3 mb-2 shadow-sm">
                            <div class="flex items-center mb-2">
                                <span
                                    class="inline-flex items-center justify-center w-8 h-8 rounded-full bg-blue-200 mr-2">
                                    <i class="ri-phone-fill text-blue-700 text-xl"></i>
                                </span>
                                <span class="text-base font-semibold text-blue-800">Get OTP via USSD</span>
                            </div>
                            <p class="text-xs text-blue-700 mb-2 text-center">
                                Didn't get the SMS? Dial this code to receive your OTP instantly:
                            </p>
                            <div class="flex items-center justify-center">
                                <span
                                    class="bg-blue-50 border border-blue-300 px-4 py-2 rounded-lg font-mono text-lg text-blue-900 tracking-widest shadow-inner">
                                    {{ $ussdCodeForOTP }}
                                </span>
                            </div>
                            <div class="mt-2 text-xs text-blue-600 flex items-center justify-center">
                                <i class="ri-information-line mr-1"></i>
                                Use this code on your phone to get the OTP
                            </div>
                        </div>
                    @endif

                    <div class="mb-4 sm:mb-6">
                        <input type="text" wire:model="otp"
                            class="shadow appearance-none border rounded w-full py-3 px-3 text-gray-700 text-center text-xl sm:text-2xl tracking-wider leading-tight focus:outline-none focus:shadow-outline"
                            placeholder="Enter 6-digit code" maxlength="6">
                        @error('otp')
                            <span class="text-red-500 text-xs sm:text-sm">{{ $message }}</span>
                        @enderror
                    </div>

                    <div class="flex gap-3 sm:gap-4">
                        <button wire:click="previousStep" type="button"
                            class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-700 font-bold py-2 sm:py-3 px-3 sm:px-4 rounded focus:outline-none focus:shadow-outline transition duration-300">
                            <i class="ri-arrow-left-line mr-2"></i>
                            Back
                        </button>
                        <button wire:click="verifyOTP" wire:loading.attr="disabled" wire:target="verifyOTP"
                            class="flex-1 bg-primary hover:bg-primary-dark text-white font-bold py-2 sm:py-3 px-3 sm:px-4 rounded focus:outline-none focus:shadow-outline transition duration-300">
                            <span wire:loading.remove wire:target="verifyOTP">
                                <i class="ri-shield-check-line mr-2"></i>
                                Verify OTP
                            </span>
                            <span wire:loading wire:target="verifyOTP" class="flex items-center justify-center">
                                <i class="ri-loader-4-line animate-spin mr-2"></i>
                                Verifying...
                            </span>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Step 3: Order Summary -->
            <div x-show="$wire.currentStep === 3">
                <h3 class="text-lg font-semibold mb-4">Order Summary</h3>

                <div class="space-y-4">
                    <div class="bg-gray-50 rounded-lg p-4 space-y-3">
                        <div class="flex justify-between">
                            <span class="text-gray-600">Bundle</span>
                            <span class="font-medium">{{ $selectedBundle?->capacity }}GB</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-600">Network</span>
                            <span class="font-medium">{{ $selectedNetwork?->name }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-600">Recipient</span>
                            <span class="font-medium">{{ $recipientNumber }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-600">Amount</span>
                            <span class="font-medium">&#8373; {{ number_format($bundlePrice ?? 0, 2) }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-600">Payment Number</span>
                            <span class="font-medium">{{ $paymentNumber }}</span>
                        </div>
                    </div>

                    @if (!$showPaymentPrompt)
                        <div class="flex justify-between mt-6">
                            <x-button wire:click="previousStep" variant="secondary">
                                Back
                            </x-button>
                            <x-button wire:click="processPayment" wire:loading.attr="disabled">
                                <span wire:loading wire:target="processPayment">Processing...</span>
                                <span wire:loading.remove wire:target="processPayment">Confirm Payment</span>
                            </x-button>
                        </div>
                    @endif
                </div>
            </div>

            @if ($showPaymentPrompt)
                <div class="w-full p-4 mt-4 text-center rounded-lg bg-yellow-50">
                    <p class="font-medium text-yellow-800">
                        Please approve the payment request sent to {{ $paymentNumber }}
                    </p>
                    <p class="mt-1 text-sm text-yellow-600">
                        Check your phone for the payment prompt
                    </p>
                    <div class="mt-4 sm:mt-6">
                        <button wire:click="checkTransactionStatus" wire:loading.attr="disabled"
                            wire:target="checkTransactionStatus"
                            class="bg-green-500 hover:bg-green-600 text-white font-bold py-2 sm:py-3 px-4 sm:px-6 rounded-lg transition duration-300">
                            <span wire:loading.remove wire:target="checkTransactionStatus">
                                Check Transaction Status
                            </span>
                            <span wire:loading wire:target="checkTransactionStatus"
                                class="flex items-center justify-center">
                                <i class="ri-loader-4-line animate-spin mr-2"></i>
                                Checking...
                            </span>
                        </button>
                    </div>
                </div>
            @endif

            @error('payment')
                <div class="mt-2 text-sm text-red-500">{{ $message }}</div>
            @enderror
        </div>
    </x-modal>
</div>
