{% extends "base.html" %}

{% block title %}Payment System Settings - Admin{% endblock %}

{% block content %}
<div class="container-fluid" style="padding: 20px; background:var(--bg-accent); min-height: 100vh;">
    <div style="max-width: 1400px; margin: 0 auto;">
        <h2 style="color: var(--color-link); margin-bottom: 30px;">
            <i class="fas fa-cog me-2"></i><span data-i18n="payments_page.title">Payment System Settings</span>
        </h2>

        <!-- Currency Selection Warning -->
        <div style="background: var(--bg-page); border-left: 4px solid #f39c12; padding: 15px; margin-bottom: 25px; border-radius: 4px;">
            <div style="color: #f39c12; font-weight: bold; margin-bottom: 8px;">
                <i class="fas fa-info-circle me-2"></i>Important Note About Currency Selection
            </div>
            <div style="color: var(--color-text); font-size: 14px;">
                We do not suggest using USD if you are not in the USA. This project does not support the actions of the USA in the international context and we don't support a politic of war and threats to allies.
            </div>
        </div>

        <!-- Global Currency Settings -->
        <div style="background: var(--bg-panel); border: 2px solid #17a2b8; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
            <h3 style="margin: 0 0 20px 0; color: var(--color-link);">
                <i class="fas fa-dollar-sign me-2"></i><span data-i18n="payments_page.currency_settings">Global Currency Settings</span>
            </h3>

            <form id="currencySettingsForm">
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px; margin-bottom: 20px;">
                    <div>
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);" data-i18n="payments_page.currency_code">Currency Code</label>
                        <select style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; font-size: 14px; background: var(--bg-page); color: var(--color-text);" id="currencyCode">
                            <option value="USD">USD - US Dollar</option>
                            <option value="EUR">EUR - Euro</option>
                            <option value="GBP">GBP - British Pound</option>
                            <option value="JPY">JPY - Japanese Yen</option>
                            <option value="CAD">CAD - Canadian Dollar</option>
                            <option value="AUD">AUD - Australian Dollar</option>
                            <option value="CHF">CHF - Swiss Franc</option>
                            <option value="CNY">CNY - Chinese Yuan</option>
                            <option value="INR">INR - Indian Rupee</option>
                            <option value="BRL">BRL - Brazilian Real</option>
                            <option value="MXN">MXN - Mexican Peso</option>
                            <option value="SGD">SGD - Singapore Dollar</option>
                            <option value="HKD">HKD - Hong Kong Dollar</option>
                            <option value="NOK">NOK - Norwegian Krone</option>
                            <option value="SEK">SEK - Swedish Krona</option>
                            <option value="DKK">DKK - Danish Krone</option>
                            <option value="NZD">NZD - New Zealand Dollar</option>
                            <option value="ZAR">ZAR - South African Rand</option>
                            <option value="RUB">RUB - Russian Ruble</option>
                            <option value="TRY">TRY - Turkish Lira</option>
                            <option value="KRW">KRW - South Korean Won</option>
                            <option value="IDR">IDR - Indonesian Rupiah</option>
                            <option value="MYR">MYR - Malaysian Ringgit</option>
                            <option value="THB">THB - Thai Baht</option>
                            <option value="PHP">PHP - Philippine Peso</option>
                            <option value="VND">VND - Vietnamese Dong</option>
                            <option value="PKR">PKR - Pakistani Rupee</option>
                            <option value="BDT">BDT - Bangladeshi Taka</option>
                            <option value="EGP">EGP - Egyptian Pound</option>
                            <option value="NGN">NGN - Nigerian Naira</option>
                            <option value="KES">KES - Kenyan Shilling</option>
                            <option value="GHS">GHS - Ghanaian Cedi</option>
                            <option value="MAD">MAD - Moroccan Dirham</option>
                            <option value="TND">TND - Tunisian Dinar</option>
                            <option value="DZD">DZD - Algerian Dinar</option>
                            <option value="SAR">SAR - Saudi Riyal</option>
                            <option value="AED">AED - UAE Dirham</option>
                            <option value="QAR">QAR - Qatari Riyal</option>
                            <option value="KWD">KWD - Kuwaiti Dinar</option>
                            <option value="BHD">BHD - Bahraini Dinar</option>
                            <option value="OMR">OMR - Omani Rial</option>
                            <option value="ILS">ILS - Israeli Shekel</option>
                            <option value="PLN">PLN - Polish Zloty</option>
                            <option value="CZK">CZK - Czech Koruna</option>
                            <option value="HUF">HUF - Hungarian Forint</option>
                            <option value="RON">RON - Romanian Leu</option>
                            <option value="BGN">BGN - Bulgarian Lev</option>
                            <option value="HRK">HRK - Croatian Kuna</option>
                            <option value="RSD">RSD - Serbian Dinar</option>
                            <option value="UAH">UAH - Ukrainian Hryvnia</option>
                            <option value="ARS">ARS - Argentine Peso</option>
                            <option value="CLP">CLP - Chilean Peso</option>
                            <option value="COP">COP - Colombian Peso</option>
                            <option value="PEN">PEN - Peruvian Sol</option>
                            <option value="UYU">UYU - Uruguayan Peso</option>
                            <option value="TWD">TWD - Taiwan Dollar</option>
                            <option value="LKR">LKR - Sri Lankan Rupee</option>
                            <option value="NPR">NPR - Nepalese Rupee</option>
                            <option value="MMK">MMK - Myanmar Kyat</option>
                            <option value="KZT">KZT - Kazakhstani Tenge</option>
                        </select>
                    </div>
                    <div>
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);" data-i18n="payments_page.currency_symbol">Currency Symbol</label>
                        <input type="text" style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; font-size: 14px; background: var(--bg-page); color: var(--color-text);" id="currencySymbol" value="{{ currency_symbol }}">
                    </div>
                    <div>
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);" data-i18n="payments_page.decimal_places">Decimal Places</label>
                        <select style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; font-size: 14px; background: var(--bg-page); color: var(--color-text);" id="currencyDecimals">
                            <option value="0">0</option>
                            <option value="1">1</option>
                            <option value="2" selected>2</option>
                            <option value="3">3</option>
                        </select>
                    </div>
                </div>
                <button type="submit" class="btn" style="background: var(--color-link); color: white;">
                    <i class="fas fa-save me-2"></i><span data-i18n="payments_page.save_currency">Save Currency Settings</span>
                </button>
            </form>
        </div>

        <!-- Encryption Key Configuration -->
        <div style="background: var(--bg-panel); border: 2px solid #e74c3c; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
            <h3 style="margin: 0 0 20px 0; color: #e74c3c;">
                <i class="fas fa-key me-2"></i><span data-i18n="payments_page.encryption_title">Encryption Key Configuration</span>
            </h3>
            
            <div style="margin-bottom: 20px; padding: 15px; background: var(--bg-page); border-radius: 8px; border-left: 4px solid #e74c3c;">
                <div style="color: #e74c3c; font-weight: bold; margin-bottom: 5px;">
                    <i class="fas fa-exclamation-triangle me-2"></i>Critical Security Setting
                </div>
                <div style="color: var(--color-text); font-size: 14px;">
                    The encryption key is used to encrypt HD wallet master keys. Once set, DO NOT change it or you will lose access to all crypto wallets.
                    If not set, a temporary key is generated on each restart (not recommended for production).
                </div>
            </div>
            
            <div style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 10px; color: var(--color-text); font-weight: 500;">
                    Encryption Key Status
                </label>
                <div id="encryptionKeyStatus" style="padding: 15px; background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; color: var(--color-text);">
                    <i class="fas fa-spinner fa-spin"></i> Loading...
                </div>
            </div>
            
            <div style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 10px; color: var(--color-text); font-weight: 500;">
                    Set New Encryption Key (44 characters, URL-safe base64)
                </label>
                <input type="text" id="encryptionKey" placeholder="Click Generate to create a secure key" style="width: 100%; padding: 10px; border:1px solid var(--color-border); border-radius: 5px; background: var(--bg-page); color: var(--color-text); font-family: monospace;">
                <div style="margin-top: 10px; color: var(--color-subtle); font-size: 14px;">
                    <i class="fas fa-info-circle me-2"></i>Generate a key, copy it to a safe place, then save it. You cannot retrieve it from the interface later.
                </div>
            </div>

            <div id="encryptionKeyBackup" style="display:none; margin-bottom: 20px; padding: 15px; background: var(--alert-info-bg); border: 2px solid #f39c12; border-radius: 8px;">
                <div style="color: #f39c12; font-weight: bold; margin-bottom: 8px;">
                    <i class="fas fa-exclamation-triangle me-2"></i>Save this key now — it will not be shown again after you leave this page
                </div>
                <div style="font-family: monospace; font-size: 14px; color: var(--color-text); word-break: break-all;" id="encryptionKeyBackupValue"></div>
                <button type="button" class="btn btn-sm mt-2" onclick="copyEncryptionKey()" style="background: #f39c12; color: #000;">
                    <i class="fas fa-copy me-1"></i>Copy to Clipboard
                </button>
            </div>

            <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                <button type="button" class="btn" onclick="generateEncryptionKey()" style="background: var(--color-primary); color: white;">
                    <i class="fas fa-random me-2"></i>Generate New Key
                </button>
                <button type="button" class="btn" onclick="saveEncryptionKey()" style="background: #e74c3c; color: white;">
                    <i class="fas fa-save me-2"></i>Save Encryption Key
                </button>
                <button type="button" class="btn" onclick="resetCryptoSeeds()" style="background: #c0392b; color: white;">
                    <i class="fas fa-trash me-2"></i>Reset Crypto Seeds
                </button>
            </div>
        </div>

        <!-- System Status -->
        <div style="background: var(--bg-panel); border: 2px solid var(--color-link); border-radius: 8px; padding: 20px; margin-bottom: 20px;">
            <h3 style="margin: 0 0 20px 0; color: var(--color-link);">
                <i class="fas fa-heartbeat me-2"></i>System Status
            </h3>
            
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;">
                <div style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; padding: 15px;">
                    <div style="color: var(--color-subtle); font-size: 14px; margin-bottom: 5px;">Master Keys Status</div>
                    <div id="masterKeysStatus" style="font-size: 24px; font-weight: bold; color: var(--color-link);">
                        <i class="fas fa-spinner fa-spin"></i> Loading...
                    </div>
                </div>
                
                <div style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; padding: 15px;">
                    <div style="color: var(--color-subtle); font-size: 14px; margin-bottom: 5px;">Total Crypto Balance</div>
                    <div id="totalBalance" style="font-size: 24px; font-weight: bold; color: var(--color-link);">
                        <i class="fas fa-spinner fa-spin"></i> Loading...
                    </div>
                </div>
                
                <div style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; padding: 15px;">
                    <div style="color: var(--color-subtle); font-size: 14px; margin-bottom: 5px;">Pending Payments</div>
                    <div id="pendingPayments" style="font-size: 24px; font-weight: bold; color: #f39c12;">
                        <i class="fas fa-spinner fa-spin"></i> Loading...
                    </div>
                </div>
                
                <div style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; padding: 15px;">
                    <div style="color: var(--color-subtle); font-size: 14px; margin-bottom: 5px;">Failed Payments</div>
                    <div id="failedPayments" style="font-size: 24px; font-weight: bold; color: #e74c3c;">
                        <i class="fas fa-spinner fa-spin"></i> Loading...
                    </div>
                </div>
            </div>
            
            <div style="margin-top: 15px; padding: 15px; background: var(--bg-page); border-radius: 8px; border-left: 4px solid #4a9eff;">
                <div style="color: var(--color-link); font-weight: bold; margin-bottom: 5px;">
                    <i class="fas fa-info-circle me-2"></i>About Master Keys
                </div>
                <div style="color: var(--color-text); font-size: 14px;">
                    Master keys are automatically generated on first startup and encrypted with your ENCRYPTION_KEY. 
                    They are used to derive unique payment addresses for each user. The actual keys are never displayed for security.
                </div>
            </div>
        </div>

        <!-- Payment Gateways Configuration -->
        <div style="background: var(--bg-panel); border: 2px solid #f39c12; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
            <h3 style="margin: 0 0 20px 0; color: #f39c12;">
                <i class="fas fa-credit-card me-2"></i>Payment Gateways Configuration
            </h3>

            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 20px;">
                <!-- PayPal -->
                <div style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; overflow: hidden;">
                    <div style="background: #0070ba; color: white; padding: 15px; display: flex; justify-content: space-between; align-items: center;">
                        <h6 style="margin: 0;"><i class="fab fa-paypal me-2"></i>PayPal</h6>
                        <label style="margin: 0; cursor: pointer;">
                            <input type="checkbox" id="paypalEnabled" style="margin-right: 5px;">Enabled
                        </label>
                    </div>
                    <div style="padding: 15px;">
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);" data-i18n="payments_page.lbl_client_id">Client ID</label>
                            <input type="text" style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; background: var(--bg-panel); color: var(--color-text);" id="paypalClientId" placeholder="PayPal Client ID">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);" data-i18n="payments_page.lbl_client_secret">Client Secret</label>
                            <input type="password" style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; background: var(--bg-panel); color: var(--color-text);" id="paypalClientSecret" placeholder="PayPal Client Secret">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);" data-i18n="payments_page.lbl_webhook_secret">Webhook Secret</label>
                            <input type="password" style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; background: var(--bg-panel); color: var(--color-text);" id="paypalWebhookSecret" placeholder="Webhook Secret">
                        </div>
                        <label style="cursor: pointer;">
                            <input type="checkbox" id="paypalSandbox" checked style="margin-right: 5px;">Sandbox Mode
                        </label>
                    </div>
                </div>

                <!-- Stripe -->
                <div style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; overflow: hidden;">
                    <div style="background: #635bff; color: white; padding: 15px; display: flex; justify-content: space-between; align-items: center;">
                        <h6 style="margin: 0;"><i class="fab fa-stripe me-2"></i>Stripe</h6>
                        <label style="margin: 0; cursor: pointer;">
                            <input type="checkbox" id="stripeEnabled" style="margin-right: 5px;">Enabled
                        </label>
                    </div>
                    <div style="padding: 15px;">
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);">Publishable Key</label>
                            <input type="text" style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; background: var(--bg-panel); color: var(--color-text);" id="stripePublishableKey" placeholder="pk_...">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);" data-i18n="payments_page.lbl_secret_key">Secret Key</label>
                            <input type="password" style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; background: var(--bg-panel); color: var(--color-text);" id="stripeSecretKey" placeholder="sk_...">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);" data-i18n="payments_page.lbl_webhook_secret">Webhook Secret</label>
                            <input type="password" style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; background: var(--bg-panel); color: var(--color-text);" id="stripeWebhookSecret" placeholder="whsec_...">
                        </div>
                        <label style="cursor: pointer;">
                            <input type="checkbox" id="stripeSandbox" checked style="margin-right: 5px;">Test Mode
                        </label>
                    </div>
                </div>

                <!-- Bitcoin -->
                <div style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; overflow: hidden;">
                    <div style="background: #f7931a; color: white; padding: 15px; display: flex; justify-content: space-between; align-items: center;">
                        <h6 style="margin: 0;"><i class="fab fa-bitcoin me-2"></i>Bitcoin</h6>
                        <label style="margin: 0; cursor: pointer;">
                            <input type="checkbox" id="bitcoinEnabled" style="margin-right: 5px;">Enabled
                        </label>
                    </div>
                    <div style="padding: 15px;">
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);">Bitcoin Address</label>
                            <input type="text" style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; background: var(--bg-panel); color: var(--color-text);" id="bitcoinAddress" placeholder="bc1q...">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);" data-i18n="payments_page.lbl_min_confirmations">Minimum Confirmations</label>
                            <input type="number" style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; background: var(--bg-panel); color: var(--color-text);" id="bitcoinConfirmations" value="3" min="1" max="10">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);">Expiration Time (minutes)</label>
                            <input type="number" style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; background: var(--bg-panel); color: var(--color-text);" id="bitcoinExpiration" value="120" min="15" max="1440">
                        </div>
                    </div>
                </div>

                <!-- Ethereum -->
                <div style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; overflow: hidden;">
                    <div style="background: #627eea; color: white; padding: 15px; display: flex; justify-content: space-between; align-items: center;">
                        <h6 style="margin: 0;"><i class="fab fa-ethereum me-2"></i>Ethereum (ETH)</h6>
                        <label style="margin: 0; cursor: pointer;">
                            <input type="checkbox" id="ethEnabled" style="margin-right: 5px;">Enabled
                        </label>
                    </div>
                    <div style="padding: 15px;">
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);">ETH Wallet Address</label>
                            <input type="text" style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; background: var(--bg-panel); color: var(--color-text);" id="ethAddress" placeholder="0x...">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);" data-i18n="payments_page.lbl_min_confirmations">Minimum Confirmations</label>
                            <input type="number" style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; background: var(--bg-panel); color: var(--color-text);" id="ethConfirmations" value="12" min="1" max="50">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);">Chain ID</label>
                            <select style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; background: var(--bg-panel); color: var(--color-text);" id="ethChainId">
                                <option value="1">Ethereum Mainnet</option>
                                <option value="5">Goerli Testnet</option>
                                <option value="11155111">Sepolia Testnet</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- USDT -->
                <div style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; overflow: hidden;">
                    <div style="background: #26a17b; color: white; padding: 15px; display: flex; justify-content: space-between; align-items: center;">
                        <h6 style="margin: 0;"><i class="fas fa-dollar-sign me-2"></i>Tether (USDT)</h6>
                        <label style="margin: 0; cursor: pointer;">
                            <input type="checkbox" id="usdtEnabled" style="margin-right: 5px;">Enabled
                        </label>
                    </div>
                    <div style="padding: 15px;">
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);">USDT Wallet Address</label>
                            <input type="text" style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; background: var(--bg-panel); color: var(--color-text);" id="usdtAddress" placeholder="0x...">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);" data-i18n="payments_page.lbl_network">Network</label>
                            <select style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; background: var(--bg-panel); color: var(--color-text);" id="usdtNetwork">
                                <option value="erc20">ERC20 (Ethereum)</option>
                                <option value="trc20">TRC20 (Tron)</option>
                                <option value="bep20">BEP20 (BSC)</option>
                                <option value="solana">Solana</option>
                            </select>
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);" data-i18n="payments_page.lbl_min_confirmations">Minimum Confirmations</label>
                            <input type="number" style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; background: var(--bg-panel); color: var(--color-text);" id="usdtConfirmations" value="3" min="1" max="50">
                        </div>
                    </div>
                </div>

                <!-- USDC -->
                <div style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; overflow: hidden;">
                    <div style="background: #2775ca; color: white; padding: 15px; display: flex; justify-content: space-between; align-items: center;">
                        <h6 style="margin: 0;"><i class="fas fa-coins me-2"></i>USD Coin (USDC)</h6>
                        <label style="margin: 0; cursor: pointer;">
                            <input type="checkbox" id="usdcEnabled" style="margin-right: 5px;">Enabled
                        </label>
                    </div>
                    <div style="padding: 15px;">
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);">USDC Wallet Address</label>
                            <input type="text" style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; background: var(--bg-panel); color: var(--color-text);" id="usdcAddress" placeholder="0x...">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);" data-i18n="payments_page.lbl_network">Network</label>
                            <select style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; background: var(--bg-panel); color: var(--color-text);" id="usdcNetwork">
                                <option value="erc20">ERC20 (Ethereum)</option>
                                <option value="solana">Solana</option>
                                <option value="bep20">BEP20 (BSC)</option>
                                <option value="algorand">Algorand</option>
                            </select>
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: var(--color-text);" data-i18n="payments_page.lbl_min_confirmations">Minimum Confirmations</label>
                            <input type="number" style="width: 100%; padding: 8px; border:1px solid var(--color-border); border-radius: 3px; background: var(--bg-panel); color: var(--color-text);" id="usdcConfirmations" value="3" min="1" max="50">
                        </div>
                    </div>
                </div>
            </div>

            <button type="button" class="btn" onclick="savePaymentGateways()" style="background: #f39c12; color: white; margin-top: 20px;">
                <i class="fas fa-save me-2"></i>Save Payment Gateway Configuration
            </button>
        </div>

        <!-- Price Sources Configuration -->
        <div style="background: var(--bg-panel); border: 2px solid #f39c12; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
            <h3 style="margin: 0 0 20px 0; color: #f39c12;">
                <i class="fas fa-chart-line me-2"></i><span data-i18n="payments_page.crypto_prices">Crypto Price Sources</span>
            </h3>
            
            <div style="margin-bottom: 15px; color: var(--color-text);">
                Select which exchanges to use for cryptocurrency price aggregation:
            </div>
            
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 20px;">
                <label style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; padding: 15px; cursor: pointer; display: flex; align-items: center;">
                    <input type="checkbox" id="priceCoinbase" checked style="margin-right: 10px; width: 20px; height: 20px;">
                    <span style="color: var(--color-text); font-weight: 500;">Coinbase</span>
                </label>
                
                <label style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; padding: 15px; cursor: pointer; display: flex; align-items: center;">
                    <input type="checkbox" id="priceBinance" checked style="margin-right: 10px; width: 20px; height: 20px;">
                    <span style="color: var(--color-text); font-weight: 500;">Binance</span>
                </label>
                
                <label style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; padding: 15px; cursor: pointer; display: flex; align-items: center;">
                    <input type="checkbox" id="priceKraken" checked style="margin-right: 10px; width: 20px; height: 20px;">
                    <span style="color: var(--color-text); font-weight: 500;">Kraken</span>
                </label>
            </div>
            
            <!-- Live Crypto Prices Display -->
            <div style="margin-bottom: 20px; padding: 20px; background: var(--bg-page); border-radius: 8px; border-left: 4px solid #4a9eff;">
                <div style="color: var(--color-link); font-weight: bold; margin-bottom: 15px; display: flex; align-items: center;">
                    <i class="fas fa-coins me-2"></i>Live Cryptocurrency Prices
                    <button onclick="refreshCryptoPrices()" style="margin-left: auto; background: transparent; border: 1px solid #4a9eff; color: var(--color-link); padding: 5px 15px; border-radius: 5px; cursor: pointer; font-size: 12px;">
                        <i class="fas fa-sync-alt me-1"></i>Refresh
                    </button>
                </div>
                
                <!-- Bitcoin -->
                <div style="margin-bottom: 20px; padding: 15px; background: var(--bg-panel); border-radius: 8px; border-left: 3px solid #f7931a;">
                    <div style="color: #f7931a; font-weight: bold; margin-bottom: 10px;">
                        <i class="fab fa-bitcoin me-2"></i>Bitcoin (BTC)
                    </div>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; margin-bottom: 10px;">
                        <div style="background:var(--bg-accent); padding: 10px; border-radius: 5px;">
                            <div style="color: var(--color-subtle); font-size: 11px;">Coinbase</div>
                            <div id="priceBtcCoinbase" style="color: var(--color-link); font-size: 16px; font-weight: bold;">
                                <i class="fas fa-spinner fa-spin"></i>
                            </div>
                        </div>
                        <div style="background:var(--bg-accent); padding: 10px; border-radius: 5px;">
                            <div style="color: var(--color-subtle); font-size: 11px;">Binance</div>
                            <div id="priceBtcBinance" style="color: var(--color-link); font-size: 16px; font-weight: bold;">
                                <i class="fas fa-spinner fa-spin"></i>
                            </div>
                        </div>
                        <div style="background:var(--bg-accent); padding: 10px; border-radius: 5px;">
                            <div style="color: var(--color-subtle); font-size: 11px;">Kraken</div>
                            <div id="priceBtcKraken" style="color: var(--color-link); font-size: 16px; font-weight: bold;">
                                <i class="fas fa-spinner fa-spin"></i>
                            </div>
                        </div>
                    </div>
                    <div style="background:var(--bg-accent); padding: 10px; border-radius: 5px; border: 2px solid #f7931a;">
                        <div style="color: #f7931a; font-size: 12px; font-weight: bold;">Average (Applied)</div>
                        <div id="priceBtcAverage" style="color: #f7931a; font-size: 20px; font-weight: bold;">
                            <i class="fas fa-spinner fa-spin"></i>
                        </div>
                    </div>
                </div>
                
                <!-- Ethereum -->
                <div style="margin-bottom: 20px; padding: 15px; background: var(--bg-panel); border-radius: 8px; border-left: 3px solid #627eea;">
                    <div style="color: #627eea; font-weight: bold; margin-bottom: 10px;">
                        <i class="fab fa-ethereum me-2"></i>Ethereum (ETH)
                    </div>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; margin-bottom: 10px;">
                        <div style="background:var(--bg-accent); padding: 10px; border-radius: 5px;">
                            <div style="color: var(--color-subtle); font-size: 11px;">Coinbase</div>
                            <div id="priceEthCoinbase" style="color: var(--color-link); font-size: 16px; font-weight: bold;">
                                <i class="fas fa-spinner fa-spin"></i>
                            </div>
                        </div>
                        <div style="background:var(--bg-accent); padding: 10px; border-radius: 5px;">
                            <div style="color: var(--color-subtle); font-size: 11px;">Binance</div>
                            <div id="priceEthBinance" style="color: var(--color-link); font-size: 16px; font-weight: bold;">
                                <i class="fas fa-spinner fa-spin"></i>
                            </div>
                        </div>
                        <div style="background:var(--bg-accent); padding: 10px; border-radius: 5px;">
                            <div style="color: var(--color-subtle); font-size: 11px;">Kraken</div>
                            <div id="priceEthKraken" style="color: var(--color-link); font-size: 16px; font-weight: bold;">
                                <i class="fas fa-spinner fa-spin"></i>
                            </div>
                        </div>
                    </div>
                    <div style="background:var(--bg-accent); padding: 10px; border-radius: 5px; border: 2px solid #627eea;">
                        <div style="color: #627eea; font-size: 12px; font-weight: bold;">Average (Applied)</div>
                        <div id="priceEthAverage" style="color: #627eea; font-size: 20px; font-weight: bold;">
                            <i class="fas fa-spinner fa-spin"></i>
                        </div>
                    </div>
                </div>
                
                <!-- USDT -->
                <div style="margin-bottom: 20px; padding: 15px; background: var(--bg-panel); border-radius: 8px; border-left: 3px solid #26a17b;">
                    <div style="color: #26a17b; font-weight: bold; margin-bottom: 10px;">
                        <i class="fas fa-dollar-sign me-2"></i>Tether (USDT)
                    </div>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; margin-bottom: 10px;">
                        <div style="background:var(--bg-accent); padding: 10px; border-radius: 5px;">
                            <div style="color: var(--color-subtle); font-size: 11px;">Coinbase</div>
                            <div id="priceUsdtCoinbase" style="color: var(--color-link); font-size: 16px; font-weight: bold;">
                                <i class="fas fa-spinner fa-spin"></i>
                            </div>
                        </div>
                        <div style="background:var(--bg-accent); padding: 10px; border-radius: 5px;">
                            <div style="color: var(--color-subtle); font-size: 11px;">Binance</div>
                            <div id="priceUsdtBinance" style="color: var(--color-link); font-size: 16px; font-weight: bold;">
                                <i class="fas fa-spinner fa-spin"></i>
                            </div>
                        </div>
                        <div style="background:var(--bg-accent); padding: 10px; border-radius: 5px;">
                            <div style="color: var(--color-subtle); font-size: 11px;">Kraken</div>
                            <div id="priceUsdtKraken" style="color: var(--color-link); font-size: 16px; font-weight: bold;">
                                <i class="fas fa-spinner fa-spin"></i>
                            </div>
                        </div>
                    </div>
                    <div style="background:var(--bg-accent); padding: 10px; border-radius: 5px; border: 2px solid #26a17b;">
                        <div style="color: #26a17b; font-size: 12px; font-weight: bold;">Average (Applied)</div>
                        <div id="priceUsdtAverage" style="color: #26a17b; font-size: 20px; font-weight: bold;">
                            <i class="fas fa-spinner fa-spin"></i>
                        </div>
                    </div>
                </div>
                
                <!-- USDC -->
                <div style="margin-bottom: 15px; padding: 15px; background: var(--bg-panel); border-radius: 8px; border-left: 3px solid #2775ca;">
                    <div style="color: #2775ca; font-weight: bold; margin-bottom: 10px;">
                        <i class="fas fa-coins me-2"></i>USD Coin (USDC)
                    </div>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; margin-bottom: 10px;">
                        <div style="background:var(--bg-accent); padding: 10px; border-radius: 5px;">
                            <div style="color: var(--color-subtle); font-size: 11px;">Coinbase</div>
                            <div id="priceUsdcCoinbase" style="color: var(--color-link); font-size: 16px; font-weight: bold;">
                                <i class="fas fa-spinner fa-spin"></i>
                            </div>
                        </div>
                        <div style="background:var(--bg-accent); padding: 10px; border-radius: 5px;">
                            <div style="color: var(--color-subtle); font-size: 11px;">Binance</div>
                            <div id="priceUsdcBinance" style="color: var(--color-link); font-size: 16px; font-weight: bold;">
                                <i class="fas fa-spinner fa-spin"></i>
                            </div>
                        </div>
                        <div style="background:var(--bg-accent); padding: 10px; border-radius: 5px;">
                            <div style="color: var(--color-subtle); font-size: 11px;">Kraken</div>
                            <div id="priceUsdcKraken" style="color: var(--color-link); font-size: 16px; font-weight: bold;">
                                <i class="fas fa-spinner fa-spin"></i>
                            </div>
                        </div>
                    </div>
                    <div style="background:var(--bg-accent); padding: 10px; border-radius: 5px; border: 2px solid #2775ca;">
                        <div style="color: #2775ca; font-size: 12px; font-weight: bold;">Average (Applied)</div>
                        <div id="priceUsdcAverage" style="color: #2775ca; font-size: 20px; font-weight: bold;">
                            <i class="fas fa-spinner fa-spin"></i>
                        </div>
                    </div>
                </div>
                
                <div style="color: var(--color-subtle); font-size: 12px; text-align: center;">
                    Last updated: <span id="priceLastUpdated">-</span>
                </div>
            </div>
            
            <button type="button" class="btn" onclick="savePriceSources()" style="background: #f39c12; color: white;">
                <i class="fas fa-save me-2"></i>Save Price Sources
            </button>
        </div>

        <!-- Blockchain Monitoring -->
        <div style="background: var(--bg-panel); border: 2px solid #9b59b6; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
            <h3 style="margin: 0 0 20px 0; color: #9b59b6;">
                <i class="fas fa-cube me-2"></i>Blockchain Monitoring
            </h3>
            
            <div style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 10px; color: var(--color-text); font-weight: 500;">Monitoring Mode</label>
                <select id="blockchainMode" style="width: 100%; max-width: 400px; padding: 10px; border:1px solid var(--color-border); border-radius: 5px; background: var(--bg-page); color: var(--color-text);">
                    <option value="api">API Polling (Recommended)</option>
                    <option value="webhook">Webhook (Requires public URL)</option>
                </select>
                <div style="margin-top: 10px; color: var(--color-subtle); font-size: 14px;">
                    API Polling: Checks blockchain APIs every minute for new transactions<br>
                    Webhook: Receives instant notifications (requires webhook setup)
                </div>
            </div>
            
            <div style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 10px; color: var(--color-text); font-weight: 500;">Polling Interval (seconds)</label>
                <input type="number" id="pollingInterval" value="60" min="30" max="300" style="width: 100%; max-width: 400px; padding: 10px; border:1px solid var(--color-border); border-radius: 5px; background: var(--bg-page); color: var(--color-text);">
            </div>
            
            <button type="button" class="btn" onclick="saveBlockchainConfig()" style="background: var(--color-primary); color: white;">
                <i class="fas fa-save me-2"></i>Save Blockchain Configuration
            </button>
        </div>

        <!-- Email Notifications -->
        <div style="background: var(--bg-panel); border: 2px solid #27ae60; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
            <h3 style="margin: 0 0 20px 0; color: #27ae60;">
                <i class="fas fa-envelope me-2"></i>Email Notifications
            </h3>
            
            <div style="margin-bottom: 15px; color: var(--color-text);">
                Enable or disable email notifications for payment events:
            </div>
            
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 15px; margin-bottom: 20px;">
                <label style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; padding: 15px; cursor: pointer; display: flex; align-items: center; justify-content: space-between;">
                    <span style="color: var(--color-text);">Payment Success</span>
                    <input type="checkbox" id="emailPaymentSuccess" checked style="width: 20px; height: 20px;">
                </label>
                
                <label style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; padding: 15px; cursor: pointer; display: flex; align-items: center; justify-content: space-between;">
                    <span style="color: var(--color-text);">Payment Failed</span>
                    <input type="checkbox" id="emailPaymentFailed" checked style="width: 20px; height: 20px;">
                </label>
                
                <label style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; padding: 15px; cursor: pointer; display: flex; align-items: center; justify-content: space-between;">
                    <span style="color: var(--color-text);">Subscription Upgraded</span>
                    <input type="checkbox" id="emailSubscriptionUpgraded" checked style="width: 20px; height: 20px;">
                </label>
                
                <label style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; padding: 15px; cursor: pointer; display: flex; align-items: center; justify-content: space-between;">
                    <span style="color: var(--color-text);">Subscription Downgraded</span>
                    <input type="checkbox" id="emailSubscriptionDowngraded" checked style="width: 20px; height: 20px;">
                </label>
                
                <label style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; padding: 15px; cursor: pointer; display: flex; align-items: center; justify-content: space-between;">
                    <span style="color: var(--color-text);">Subscription Cancelled</span>
                    <input type="checkbox" id="emailSubscriptionCancelled" checked style="width: 20px; height: 20px;">
                </label>
                
                <label style="background: var(--bg-page); border:1px solid var(--color-border); border-radius: 8px; padding: 15px; cursor: pointer; display: flex; align-items: center; justify-content: space-between;">
                    <span style="color: var(--color-text);">Payment Retry</span>
                    <input type="checkbox" id="emailPaymentRetry" checked style="width: 20px; height: 20px;">
                </label>
            </div>
            
            <button type="button" class="btn" onclick="saveEmailConfig()" style="background: #27ae60; color: white;">
                <i class="fas fa-save me-2"></i>Save Email Configuration
            </button>
        </div>

        <!-- Consolidation Settings -->
        <div style="background: var(--bg-panel); border: 2px solid #e67e22; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
            <h3 style="margin: 0 0 20px 0; color: #e67e22;">
                <i class="fas fa-compress-arrows-alt me-2"></i>Wallet Consolidation
            </h3>
            
            <div style="margin-bottom: 15px; color: var(--color-text);">
                Set minimum balance thresholds for automatic consolidation to admin addresses:
            </div>
            
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px; margin-bottom: 20px;">
                <div>
                    <label style="display: block; margin-bottom: 5px; color: var(--color-text); font-weight: 500;">
                        <i class="fab fa-bitcoin me-2"></i>Bitcoin (BTC)
                    </label>
                    <input type="number" id="consolidationBTC" value="0.01" step="0.001" min="0" style="width: 100%; padding: 10px; border:1px solid var(--color-border); border-radius: 5px; background: var(--bg-page); color: var(--color-text);">
                </div>
                
                <div>
                    <label style="display: block; margin-bottom: 5px; color: var(--color-text); font-weight: 500;">
                        <i class="fab fa-ethereum me-2"></i>Ethereum (ETH)
                    </label>
                    <input type="number" id="consolidationETH" value="0.1" step="0.01" min="0" style="width: 100%; padding: 10px; border:1px solid var(--color-border); border-radius: 5px; background: var(--bg-page); color: var(--color-text);">
                </div>
                
                <div>
                    <label style="display: block; margin-bottom: 5px; color: var(--color-text); font-weight: 500;">
                        <i class="fas fa-dollar-sign me-2"></i>USDT
                    </label>
                    <input type="number" id="consolidationUSDT" value="100" step="10" min="0" style="width: 100%; padding: 10px; border:1px solid var(--color-border); border-radius: 5px; background: var(--bg-page); color: var(--color-text);">
                </div>
                
                <div>
                    <label style="display: block; margin-bottom: 5px; color: var(--color-text); font-weight: 500;">
                        <i class="fas fa-coins me-2"></i>USDC
                    </label>
                    <input type="number" id="consolidationUSDC" value="100" step="10" min="0" style="width: 100%; padding: 10px; border:1px solid var(--color-border); border-radius: 5px; background: var(--bg-page); color: var(--color-text);">
                </div>
            </div>
            
            <button type="button" class="btn" onclick="saveConsolidationConfig()" style="background: #e67e22; color: white;">
                <i class="fas fa-save me-2"></i>Save Consolidation Settings
            </button>
        </div>

        <!-- Back Button -->
        <div style="margin-top: 30px;">
            <a href="{{ url_for(request, '/dashboard/admin/tiers') }}" class="btn" style="background:var(--bg-accent); color: var(--color-link); border: 1px solid #4a9eff;">
                <i class="fas fa-arrow-left me-2"></i>Back to Tiers
            </a>
        </div>
    </div>
