<x-app-layout>
    <x-module-hero
        title="Payment Integration Documentation"
        description="Learn how to use PaymentService in your modules"
        icon="fa-book">
        <x-slot name="tabs">
            <a href="{{ route('config.payment.index') }}"
               class="module-hero-tab {{ request()->routeIs('config.payment.index') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }} inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium transition">
                <i class="fas fa-tachometer-alt"></i> Dashboard
            </a>
            @can('create payment configuration')
            <a href="{{ route('config.payment.create') }}"
               class="module-hero-tab {{ request()->routeIs('config.payment.create') || request()->routeIs('config.payment.edit') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }} inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium transition">
                <i class="fas fa-plus"></i> Configure
            </a>
            @endcan
            @can('test payment connection')
            <a href="{{ route('config.payment.test-interface') }}"
               class="module-hero-tab {{ request()->routeIs('config.payment.test-interface') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }} inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium transition">
                <i class="fas fa-plug"></i> Test Connection
            </a>
            @endcan
            @can('view payment logs')
            <a href="{{ route('config.payment.logs') }}"
               class="module-hero-tab {{ request()->routeIs('config.payment.logs') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }} inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium transition">
                <i class="fas fa-history"></i> API Logs
            </a>
            @endcan
            <a href="{{ route('config.payment.documentation') }}"
               class="module-hero-tab {{ request()->routeIs('config.payment.documentation') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }} inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium transition">
                <i class="fas fa-book"></i> Documentation
            </a>
        </x-slot>
    </x-module-hero>

    <div class="p-6">

        {{-- Service Status Banner --}}
        <div class="mb-6 bg-white rounded-lg shadow-sm border border-gray-200 p-4">
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <div class="p-2 rounded-full {{ $serviceStatus['ready'] ? 'bg-green-100' : 'bg-yellow-100' }}">
                        <i class="fas {{ $serviceStatus['ready'] ? 'fa-check-circle text-green-600' : 'fa-exclamation-circle text-yellow-600' }}"></i>
                    </div>
                    <div>
                        <h3 class="font-semibold text-gray-800 text-sm">Payment Service Status</h3>
                        <p class="text-xs text-gray-500">
                            {{ $serviceStatus['ready'] ? 'Service is configured and ready to use' : 'Service is not configured yet' }}
                        </p>
                    </div>
                </div>
                <span class="px-3 py-1 rounded-full text-xs font-semibold {{ ($serviceStatus['environment'] ?? 'sandbox') === 'production' ? 'bg-red-100 text-red-800' : 'bg-blue-100 text-blue-800' }}">
                    {{ ucfirst($serviceStatus['environment'] ?? 'sandbox') }} Mode
                </span>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">

            {{-- Sidebar TOC --}}
            <div class="lg:col-span-1">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4 sticky top-6">
                    <h3 class="text-sm font-semibold text-gray-800 mb-3">Contents</h3>
                    <nav class="space-y-1">
                        <a href="#getting-started" class="block text-sm text-green-600 hover:underline">Getting Started</a>
                        <a href="#injection" class="block text-sm text-green-600 hover:underline">Using PaymentService</a>
                        <a href="#collection" class="block text-sm text-green-600 hover:underline">Collection (Request Payment)</a>
                        <a href="#disbursement" class="block text-sm text-green-600 hover:underline">Disbursement (Send Money)</a>
                        <a href="#status-check" class="block text-sm text-green-600 hover:underline">Check Transaction Status</a>
                        <a href="#helpers" class="block text-sm text-green-600 hover:underline">Helper Methods</a>
                        <a href="#error-handling" class="block text-sm text-green-600 hover:underline">Error Handling</a>
                        <a href="#complete-example" class="block text-sm text-green-600 hover:underline">Complete Example</a>
                        <a href="#api-reference" class="block text-sm text-green-600 hover:underline">API Reference</a>
                    </nav>
                </div>
            </div>

            {{-- Main Content --}}
            <div class="lg:col-span-3 space-y-6">

                {{-- Getting Started --}}
                <section id="getting-started" class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <h2 class="text-xl font-bold text-gray-800 mb-3 flex items-center gap-2">
                        <i class="fas fa-rocket text-green-500"></i> Getting Started
                    </h2>
                    <p class="text-gray-600 text-sm mb-3">
                        The <code class="bg-gray-100 px-1 rounded">PaymentService</code> provides a clean, standardized interface for processing payments via MTN MoMo API.
                        Other modules can use this service to initiate collections (request payments) and disbursements (send money).
                    </p>
                    <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                        <h4 class="font-semibold text-blue-800 text-sm mb-2">Prerequisites</h4>
                        <ul class="list-disc list-inside text-sm text-blue-700 space-y-1">
                            <li>Payment configuration must be set up (see Configure tab)</li>
                            <li>Appropriate API credentials configured (Collection and/or Disbursement)</li>
                            <li>Correct environment selected (sandbox for testing, production for live)</li>
                        </ul>
                    </div>
                </section>

                {{-- Service Injection --}}
                <section id="injection" class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <h2 class="text-xl font-bold text-gray-800 mb-3 flex items-center gap-2">
                        <i class="fas fa-syringe text-purple-500"></i> Using PaymentService
                    </h2>
                    <p class="text-gray-600 text-sm mb-3">Inject the PaymentService into your controller or service:</p>
                    <pre class="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto text-xs"><code>use App\Services\PaymentService;

