@extends('layouts.app')

@section('content')
<div class="checkout-container py-5">
    <div class="container">
        <!-- Header -->
        <div class="row mb-5">
            <div class="col-12">
                <h1 class="display-5 fw-bold mb-2">Confirmer votre commande</h1>
                <p class="text-muted">Boutique: <strong>{{ $user->shop_name ?? $user->name }}</strong></p>
            </div>
        </div>

        <form method="POST" action="{{ route('user.shop.place-order', ['username' => $user->username]) }}" id="checkoutForm">
            @csrf
            <div class="row">
                <!-- Main Checkout Form -->
                <div class="col-lg-8">
                    <!-- Contact Information -->
                    <div class="card shadow-sm mb-4">
                        <div class="card-header bg-light border-bottom">
                            <h5 class="mb-0 fw-bold">1. Informations de Contact</h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="name" class="form-label">Nom Complet <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="name" name="name" 
                                        value="{{ auth()->check() ? auth()->user()->name : old('name') }}" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="email" class="form-label">Email <span class="text-danger">*</span></label>
                                    <input type="email" class="form-control" id="email" name="email" 
                                        value="{{ auth()->check() ? auth()->user()->email : old('email') }}" required>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="phone" class="form-label">Téléphone <span class="text-danger">*</span></label>
                                    <input type="tel" class="form-control" id="phone" name="phone" 
                                        value="{{ auth()->check() ? auth()->user()->phone : old('phone') }}" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="address" class="form-label">Adresse <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="address" name="address" 
                                        value="{{ auth()->check() ? auth()->user()->address : old('address') }}" required>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Delivery Address -->
                    <div class="card shadow-sm mb-4">
                        <div class="card-header bg-light border-bottom">
                            <h5 class="mb-0 fw-bold">2. Adresse de Livraison</h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="countrySelect" class="form-label">Pays <span class="text-danger">*</span></label>
                                    <select class="form-select" id="countrySelect" name="country" required>
                                        <option value="">-- Sélectionnez un pays --</option>
                                        @forelse($countries as $country)
                                            <option value="{{ $country }}">{{ $country }}</option>
                                        @empty
                                            <option disabled>Aucun pays disponible</option>
                                        @endforelse
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="citySelect" class="form-label">Ville <span class="text-danger">*</span></label>
                                    <select class="form-select" id="citySelect" name="city" required disabled>
                                        <option value="">-- Sélectionnez une ville --</option>
                                    </select>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="districtSelect" class="form-label">Quartier/District</label>
                                    <select class="form-select" id="districtSelect" name="district" disabled>
                                        <option value="">-- Sélectionnez un quartier --</option>
                                    </select>
                                </div>
                            </div>
                            <!-- Delivery Info -->
                            <div class="alert alert-info d-flex align-items-center mt-3" role="alert" id="deliveryInfo">
                                <i class="fas fa-info-circle me-2"></i>
                                <div id="deliveryMessage">Sélectionnez votre pays et ville pour voir le délai de livraison</div>
                            </div>
                        </div>
                    </div>

                    <!-- Payment Method -->
                    <div class="card shadow-sm mb-4">
                        <div class="card-header bg-light border-bottom">
                            <h5 class="mb-0 fw-bold">3. Méthode de Paiement</h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <div class="payment-option card h-100" style="cursor: pointer; border: 2px solid #ddd; transition: all 0.3s;">
                                        <div class="card-body text-center">
                                            <input class="form-check-input payment-method-radio" type="radio" name="payment_method" 
                                                id="flutterwave" value="flutterwave" required style="display: none;">
                                            <label for="flutterwave" style="cursor: pointer; display: block;">
                                                <i class="fas fa-wallet text-primary mb-2" style="font-size: 2rem;"></i>
                                                <h6>FlutterWave</h6>
                                                <small class="text-muted">Paiement sécurisé en ligne</small>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <div class="payment-option card h-100" style="cursor: pointer; border: 2px solid #ddd; transition: all 0.3s;">
                                        <div class="card-body text-center">
                                            <input class="form-check-input payment-method-radio" type="radio" name="payment_method" 
                                                id="cash" value="cash" style="display: none;">
                                            <label for="cash" style="cursor: pointer; display: block;">
                                                <i class="fas fa-money-bill-wave text-success mb-2" style="font-size: 2rem;"></i>
                                                <h6>Paiement à la Livraison</h6>
                                                <small class="text-muted">Payez à la réception</small>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Hidden Fields -->
                    <input type="hidden" name="shipping_fee" id="shippingFeeInput" value="0">
                    <input type="hidden" name="total" id="grandTotalInput" value="{{ $total }}">
                    <input type="hidden" name="referrer_code" value="{{ session('referrer_code') }}">
                    <input type="hidden" name="referrer_user_id" value="{{ session('referrer_user_id') }}">
                </div>

                <!-- Order Summary Sidebar -->
                <div class="col-lg-4">
                    <div class="card shadow-sm" style="position: sticky; top: 20px;">
                        <div class="card-header bg-dark text-white">
                            <h6 class="mb-0 fw-bold">Résumé de votre commande</h6>
                        </div>
                        <div class="card-body">
                            <!-- Products List -->
                            <div class="mb-4" style="max-height: 300px; overflow-y: auto;">
                                @forelse($cartItems as $cartItem)
                                    <div class="d-flex justify-content-between mb-2 pb-2 border-bottom">
                                        <div>
                                            <p class="mb-0 text-dark"><strong>{{ $cartItem['name'] }}</strong></p>
                                            <small class="text-muted">{{ $cartItem['quantity'] }}x</small>
                                        </div>
                                        <div class="text-end">
                                            <p class="mb-0"><strong>{{ number_format($cartItem['price'] * $cartItem['quantity'], 0, ',', ' ') }} FCFA</strong></p>
                                        </div>
                                    </div>
                                @empty
                                    <p class="text-muted text-center">Aucun produit</p>
                                @endforelse
                            </div>

                            <!-- Pricing -->
                            <div class="border-top pt-3">
                                <div class="d-flex justify-content-between mb-2">
                                    <span>Sous-total:</span>
                                    <span id="subtotalDisplay">{{ number_format($subtotal, 0, ',', ' ') }} FCFA</span>
                                </div>

                                @if($discount > 0)
                                    <div class="d-flex justify-content-between mb-2 text-success">
                                    <span>
                                        <i class="fas fa-tag"></i> Remise ({{ $discountPercentage }}%):
                                    </span>
                                    <span>- {{ number_format($discount, 0, ',', ' ') }} FCFA</span>
                                    </div>
                                @endif

                                <div class="d-flex justify-content-between mb-3 text-success">
                                    <span>Frais de Livraison:</span>
                                    <span id="shippingDisplay"><span class="text-warning">Sélectionner l'adresse</span></span>
                                </div>

                                <div class="border-top pt-3">
                                    <div class="d-flex justify-content-between mb-3">
                                        <span class="fw-bold h5">Total:</span>
                                        <span class="h5 fw-bold text-primary" id="grandTotalDisplay">{{ number_format($total, 0, ',', ' ') }} FCFA</span>
                                    </div>
                                </div>
                            </div>

                            <!-- Action Buttons -->
                            <div class="mt-4">
                                <button type="button" class="btn btn-success btn-lg w-100 mb-2" id="payButton" onclick="handlePayment()">
                                    <i class="fas fa-lock"></i> Passer la Commande
                                </button>
                                <a href="{{ route('user.shop.cart', $user->username) }}" class="btn btn-outline-secondary btn-lg w-100">
                                    <i class="fas fa-arrow-left"></i> Retour au Panier
                                </a>
                            </div>

                            <!-- Security Badge -->
                            <div class="text-center mt-3 text-muted small">
                                <i class="fas fa-shield-alt"></i> Paiement 100% sécurisé
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<script src="https://checkout.flutterwave.com/v3.js"></script>
<script>
    const subtotal = {{ $subtotal }};
    const discount = {{ $discount }};
    let currentShippingFee = 0;

    // Payment option selection
    document.querySelectorAll('.payment-option').forEach(option => {
        option.addEventListener('click', function() {
            const radio = this.querySelector('.payment-method-radio');
            radio.checked = true;
            
            // Update UI
            document.querySelectorAll('.payment-option').forEach(o => {
                o.style.borderColor = '#ddd';
                o.style.backgroundColor = 'transparent';
            });
            this.style.borderColor = '#28a745';
            this.style.backgroundColor = '#f0f8f5';
        });
    });

    // Country selection - Load cities
    document.getElementById('countrySelect').addEventListener('change', function() {
        const country = this.value;
        const citySelect = document.getElementById('citySelect');
        const districtSelect = document.getElementById('districtSelect');
        
        citySelect.innerHTML = '<option value="">-- Sélectionnez une ville --</option>';
        districtSelect.innerHTML = '<option value="">-- Sélectionnez un quartier --</option>';
        districtSelect.disabled = true;
        
        if (country) {
            citySelect.disabled = false;
            getShippingFees(country, '', '');
        } else {
            citySelect.disabled = true;
        }
    });

    // City selection - Load districts
    document.getElementById('citySelect').addEventListener('change', function() {
        const country = document.getElementById('countrySelect').value;
        const city = this.value;
        const districtSelect = document.getElementById('districtSelect');
        
        districtSelect.innerHTML = '<option value="">-- Sélectionnez un quartier --</option>';
        
        if (city) {
            districtSelect.disabled = false;
            getShippingFees(country, city, '');
        } else {
            districtSelect.disabled = true;
        }
    });

    // District selection - Calculate shipping fee
    document.getElementById('districtSelect').addEventListener('change', function() {
        const country = document.getElementById('countrySelect').value;
        const city = document.getElementById('citySelect').value;
        const district = this.value;
        
        if (country && city) {
            getShippingFees(country, city, district);
        }
    });

    function getShippingFees(country, city, district) {
        const url = "{{ route('user.shop.shipping-fees', $user->username) }}";
        
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({
                country: country,
                city: city,
                district: district
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                currentShippingFee = data.fee;
                
                // Update cities dropdown if needed
                if (!city && data.cities && data.cities.length > 0) {
                    const citySelect = document.getElementById('citySelect');
                    data.cities.forEach(c => {
                        const option = document.createElement('option');
                        option.value = c;
                        option.textContent = c;
                        citySelect.appendChild(option);
                    });
                }
                
                // Update districts dropdown if needed
                if (city && !district && data.districts && data.districts.length > 0) {
                    const districtSelect = document.getElementById('districtSelect');
                    data.districts.forEach(d => {
                        const option = document.createElement('option');
                        option.value = d;
                        option.textContent = d;
                        districtSelect.appendChild(option);
                    });
                }
                
                // Update shipping display and totals
                updateTotals();
                
                // Update delivery message
                const deliveryMessage = document.getElementById('deliveryMessage');
                if (data.delivery_delay) {
                    deliveryMessage.textContent = `✓ Livraison estimée: ${data.delivery_delay}`;
                }
            }
        })
        .catch(error => {
            console.error('Erreur:', error);
            currentShippingFee = 0;
            updateTotals();
        });
    }

    function updateTotals() {
        const grandTotal = Number(subtotal) + Number(currentShippingFee) - Number(discount);
        
        const shippingDisplay = document.getElementById('shippingDisplay');
        if (currentShippingFee > 0) {
            shippingDisplay.innerHTML = `<span class="text-success">${currentShippingFee.toLocaleString('fr-FR')} FCFA</span>`;
        } else if (currentShippingFee === 0 && document.getElementById('countrySelect').value) {
            shippingDisplay.innerHTML = '<span class="text-success">Gratuit</span>';
        } else {
            shippingDisplay.innerHTML = '<span class="text-warning">Sélectionner l\'adresse</span>';
        }
        
        document.getElementById('grandTotalDisplay').textContent = grandTotal.toLocaleString('fr-FR') + ' FCFA';
        document.getElementById('grandTotalInput').value = grandTotal;
        document.getElementById('shippingFeeInput').value = currentShippingFee;
    }

    function handlePayment() {
        const form = document.getElementById('checkoutForm');
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }

        const paymentMethod = document.querySelector('input[name="payment_method"]:checked');
        if (!paymentMethod) {
            alert('Veuillez sélectionner une méthode de paiement');
            return;
        }

        if (paymentMethod.value === 'flutterwave') {
            payWithFlutterwave();
        } else if (paymentMethod.value === 'cash') {
            // Direct submission for cash on delivery
            form.submit();
        }
    }

    function payWithFlutterwave() {
        const form = document.getElementById('checkoutForm');
        const grandTotal = Number(document.getElementById('grandTotalInput').value);

        const customerData = {
            email: document.getElementById('email').value,
            phone: document.getElementById('phone').value,
            name: document.getElementById('name').value,
            total: grandTotal,
            currency: 'XOF',
            shipping_fee: document.getElementById('shippingFeeInput').value,
            country: document.getElementById('countrySelect').value,
            city: document.getElementById('citySelect').value,
            referrer_code: document.querySelector('input[name="referrer_code"]').value
        };

        const payButton = document.getElementById('payButton');
        const originalText = payButton.innerHTML;
        payButton.disabled = true;
        payButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Traitement...';

        FlutterwaveCheckout({
            public_key: "{{ config('services.flutterwave.public_key') }}",
            tx_ref: 'boutique_' + Date.now(),
            amount: grandTotal,
            currency: 'XOF',
            payment_options: 'card,mobilemoney,ussd,bank_transfer',
            customer: {
                email: customerData.email,
                phonenumber: customerData.phone,
                name: customerData.name
            },
            customizations: {
                title: 'Boutique {{ $user->shop_name ?? $user->name }}',
                description: 'Achat de produits',
                logo: "{{ asset('images/logo.svg') }}"
            },
            callback: function(data) {
                if (data.status === 'successful' && data.tx_ref) {
                    // Store transaction details and submit
                    const paymentMethodInput = document.querySelector('input[name="payment_method"]:checked');
                    const flutterwaveInput = document.createElement('input');
                    flutterwaveInput.type = 'hidden';
                    flutterwaveInput.name = 'flutterwave_txn_ref';
                    flutterwaveInput.value = data.tx_ref;
                    form.appendChild(flutterwaveInput);

                    form.submit();
                } else {
                    alert('Paiement échoué. Veuillez réessayer.');
                    payButton.disabled = false;
                    payButton.innerHTML = originalText;
                }
            },
            onclose: function() {
                payButton.disabled = false;
                payButton.innerHTML = originalText;
            }
        });
    }
</script>

<style>
    .checkout-container {
        background: #f8f9fa;
    }

    .payment-option {
        border-radius: 8px;
    }

    .payment-option:hover {
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    #payButton {
        font-size: 1.1rem;
        padding: 0.8rem;
        border-radius: 8px;
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        border: none;
        transition: all 0.3s;
    }

    #payButton:hover:not(:disabled) {
        background: linear-gradient(135deg, #218838 0%, #1aa179 100%);
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(40, 167, 69, 0.4);
    }

    #payButton:disabled {
        opacity: 0.7;
        cursor: not-allowed;
    }

    .card {
        border: 1px solid #e0e0e0;
        border-radius: 8px;
    }

    .card-header {
        border-radius: 8px 8px 0 0;
    }
</style>
@endsection