</div>

<script>
// Load encryption key status
async function loadEncryptionKeyStatus() {
    try {
        const response = await fetch('{{ url_for(request, "/api/admin/settings/encryption-key") }}');
        const data = await response.json();
        
        const statusEl = document.getElementById('encryptionKeyStatus');
        if (data.is_set) {
            statusEl.innerHTML = '<i class="fas fa-check-circle" style="color: #27ae60;"></i> Encryption key is configured (Source: ' + data.source + ')';
        } else {
            statusEl.innerHTML = '<i class="fas fa-exclamation-triangle" style="color: #e74c3c;"></i> No encryption key set - using temporary key (will change on restart)';
        }
    } catch (error) {
        console.error('Error loading encryption key status:', error);
        document.getElementById('encryptionKeyStatus').innerHTML = '<i class="fas fa-times-circle" style="color: #e74c3c;"></i> Error loading status';
    }
}

// Generate random encryption key (URL-safe base64, required by Fernet)
function generateEncryptionKey() {
    const array = new Uint8Array(32);
    crypto.getRandomValues(array);
    // URL-safe base64: replace + with - and / with _
    const base64 = btoa(String.fromCharCode.apply(null, array))
        .replace(/\+/g, '-').replace(/\//g, '_');
    document.getElementById('encryptionKey').value = base64;
    document.getElementById('encryptionKeyBackup').style.display = 'block';
    document.getElementById('encryptionKeyBackupValue').textContent = base64;
    showToast('Encryption key generated. Copy it now and store it safely before saving!', 'warning');
}

// Copy key to clipboard then hide it
function copyEncryptionKey() {
    const key = document.getElementById('encryptionKey').value.trim();
    if (!key) return;
    navigator.clipboard.writeText(key).then(() => {
        showToast('Key copied to clipboard. Store it safely!', 'success');
        document.getElementById('encryptionKeyBackup').style.display = 'none';
        document.getElementById('encryptionKey').value = '';
    });
}

// Save encryption key
async function saveEncryptionKey() {
    const key = document.getElementById('encryptionKey').value.trim();

    if (!key) {
        showToast('Please enter or generate an encryption key', 'danger');
        return;
    }

    if (key.length !== 44) {
        showToast('Encryption key must be 44 characters (URL-safe base64)', 'danger');
        return;
    }

    const ok = await showDangerConfirm('WARNING: Setting or changing the encryption key will affect all encrypted data. Are you sure?', 'Change Encryption Key');
    if (!ok) return;

    try {
        const response = await fetch('{{ url_for(request, "/api/admin/settings/encryption-key") }}', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({encryption_key: key})
        });

        const result = await response.json();

        if (response.ok && result.success) {
            showToast('Encryption key saved. COPY THE KEY ABOVE before restarting the server!', 'success');
            loadEncryptionKeyStatus();
            // Do NOT clear the field — user needs to copy it for backup
        } else {
            showToast(result.error || 'Failed to save encryption key', 'danger');
        }
    } catch (error) {
        showToast('Error saving encryption key: ' + error.message, 'danger');
    }
}