// Constructor Injection
class OrderController extends Controller
{
    public function __construct(protected PaymentService $paymentService) {}
}

// Method Injection
public function processPayment(Request $request, PaymentService $paymentService) {}

// App Facade
$paymentService = app(PaymentService::class);</code></pre>
                </section>

                {{-- Collection --}}
                <section id="collection" class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <h2 class="text-xl font-bold text-gray-800 mb-3 flex items-center gap-2">
                        <i class="fas fa-arrow-down text-blue-500"></i> Collection (Request Payment)
                    </h2>
                    <p class="text-gray-600 text-sm mb-3">Request payment from a customer via MTN MoMo Mobile Money:</p>
                    <pre class="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto text-xs"><code>$result = $this->paymentService->initiateCollection(
    phoneNumber: '256771234567',  // Customer phone (MSISDN format)
    amount: 5000,                  // Amount to collect
    reference: 'INV-2024-001',     // Unique transaction reference
    payerMessage: 'Payment for Invoice #2024-001',
    payeeNote: 'Thank you for your payment!'
);

if ($result['success']) {
    echo "Transaction ID: " . $result['transaction_id'];
    // Customer receives a prompt on their phone
} else {
    echo "Error: " . $result['message'];
}</code></pre>
                    <h3 class="text-sm font-semibold text-gray-800 mt-4 mb-2">Response Format</h3>
                    <pre class="bg-gray-100 p-3 rounded-lg text-xs"><code>[
    'success' => true,
    'transaction_id' => 'INV-2024-001',
    'message' => 'Collection request initiated successfully',
    'data' => ['reference' => 'INV-2024-001', 'amount' => 5000, 'environment' => 'sandbox']
]</code></pre>
                </section>

                {{-- Disbursement --}}
                <section id="disbursement" class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <h2 class="text-xl font-bold text-gray-800 mb-3 flex items-center gap-2">
                        <i class="fas fa-arrow-up text-purple-500"></i> Disbursement (Send Money)
                    </h2>
                    <p class="text-gray-600 text-sm mb-3">Send money to a customer via MTN MoMo Card Payments:</p>
                    <pre class="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto text-xs"><code>$result = $this->paymentService->initiateDisbursement(
    phoneNumber: '256771234567',
    amount: 10000,
    reference: 'PAYOUT-2024-001',
    payerMessage: 'Commission payout',
    payeeNote: 'Your commission for January 2024'
);

if ($result['success']) {
    echo "Transaction ID: " . $result['transaction_id'];
}</code></pre>
                </section>

                {{-- Status Check --}}
                <section id="status-check" class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <h2 class="text-xl font-bold text-gray-800 mb-3 flex items-center gap-2">
                        <i class="fas fa-search text-yellow-500"></i> Check Transaction Status
                    </h2>
                    <pre class="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto text-xs"><code>// Check collection status
