<?php

use Carbon\Carbon;
use App\Models\AFAPackage;
use App\Models\AFAPricing;
use Livewire\Volt\Component;
use App\Models\AFARegistration;
use App\Models\AgentAFAPricing;
use App\Http\Integrations\Imake\MoorlePay;
use App\Http\Integrations\Imake\Requests\MoorlePay\VerifyOTP;
use App\Http\Integrations\Imake\Requests\MoorlePay\MakePayment;
use App\Http\Integrations\Imake\Requests\MoorlePay\InitiatePayment;

new class extends Component {
    public $fullname;
    public $phone;
    public $ghana_card;
    public $occupation;
    public $dob;
    public $afa_cost = 0;
    public $afa_price = 0;
    public $afa_profit = 0;

    public $afaPackage;
    public $originalPrice;

    // Payment Properties
    public $paymentNumber = '';
    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 $agent;

    public function mount($agent)
    {
        $this->agent = $agent;
        $this->getAfaPricing();
    }

    public function getAfaPricing()
    {
        $this->afaPackage = AFAPackage::where('status', 'active')->first();
        $pricing = AgentAFAPricing::where('user_id', $this->agent->id)->where('package_id', $this->afaPackage->id)->first();

        $this->originalPrice = AFAPricing::where('package_id', $this->afaPackage->id)
            ->where('role_id', $this->agent->userRole())
            ->first();

        $this->afa_price = $pricing->price ?? $this->afaPackage->price;
        $this->afa_cost = $this->afaPackage->cost;
        $this->afa_profit = $this->afa_price - $this->originalPrice->price;

        //check if the package price is higher than the agent price
        if ($this->originalPrice->price > $this->afa_price) {
            toastr('AFA price is lower than the original price. Please contact the business owner directly.', 'error');
            return;
        }
    }

    public function initiatePayment()
    {
        $this->validate([
            'fullname' => 'required|string|min:3',
            'phone' => 'required|string|regex:/^[0-9]{10}$/',
            'ghana_card' => 'required|string|min:15',
            'occupation' => 'required|string',
            'dob' => 'required|date|before:today',
            'paymentNumber' => 'required|digits:10',
            'paymentNetwork' => 'required',
        ]);

        $this->uniqueRef = 'AFA-' . (string) Str::uuid();
        $this->isProcessing = true;

        //check if real pricing is higher than the package price
        if ($this->originalPrice->price > $this->afa_price) {
            toastr('AFA price is lower than the original price. Please contact the business owner directly.', 'error');
            return;
        }

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

            if ($response->ok() && $response->json()['status'] == 1) {
                $this->paymentSummary = [
                    'amount' => $this->afa_price,
                    'payment_number' => $this->paymentNumber,
                    'channel' => $this->paymentNetwork,
                ];
                $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;
        }
    }

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

        $this->isProcessing = true;

        try {
            $connector = new MoorlePay();
            $request = new VerifyOTP($this->afa_price, $this->paymentNumber, $this->otp, $this->paymentNetwork, $this->uniqueRef);
            $response = $connector->send($request);

            if ($response->ok() && $response->json()['status'] == 1) {
                $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 register()
    {
        $this->isProcessing = true;

        try {
            $moorlepay = new MoorlePay();
            $request = new MakePayment($this->afa_price, $this->paymentNumber, $this->otp, $this->paymentNetwork, $this->uniqueRef);
            $response = $moorlepay->send($request);

            if ($response->ok() && $response->json()['status'] == 1) {
                $registration = AFARegistration::create([
                    'fullname' => $this->fullname,
                    'phone' => $this->phone,
                    'ghana_card' => $this->ghana_card,
                    'occupation' => $this->occupation,
                    'dob' => $this->dob,
                    'cost' => $this->afa_cost,
                    'price' => $this->originalPrice->price,
                    'profit' => $this->originalPrice->price - $this->afa_cost,
                    'user_id' => $this->agent->id,
                    'status' => 'pending',
                    'payment_status' => 'pending',
                    'is_customer' => true,
                ]);

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

                $this->showPaymentPrompt = true;
                toastr()->success('AFA Registration submitted successfully');
            } else {
                $this->addError('payment', 'Payment failed. Please try again.' . $response->json()['message']);
            }
        } catch (\Exception $e) {
            $this->addError('payment', 'An error occurred. Please try again.' . $e->getMessage());
        } finally {
            $this->isProcessing = false;
        }
    }

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

<div class="p-6">
    <!-- Step 1: Registration Details & Payment Info -->
    <div x-show="$wire.currentStep === 1">
        <!-- Registration Form -->
        <div class="space-y-4">
            <div class="bg-gray-50 rounded-lg p-4 mb-6">
                <div class="flex justify-between items-center">
                    <span class="text-gray-600">Registration Fee</span>
                    <span class="font-medium">&#8373; {{ number_format($afa_price, 2) }}</span>
                </div>
            </div>

            <x-input wire:model="fullname" label="Full Name" placeholder="Enter your full name" name="fullname"
                type="text" />
            <x-input wire:model="phone" label="Phone Number" type="tel" maxlength="10"
                placeholder="Enter your phone number" name="phone" />
            <x-input wire:model="ghana_card" label="Ghana Card Number" placeholder="Enter your Ghana card number"
                name="ghana_card" type="text" />
            <x-input wire:model="occupation" label="Occupation" placeholder="Enter your occupation" type="text"
                name="occupation" />
            <x-input wire:model="dob" label="Date of Birth" type="date" name="dob" />

            <!-- Payment Details -->
            <x-select wire:model="paymentNetwork" label="Payment Network" name="paymentNetwork">
                <option value="">Select network</option>
                <option value="13">MTN</option>
                <option value="6">Telecel</option>
                <option value="7">AT</option>
            </x-select>

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

        <div class="mt-6 flex justify-end space-x-3">
            <button wire:click="$dispatch('close-modal')"
                class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors duration-200">
                Cancel
            </button>
            <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>
    </div>

    <!-- Step 2: OTP Verification -->
    <div x-show="$wire.currentStep === 2">
        <h3 class="text-lg font-semibold mb-4">Verify OTP</h3>

        <div class="bg-gray-50 rounded-lg p-4 mb-6">
            <p class="text-sm text-gray-600">
                Enter the 6-digit code sent to {{ $paymentNumber }}
            </p>
        </div>

        <x-input type="text" wire:model="otp" label="Enter OTP" placeholder="Enter 6-digit code" name="otp"
            maxlength="6" />

        <div class="flex justify-between mt-6">
            <x-button wire:click="previousStep" variant="secondary">
                Back
            </x-button>
            <x-button wire:click="verifyOTP" wire:loading.attr="disabled">
                <span wire:loading wire:target="verifyOTP">Verifying...</span>
                <span wire:loading.remove wire:target="verifyOTP">Verify OTP</span>
            </x-button>
        </div>
    </div>

    <!-- Step 3: Registration Summary -->
    <div x-show="$wire.currentStep === 3">
        <h3 class="text-lg font-semibold mb-4">Registration 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">Full Name</span>
                    <span class="font-medium">{{ $fullname }}</span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-600">Phone Number</span>
                    <span class="font-medium">{{ $phone }}</span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-600">Amount</span>
                    <span class="font-medium">&#8373; {{ number_format($afa_price, 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="register" wire:loading.attr="disabled">
                        <span wire:loading wire:target="register">Processing...</span>
                        <span wire:loading.remove wire:target="register">Confirm Registration</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>
            <x-button wire:click="$dispatch('close-modal')" class="mt-4">
                Close
            </x-button>
        </div>
    @endif

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