// Reset crypto wallet seeds (delete master keys so they are regenerated with the new encryption key)
async function resetCryptoSeeds() {
    const ok = await showDangerConfirm(
        'WARNING: This will delete all crypto master seeds. All existing derived addresses will be lost. Only do this after setting a new encryption key. Are you sure?',
        'Reset Crypto Seeds'
    );
    if (!ok) return;

    try {
        const response = await fetch('{{ url_for(request, "/api/admin/settings/crypto-seeds-reset") }}', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'}
        });
        const result = await response.json();
        if (response.ok && result.success) {
            showToast('Crypto seeds deleted. Restart the server to generate new ones.', 'success');
        } else {
            showToast(result.error || 'Failed to reset crypto seeds', 'danger');
        }
    } catch (error) {
        showToast('Error: ' + error.message, 'danger');
    }
}

// Load system status
async function loadSystemStatus() {
    try {
        const response = await fetch('{{ url_for(request, "/api/admin/payment-system/status") }}');
        const data = await response.json();
        
        // Update master keys status
        const masterKeysEl = document.getElementById('masterKeysStatus');
        if (data.master_keys_initialized) {
            masterKeysEl.innerHTML = '<i class="fas fa-check-circle" style="color: #27ae60;"></i> ' + data.master_keys_count + ' ' + window.i18n.t('payments.keys_active');
        } else {
            masterKeysEl.innerHTML = '<i class="fas fa-exclamation-triangle" style="color: #e74c3c;"></i> Not Initialized';
        }
        
        // Update balances
        document.getElementById('totalBalance').textContent = '{{ currency_symbol }}' + (data.total_balance_usd || 0).toFixed(2);
        document.getElementById('pendingPayments').textContent = data.pending_payments || 0;
        document.getElementById('failedPayments').textContent = data.failed_payments || 0;
    } catch (error) {
        console.error('Error loading system status:', error);
        document.getElementById('masterKeysStatus').innerHTML = '<i class="fas fa-times-circle" style="color: #e74c3c;"></i> Error';
    }
}