$result = $this->paymentService->checkTransactionStatus(
    transactionId: 'INV-2024-001',
    type: 'collection'
);

// Check disbursement status
$result = $this->paymentService->checkTransactionStatus(
    transactionId: 'PAYOUT-2024-001',
    type: 'disbursement'
);

if ($result['success']) {
    echo "Status: " . $result['status']; // PENDING, SUCCESSFUL, FAILED
}
// Possible statuses: PENDING, SUCCESSFUL, FAILED, TIMEOUT</code></pre>
                </section>

                {{-- Helper Methods --}}
                <section id="helpers" class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <h2 class="text-xl font-bold text-gray-800 mb-3 flex items-center gap-2">
                        <i class="fas fa-tools text-gray-500"></i> Helper Methods
                    </h2>
                    <pre class="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto text-xs"><code>$reference = $this->paymentService->generateReference(); // UUID

if ($this->paymentService->isReady()) { /* Service is configured */ }
if ($this->paymentService->canCollect()) { /* Collection API available */ }
if ($this->paymentService->canDisburse()) { /* Disbursement API available */ }

$status = $this->paymentService->getStatus();
// Returns: ['ready' => true, 'environment' => 'sandbox', 'collection_available' => true, ...]</code></pre>
                </section>

                {{-- Error Handling --}}
                <section id="error-handling" class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <h2 class="text-xl font-bold text-gray-800 mb-3 flex items-center gap-2">
                        <i class="fas fa-exclamation-triangle text-red-500"></i> Error Handling
                    </h2>
                    <pre class="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto text-xs"><code>try {
    $result = $this->paymentService->initiateCollection(
        phoneNumber: $request->phone,
        amount: $request->amount,
        reference: $request->reference
    );

    if (!$result['success']) {
        return back()->withErrors(['payment' => $result['message']]);
    }

    $order->update(['transaction_id' => $result['transaction_id'], 'payment_status' => 'pending']);
    return redirect()->route('orders.show', $order)->with('success', 'Payment request sent!');

} catch (\Exception $e) {
    Log::error('Payment failed', ['error' => $e->getMessage()]);
    return back()->withErrors(['payment' => 'Payment processing failed. Please try again.']);
}</code></pre>
                    <h3 class="text-sm font-semibold text-gray-800 mt-4 mb-2">Common Errors</h3>
                    <div class="overflow-x-auto">
                        <table class="w-full table-zebra text-sm">
                            <thead>
                                <tr>
                                    <th class="px-3 py-2 text-left th-col-1">Error</th>
                                    <th class="px-3 py-2 text-left th-col-2">Cause</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0"><td class="px-3 py-2 text-xs font-mono">Invalid phone number format</td><td class="px-3 py-2 text-xs">Phone must be MSISDN format (e.g., 256771234567)</td></tr>
                                <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0"><td class="px-3 py-2 text-xs font-mono">Amount must be greater than zero</td><td class="px-3 py-2 text-xs">Invalid amount provided</td></tr>
                                <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0"><td class="px-3 py-2 text-xs font-mono">Collection API is not configured</td><td class="px-3 py-2 text-xs">Collection credentials missing</td></tr>
                                <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0"><td class="px-3 py-2 text-xs font-mono">Disbursement API is not configured</td><td class="px-3 py-2 text-xs">Disbursement credentials missing</td></tr>
                            </tbody>
                        </table>
                    </div>
                </section>

                {{-- Complete Example --}}
                <section id="complete-example" class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <h2 class="text-xl font-bold text-gray-800 mb-3 flex items-center gap-2">
                        <i class="fas fa-code text-teal-500"></i> Complete Example: Order Payment
                    </h2>
                    <pre class="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto text-xs"><code>use App\Services\PaymentService;

class OrderPaymentController extends Controller
{
    public function __construct(protected PaymentService $paymentService) {}

