@extends('layouts.app')

@section('content')
<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h4 class="mb-0">💎 Produit d'Investissement Obligatoire</h4>
                </div>

                <div class="card-body">
                    @if($errors->any())
                        <div class="alert alert-danger">
                            <ul class="mb-0">
                                @foreach($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif

                    @if(session('success'))
                        <div class="alert alert-success alert-dismissible fade show">
                            {{ session('success') }}
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    @endif

                    @if(session('error'))
                        <div class="alert alert-danger alert-dismissible fade show">
                            {{ session('error') }}
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    @endif

                    <div class="mb-4">
                        <h5>Bienvenue, {{ Auth::user()->name }} !</h5>
                        <p class="text-muted">
                            Avant d'accéder à la boutique et de commencer à générer des commissions,
                            vous devez d'abord payer votre produit d'investissement obligatoire.
                        </p>
                    </div>

                    <hr>

                    <div class="investment-details mb-4">
                        <h6>📦 Détails du produit</h6>
                        
                        <div class="details-row">
                            <span>Produit :</span>
                            <strong>{{ $product->name }}</strong>
                        </div>

                        <div class="details-row">
                            <span>Description :</span>
                            <span>{{ $product->description }}</span>
                        </div>

                        <div class="details-row">
                            <span>Montant :</span>
                            <strong class="text-success">{{ number_format($product->price, 0, ',', ' ') }} XOF</strong>
                        </div>

                        <div class="details-row">
                            <span>Quantité :</span>
                            <strong>1</strong>
                        </div>

                        <hr>

                        <div class="details-row text-lg">
                            <span>Total à payer :</span>
                            <strong class="text-primary" style="font-size: 1.3em;">
                                {{ number_format($product->price, 0, ',', ' ') }} XOF
                            </strong>
                        </div>
                    </div>

                    <div class="alert alert-info mb-4">
                        <strong>✓ Une seule fois</strong><br>
                        Vous ne payerez ce produit qu'une seule fois. Après ce paiement,
                        vous aurez accès complet à la boutique et pourrez commencer à générer
                        des revenus via les commissions MLM.
                    </div>

                    <x-payment-method-selector 
                        :amount="$product->price"
                        :email="auth()->user()->email ?? ''"
                        :name="auth()->user()->name ?? ''"
                        :phone="auth()->user()->phone ?? ''"
                        :redirectUrl="route('payment.mobile-money.callback')"
                        :showMobileMoney="true"
                        :wallet="$wallet"
                    />

                    <div class="d-grid gap-2">
                        <button type="button" class="btn btn-success btn-lg" id="payBtn">
                            💳 Procéder au paiement
                        </button>
                        <a href="{{ route('member.dashboard') }}" class="btn btn-outline-secondary">
                            Retour
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Loading Modal -->
<div class="modal fade" id="loadingModal" tabindex="-1" backdrop="static" keyboard="false">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-body text-center py-5">
                <div class="spinner-border text-primary mb-3" role="status">
                    <span class="visually-hidden">Chargement...</span>
                </div>
                <p>Préparation du paiement...</p>
            </div>
        </div>
    </div>
</div>

<style>
    .investment-details {
        background-color: #f8f9fa;
        padding: 15px;
        border-radius: 5px;
    }

    .details-row {
        display: flex;
        justify-content: space-between;
        padding: 8px 0;
        border-bottom: 1px solid #dee2e6;
    }

    .details-row:last-child {
        border-bottom: none;
    }
</style>

<script>
    document.getElementById('payBtn').addEventListener('click', async function() {
        const btn = this;
        btn.disabled = true;

        const paymentMethodInput = document.querySelector('input[name="payment_method"]:checked');
        const paymentMethod = paymentMethodInput ? paymentMethodInput.value : 'card';

        let loadingModal;

        try {
            // Paiement via Wallet
            if (paymentMethod === 'wallet') {
                loadingModal = new bootstrap.Modal(document.getElementById('loadingModal'));
                loadingModal.show();

                const response = await fetch('{{ route("wallet.pay.investment") }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({})
                });

                const data = await response.json();

                if (!data.success) {
                    throw new Error(data.message || 'Erreur lors du paiement wallet');
                }

                if (loadingModal) loadingModal.hide();
                alert(data.message || 'Paiement effectué avec succès !');
                
                if (data.redirect_url) {
                    window.location.href = data.redirect_url;
                } else {
                    window.location.href = '{{ route("shop.index") }}';
                }
                return;
            }

            // Paiement par Carte ou Mobile Money
            loadingModal = new bootstrap.Modal(document.getElementById('loadingModal'));
            loadingModal.show();

            const response = await fetch('{{ route("investment-product.initiate") }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                }
            });

            const data = await response.json();

            if (!data.success) {
                throw new Error(data.message || 'Erreur lors de la préparation du paiement');
            }

            const txRef = data.tx_ref;

            if (paymentMethod === 'mobile_money') {
                const mmCountry = document.getElementById('mm_country')?.value;
                const mmNetwork = document.getElementById('mm_network')?.value;
                const mmPhone = document.getElementById('mm_phone')?.value;
                const mmAuthCode = document.getElementById('mm_authorization_code')?.value;

                if (!mmCountry || !mmNetwork || !mmPhone) {
                    throw new Error('Merci de renseigner les informations Mobile Money');
                }

                const mmPayload = {
                    tx_ref: txRef,
                    amount: data.amount,
                    country: mmCountry,
                    network: mmNetwork,
                    phone_number: mmPhone,
                    email: data.customer_email,
                    fullname: data.customer_name,
                    payment_type: 'investment',
                    order_id: data.order_id ?? null,
                    redirect_url: "{{ route('payment.mobile-money.callback') }}"
                };

                if (mmAuthCode) {
                    mmPayload.authorization_code = mmAuthCode;
                }

                const mmResponse = await fetch("{{ route('payment.mobile-money.initiate') }}", {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify(mmPayload)
                });

                const mmResult = await mmResponse.json();

                if (!mmResult.success) {
                    throw new Error(mmResult.message || 'Erreur lors de l\'initiation Mobile Money');
                }

                const mmData = mmResult.data || {};

                if (mmData.redirect_url) {
                    window.location.href = mmData.redirect_url;
                    return;
                }

                if (mmData.qr_code) {
                    displayInvestmentQr(mmData.qr_code, mmData.redirect_url || null);
                    return;
                }

                window.location.href = "{{ route('payment.mobile-money.callback') }}?tx_ref=" + (mmData.tx_ref || txRef);
                return;
            }

            FlutterwaveCheckout({
                public_key: '{{ config("payment.flutterwave.public_key") }}',
                tx_ref: txRef,
                amount: data.amount,
                currency: 'XOF',
                payment_options: 'card',
                redirect_url: "{{ route('investment-product.callback') }}?tx_ref=" + encodeURIComponent(txRef),
                customer: {
                    email: data.customer_email,
                    name: data.customer_name,
                },
                customizations: {
                    title: "Produit d'Investissement",
                    description: "Paiement du produit d'investissement obligatoire",
                    logo: "{{ asset('images/logo.svg') }}"
                },
                callback: function(flwData) {
                    console.log('Flutterwave response:', flwData);
                    if (flwData.status === 'successful') {
                        window.location.href = '{{ route("investment-product.callback") }}?tx_ref=' + encodeURIComponent(txRef) + '&status=successful';
                    } else {
                        if (loadingModal) loadingModal.hide();
                        alert('Paiement non confirmé');
                        btn.disabled = false;
                    }
                },
                onclose: function() {
                    if (loadingModal) loadingModal.hide();
                    btn.disabled = false;
                }
            });

        } catch (error) {
            console.error('Error:', error);
            alert('Erreur : ' + error.message);
            btn.disabled = false;
            if (loadingModal) {
                loadingModal.hide();
            }
        }
    });

    function displayInvestmentQr(qrCodeBase64, redirectUrl) {
        const modal = document.createElement('div');
        modal.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.85);display:flex;align-items:center;justify-content:center;z-index:9999;';
        modal.innerHTML = `
            <div style="background:white;padding:30px;border-radius:12px;text-align:center;max-width:460px;width:90%;box-shadow:0 10px 40px rgba(0,0,0,0.3);">
                <h4 style="margin-bottom:10px;">Scannez pour payer</h4>
                <p style="color:#666;margin-bottom:20px;">Ouvrez votre application Mobile Money pour confirmer</p>
                <img src="${qrCodeBase64}" alt="QR Code" style="max-width:260px;margin:10px auto;display:block;border:2px solid #0d6efd;border-radius:8px;">
                <div style="margin-top:15px;display:flex;justify-content:center;gap:10px;flex-wrap:wrap;">
                    ${redirectUrl ? `<a href="${redirectUrl}" target="_blank" style="padding:10px 18px;background:#0d6efd;color:white;text-decoration:none;border-radius:6px;">Ouvrir l'application</a>` : ''}
                    <button onclick="this.closest('div[style*=\'position:fixed\']').remove();" style="padding:10px 18px;background:#6c757d;color:white;border:none;border-radius:6px;cursor:pointer;">Fermer</button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
    }
</script>

<!-- Charger Flutterwave -->
<script src="https://checkout.flutterwave.com/v3.js"></script>
@endsection