// Load configuration
async function loadConfiguration() {
    try {
        const response = await fetch('{{ url_for(request, "/api/admin/payment-system/config") }}');
        const data = await response.json();
        
        // Load price sources
        if (data.price_sources) {
            document.getElementById('priceCoinbase').checked = data.price_sources.coinbase || false;
            document.getElementById('priceBinance').checked = data.price_sources.binance || false;
            document.getElementById('priceKraken').checked = data.price_sources.kraken || false;
        }
        
        // Load blockchain config
        if (data.blockchain) {
            document.getElementById('blockchainMode').value = data.blockchain.mode || 'api';
            document.getElementById('pollingInterval').value = data.blockchain.polling_interval || 60;
        }
        
        // Load email config
        if (data.email_notifications) {
            document.getElementById('emailPaymentSuccess').checked = data.email_notifications.payment_success !== false;
            document.getElementById('emailPaymentFailed').checked = data.email_notifications.payment_failed !== false;
            document.getElementById('emailSubscriptionUpgraded').checked = data.email_notifications.subscription_upgraded !== false;
            document.getElementById('emailSubscriptionDowngraded').checked = data.email_notifications.subscription_downgraded !== false;
            document.getElementById('emailSubscriptionCancelled').checked = data.email_notifications.subscription_cancelled !== false;
            document.getElementById('emailPaymentRetry').checked = data.email_notifications.payment_retry !== false;
        }
        
        // Load consolidation config
        if (data.consolidation) {
            document.getElementById('consolidationBTC').value = data.consolidation.btc || 0.01;
            document.getElementById('consolidationETH').value = data.consolidation.eth || 0.1;
            document.getElementById('consolidationUSDT').value = data.consolidation.usdt || 100;
            document.getElementById('consolidationUSDC').value = data.consolidation.usdc || 100;
        }
    } catch (error) {
        console.error('Error loading configuration:', error);
    }
}