    public function pay(Request $request, Order $order)
    {
        $validated = $request->validate([
            'phone' => 'required|string|regex:/^[1-9]\d{8,14}$/',
        ]);

        if (!$this->paymentService->canCollect()) {
            return back()->withErrors(['payment' => 'Payment service is not available.']);
        }

        $reference = 'ORD-' . $order->id . '-' . time();

        $result = $this->paymentService->initiateCollection(
            phoneNumber: $validated['phone'],
            amount: $order->total_amount,
            reference: $reference,
            payerMessage: 'Payment for Order #' . $order->id
        );

        if ($result['success']) {
            $order->update([
                'payment_reference' => $result['transaction_id'],
                'payment_status' => 'pending',
            ]);
            return redirect()->route('orders.show', $order)
                ->with('success', 'Payment request sent! Please check your phone.');
        }

        return back()->withInput()->withErrors(['payment' => $result['message']]);
    }
}</code></pre>
                </section>

                {{-- API Reference --}}
                <section id="api-reference" class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <h2 class="text-xl font-bold text-gray-800 mb-3 flex items-center gap-2">
                        <i class="fas fa-list-alt text-blue-500"></i> API Reference
                    </h2>
                    <div class="overflow-x-auto">
                        <table class="w-full table-zebra text-sm">
                            <thead>
                                <tr>
                                    <th class="px-3 py-2 text-left th-col-1">Method</th>
                                    <th class="px-3 py-2 text-left th-col-2">Parameters</th>
                                    <th class="px-3 py-2 text-left th-col-3">Returns</th>
                                    <th class="px-3 py-2 text-left th-col-4">Description</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0">
                                    <td class="px-3 py-2 font-mono text-xs">initiateCollection()</td>
                                    <td class="px-3 py-2 text-xs">phone, amount, reference, ?payerMessage, ?payeeNote</td>
                                    <td class="px-3 py-2 text-xs">array</td>
                                    <td class="px-3 py-2 text-xs">Request payment from customer (MoMo Mobile Money)</td>
                                </tr>
                                <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0">
                                    <td class="px-3 py-2 font-mono text-xs">initiateDisbursement()</td>
                                    <td class="px-3 py-2 text-xs">phone, amount, reference, ?payerMessage, ?payeeNote</td>
                                    <td class="px-3 py-2 text-xs">array</td>
                                    <td class="px-3 py-2 text-xs">Send money to customer (MoMo Card Payments)</td>
                                </tr>
                                <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0">
                                    <td class="px-3 py-2 font-mono text-xs">checkTransactionStatus()</td>
                                    <td class="px-3 py-2 text-xs">transactionId, type</td>
                                    <td class="px-3 py-2 text-xs">array</td>
                                    <td class="px-3 py-2 text-xs">Check transaction status</td>
                                </tr>
                                <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0">
                                    <td class="px-3 py-2 font-mono text-xs">generateReference()</td>
                                    <td class="px-3 py-2 text-xs">none</td>
                                    <td class="px-3 py-2 text-xs">string (UUID)</td>
                                    <td class="px-3 py-2 text-xs">Generate unique reference</td>
                                </tr>
                                <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0">
                                    <td class="px-3 py-2 font-mono text-xs">isReady()</td>
                                    <td class="px-3 py-2 text-xs">none</td>
                                    <td class="px-3 py-2 text-xs">bool</td>
                                    <td class="px-3 py-2 text-xs">Check if service is configured</td>
                                </tr>
                                <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0">
                                    <td class="px-3 py-2 font-mono text-xs">canCollect()</td>
                                    <td class="px-3 py-2 text-xs">none</td>
                                    <td class="px-3 py-2 text-xs">bool</td>
                                    <td class="px-3 py-2 text-xs">Check collection availability</td>
                                </tr>
                                <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0">
                                    <td class="px-3 py-2 font-mono text-xs">canDisburse()</td>
                                    <td class="px-3 py-2 text-xs">none</td>
                                    <td class="px-3 py-2 text-xs">bool</td>
                                    <td class="px-3 py-2 text-xs">Check disbursement availability</td>
                                </tr>
                                <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0">
                                    <td class="px-3 py-2 font-mono text-xs">getStatus()</td>
                                    <td class="px-3 py-2 text-xs">none</td>
                                    <td class="px-3 py-2 text-xs">array</td>
                                    <td class="px-3 py-2 text-xs">Get service status info</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </section>

            </div>
        </div>
    </div>
</x-app-layout>
