<?php $current_page = 'disbursements'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Disbursements - Admin App</title>
    <link rel="icon" href="/favicon.svg" type="image/svg+xml">
    <link rel="icon" href="/favicon.ico" sizes="any">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <?= view('admin/partials/admin_styles') ?>
    <style>
        .page-header { margin-bottom: 1.5rem; }
        .page-title { font-size: 1.5rem; color: #1e293b; font-weight: 700; display: flex; align-items: center; gap: 0.5rem; }
        .breadcrumb { display: flex; align-items: center; gap: 0.5rem; color: #64748b; margin-top: 0.35rem; font-size: 0.9rem; }
        .breadcrumb a { color: #6366f1; text-decoration: none; font-weight: 500; }
        .report-section { margin-bottom: 1.5rem; }
        .report-link { background: #fff; padding: 0.75rem 1.25rem; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.06); border: 1px solid #e2e8f0; display: inline-flex; align-items: center; gap: 0.5rem; color: #6366f1; text-decoration: none; font-weight: 500; }
        .report-link:hover { border-color: #6366f1; }

        .card {
            background: white;
            padding: 2.5rem;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.05);
            margin-bottom: 2rem;
            border: 1px solid rgba(0,0,0,0.04);
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            color: #2d3748;
            font-weight: 600;
            font-size: 0.95rem;
        }

        .form-label i {
            color: #667eea;
            margin-right: 0.5rem;
        }

        .form-input {
            width: 100%;
            padding: 0.875rem 1rem;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            font-size: 1rem;
            transition: all 0.3s ease;
            background: #f8f9fa;
        }

        .form-input:focus {
            outline: none;
            border-color: #667eea;
            background: white;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .form-textarea {
            min-height: 100px;
            resize: vertical;
        }

        .form-select {
            width: 100%;
            padding: 0.875rem 1rem;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            font-size: 1rem;
            transition: all 0.3s ease;
            background: #f8f9fa;
            cursor: pointer;
        }

        .form-select:focus {
            outline: none;
            border-color: #667eea;
            background: white;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .btn {
            padding: 0.875rem 2rem;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        .btn-primary:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .btn-secondary {
            background: #e2e8f0;
            color: #2d3748;
        }

        .btn-secondary:hover {
            background: #cbd5e0;
        }

        .alert {
            padding: 1rem 1.5rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            display: none;
        }

        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border-left: 4px solid #10b981;
        }

        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }

        .alert-info {
            background: #dbeafe;
            color: #1e40af;
            border-left: 4px solid #3b82f6;
        }

        .info-box {
            background: #f0f9ff;
            border: 1px solid #bae6fd;
            border-radius: 8px;
            padding: 1rem 1.5rem;
            margin-bottom: 2rem;
            color: #1e40af;
        }

        .info-box i {
            margin-right: 0.5rem;
        }

        .form-actions {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
            margin-top: 2rem;
            padding-top: 2rem;
            border-top: 2px solid #e9ecef;
        }

        .result-card {
            background: #f8f9fa;
            border-left: 4px solid #667eea;
            border-radius: 8px;
            padding: 1.5rem;
            margin-top: 1.5rem;
            display: none;
        }

        .result-item {
            display: flex;
            justify-content: space-between;
            padding: 0.75rem 0;
            border-bottom: 1px solid #e9ecef;
        }

        .result-item:last-child {
            border-bottom: none;
        }

        .result-label {
            color: #718096;
            font-weight: 600;
        }

        .result-value {
            color: #1a202c;
            font-weight: 700;
        }

        .tabs-container {
            margin-bottom: 2rem;
        }

        .tabs {
            display: flex;
            gap: 1rem;
            background: white;
            padding: 0.5rem;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            margin-bottom: 2rem;
        }

        .tab {
            flex: 1;
            padding: 1rem 2rem;
            border: none;
            background: transparent;
            color: #718096;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            border-radius: 8px;
            transition: all 0.3s ease;
        }

        .tab.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }

        .tab:hover:not(.active) {
            background: #f7fafc;
            color: #4a5568;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
            animation: fadeIn 0.5s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .step-indicator {
            display: flex;
            align-items: center;
            gap: 1rem;
            margin-bottom: 2rem;
            padding: 1rem;
            background: #f8f9fa;
            border-radius: 8px;
        }

        .step {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            flex: 1;
        }

        .step-number {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            background: #e2e8f0;
            color: #718096;
        }

        .step.active .step-number {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .step.completed .step-number {
            background: #10b981;
            color: white;
        }

        .step-label {
            color: #718096;
            font-weight: 600;
        }

        .step.active .step-label {
            color: #667eea;
        }

        .step-connector {
            flex: 1;
            height: 2px;
            background: #e2e8f0;
        }

        .step.active .step-connector {
            background: linear-gradient(90deg, #667eea, #e2e8f0);
        }

        .step.completed .step-connector {
            background: #10b981;
        }

        .validation-result {
            background: #f0f9ff;
            border: 2px solid #3b82f6;
            border-radius: 8px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            display: none;
        }

        .validation-result.show {
            display: block;
        }

        @media (max-width: 768px) {
            .container {
                padding: 1.5rem 1rem;
            }

            .page-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 1rem;
            }

            .form-actions {
                flex-direction: column;
            }

            .btn {
                width: 100%;
                justify-content: center;
            }
        }
    </style>
</head>
<body>
<?= view('admin/partials/header_sidebar', ['current_page' => $current_page]) ?>

    <div class="page-header">
        <h1 class="page-title"><i class="fas fa-paper-plane"></i> Disbursements</h1>
        <div class="breadcrumb">
            <a href="<?= site_url('admin/dashboard') ?>">Dashboard</a>
            <i class="fas fa-chevron-right"></i>
            <span>Disbursements</span>
        </div>
    </div>

    <div class="report-section">
        <a href="<?= site_url('admin/relworx-transactions?payment_method=mobile_money_send') ?>" class="report-link">
            <i class="fas fa-chart-bar"></i> View send history &amp; financial report
        </a>
    </div>

    <div class="tabs-container">
            <div class="tabs">
                <button class="tab active" onclick="switchTab('mobile')">
                    <i class="fas fa-mobile-alt"></i> Mobile Money
                </button>
                <button class="tab" onclick="switchTab('bank')">
                    <i class="fas fa-university"></i> Bank Transfer
                </button>
            </div>

            <!-- Mobile Money Tab -->
            <div id="mobile" class="tab-content active">
                <div class="info-box">
                    <i class="fas fa-info-circle"></i>
                    <strong>What is this?</strong> Send mobile money directly to phone numbers. The recipient will receive the specified amount credited to their mobile money account.
                </div>

                <div class="card">
            <form id="disbursementForm">
                <div class="form-group">
                    <label class="form-label" for="msisdn">
                        <i class="fas fa-phone"></i> Phone Number
                    </label>
                    <input 
                        type="text" 
                        id="msisdn" 
                        name="msisdn" 
                        class="form-input" 
                        placeholder="+256768464016"
                        required
                    >
                    <small style="color: #718096; display: block; margin-top: 0.25rem;">
                        Include country code (e.g., +256 for Uganda)
                    </small>
                </div>

                <div class="form-group">
                    <label class="form-label" for="amount">
                        <i class="fas fa-money-bill-wave"></i> Amount
                    </label>
                    <input 
                        type="number" 
                        id="amount" 
                        name="amount" 
                        class="form-input" 
                        placeholder="1000.00"
                        step="0.01"
                        min="0.01"
                        required
                    >
                </div>

                <div class="form-group">
                    <label class="form-label" for="currency">
                        <i class="fas fa-coins"></i> Currency
                    </label>
                    <select id="currency" name="currency" class="form-select" required>
                        <option value="UGX" selected>UGX (Ugandan Shilling)</option>
                        <option value="USD">USD (US Dollar)</option>
                        <option value="KES">KES (Kenyan Shilling)</option>
                        <option value="TZS">TZS (Tanzanian Shilling)</option>
                    </select>
                </div>

                <div class="form-group">
                    <label class="form-label" for="description">
                        <i class="fas fa-align-left"></i> Description
                    </label>
                    <textarea 
                        id="description" 
                        name="description" 
                        class="form-input form-textarea" 
                        placeholder="Payment description or reference"
                        required
                    ></textarea>
                </div>

                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="resetForm()">
                        <i class="fas fa-undo"></i> Reset
                    </button>
                    <button type="submit" class="btn btn-primary" id="submitBtn">
                        <i class="fas fa-paper-plane"></i> Send Disbursement
                    </button>
                </div>
            </form>

            <div id="alertBox" class="alert"></div>

            <div id="resultCard" class="result-card">
                <h3 style="margin-bottom: 1rem; color: #1a202c;">
                    <i class="fas fa-check-circle" style="color: #10b981;"></i> Disbursement Result
                </h3>
                <div id="resultContent"></div>
            </div>
        </div>
    </div>

            <!-- Bank Transfer Tab -->
            <div id="bank" class="tab-content">
                <div class="info-box">
                    <i class="fas fa-info-circle"></i>
                    <strong>What is this?</strong> Send money to bank accounts. First validate the account, then proceed with the transfer if validation is successful.
                </div>

                <div class="step-indicator">
                    <div class="step active" id="step1">
                        <div class="step-number">1</div>
                        <div class="step-label">Validate Account</div>
                    </div>
                    <div class="step-connector"></div>
                    <div class="step" id="step2">
                        <div class="step-number">2</div>
                        <div class="step-label">Complete Transfer</div>
                    </div>
                </div>

                <div class="card">
                    <form id="bankValidationForm">
                        <h3 style="margin-bottom: 1.5rem; color: #1a202c; display: flex; align-items: center; gap: 0.5rem;">
                            <i class="fas fa-university" style="color: #667eea;"></i> Step 1: Validate Bank Account
                        </h3>

                        <div class="form-group">
                            <label class="form-label" for="bank_product_code">
                                <i class="fas fa-building"></i> Bank <span style="color: #ef4444;">*</span>
                            </label>
                            <select id="bank_product_code" name="product_code" class="form-select" required onchange="onBankSelected()">
                                <option value="">-- Select Bank First --</option>
                                <option value="" disabled id="loadingBanks">Loading banks...</option>
                            </select>
                            <small style="color: #718096; display: block; margin-top: 0.25rem;">
                                Select a bank to continue
                            </small>
                        </div>

                        <div id="otherBankFields" style="display: none;">
                            <div class="form-group">
                                <label class="form-label" for="bank_msisdn">
                                    <i class="fas fa-credit-card"></i> Account Number
                                </label>
                                <input 
                                    type="text" 
                                    id="bank_msisdn" 
                                    name="msisdn" 
                                    class="form-input" 
                                    placeholder="6007244078"
                                    required
                                >
                                <small style="color: #718096; display: block; margin-top: 0.25rem;">
                                    Bank account number (not phone number)
                                </small>
                            </div>

                            <div class="form-group">
                                <label class="form-label" for="bank_amount">
                                    <i class="fas fa-money-bill-wave"></i> Amount
                                </label>
                                <input 
                                    type="number" 
                                    id="bank_amount" 
                                    name="amount" 
                                    class="form-input" 
                                    placeholder="3000"
                                    step="0.01"
                                    min="0.01"
                                    required
                                >
                            </div>

                            <div class="form-group">
                                <label class="form-label" for="bank_contact_phone">
                                    <i class="fas fa-phone"></i> Contact Phone
                                </label>
                                <input 
                                    type="text" 
                                    id="bank_contact_phone" 
                                    name="contact_phone" 
                                    class="form-input" 
                                    placeholder="+256768464016"
                                    required
                                >
                                <small style="color: #718096; display: block; margin-top: 0.25rem;">
                                    Your contact phone number (include country code)
                                </small>
                            </div>

                            <div class="form-group">
                                <label class="form-label" for="depositor_name">
                                    <i class="fas fa-user"></i> Depositor Name
                                </label>
                                <input 
                                    type="text" 
                                    id="depositor_name" 
                                    name="depositor_name" 
                                    class="form-input" 
                                    placeholder="John Doe"
                                    value="FinFlo"
                                    required
                                >
                                <small style="color: #718096; display: block; margin-top: 0.25rem;">
                                    Name of person making the deposit
                                </small>
                            </div>

                            <div class="form-group">
                                <label class="form-label" for="account_name">
                                    <i class="fas fa-id-card"></i> Account Name
                                </label>
                                <input 
                                    type="text" 
                                    id="account_name" 
                                    name="account_name" 
                                    class="form-input" 
                                    placeholder="John Doe Savings"
                                    value="FinFlo Account"
                                    required
                                >
                                <small style="color: #718096; display: block; margin-top: 0.25rem;">
                                    Name of the bank account
                                </small>
                            </div>
                        </div>

                        <div class="form-actions">
                            <button type="button" class="btn btn-secondary" onclick="resetBankForm()">
                                <i class="fas fa-undo"></i> Reset
                            </button>
                            <button type="submit" class="btn btn-primary" id="validateBankBtn">
                                <i class="fas fa-check-circle"></i> Validate Account
                            </button>
                        </div>
                    </form>

                    <div id="bankAlertBox" class="alert"></div>

                    <div id="validationResult" class="validation-result">
                        <h3 style="margin-bottom: 1rem; color: #1a202c; display: flex; align-items: center; gap: 0.5rem;">
                            <i class="fas fa-check-circle" style="color: #10b981;"></i> Validation Successful
                        </h3>
                        <div id="validationDetails"></div>
                        <div style="margin-top: 1.5rem; padding-top: 1.5rem; border-top: 2px solid #e9ecef;">
                            <button type="button" class="btn btn-primary" id="completeTransferBtn" onclick="completeBankTransfer()">
                                <i class="fas fa-paper-plane"></i> Complete Transfer
                            </button>
                        </div>
                    </div>

                    <div id="bankResultCard" class="result-card">
                        <h3 style="margin-bottom: 1rem; color: #1a202c;">
                            <i class="fas fa-check-circle" style="color: #10b981;"></i> Transfer Result
                        </h3>
                        <div id="bankResultContent"></div>
                    </div>
                </div>
            </div>
        </div>

    <script>
        document.getElementById('disbursementForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const submitBtn = document.getElementById('submitBtn');
            const alertBox = document.getElementById('alertBox');
            const resultCard = document.getElementById('resultCard');
            const resultContent = document.getElementById('resultContent');
            
            // Get form data
            const formData = {
                msisdn: document.getElementById('msisdn').value.trim(),
                amount: parseFloat(document.getElementById('amount').value),
                currency: document.getElementById('currency').value,
                description: document.getElementById('description').value.trim()
            };

            // Validate phone number format
            if (!formData.msisdn.startsWith('+')) {
                showAlert('error', 'Phone number must start with + (country code)');
                return;
            }

            // Hide previous results
            alertBox.style.display = 'none';
            resultCard.style.display = 'none';

            // Disable submit button
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';

            try {
                const response = await fetch('<?= site_url('api/mobile-money/send') ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });

                const data = await response.json();

                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fas fa-paper-plane"></i> Send Disbursement';

                if (data.success) {
                    showAlert('success', data.message || 'Disbursement sent successfully!');
                    
                    // Show result details
                    resultContent.innerHTML = `
                        <div class="result-item">
                            <span class="result-label">Status:</span>
                            <span class="result-value" style="color: #10b981;">SUCCESS</span>
                        </div>
                        <div class="result-item">
                            <span class="result-label">Transaction ID:</span>
                            <span class="result-value" style="font-family: monospace;">${data.reference || 'N/A'}</span>
                        </div>
                        <div class="result-item">
                            <span class="result-label">Internal Reference:</span>
                            <span class="result-value" style="font-family: monospace;">${data.internal_reference || 'N/A'}</span>
                        </div>
                        <div class="result-item">
                            <span class="result-label">Amount:</span>
                            <span class="result-value">${formData.amount.toLocaleString()} ${formData.currency}</span>
                        </div>
                        <div class="result-item">
                            <span class="result-label">Phone Number:</span>
                            <span class="result-value">${formData.msisdn}</span>
                        </div>
                    `;
                    resultCard.style.display = 'block';

                    // Reset form after successful submission
                    setTimeout(() => {
                        resetForm();
                    }, 5000);
                } else {
                    showAlert('error', data.message || 'Failed to send disbursement');
                    
                    if (data.error_code) {
                        resultContent.innerHTML = `
                            <div class="result-item">
                                <span class="result-label">Status:</span>
                                <span class="result-value" style="color: #ef4444;">FAILED</span>
                            </div>
                            <div class="result-item">
                                <span class="result-label">Error Code:</span>
                                <span class="result-value">${data.error_code}</span>
                            </div>
                            <div class="result-item">
                                <span class="result-label">Error Message:</span>
                                <span class="result-value">${data.message}</span>
                            </div>
                        `;
                        resultCard.style.display = 'block';
                    }
                }
            } catch (error) {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fas fa-paper-plane"></i> Send Disbursement';
                
                showAlert('error', 'Network error: ' + error.message);
                console.error('Disbursement error:', error);
            }
        });

        function showAlert(type, message) {
            const alertBox = document.getElementById('alertBox');
            alertBox.className = `alert alert-${type}`;
            alertBox.textContent = message;
            alertBox.style.display = 'block';
            
            // Auto-hide after 5 seconds for success
            if (type === 'success') {
                setTimeout(() => {
                    alertBox.style.display = 'none';
                }, 5000);
            }
        }

        function resetForm() {
            document.getElementById('disbursementForm').reset();
            document.getElementById('alertBox').style.display = 'none';
            document.getElementById('resultCard').style.display = 'none';
        }

        // Tab switching
        function switchTab(tabName) {
            // Hide all tab contents
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });

            // Remove active class from all tabs
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });

            // Show selected tab content
            document.getElementById(tabName).classList.add('active');

            // Add active class to clicked tab
            event.currentTarget.classList.add('active');
        }

        // Store validation reference globally
        let validationReference = null;

        // Bank validation form handler
        document.getElementById('bankValidationForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const validateBtn = document.getElementById('validateBankBtn');
            const bankAlertBox = document.getElementById('bankAlertBox');
            const validationResult = document.getElementById('validationResult');
            
            // Get form data
            const formData = {
                msisdn: document.getElementById('bank_msisdn').value.trim(),
                amount: parseFloat(document.getElementById('bank_amount').value),
                product_code: document.getElementById('bank_product_code').value,
                contact_phone: document.getElementById('bank_contact_phone').value.trim(),
                depositor_name: document.getElementById('depositor_name').value.trim(),
                account_name: document.getElementById('account_name').value.trim()
            };

            // Validate contact phone format
            if (!formData.contact_phone.startsWith('+')) {
                showBankAlert('error', 'Contact phone must start with + (country code)');
                return;
            }

            // Hide previous results
            bankAlertBox.style.display = 'none';
            validationResult.classList.remove('show');

            // Disable submit button
            validateBtn.disabled = true;
            validateBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Validating...';

            try {
                const response = await fetch('<?= site_url('api/mobile-money/validate-bank') ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });

                const data = await response.json();

                validateBtn.disabled = false;
                validateBtn.innerHTML = '<i class="fas fa-check-circle"></i> Validate Account';

                if (data.success) {
                    // Store validation reference
                    validationReference = data.validation_reference;
                    
                    // Show validation result
                    document.getElementById('validationDetails').innerHTML = `
                        <div class="result-item">
                            <span class="result-label">Account Name:</span>
                            <span class="result-value">${data.customer_name || 'N/A'}</span>
                        </div>
                        <div class="result-item">
                            <span class="result-label">Account Number:</span>
                            <span class="result-value">${data.msisdn}</span>
                        </div>
                        <div class="result-item">
                            <span class="result-label">Amount:</span>
                            <span class="result-value">${data.amount.toLocaleString()} ${data.currency || 'UGX'}</span>
                        </div>
                        <div class="result-item">
                            <span class="result-label">Validation Reference:</span>
                            <span class="result-value" style="font-family: monospace;">${data.validation_reference}</span>
                        </div>
                    `;
                    
                    validationResult.classList.add('show');
                    
                    // Update step indicator
                    document.getElementById('step1').classList.remove('active');
                    document.getElementById('step1').classList.add('completed');
                    document.getElementById('step2').classList.add('active');
                    
                    showBankAlert('success', 'Account validated successfully! Click "Complete Transfer" to proceed.');
                } else {
                    showBankAlert('error', data.message || 'Validation failed');
                }
            } catch (error) {
                validateBtn.disabled = false;
                validateBtn.innerHTML = '<i class="fas fa-check-circle"></i> Validate Account';
                
                showBankAlert('error', 'Network error: ' + error.message);
                console.error('Bank validation error:', error);
            }
        });

        // Complete bank transfer
        async function completeBankTransfer() {
            if (!validationReference) {
                showBankAlert('error', 'Please validate the account first');
                return;
            }

            const completeBtn = document.getElementById('completeTransferBtn');
            const bankAlertBox = document.getElementById('bankAlertBox');
            const bankResultCard = document.getElementById('bankResultCard');
            const bankResultContent = document.getElementById('bankResultContent');

            // Hide previous results
            bankAlertBox.style.display = 'none';
            bankResultCard.style.display = 'none';

            // Disable button
            completeBtn.disabled = true;
            completeBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';

            try {
                const response = await fetch('<?= site_url('api/mobile-money/purchase-product') ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        validation_reference: validationReference
                    })
                });

                const data = await response.json();

                completeBtn.disabled = false;
                completeBtn.innerHTML = '<i class="fas fa-paper-plane"></i> Complete Transfer';

                if (data.success) {
                    showBankAlert('success', data.message || 'Bank transfer completed successfully!');
                    
                    // Show result details
                    bankResultContent.innerHTML = `
                        <div class="result-item">
                            <span class="result-label">Status:</span>
                            <span class="result-value" style="color: #10b981;">SUCCESS</span>
                        </div>
                        <div class="result-item">
                            <span class="result-label">Internal Reference:</span>
                            <span class="result-value" style="font-family: monospace;">${data.internal_reference || 'N/A'}</span>
                        </div>
                        <div class="result-item">
                            <span class="result-label">Validation Reference:</span>
                            <span class="result-value" style="font-family: monospace;">${validationReference}</span>
                        </div>
                    `;
                    bankResultCard.style.display = 'block';

                    // Reset form after successful submission
                    setTimeout(() => {
                        resetBankForm();
                    }, 5000);
                } else {
                    showBankAlert('error', data.message || 'Failed to complete transfer');
                    
                    if (data.error_code) {
                        bankResultContent.innerHTML = `
                            <div class="result-item">
                                <span class="result-label">Status:</span>
                                <span class="result-value" style="color: #ef4444;">FAILED</span>
                            </div>
                            <div class="result-item">
                                <span class="result-label">Error Code:</span>
                                <span class="result-value">${data.error_code}</span>
                            </div>
                            <div class="result-item">
                                <span class="result-label">Error Message:</span>
                                <span class="result-value">${data.message}</span>
                            </div>
                        `;
                        bankResultCard.style.display = 'block';
                    }
                }
            } catch (error) {
                completeBtn.disabled = false;
                completeBtn.innerHTML = '<i class="fas fa-paper-plane"></i> Complete Transfer';
                
                showBankAlert('error', 'Network error: ' + error.message);
                console.error('Bank transfer error:', error);
            }
        }

        function showBankAlert(type, message) {
            const alertBox = document.getElementById('bankAlertBox');
            alertBox.className = `alert alert-${type}`;
            alertBox.textContent = message;
            alertBox.style.display = 'block';
            
            // Auto-hide after 5 seconds for success
            if (type === 'success') {
                setTimeout(() => {
                    alertBox.style.display = 'none';
                }, 5000);
            }
        }

        function resetBankForm() {
            document.getElementById('bankValidationForm').reset();
            document.getElementById('bankAlertBox').style.display = 'none';
            document.getElementById('validationResult').classList.remove('show');
            document.getElementById('bankResultCard').style.display = 'none';
            document.getElementById('otherBankFields').style.display = 'none';
            validationReference = null;
            
            // Reset step indicator
            document.getElementById('step1').classList.add('active');
            document.getElementById('step1').classList.remove('completed');
            document.getElementById('step2').classList.remove('active');
        }

        // Load banks from API on page load
        async function loadBanks() {
            const bankSelect = document.getElementById('bank_product_code');
            const loadingOption = document.getElementById('loadingBanks');
            
            try {
                const response = await fetch('<?= site_url('api/mobile-money/services/categorized') ?>');
                const data = await response.json();
                
                if (data.success && data.categories) {
                    // Find BANK_TRANSFERS category
                    const bankCategory = data.categories.find(cat => cat.category === 'BANK_TRANSFERS');
                    
                    // Remove loading option
                    if (loadingOption) {
                        loadingOption.remove();
                    }
                    
                    // Clear existing options (except first one)
                    bankSelect.innerHTML = '<option value="">-- Select Bank First --</option>';
                    
                    if (bankCategory && bankCategory.services) {
                        // Sort banks alphabetically by name
                        const sortedBanks = bankCategory.services.sort((a, b) => {
                            return a.name.localeCompare(b.name);
                        });
                        
                        // Add bank options
                        sortedBanks.forEach(bank => {
                            const option = document.createElement('option');
                            option.value = bank.code;
                            option.textContent = bank.name;
                            bankSelect.appendChild(option);
                        });
                        
                        if (sortedBanks.length === 0) {
                            const option = document.createElement('option');
                            option.value = '';
                            option.textContent = 'No banks available';
                            option.disabled = true;
                            bankSelect.appendChild(option);
                        }
                    } else {
                        const option = document.createElement('option');
                        option.value = '';
                        option.textContent = 'No banks found';
                        option.disabled = true;
                        bankSelect.appendChild(option);
                    }
                } else {
                    if (loadingOption) {
                        loadingOption.textContent = 'Failed to load banks';
                    }
                }
            } catch (error) {
                console.error('Error loading banks:', error);
                if (loadingOption) {
                    loadingOption.textContent = 'Error loading banks';
                }
            }
        }

        // Show other fields when bank is selected
        function onBankSelected() {
            const bankSelect = document.getElementById('bank_product_code');
            const otherFields = document.getElementById('otherBankFields');
            
            if (bankSelect.value) {
                otherFields.style.display = 'block';
            } else {
                otherFields.style.display = 'none';
            }
        }

        // Load banks when page loads
        document.addEventListener('DOMContentLoaded', function() {
            loadBanks();
        });
    </script>
<?= view('admin/partials/footer') ?>
</body>
</html>