// Save functions
async function savePriceSources() {
    const config = {
        coinbase: document.getElementById('priceCoinbase').checked,
        binance: document.getElementById('priceBinance').checked,
        kraken: document.getElementById('priceKraken').checked
    };
    
    try {
        const response = await fetch('{{ url_for(request, "/api/admin/payment-system/config/price-sources") }}', {
            method: 'PUT',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(config)
        });
        
        if (response.ok) {
            showToast('Price sources configuration saved', 'success');
        } else {
            showToast('Failed to save price sources', 'danger');
        }
    } catch (error) {
        showToast('Error saving price sources: ' + error.message, 'danger');
    }
}

async function saveBlockchainConfig() {
    const config = {
        mode: document.getElementById('blockchainMode').value,
        polling_interval: parseInt(document.getElementById('pollingInterval').value)
    };
    
    try {
        const response = await fetch('{{ url_for(request, "/api/admin/payment-system/config/blockchain") }}', {
            method: 'PUT',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(config)
        });
        
        if (response.ok) {
            showToast('Blockchain configuration saved', 'success');
        } else {
            showToast('Failed to save blockchain configuration', 'danger');
        }
    } catch (error) {
        showToast('Error saving blockchain configuration: ' + error.message, 'danger');
    }
}

async function saveEmailConfig() {
    const config = {
        payment_success: document.getElementById('emailPaymentSuccess').checked,
        payment_failed: document.getElementById('emailPaymentFailed').checked,
        subscription_upgraded: document.getElementById('emailSubscriptionUpgraded').checked,
        subscription_downgraded: document.getElementById('emailSubscriptionDowngraded').checked,
        subscription_cancelled: document.getElementById('emailSubscriptionCancelled').checked,
        payment_retry: document.getElementById('emailPaymentRetry').checked
    };
    
    try {
        const response = await fetch('{{ url_for(request, "/api/admin/payment-system/config/email") }}', {
            method: 'PUT',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(config)
        });
        
        if (response.ok) {
            showToast('Email configuration saved', 'success');
        } else {
            showToast('Failed to save email configuration', 'danger');
        }
    } catch (error) {
        showToast('Error saving email configuration: ' + error.message, 'danger');
    }
}

