<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Make Payment | IMMIA FINANCE LIMITED</title>
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        :root {
            --primary: #1e40af;
            --primary-dark: #1e3a8a;
            --secondary: #0f172a;
            --accent: #06b6d4;
            --light: #f8fafc;
        }
        
        .sidebar {
            transition: all 0.3s ease;
        }
        
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }
            
            .sidebar.active {
                transform: translateX(0);
            }
        }
        
        .card-hover {
            transition: all 0.3s ease;
        }
        
        .card-hover:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }
        
        .notification-dot {
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        
        .text-truncate-safe {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            min-width: 0;
        }

        .payment-method {
            transition: all 0.3s ease;
        }

        .payment-method.selected {
            border-color: #1e40af;
            background-color: #eff6ff;
        }

        .payment-step {
            transition: all 0.3s ease;
        }

        .payment-step.active {
            color: #1e40af;
            border-color: #1e40af;
        }

        .payment-step.completed {
            color: #059669;
            border-color: #059669;
        }

        .loading-spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #3498db;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body class="bg-gray-50">
   @php
    $customer = Auth::guard('customer')->user();
    $hasProfilePicture = $customer->docpath && Storage::disk('public')->exists($customer->docpath);
    $profilePictureUrl = $hasProfilePicture ? asset('storage/' . $customer->docpath) : 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?auto=format&fit=crop&w=500&q=60';
    @endphp

    <!-- Mobile Menu Button -->
    <button id="mobile-menu-button" class="lg:hidden fixed top-4 left-4 z-50 bg-blue-600 text-white p-3 rounded-lg shadow-lg">
        <i class="fas fa-bars"></i>
    </button>

    <!-- Sidebar -->
    <div id="sidebar" class="sidebar fixed inset-y-0 left-0 z-40 w-64 bg-white shadow-lg">
        <!-- Logo -->
        <div class="p-6 border-b border-gray-200">
            <div class="flex items-center space-x-3">
                <div class="w-10 h-10 bg-blue-600 rounded-lg flex items-center justify-center">
                    <i class="fas fa-hand-holding-usd text-white text-lg"></i>
                </div>
                <div>
                    <h1 class="text-xl font-bold text-blue-600">IMMIA FINANCE</h1>
                    <p class="text-gray-500 text-xs">Client Portal</p>
                </div>
            </div>
        </div>
        
        <!-- Navigation -->
        <nav class="p-4 space-y-2">
            <a href="{{ route('customer.dashboard') }}" class="flex items-center space-x-3 p-3 text-gray-700 hover:bg-gray-100 rounded-lg font-medium">
                <i class="fas fa-tachometer-alt w-5"></i>
                <span>Dashboard</span>
            </a>
            <a href="{{ route('customer.applications.index') }}" class="flex items-center space-x-3 p-3 text-gray-700 hover:bg-gray-100 rounded-lg font-medium">
                <i class="fas fa-file-invoice-dollar w-5"></i>
                <span>My Applications</span>
            </a>
            <a href="{{ route('customer.loans.index') }}" class="flex items-center space-x-3 p-3 text-gray-700 hover:bg-gray-100 rounded-lg font-medium">
                <i class="fas fa-hand-holding-usd w-5"></i>
                <span>My Loans</span>
            </a>
            <a href="{{ route('customer.loan.application.show') }}" class="flex items-center space-x-3 p-3 text-gray-700 hover:bg-gray-100 rounded-lg font-medium">
               <i class="fas fa-paper-plane w-5"></i>
               <span>Apply for Loan</span>
            </a>
            <a href="{{ route('customer.payments.make') }}" class="flex items-center space-x-3 p-3 bg-blue-50 text-blue-600 rounded-lg font-medium">
                <i class="fas fa-money-bill-wave w-5"></i>
                <span>Make Payment</span>
            </a>
           <a href="{{ route('customer.transactions.history') }}" 
        class="flex items-center space-x-3 p-3 text-gray-700 hover:bg-gray-100 rounded-lg font-medium">
        <i class="fas fa-history w-5"></i>
        <span>Transaction History</span>
           </a>
            <a href="#" class="flex items-center space-x-3 p-3 text-gray-700 hover:bg-gray-100 rounded-lg font-medium">
                <i class="fas fa-file-alt w-5"></i>
                <span>Documents</span>
            </a>
            <a href="{{ route('customer.profile.show') }}" class="flex items-center space-x-3 p-3 text-gray-700 hover:bg-gray-100 rounded-lg font-medium">
                <i class="fas fa-user-cog w-5"></i>
                <span>Profile Settings</span>
            </a>
            <a href="#" class="flex items-center space-x-3 p-3 text-gray-700 hover:bg-gray-100 rounded-lg font-medium">
                <i class="fas fa-question-circle w-5"></i>
                <span>Help & Support</span>
            </a>
            <form method="POST" action="{{ route('customer.logout') }}" class="mt-8">
                @csrf
                <button type="submit" class="flex items-center space-x-3 p-3 text-gray-700 hover:bg-gray-100 rounded-lg font-medium w-full">
                    <i class="fas fa-sign-out-alt w-5"></i>
                    <span>Logout</span>
                </button>
            </form>
        </nav>
    </div>

    <!-- Main Content -->
    <div class="lg:ml-64">
        <!-- Top Bar -->
        <header class="bg-white shadow-sm border-b border-gray-200">
            <div class="flex justify-between items-center px-4 sm:px-6 py-4">
                <div class="min-w-0 flex-1">
                    <h1 class="text-xl sm:text-2xl font-bold text-gray-900 text-truncate-safe">Make Payment</h1>
                    <p class="text-gray-600 text-sm text-truncate-safe">Pay your loan installments securely via Mobile Money</p>
                </div>
                
                <div class="flex items-center space-x-2 sm:space-x-4">
                    <!-- Notifications -->
                    <div class="relative">
                        <button class="p-2 text-gray-600 hover:text-blue-600 relative">
                            <i class="fas fa-bell text-lg sm:text-xl"></i>
                            <span class="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full notification-dot"></span>
                        </button>
                    </div>
                    
                    <!-- User Menu -->
                    <div class="relative">
                        <button class="flex items-center space-x-2 sm:space-x-3 p-2 rounded-lg hover:bg-gray-100">
                            <div class="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center overflow-hidden">
                                @if($hasProfilePicture)
                                    <img src="{{ $profilePictureUrl }}" alt="Profile" class="w-full h-full object-cover">
                                @else
                                    <i class="fas fa-user text-blue-600 text-sm"></i>
                                @endif
                            </div>
                            <span class="text-gray-700 font-medium hidden sm:block">{{ $customer->customer }}</span>
                            <i class="fas fa-chevron-down text-gray-400 hidden sm:block"></i>
                        </button>
                    </div>
                </div>
            </div>
        </header>

        <!-- Main Content Area -->
        <main class="p-4 sm:p-6">
            <!-- Flash Messages -->
            @if(session('success'))
                <div class="mb-6 bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-lg">
                    <div class="flex items-center">
                        <i class="fas fa-check-circle mr-2"></i>
                        <span>{!! session('success') !!}</span>
                    </div>
                </div>
            @endif

            @if(session('error'))
                <div class="mb-6 bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
                    <div class="flex items-center">
                        <i class="fas fa-exclamation-circle mr-2"></i>
                        <span>{{ session('error') }}</span>
                    </div>
                </div>
            @endif

            <div class="max-w-4xl mx-auto">
                <!-- Payment Progress Steps -->
                <div class="bg-white rounded-xl shadow-sm border mb-6">
                    <div class="p-6">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center space-x-2 payment-step active" id="step-1">
                                <div class="w-8 h-8 bg-blue-600 text-white rounded-full flex items-center justify-center text-sm font-semibold">1</div>
                                <span class="font-medium">Select Payment Method</span>
                            </div>
                            <div class="flex-1 h-1 bg-gray-200 mx-4"></div>
                            <div class="flex items-center space-x-2 payment-step" id="step-2">
                                <div class="w-8 h-8 bg-gray-200 text-gray-600 rounded-full flex items-center justify-center text-sm font-semibold">2</div>
                                <span class="font-medium text-gray-500">Enter Details</span>
                            </div>
                            <div class="flex-1 h-1 bg-gray-200 mx-4"></div>
                            <div class="flex items-center space-x-2 payment-step" id="step-3">
                                <div class="w-8 h-8 bg-gray-200 text-gray-600 rounded-full flex items-center justify-center text-sm font-semibold">3</div>
                                <span class="font-medium text-gray-500">Confirm Payment</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Payment Methods -->
                <div class="bg-white rounded-xl shadow-sm border mb-6" id="step-1-content">
                    <div class="p-6 border-b border-gray-200">
                        <h2 class="text-xl font-bold text-gray-900">Select Payment Method</h2>
                        <p class="text-gray-600">Choose your preferred mobile money service</p>
                    </div>
                    <div class="p-6">
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <!-- Airtel Money -->
                            <div class="payment-method border-2 border-gray-200 rounded-lg p-6 text-center cursor-pointer card-hover" data-method="airtel">
                                <div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                    <i class="fas fa-mobile-alt text-red-600 text-2xl"></i>
                                </div>
                                <h3 class="text-lg font-semibold text-gray-900 mb-2">Airtel Money</h3>
                                <p class="text-gray-600 text-sm mb-4">Pay using your Airtel mobile money account</p>
                                <div class="text-xs text-gray-500">
                                    <i class="fas fa-shield-alt mr-1"></i>
                                    Secure & Instant
                                </div>
                            </div>

                            <!-- MTN Mobile Money -->
                            <div class="payment-method border-2 border-gray-200 rounded-lg p-6 text-center cursor-pointer card-hover" data-method="mtn">
                                <div class="w-16 h-16 bg-yellow-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                    <i class="fas fa-sim-card text-yellow-600 text-2xl"></i>
                                </div>
                                <h3 class="text-lg font-semibold text-gray-900 mb-2">MTN Mobile Money</h3>
                                <p class="text-gray-600 text-sm mb-4">Pay using your MTN mobile money account</p>
                                <div class="text-xs text-gray-500">
                                    <i class="fas fa-shield-alt mr-1"></i>
                                    Secure & Instant
                                </div>
                            </div>

                            <!-- Zamtel Mobile Money -->
                            <div class="payment-method border-2 border-gray-200 rounded-lg p-6 text-center cursor-pointer card-hover" data-method="zamtel">
                                <div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                    <i class="fas fa-wallet text-green-600 text-2xl"></i>
                                </div>
                                <h3 class="text-lg font-semibold text-gray-900 mb-2">Zamtel Mobile Money</h3>
                                <p class="text-gray-600 text-sm mb-4">Pay using your Zamtel mobile money account</p>
                                <div class="text-xs text-gray-500">
                                    <i class="fas fa-shield-alt mr-1"></i>
                                    Secure & Instant
                                </div>
                            </div>
                        </div>

                        <div class="mt-6 flex justify-end">
                            <button id="next-to-step-2" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg font-semibold transition-colors disabled:bg-gray-400 disabled:cursor-not-allowed" disabled>
                                Continue to Payment Details
                                <i class="fas fa-arrow-right ml-2"></i>
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Payment Details Form -->
                <div class="bg-white rounded-xl shadow-sm border mb-6 hidden" id="step-2-content">
                    <div class="p-6 border-b border-gray-200">
                        <h2 class="text-xl font-bold text-gray-900">Enter Payment Details</h2>
                        <p class="text-gray-600">Provide your payment information</p>
                    </div>
                    <div class="p-6">
                        <form id="payment-form">
                            @csrf
                            
                            <!-- Hidden field for payment method -->
                            <input type="hidden" name="payment_method" id="payment-method-input">
                            
                            <!-- Selected Method Display -->
                            <div class="mb-6 p-4 bg-blue-50 rounded-lg">
                                <div class="flex items-center justify-between">
                                    <div class="flex items-center space-x-3">
                                        <div id="selected-method-icon" class="w-10 h-10 rounded-full flex items-center justify-center">
                                            <!-- Icon will be dynamically inserted -->
                                        </div>
                                        <div>
                                            <h3 id="selected-method-name" class="font-semibold text-gray-900"></h3>
                                            <p class="text-gray-600 text-sm" id="selected-method-description"></p>
                                        </div>
                                    </div>
                                    <button type="button" id="change-method" class="text-blue-600 hover:text-blue-700 text-sm font-medium">
                                        Change Method
                                    </button>
                                </div>
                            </div>

                            <!-- Loan Selection -->
                            <div class="mb-6">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    Select Loan to Pay
                                </label>
                                <select name="loan_id" class="w-full border border-gray-300 rounded-lg px-4 py-3 focus:border-blue-500 focus:ring-blue-500" required>
                                    <option value="">Choose a loan...</option>
                                    @foreach($activeLoans as $loan)
                                    <option value="{{ $loan->loanid }}" data-outstanding="{{ $loan->outstanding_balance }}">
                                        Loan #{{ $loan->loannumber }} - ZMW {{ number_format($loan->outstanding_balance, 2) }} Outstanding
                                    </option>
                                    @endforeach
                                </select>
                            </div>

                            <!-- Amount Input -->
                            <div class="mb-6">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    Payment Amount (ZMW)
                                </label>
                                <div class="relative">
                                    <span class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500">ZMW</span>
                                    <input type="number" name="amount" min="1" step="0.01" 
                                           class="w-full border border-gray-300 rounded-lg pl-12 pr-4 py-3 focus:border-blue-500 focus:ring-blue-500" 
                                           placeholder="0.00" required>
                                </div>
                                <div class="mt-2 flex space-x-2">
                                    <button type="button" class="quick-amount text-xs bg-gray-100 hover:bg-gray-200 px-3 py-1 rounded" data-amount="{{ $loanStats['total_next_due_amount'] ?? 0 }}">
                                        Next Due: ZMW {{ number_format($loanStats['total_next_due_amount'] ?? 0, 2) }}
                                    </button>
                                    <button type="button" class="quick-amount text-xs bg-gray-100 hover:bg-gray-200 px-3 py-1 rounded" data-amount="{{ $loanStats['total_overdue_amount'] ?? 0 }}">
                                        Overdue: ZMW {{ number_format($loanStats['total_overdue_amount'] ?? 0, 2) }}
                                    </button>
                                </div>
                            </div>

                            <!-- Mobile Money Details -->
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">
                                        Mobile Number
                                    </label>
                                    <input type="tel" name="mobile_number" 
                                           class="w-full border border-gray-300 rounded-lg px-4 py-3 focus:border-blue-500 focus:ring-blue-500" 
                                           placeholder="e.g., 0971234567" required>
                                    <p class="text-xs text-gray-500 mt-1">Enter your mobile money number</p>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">
                                        Payment Description
                                    </label>
                                    <input type="text" name="description" 
                                           class="w-full border border-gray-300 rounded-lg px-4 py-3 focus:border-blue-500 focus:ring-blue-500" 
                                           placeholder="e.g., Loan installment payment">
                                </div>
                            </div>

                            <div class="flex justify-between">
                                <button type="button" id="back-to-step-1" class="bg-gray-500 hover:bg-gray-600 text-white px-6 py-3 rounded-lg font-semibold transition-colors">
                                    <i class="fas fa-arrow-left mr-2"></i>
                                    Back
                                </button>
                                <button type="submit" id="proceed-to-confirm" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg font-semibold transition-colors">
                                    Proceed to Confirm
                                    <i class="fas fa-arrow-right ml-2"></i>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Payment Confirmation -->
                <div class="bg-white rounded-xl shadow-sm border mb-6 hidden" id="step-3-content">
                    <div class="p-6 border-b border-gray-200">
                        <h2 class="text-xl font-bold text-gray-900">Confirm Payment</h2>
                        <p class="text-gray-600">Review and confirm your payment details</p>
                    </div>
                    <div class="p-6">
                        <div class="bg-blue-50 rounded-lg p-6 mb-6">
                            <div class="text-center">
                                <i class="fas fa-shield-alt text-blue-600 text-4xl mb-4"></i>
                                <h3 class="text-lg font-semibold text-gray-900 mb-2">Secure Payment</h3>
                                <p class="text-gray-600">Your payment is protected with bank-level security</p>
                            </div>
                        </div>

                        <!-- Payment Summary -->
                        <div class="border border-gray-200 rounded-lg p-6 mb-6">
                            <h4 class="text-lg font-semibold text-gray-900 mb-4">Payment Summary</h4>
                            <div class="space-y-3">
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Payment Method:</span>
                                    <span id="confirm-method" class="font-semibold"></span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Loan Number:</span>
                                    <span id="confirm-loan" class="font-semibold"></span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Mobile Number:</span>
                                    <span id="confirm-mobile" class="font-semibold"></span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Description:</span>
                                    <span id="confirm-description" class="font-semibold"></span>
                                </div>
                                <div class="flex justify-between text-lg border-t border-gray-200 pt-3">
                                    <span class="text-gray-900 font-semibold">Amount:</span>
                                    <span id="confirm-amount" class="font-bold text-blue-600"></span>
                                </div>
                            </div>
                        </div>

                        <!-- Terms and Conditions -->
                        <div class="mb-6">
                            <label class="flex items-start space-x-3">
                                <input type="checkbox" id="terms-agreement" class="mt-1 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                                <span class="text-sm text-gray-600">
                                    I agree to the <a href="#" class="text-blue-600 hover:text-blue-700">Terms and Conditions</a> and confirm that I have sufficient funds in my mobile money account to complete this transaction. I understand that I will receive a USSD prompt to authorize this payment.
                                </span>
                            </label>
                        </div>

                        <div class="flex justify-between">
                            <button type="button" id="back-to-step-2" class="bg-gray-500 hover:bg-gray-600 text-white px-6 py-3 rounded-lg font-semibold transition-colors">
                                <i class="fas fa-arrow-left mr-2"></i>
                                Back
                            </button>
                            <button type="button" id="confirm-payment" class="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg font-semibold transition-colors disabled:bg-gray-400 disabled:cursor-not-allowed" disabled>
                                <i class="fas fa-lock mr-2"></i>
                                Confirm & Pay
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Security Notice -->
                <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                    <div class="flex items-start space-x-3">
                        <i class="fas fa-exclamation-triangle text-yellow-600 mt-1"></i>
                        <div>
                            <h4 class="font-semibold text-yellow-800">Security Notice</h4>
                            <p class="text-yellow-700 text-sm mt-1">
                                • Never share your mobile money PIN with anyone<br>
                                • IMMIA Finance will never ask for your PIN via phone call or SMS<br>
                                • Ensure you have sufficient funds before making payment<br>
                                • You will receive a USSD prompt to authorize the payment<br>
                                • Transactions are processed securely and instantly
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- Payment Processing Modal -->
    <div id="processing-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl p-8 max-w-md w-full mx-4 text-center">
            <div class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <i class="fas fa-spinner fa-spin text-blue-600 text-2xl"></i>
            </div>
            <h3 class="text-xl font-semibold text-gray-900 mb-2">Processing Payment</h3>
            <p class="text-gray-600 mb-4" id="processing-message">Please wait while we process your payment...</p>
            <div class="w-full bg-gray-200 rounded-full h-2">
                <div class="bg-blue-600 h-2 rounded-full animate-pulse"></div>
            </div>
        </div>
    </div>

    <!-- Payment Success Modal -->
    <div id="success-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl p-8 max-w-md w-full mx-4 text-center">
            <div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <i class="fas fa-check text-green-600 text-2xl"></i>
            </div>
            <h3 class="text-xl font-semibold text-gray-900 mb-2">Payment Successful!</h3>
            <p class="text-gray-600 mb-4">Your payment has been processed successfully and recorded in our system.</p>
            <div class="space-y-3 text-left bg-gray-50 rounded-lg p-4 mb-6">
                <div class="flex justify-between">
                    <span class="text-gray-600">Reference Number:</span>
                    <span class="font-semibold" id="success-reference"></span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-600">Amount Paid:</span>
                    <span class="font-semibold" id="success-amount"></span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-600">Date & Time:</span>
                    <span class="font-semibold" id="success-date"></span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-600">Transaction ID:</span>
                    <span class="font-semibold" id="success-transaction-id"></span>
                </div>
            </div>
            <div class="flex space-x-3">
                <button onclick="window.location.href='{{ route('customer.dashboard') }}'" class="flex-1 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg font-semibold transition-colors">
                    Back to Dashboard
                </button>
                <button onclick="window.location.href='{{ route('customer.payments.make') }}'" class="flex-1 bg-gray-500 hover:bg-gray-600 text-white px-4 py-2 rounded-lg font-semibold transition-colors">
                    Make Another Payment
                </button>
            </div>
        </div>
    </div>

    <script>
        // Payment method selection
        let selectedMethod = null;
        let currentTransactionId = null;
        let currentPendingPaymentId = null;
        let pollingInterval = null;

        const methodIcons = {
            airtel: { 
                icon: 'fas fa-mobile-alt', 
                color: 'bg-red-100', 
                text: 'text-red-600', 
                name: 'Airtel Money',
                displayName: 'Airtel Mobile Money'
            },
            mtn: { 
                icon: 'fas fa-sim-card', 
                color: 'bg-yellow-100', 
                text: 'text-yellow-600', 
                name: 'MTN Mobile Money',
                displayName: 'MTN Mobile Money'
            },
            zamtel: { 
                icon: 'fas fa-wallet', 
                color: 'bg-green-100', 
                text: 'text-green-600', 
                name: 'Zamtel Mobile Money',
                displayName: 'Zamtel Mobile Money'
            }
        };

        document.querySelectorAll('.payment-method').forEach(method => {
            method.addEventListener('click', function() {
                // Remove selected class from all methods
                document.querySelectorAll('.payment-method').forEach(m => {
                    m.classList.remove('selected');
                });
                
                // Add selected class to clicked method
                this.classList.add('selected');
                
                // Enable next button
                document.getElementById('next-to-step-2').disabled = false;
                
                // Store selected method and set hidden input
                selectedMethod = this.dataset.method;
                document.getElementById('payment-method-input').value = selectedMethod;
            });
        });

        // Step navigation
        document.getElementById('next-to-step-2').addEventListener('click', function() {
            if (!selectedMethod) return;
            
            // Update step 2 with selected method
            const method = methodIcons[selectedMethod];
            document.getElementById('selected-method-icon').innerHTML = `<i class="${method.icon} ${method.text} text-2xl"></i>`;
            document.getElementById('selected-method-icon').className = `w-10 h-10 ${method.color} rounded-full flex items-center justify-center`;
            document.getElementById('selected-method-name').textContent = method.name;
            document.getElementById('selected-method-description').textContent = `Payment via ${method.name}`;
            
            // Show/hide steps
            document.getElementById('step-1-content').classList.add('hidden');
            document.getElementById('step-2-content').classList.remove('hidden');
            
            // Update progress steps
            document.getElementById('step-1').classList.add('completed');
            document.getElementById('step-2').classList.add('active');
        });

        document.getElementById('change-method').addEventListener('click', function() {
            document.getElementById('step-2-content').classList.add('hidden');
            document.getElementById('step-1-content').classList.remove('hidden');
            
            document.getElementById('step-1').classList.remove('completed');
            document.getElementById('step-2').classList.remove('active');
        });

        document.getElementById('back-to-step-1').addEventListener('click', function() {
            document.getElementById('step-2-content').classList.add('hidden');
            document.getElementById('step-1-content').classList.remove('hidden');
            
            document.getElementById('step-1').classList.remove('completed');
            document.getElementById('step-2').classList.remove('active');
        });

        // Quick amount buttons
        document.querySelectorAll('.quick-amount').forEach(button => {
            button.addEventListener('click', function() {
                const amount = this.dataset.amount;
                if (amount > 0) {
                    document.querySelector('input[name="amount"]').value = amount;
                } else {
                    alert('No amount due for this option');
                }
            });
        });

        // Form submission to step 3
        document.getElementById('payment-form').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // Basic validation
            const amount = document.querySelector('input[name="amount"]').value;
            const loanId = document.querySelector('select[name="loan_id"]').value;
            const mobileNumber = document.querySelector('input[name="mobile_number"]').value;
            const description = document.querySelector('input[name="description"]').value;

            if (!loanId) {
                alert('Please select a loan to pay');
                return;
            }

            if (!amount || amount <= 0) {
                alert('Please enter a valid payment amount');
                return;
            }

            if (!mobileNumber) {
                alert('Please enter your mobile number');
                return;
            }

            // Get form data
            const formData = new FormData(this);
            const loanSelect = document.querySelector('select[name="loan_id"]');
            const selectedOption = loanSelect.options[loanSelect.selectedIndex];
            
            // Update confirmation details
            document.getElementById('confirm-method').textContent = methodIcons[selectedMethod].displayName;
            document.getElementById('confirm-loan').textContent = selectedOption.text.split(' - ')[0];
            document.getElementById('confirm-mobile').textContent = formData.get('mobile_number');
            document.getElementById('confirm-description').textContent = description || 'Loan repayment payment';
            document.getElementById('confirm-amount').textContent = 'ZMW ' + parseFloat(formData.get('amount')).toFixed(2);
            
            // Show step 3
            document.getElementById('step-2-content').classList.add('hidden');
            document.getElementById('step-3-content').classList.remove('hidden');
            
            // Update progress steps
            document.getElementById('step-2').classList.add('completed');
            document.getElementById('step-3').classList.add('active');
        });

        document.getElementById('back-to-step-2').addEventListener('click', function() {
            document.getElementById('step-3-content').classList.add('hidden');
            document.getElementById('step-2-content').classList.remove('hidden');
            
            document.getElementById('step-2').classList.remove('completed');
            document.getElementById('step-3').classList.remove('active');
        });

        // Terms agreement
        document.getElementById('terms-agreement').addEventListener('change', function() {
            document.getElementById('confirm-payment').disabled = !this.checked;
        });

        // Final payment confirmation
        document.getElementById('confirm-payment').addEventListener('click', function() {
            if (!selectedMethod) {
                alert('Please select a payment method');
                return;
            }

            if (!document.getElementById('terms-agreement').checked) {
                alert('Please agree to the terms and conditions');
                return;
            }

            // Show processing modal
            document.getElementById('processing-modal').classList.remove('hidden');
            document.getElementById('processing-message').textContent = 'Initiating payment request...';
            
            // Get form data
            const formData = new FormData(document.getElementById('payment-form'));
            const paymentData = {
                loan_id: formData.get('loan_id'),
                amount: formData.get('amount'),
                mobile_number: formData.get('mobile_number'),
                payment_method: selectedMethod,
                description: formData.get('description')
            };

            // Make API call to process payment
            fetch('{{ route("customer.payments.process") }}', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify(paymentData)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    currentTransactionId = data.transaction_id;
                    currentPendingPaymentId = data.pending_payment_id;
                    
                    if (data.polling_required) {
                        // Payment is pending - start polling
                        document.getElementById('processing-message').textContent = 'Waiting for payment confirmation from mobile network...';
                        startPollingStatus(data.transaction_id, data.pending_payment_id, formData.get('loan_id'));
                    } else {
                        // Payment was immediately successful
                        completePaymentSuccess(data);
                    }
                } else {
                    throw new Error(data.message || 'Payment initiation failed');
                }
            })
            .catch(error => {
                document.getElementById('processing-modal').classList.add('hidden');
                console.error('Error:', error);
                alert('Payment failed: ' + error.message);
            });
        });

        // Poll payment status
        function startPollingStatus(transactionId, pendingPaymentId, loanId) {
            let attempts = 0;
            const maxAttempts = 30; // 5 minutes at 10-second intervals
            
            pollingInterval = setInterval(() => {
                attempts++;
                
                if (attempts > maxAttempts) {
                    clearInterval(pollingInterval);
                    document.getElementById('processing-modal').classList.add('hidden');
                    alert('Payment status check timed out. Please check your mobile money account and refresh the page to see updated status.');
                    return;
                }

                fetch('{{ route("customer.api.mobile-money.check-status") }}', {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Accept': 'application/json',
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: JSON.stringify({
                        transaction_id: transactionId,
                        loan_id: loanId,
                        pending_payment_id: pendingPaymentId
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Payment successful
                        clearInterval(pollingInterval);
                        completePaymentSuccess(data);
                    } else if (data.status === 'Failed') {
                        // Payment failed
                        clearInterval(pollingInterval);
                        document.getElementById('processing-modal').classList.add('hidden');
                        alert('Payment failed: ' + (data.error || 'Transaction was not completed'));
                    }
                    // If still pending, continue polling
                })
                .catch(error => {
                    console.error('Status check error:', error);
                    // Continue polling on network errors
                });
            }, 10000); // Check every 10 seconds
        }

        // Complete payment success flow
        function completePaymentSuccess(data) {
            document.getElementById('processing-modal').classList.add('hidden');
            
            // Update success modal with actual data from server
            document.getElementById('success-reference').textContent = data.reference_number || currentTransactionId;
            document.getElementById('success-amount').textContent = 'ZMW ' + parseFloat(data.amount).toFixed(2);
            document.getElementById('success-date').textContent = new Date().toLocaleString();
            document.getElementById('success-transaction-id').textContent = data.repayment_id || currentTransactionId;
            
            // Show success modal
            document.getElementById('success-modal').classList.remove('hidden');
            
            // Reset form and state
            resetPaymentForm();
        }

        // Reset payment form
        function resetPaymentForm() {
            document.getElementById('payment-form').reset();
            document.getElementById('terms-agreement').checked = false;
            document.getElementById('confirm-payment').disabled = true;
            
            selectedMethod = null;
            currentTransactionId = null;
            currentPendingPaymentId = null;
            
            if (pollingInterval) {
                clearInterval(pollingInterval);
                pollingInterval = null;
            }
            
            // Reset to step 1
            document.getElementById('step-3-content').classList.add('hidden');
            document.getElementById('step-1-content').classList.remove('hidden');
            
            document.getElementById('step-1').classList.remove('completed');
            document.getElementById('step-2').classList.remove('active', 'completed');
            document.getElementById('step-3').classList.remove('active');
            
            document.querySelectorAll('.payment-method').forEach(m => {
                m.classList.remove('selected');
            });
            document.getElementById('next-to-step-2').disabled = true;
        }

        // Mobile menu toggle
        document.getElementById('mobile-menu-button').addEventListener('click', function() {
            document.getElementById('sidebar').classList.toggle('active');
        });

        // Close sidebar when clicking outside on mobile
        document.addEventListener('click', function(event) {
            const sidebar = document.getElementById('sidebar');
            const mobileButton = document.getElementById('mobile-menu-button');
            
            if (window.innerWidth < 1024 && 
                !sidebar.contains(event.target) && 
                !mobileButton.contains(event.target)) {
                sidebar.classList.remove('active');
            }
        });

        // Handle window resize
        window.addEventListener('resize', function() {
            if (window.innerWidth >= 1024) {
                document.getElementById('sidebar').classList.remove('active');
            }
        });

        // Auto-format mobile number input
        document.querySelector('input[name="mobile_number"]').addEventListener('input', function(e) {
            let value = e.target.value.replace(/\D/g, '');
            if (value.length > 0) {
                value = value.substring(0, 10);
            }
            e.target.value = value;
        });
    </script>
</body>
</html>