async function saveConsolidationConfig() {
    const config = {
        btc: parseFloat(document.getElementById('consolidationBTC').value),
        eth: parseFloat(document.getElementById('consolidationETH').value),
        usdt: parseFloat(document.getElementById('consolidationUSDT').value),
        usdc: parseFloat(document.getElementById('consolidationUSDC').value)
    };
    
    console.log('Saving consolidation config:', config);
    
    try {
        const response = await fetch('{{ url_for(request, "/api/admin/payment-system/config/consolidation") }}', {
            method: 'PUT',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(config)
        });
        
        const result = await response.json();
        console.log('Save response:', result);
        
        if (response.ok && result.success) {
            showToast('Consolidation settings saved successfully', 'success');
        } else {
            showToast(result.error || 'Failed to save consolidation settings', 'danger');
        }
    } catch (error) {
        console.error('Error saving consolidation settings:', error);
        showToast('Error saving consolidation settings: ' + error.message, 'danger');
    }
}

function showToast(message, type) {
    // Remove any existing alerts
    const existingAlerts = document.querySelectorAll('.payment-alert');
    existingAlerts.forEach(alert => alert.remove());
    
    // Create prominent alert at top of page
    const alertDiv = document.createElement('div');
    alertDiv.className = 'payment-alert';
    alertDiv.style.cssText = `
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        z-index: 10000;
        min-width: 400px;
        max-width: calc(100vw - 16px);
        padding: 20px 30px;
        border-radius: 8px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.3);
        font-size: 16px;
        font-weight: 500;
        text-align: center;
        animation: slideDown 0.3s ease-out;
    `;
    
    // Set colors based on type
    if (type === 'success') {
        alertDiv.style.background = 'linear-gradient(135deg, #27ae60 0%, #2ecc71 100%)';
        alertDiv.style.color = 'white';
        alertDiv.style.border = '2px solid #27ae60';
        alertDiv.innerHTML = `
            <i class="fas fa-check-circle" style="font-size: 24px; margin-right: 10px; vertical-align: middle;"></i>
            <span style="vertical-align: middle;">${message}</span>
        `;
    } else if (type === 'danger') {
        alertDiv.style.background = 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)';
        alertDiv.style.color = 'white';
        alertDiv.style.border = '2px solid #e74c3c';
        alertDiv.innerHTML = `
            <i class="fas fa-exclamation-circle" style="font-size: 24px; margin-right: 10px; vertical-align: middle;"></i>
            <span style="vertical-align: middle;">${message}</span>
        `;
    } else if (type === 'warning') {
        alertDiv.style.background = 'linear-gradient(135deg, #f39c12 0%, #e67e22 100%)';
        alertDiv.style.color = 'white';
        alertDiv.style.border = '2px solid #f39c12';
        alertDiv.innerHTML = `
            <i class="fas fa-exclamation-triangle" style="font-size: 24px; margin-right: 10px; vertical-align: middle;"></i>
            <span style="vertical-align: middle;">${message}</span>
        `;
    }
    
    // Add animation keyframes
    if (!document.getElementById('alertAnimations')) {
        const style = document.createElement('style');
        style.id = 'alertAnimations';
        style.textContent = `
            @keyframes slideDown {
                from {
                    opacity: 0;
                    transform: translateX(-50%) translateY(-20px);
                }
                to {
                    opacity: 1;
                    transform: translateX(-50%) translateY(0);
                }
            }
            @keyframes slideUp {
                from {
                    opacity: 1;
                    transform: translateX(-50%) translateY(0);
                }
                to {
                    opacity: 0;
                    transform: translateX(-50%) translateY(-20px);
                }
            }
        `;
        document.head.appendChild(style);
    }
    
    document.body.appendChild(alertDiv);
    
    // Auto-remove after 4 seconds with fade out animation
    setTimeout(() => {
        alertDiv.style.animation = 'slideUp 0.3s ease-out';
        setTimeout(() => {
            if (alertDiv.parentNode) {
                alertDiv.parentNode.removeChild(alertDiv);
            }
        }, 300);
    }, 4000);
}


// Load and save payment gateway functions
function loadPaymentGateways() {
    fetch('{{ url_for(request, "/api/admin/settings/payment-gateways") }}')
        .then(response => response.json())
        .then(gateways => {
            // Load gateway configuration into form fields
            if (gateways.paypal) {
                document.getElementById('paypalEnabled').checked = gateways.paypal.enabled || false;
                document.getElementById('paypalClientId').value = gateways.paypal.client_id || '';
                document.getElementById('paypalClientSecret').value = gateways.paypal.client_secret || '';
                document.getElementById('paypalWebhookSecret').value = gateways.paypal.webhook_secret || '';
                document.getElementById('paypalSandbox').checked = gateways.paypal.sandbox === true;
            }
            
            if (gateways.stripe) {
                document.getElementById('stripeEnabled').checked = gateways.stripe.enabled || false;
                document.getElementById('stripePublishableKey').value = gateways.stripe.publishable_key || '';
                document.getElementById('stripeSecretKey').value = gateways.stripe.secret_key || '';
                document.getElementById('stripeWebhookSecret').value = gateways.stripe.webhook_secret || '';
                document.getElementById('stripeSandbox').checked = gateways.stripe.sandbox === true;
            }
            
            if (gateways.bitcoin) {
                document.getElementById('bitcoinEnabled').checked = gateways.bitcoin.enabled || false;
                document.getElementById('bitcoinAddress').value = gateways.bitcoin.address || '';
                document.getElementById('bitcoinConfirmations').value = gateways.bitcoin.confirmations || 3;
                document.getElementById('bitcoinExpiration').value = gateways.bitcoin.expiration_minutes || 120;
            }
            
            if (gateways.ethereum) {
                document.getElementById('ethEnabled').checked = gateways.ethereum.enabled || false;
                document.getElementById('ethAddress').value = gateways.ethereum.address || '';
                document.getElementById('ethConfirmations').value = gateways.ethereum.confirmations || 12;
                document.getElementById('ethChainId').value = gateways.ethereum.chain_id || 1;
            }
            
            if (gateways.usdt) {
                document.getElementById('usdtEnabled').checked = gateways.usdt.enabled || false;
                document.getElementById('usdtAddress').value = gateways.usdt.address || '';
                document.getElementById('usdtNetwork').value = gateways.usdt.network || 'erc20';
                document.getElementById('usdtConfirmations').value = gateways.usdt.confirmations || 3;
            }
            
            if (gateways.usdc) {
                document.getElementById('usdcEnabled').checked = gateways.usdc.enabled || false;
                document.getElementById('usdcAddress').value = gateways.usdc.address || '';
                document.getElementById('usdcNetwork').value = gateways.usdc.network || 'erc20';
                document.getElementById('usdcConfirmations').value = gateways.usdc.confirmations || 3;
            }
        });
}

function savePaymentGateways() {
    const gatewaysData = {
        paypal: {
            enabled: document.getElementById('paypalEnabled').checked,
            client_id: document.getElementById('paypalClientId').value,
            client_secret: document.getElementById('paypalClientSecret').value,
            webhook_secret: document.getElementById('paypalWebhookSecret').value,
            sandbox: document.getElementById('paypalSandbox').checked
        },
        stripe: {
            enabled: document.getElementById('stripeEnabled').checked,
            publishable_key: document.getElementById('stripePublishableKey').value,
            secret_key: document.getElementById('stripeSecretKey').value,
            webhook_secret: document.getElementById('stripeWebhookSecret').value,
            sandbox: document.getElementById('stripeSandbox').checked
        },
        bitcoin: {
            enabled: document.getElementById('bitcoinEnabled').checked,
            address: document.getElementById('bitcoinAddress').value,
            confirmations: parseInt(document.getElementById('bitcoinConfirmations').value),
            expiration_minutes: parseInt(document.getElementById('bitcoinExpiration').value)
        },
        ethereum: {
            enabled: document.getElementById('ethEnabled').checked,
            address: document.getElementById('ethAddress').value,
            confirmations: parseInt(document.getElementById('ethConfirmations').value),
            chain_id: parseInt(document.getElementById('ethChainId').value)
        },
        usdt: {
            enabled: document.getElementById('usdtEnabled').checked,
            address: document.getElementById('usdtAddress').value,
            network: document.getElementById('usdtNetwork').value,
            confirmations: parseInt(document.getElementById('usdtConfirmations').value)
        },
        usdc: {
            enabled: document.getElementById('usdcEnabled').checked,
            address: document.getElementById('usdcAddress').value,
            network: document.getElementById('usdcNetwork').value,
            confirmations: parseInt(document.getElementById('usdcConfirmations').value)
        }
    };
    
    console.log('Saving payment gateways:', gatewaysData);
    
    fetch('{{ url_for(request, "/api/admin/settings/payment-gateways") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(gatewaysData)
    })
    .then(response => {
        console.log('Response status:', response.status);
        if (!response.ok) {
            throw new Error('Failed to save payment gateway configuration');
        }
        return response.json();
    })
    .then(result => {
        console.log('Save result:', result);
        if (result.success) {
            showToast('Payment gateway configuration saved successfully', 'success');
            // Reload to verify
            setTimeout(() => loadPaymentGateways(), 500);
        } else {
            showToast(result.error || 'Error saving payment gateway configuration', 'danger');
        }
    })
    .catch(error => {
        console.error('Error saving payment gateways:', error);
        showToast('Error saving payment gateway configuration: ' + error.message, 'danger');
    });
}

// Load data on page load - update to include payment gateways
document.addEventListener('DOMContentLoaded', function() {
    loadEncryptionKeyStatus();
    loadSystemStatus();
    loadConfiguration();
    loadPaymentGateways();
    loadCryptoPrices();
    loadCurrencySettings();
    
    // Auto-refresh crypto prices every 60 seconds
    setInterval(loadCryptoPrices, 60000);
});

// Load crypto prices from all sources
async function loadCryptoPrices() {
    try {
        const response = await fetch('{{ url_for(request, "/api/admin/crypto/prices") }}');
        const data = await response.json();
        
        // Get currency settings for symbol
        const currencyResponse = await fetch('{{ url_for(request, "/api/admin/settings/currency") }}');
        const currencyData = await currencyResponse.json();
        const currencySymbol = currencyData.currency_symbol || '$';
        
        // Update BTC prices
        updateCryptoPrice('Btc', data.btc, currencySymbol);
        
        // Update ETH prices
        updateCryptoPrice('Eth', data.eth, currencySymbol);
        
        // Update USDT prices
        updateCryptoPrice('Usdt', data.usdt, currencySymbol);
        
        // Update USDC prices
        updateCryptoPrice('Usdc', data.usdc, currencySymbol);
        
        // Update last updated time
        const now = new Date();
        document.getElementById('priceLastUpdated').textContent = now.toLocaleTimeString();
        
    } catch (error) {
        console.error('Error loading crypto prices:', error);
        ['Btc', 'Eth', 'Usdt', 'Usdc'].forEach(crypto => {
            document.getElementById(`price${crypto}Coinbase`).innerHTML = '<span style="color: #e74c3c;">Error</span>';
            document.getElementById(`price${crypto}Binance`).innerHTML = '<span style="color: #e74c3c;">Error</span>';
            document.getElementById(`price${crypto}Kraken`).innerHTML = '<span style="color: #e74c3c;">Error</span>';
            document.getElementById(`price${crypto}Average`).innerHTML = '<span style="color: #e74c3c;">Error</span>';
        });
    }
}

// Helper function to update individual crypto prices
function updateCryptoPrice(crypto, priceData, currencySymbol) {
    // Update Coinbase
    if (priceData.coinbase !== null && priceData.coinbase !== undefined) {
        document.getElementById(`price${crypto}Coinbase`).textContent = currencySymbol + priceData.coinbase.toFixed(2);
        document.getElementById(`price${crypto}Coinbase`).style.color = '#27ae60';
    } else {
        document.getElementById(`price${crypto}Coinbase`).innerHTML = '<span style="color: var(--color-subtle);">Disabled</span>';
    }
    
    // Update Binance
    if (priceData.binance !== null && priceData.binance !== undefined) {
        document.getElementById(`price${crypto}Binance`).textContent = currencySymbol + priceData.binance.toFixed(2);
        document.getElementById(`price${crypto}Binance`).style.color = '#27ae60';
    } else {
        document.getElementById(`price${crypto}Binance`).innerHTML = '<span style="color: var(--color-subtle);">Disabled</span>';
    }
    
    // Update Kraken
    if (priceData.kraken !== null && priceData.kraken !== undefined) {
        document.getElementById(`price${crypto}Kraken`).textContent = currencySymbol + priceData.kraken.toFixed(2);
        document.getElementById(`price${crypto}Kraken`).style.color = '#27ae60';
    } else {
        document.getElementById(`price${crypto}Kraken`).innerHTML = '<span style="color: var(--color-subtle);">Disabled</span>';
    }
    
    // Update Average
    if (priceData.average !== null && priceData.average !== undefined) {
        document.getElementById(`price${crypto}Average`).textContent = currencySymbol + priceData.average.toFixed(2);
    } else {
        document.getElementById(`price${crypto}Average`).innerHTML = '<span style="color: #e74c3c;">No sources</span>';
    }
}

function loadCurrencySettings() {
    fetch('{{ url_for(request, "/api/admin/settings/currency") }}')
        .then(response => response.json())
        .then(settings => {
            document.getElementById('currencyCode').value = settings.currency_code;
            document.getElementById('currencySymbol').value = settings.currency_symbol;
            document.getElementById('currencyDecimals').value = settings.currency_decimals;
        });
}

const CURRENCY_SYMBOLS = {
    USD: '$', EUR: '€', GBP: '£', JPY: '¥', CAD: 'CA$',
    AUD: 'A$', CHF: 'Fr', CNY: '¥', INR: '₹', BRL: 'R$',
    MXN: '$', SGD: 'S$', HKD: 'HK$', NOK: 'kr', SEK: 'kr',
    DKK: 'kr', NZD: 'NZ$', ZAR: 'R', RUB: '₽', TRY: '₺',
    KRW: '₩', IDR: 'Rp', MYR: 'RM', THB: '฿', PHP: '₱',
    VND: '₫', PKR: '₨', BDT: '৳', EGP: 'E£', NGN: '₦',
    KES: 'KSh', GHS: 'GH₵', MAD: 'د.م.', TND: 'د.ت', DZD: 'د.ج',
    SAR: '﷼', AED: 'د.إ', QAR: '﷼', KWD: 'د.ك', BHD: '.د.ب',
    OMR: '﷼', ILS: '₪', PLN: 'zł', CZK: 'Kč', HUF: 'Ft',
    RON: 'lei', BGN: 'лв', HRK: 'kn', RSD: 'din', UAH: '₴',
    ARS: '$', CLP: '$', COP: '$', PEN: 'S/', UYU: '$U',
    TWD: 'NT$', LKR: '₨', NPR: '₨', MMK: 'K', KZT: '₸'
};
document.getElementById('currencyCode').addEventListener('change', function() {
    const sym = CURRENCY_SYMBOLS[this.value];
    if (sym) document.getElementById('currencySymbol').value = sym;
});

document.getElementById('currencySettingsForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const currencyData = {
        currency_code: document.getElementById('currencyCode').value,
        currency_symbol: document.getElementById('currencySymbol').value,
        currency_decimals: parseInt(document.getElementById('currencyDecimals').value)
    };

    fetch('{{ url_for(request, "/api/admin/settings/currency") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(currencyData)
    })
    .then(response => response.json())
    .then(result => {
        showToast('Currency settings saved successfully', 'success');
    })
    .catch(error => {
        showToast('Error saving currency settings', 'danger');
    });
});

// Refresh crypto prices manually
function refreshCryptoPrices() {
    ['Btc', 'Eth', 'Usdt', 'Usdc'].forEach(crypto => {
        document.getElementById(`price${crypto}Coinbase`).innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        document.getElementById(`price${crypto}Binance`).innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        document.getElementById(`price${crypto}Kraken`).innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        document.getElementById(`price${crypto}Average`).innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
    });
    loadCryptoPrices();
}

</script>
{% endblock %}
