@extends('admin.layouts.master')
@section('title', 'تنظیمات API')
@section('css')
    <style>
        .api-section {
            margin-bottom: 2rem;
        }
        .api-section-title {
            background: #f8f9fa;
            padding: 0.75rem 1rem;
            border-radius: 0.25rem;
            margin-bottom: 1rem;
            font-weight: 600;
            border-left: 4px solid #556ee6;
        }
        .password-toggle {
            cursor: pointer;
        }
    </style>
@stop

@section('content')
    <div class="row">
        <div class="col-12">
            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                <h4 class="mb-sm-0 font-size-18">تنظیمات API</h4>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="card col-12">
            <div class="card-body">
                <ul class="nav nav-tabs nav-tabs-custom nav-justified" role="tablist">
                    <li class="nav-item">
                        <a class="nav-link active" data-bs-toggle="tab" href="#exchange-apis" role="tab">
                            <span>صرافی‌ها</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" data-bs-toggle="tab" href="#payment-apis" role="tab">
                            <span>درگاه‌های پرداخت</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" data-bs-toggle="tab" href="#sms-apis" role="tab">
                            <span>پیامک و اعلان</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" data-bs-toggle="tab" href="#other-apis" role="tab">
                            <span>سایر سرویس‌ها</span>
                        </a>
                    </li>
                </ul>
                <div class="mb-4">
                    <form autocomplete="off" method="post" class="needs-validation" novalidate action="">
                        @csrf
                        <div class="tab-content p-3 text-muted">
                            
                            {{-- Exchange APIs Tab --}}
                            <div class="tab-pane active" id="exchange-apis" role="tabpanel">
                                <div class="col-md-10 mx-auto my-4">
                                    
                                    {{-- Default Exchanger --}}
                                    <div class="api-section">
                                        <div class="api-section-title">تنظیمات عمومی</div>
                                        <div class="row">
                                            <div class="col-md-6 form-group mb-3">
                                                <label>صرافی پیش‌فرض</label>
                                                <select class="form-control text-center" name="default_exchanger">
                                                    <option value="binance" @if(($result->default_exchanger ?? '') == 'binance') selected @endif>Binance</option>
                                                    <option value="coinex" @if(($result->default_exchanger ?? '') == 'coinex') selected @endif>CoinEx</option>
                                                    <option value="kucoin" @if(($result->default_exchanger ?? '') == 'kucoin') selected @endif>KuCoin</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>

                                    {{-- Binance API --}}
                                    <div class="api-section">
                                        <div class="api-section-title">Binance API</div>
                                        <div class="row">
                                            <div class="col-md-6 form-group mb-3">
                                                <label>API Key</label>
                                                <div class="input-group">
                                                    <input type="password" name="binance_apikey" id="binance_apikey"
                                                           class="form-control text-center ltr-dir"
                                                           placeholder="Binance API Key" value="{{$result->binance_apikey ?? ''}}"/>
                                                    <span class="input-group-text password-toggle" onclick="togglePassword('binance_apikey')">
                                                        <i class="mdi mdi-eye"></i>
                                                    </span>
                                                </div>
                                            </div>
                                            <div class="col-md-6 form-group mb-3">
                                                <label>Secret Key</label>
                                                <div class="input-group">
                                                    <input type="password" name="binance_seckey" id="binance_seckey"
                                                           class="form-control text-center ltr-dir"
                                                           placeholder="Binance Secret Key" value="{{$result->binance_seckey ?? ''}}"/>
                                                    <span class="input-group-text password-toggle" onclick="togglePassword('binance_seckey')">
                                                        <i class="mdi mdi-eye"></i>
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    {{-- CoinEx API --}}
                                    <div class="api-section">
                                        <div class="api-section-title">CoinEx API</div>
                                        <div class="row">
                                            <div class="col-md-6 form-group mb-3">
                                                <label>API Key</label>
                                                <div class="input-group">
                                                    <input type="password" name="coinex_apikey" id="coinex_apikey"
                                                           class="form-control text-center ltr-dir"
                                                           placeholder="CoinEx API Key" value="{{$result->coinex_apikey ?? ''}}"/>
                                                    <span class="input-group-text password-toggle" onclick="togglePassword('coinex_apikey')">
                                                        <i class="mdi mdi-eye"></i>
                                                    </span>
                                                </div>
                                            </div>
                                            <div class="col-md-6 form-group mb-3">
                                                <label>Secret Key</label>
                                                <div class="input-group">
                                                    <input type="password" name="coinex_seckey" id="coinex_seckey"
                                                           class="form-control text-center ltr-dir"
                                                           placeholder="CoinEx Secret Key" value="{{$result->coinex_seckey ?? ''}}"/>
                                                    <span class="input-group-text password-toggle" onclick="togglePassword('coinex_seckey')">
                                                        <i class="mdi mdi-eye"></i>
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    {{-- KuCoin API --}}
                                    <div class="api-section">
                                        <div class="api-section-title">KuCoin API</div>
                                        <div class="row">
                                            <div class="col-md-4 form-group mb-3">
                                                <label>API Key</label>
                                                <div class="input-group">
                                                    <input type="password" name="kucoin_apikey" id="kucoin_apikey"
                                                           class="form-control text-center ltr-dir"
                                                           placeholder="KuCoin API Key" value="{{$result->kucoin_apikey ?? ''}}"/>
                                                    <span class="input-group-text password-toggle" onclick="togglePassword('kucoin_apikey')">
                                                        <i class="mdi mdi-eye"></i>
                                                    </span>
                                                </div>
                                            </div>
                                            <div class="col-md-4 form-group mb-3">
                                                <label>Secret Key</label>
                                                <div class="input-group">
                                                    <input type="password" name="kucoin_apisec" id="kucoin_apisec"
                                                           class="form-control text-center ltr-dir"
                                                           placeholder="KuCoin Secret Key" value="{{$result->kucoin_apisec ?? ''}}"/>
                                                    <span class="input-group-text password-toggle" onclick="togglePassword('kucoin_apisec')">
                                                        <i class="mdi mdi-eye"></i>
                                                    </span>
                                                </div>
                                            </div>
                                            <div class="col-md-4 form-group mb-3">
                                                <label>Passphrase</label>
                                                <div class="input-group">
                                                    <input type="password" name="kucoin_passphare" id="kucoin_passphare"
                                                           class="form-control text-center ltr-dir"
                                                           placeholder="KuCoin Passphrase" value="{{$result->kucoin_passphare ?? ''}}"/>
                                                    <span class="input-group-text password-toggle" onclick="togglePassword('kucoin_passphare')">
                                                        <i class="mdi mdi-eye"></i>
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    {{-- USDT Price Settings --}}
                                    <div class="api-section">
                                        <div class="api-section-title">قیمت USDT (دستی)</div>
                                        <div class="row">
                                            <div class="col-md-6 form-group mb-3">
                                                <label>قیمت خرید USDT</label>
                                                <input type="text" name="USDT_price_buy" id="USDT_price_buy"
                                                       class="form-control text-center ltr-dir comma"
                                                       placeholder="قیمت خرید" value="{{number_format($result->USDT_price_buy ?? 0)}}"/>
                                            </div>
                                            <div class="col-md-6 form-group mb-3">
                                                <label>قیمت فروش USDT</label>
                                                <input type="text" name="USDT_price_sell" id="USDT_price_sell"
                                                       class="form-control text-center ltr-dir comma"
                                                       placeholder="قیمت فروش" value="{{number_format($result->USDT_price_sell ?? 0)}}"/>
                                            </div>
                                        </div>
                                    </div>

                                </div>
                            </div>

                            {{-- Payment APIs Tab --}}
                            <div class="tab-pane" id="payment-apis" role="tabpanel">
                                <div class="col-md-10 mx-auto my-4">
                                    
                                    <div class="api-section">
                                        <div class="api-section-title">درگاه فعال</div>
                                        <div class="row">
                                            <div class="col-md-6 form-group mb-3">
                                                <label>درگاه پرداخت پیش‌فرض</label>
                                                <select class="form-control text-center" name="payment_gateway">
                                                    <option value="pay" @if(($result->payment_gateway ?? '') == 'pay') selected @endif>Pay.ir</option>
                                                    <option value="idpay" @if(($result->payment_gateway ?? '') == 'idpay') selected @endif>IDPay</option>
                                                    <option value="zarinpal" @if(($result->payment_gateway ?? '') == 'zarinpal') selected @endif>Zarinpal</option>
                                                    <option value="zibal" @if(($result->payment_gateway ?? '') == 'zibal') selected @endif>Zibal</option>
                                                    <option value="vandar" @if(($result->payment_gateway ?? '') == 'vandar') selected @endif>Vandar</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="api-section">
                                        <div class="api-section-title">Pay.ir</div>
                                        <div class="form-group mb-3">
                                            <label>API Token</label>
                                            <div class="input-group">
                                                <input type="password" name="PayIrToken" id="PayIrToken"
                                                       class="form-control text-center ltr-dir"
                                                       placeholder="Pay.ir Token" value="{{$result->PayIrToken ?? ''}}"/>
                                                <span class="input-group-text password-toggle" onclick="togglePassword('PayIrToken')">
                                                    <i class="mdi mdi-eye"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="api-section">
                                        <div class="api-section-title">IDPay</div>
                                        <div class="form-group mb-3">
                                            <label>API Token</label>
                                            <div class="input-group">
                                                <input type="password" name="IdpayToken" id="IdpayToken"
                                                       class="form-control text-center ltr-dir"
                                                       placeholder="IDPay Token" value="{{$result->IdpayToken ?? ''}}"/>
                                                <span class="input-group-text password-toggle" onclick="togglePassword('IdpayToken')">
                                                    <i class="mdi mdi-eye"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="api-section">
                                        <div class="api-section-title">Zarinpal</div>
                                        <div class="form-group mb-3">
                                            <label>Merchant ID</label>
                                            <div class="input-group">
                                                <input type="password" name="ZarinpalToken" id="ZarinpalToken"
                                                       class="form-control text-center ltr-dir"
                                                       placeholder="Zarinpal Merchant ID" value="{{$result->ZarinpalToken ?? ''}}"/>
                                                <span class="input-group-text password-toggle" onclick="togglePassword('ZarinpalToken')">
                                                    <i class="mdi mdi-eye"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="api-section">
                                        <div class="api-section-title">Zibal</div>
                                        <div class="form-group mb-3">
                                            <label>Merchant ID</label>
                                            <div class="input-group">
                                                <input type="password" name="ZibalToken" id="ZibalToken"
                                                       class="form-control text-center ltr-dir"
                                                       placeholder="Zibal Merchant ID" value="{{$result->ZibalToken ?? ''}}"/>
                                                <span class="input-group-text password-toggle" onclick="togglePassword('ZibalToken')">
                                                    <i class="mdi mdi-eye"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="api-section">
                                        <div class="api-section-title">Vandar</div>
                                        <div class="form-group mb-3">
                                            <label>API Token</label>
                                            <div class="input-group">
                                                <input type="password" name="VandarToken" id="VandarToken"
                                                       class="form-control text-center ltr-dir"
                                                       placeholder="Vandar Token" value="{{$result->VandarToken ?? ''}}"/>
                                                <span class="input-group-text password-toggle" onclick="togglePassword('VandarToken')">
                                                    <i class="mdi mdi-eye"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>

                                </div>
                            </div>

                            {{-- SMS & Notification APIs Tab --}}
                            <div class="tab-pane" id="sms-apis" role="tabpanel">
                                <div class="col-md-10 mx-auto my-4">
                                    
                                    <div class="api-section">
                                        <div class="api-section-title">Kavenegar (پیامک)</div>
                                        <div class="row">
                                            <div class="col-md-6 form-group mb-3">
                                                <label>API Key</label>
                                                <div class="input-group">
                                                    <input type="password" name="KavehnegarKey" id="KavehnegarKey"
                                                           class="form-control text-center ltr-dir"
                                                           placeholder="Kavenegar API Key" value="{{$result->KavehnegarKey ?? ''}}"/>
                                                    <span class="input-group-text password-toggle" onclick="togglePassword('KavehnegarKey')">
                                                        <i class="mdi mdi-eye"></i>
                                                    </span>
                                                </div>
                                            </div>
                                            <div class="col-md-6 form-group mb-3">
                                                <label>شماره فرستنده (Sender)</label>
                                                <input type="text" name="KavehnegarSender" id="KavehnegarSender"
                                                       class="form-control text-center ltr-dir"
                                                       placeholder="10004346 or your line number" 
                                                       value="{{$result->KavehnegarSender ?? '10004346'}}"/>
                                                <small class="form-text text-muted">
                                                    اولین شماره فعال در پنل کاونگار خود را وارد کنید
                                                </small>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="api-section">
                                        <div class="api-section-title">CoinEx (صرافی)</div>
                                        <div class="row">
                                            <div class="col-md-6 form-group mb-3">
                                                <label>API Key</label>
                                                <div class="input-group">
                                                    <input type="password" name="coinex_api_key" id="coinex_api_key"
                                                           class="form-control text-center ltr-dir"
                                                           placeholder="CoinEx API Key" value="{{$result->coinex_api_key ?? ''}}"/>
                                                    <span class="input-group-text password-toggle" onclick="togglePassword('coinex_api_key')">
                                                        <i class="mdi mdi-eye"></i>
                                                    </span>
                                                </div>
                                            </div>
                                            <div class="col-md-6 form-group mb-3">
                                                <label>API Secret</label>
                                                <div class="input-group">
                                                    <input type="password" name="coinex_api_secret" id="coinex_api_secret"
                                                           class="form-control text-center ltr-dir"
                                                           placeholder="CoinEx API Secret" value="{{$result->coinex_api_secret ?? ''}}"/>
                                                    <span class="input-group-text password-toggle" onclick="togglePassword('coinex_api_secret')">
                                                        <i class="mdi mdi-eye"></i>
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                        <small class="form-text text-muted">
                                            برای دریافت API Key و Secret به پنل CoinEx مراجعه کنید: 
                                            <a href="https://www.coinex.com/account/api" target="_blank">CoinEx API Settings</a>
                                        </small>
                                    </div>

                                    <div class="api-section">
                                        <div class="api-section-title">Firebase (اعلان‌ها)</div>
                                        <div class="form-group mb-3">
                                            <label>Server Key</label>
                                            <div class="input-group">
                                                <input type="password" name="FirebaseToken" id="FirebaseToken"
                                                       class="form-control text-center ltr-dir"
                                                       placeholder="Firebase Server Key" value="{{$result->FirebaseToken ?? ''}}"/>
                                                <span class="input-group-text password-toggle" onclick="togglePassword('FirebaseToken')">
                                                    <i class="mdi mdi-eye"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>

                                </div>
                            </div>

                            {{-- Other APIs Tab --}}
                            <div class="tab-pane" id="other-apis" role="tabpanel">
                                <div class="col-md-10 mx-auto my-4">
                                    
                                    <div class="api-section">
                                        <div class="api-section-title">قیمت USDT به تومان</div>
                                        <div class="row">
                                            <div class="col-md-6 form-group mb-3">
                                                <label>منبع قیمت USDT</label>
                                                <select class="form-control text-center" name="usdt_price_source" id="usdt_price_source">
                                                    <option value="tetherland" @if(($result->usdt_price_source ?? 'tetherland') == 'tetherland') selected @endif>Tetherland (توصیه می‌شود)</option>
                                                    <option value="iranian_exchange" @if(($result->usdt_price_source ?? 'tetherland') == 'iranian_exchange') selected @endif>صرافی ایرانی</option>
                                                    <option value="manual" @if(($result->usdt_price_source ?? 'tetherland') == 'manual') selected @endif>دستی</option>
                                                </select>
                                                <small class="form-text text-muted">
                                                    انتخاب منبع دریافت قیمت USDT
                                                </small>
                                            </div>
                                            <div class="col-md-6 form-group mb-3">
                                                <label>صرافی ایرانی</label>
                                                <select class="form-control text-center" name="iranian_exchange_name">
                                                    <option value="nobitex" @if(($result->iranian_exchange_name ?? 'nobitex') == 'nobitex') selected @endif>Nobitex</option>
                                                    <option value="wallex" @if(($result->iranian_exchange_name ?? 'nobitex') == 'wallex') selected @endif>Wallex</option>
                                                    <option value="exnovin" @if(($result->iranian_exchange_name ?? 'nobitex') == 'exnovin') selected @endif>Exnovin</option>
                                                    <option value="ramzinex" @if(($result->iranian_exchange_name ?? 'nobitex') == 'ramzinex') selected @endif>Ramzinex</option>
                                                </select>
                                                <small class="form-text text-muted">
                                                    انتخاب صرافی ایرانی برای دریافت قیمت
                                                </small>
                                            </div>
                                        </div>
                                        
                                        {{-- Tetherland Settings --}}
                                        <div id="tetherland-settings" class="mt-3">
                                            <div class="row">
                                                <div class="col-md-12 form-group mb-3">
                                                    <label class="font-weight-bold">تنظیمات Tetherland</label>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-6 form-group mb-3">
                                                    <label>Private Key / API Token</label>
                                                    <div class="input-group">
                                                        <input type="password" name="tetherland_private_key" id="tetherland_private_key"
                                                               class="form-control text-center ltr-dir"
                                                               placeholder="Private Key یا Token دریافتی از Tetherland"
                                                               value="{{$result->tetherland_private_key ?? ''}}"/>
                                                        <span class="input-group-text password-toggle" onclick="togglePassword('tetherland_private_key')">
                                                            <i class="mdi mdi-eye"></i>
                                                        </span>
                                                    </div>
                                                    <small class="form-text text-muted">
                                                        کلید خصوصی یا توکن دریافتی از سایت Tetherland (در صورت نیاز)
                                                    </small>
                                                </div>
                                                <div class="col-md-6 form-group mb-3">
                                                    <label>API Endpoint</label>
                                                    <input type="text" name="tetherland_api_url" id="tetherland_api_url"
                                                           class="form-control text-center ltr-dir"
                                                           placeholder="https://service.tetherland.com/api/v5/user/converter/exchange"
                                                           value="{{$result->tetherland_api_url ?? 'https://service.tetherland.com/api/v5/user/converter/exchange'}}"/>
                                                    <small class="form-text text-muted">
                                                        آدرس API Tetherland (قابل تغییر در صورت نیاز)
                                                    </small>
                                                </div>
                                            </div>
                                        </div>

                                        {{-- CoinEx Settings --}}
                                        <div id="coinex-settings" class="mt-4 border-top pt-3">
                                            <div class="row">
                                                <div class="col-md-12 form-group mb-3">
                                                    <label class="font-weight-bold">تنظیمات CoinEx (اختیاری)</label>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-6 form-group mb-3">
                                                    <label>Access ID</label>
                                                    <input type="text" name="coinex_access_id" id="coinex_access_id"
                                                           class="form-control text-center ltr-dir"
                                                           placeholder="CoinEx Access ID"
                                                           value="{{$result->coinex_access_id ?? ''}}"/>
                                                </div>
                                                <div class="col-md-6 form-group mb-3">
                                                    <label>Secret Key</label>
                                                    <div class="input-group">
                                                        <input type="password" name="coinex_secret_key" id="coinex_secret_key"
                                                               class="form-control text-center ltr-dir"
                                                               placeholder="CoinEx Secret Key"
                                                               value="{{$result->coinex_secret_key ?? ''}}"/>
                                                        <span class="input-group-text password-toggle" onclick="togglePassword('coinex_secret_key')">
                                                            <i class="mdi mdi-eye"></i>
                                                        </span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                            <div class="row">
                                                <div class="col-md-12 form-group mb-3">
                                                    <button type="button" class="btn btn-info btn-sm" onclick="testTetherlandAPI()">
                                                        <i class="mdi mdi-test-tube"></i> تست اتصال با Private Key
                                                    </button>
                                                    <span id="tetherland-status" class="ms-2"></span>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        {{-- Iranian Exchange Settings --}}
                                        <div id="iranian-exchange-settings" class="mt-3" style="display: none;">
                                            <div class="row">
                                                <div class="col-md-12 form-group mb-3">
                                                    <label class="font-weight-bold">تنظیمات صرافی ایرانی</label>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-6 form-group mb-3">
                                                    <label>API Key (اختیاری)</label>
                                                    <div class="input-group">
                                                        <input type="password" name="iranian_exchange_api_key" id="iranian_exchange_api_key"
                                                               class="form-control text-center ltr-dir"
                                                               placeholder="API Key صرافی ایرانی" value="{{$result->iranian_exchange_api_key ?? ''}}"/>
                                                        <span class="input-group-text password-toggle" onclick="togglePassword('iranian_exchange_api_key')">
                                                            <i class="mdi mdi-eye"></i>
                                                        </span>
                                                    </div>
                                                    <small class="form-text text-muted">
                                                        برای برخی صرافی‌ها نیاز به API Key است
                                                    </small>
                                                </div>
                                                <div class="col-md-6 form-group mb-3">
                                                    <label>&nbsp;</label>
                                                    <div>
                                                        <button type="button" class="btn btn-info btn-sm" onclick="testIranianExchangeAPI()">
                                                            <i class="mdi mdi-test-tube"></i> تست اتصال
                                                        </button>
                                                        <span id="iranian-exchange-status" class="ms-2"></span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="api-section">
                                        <div class="api-section-title">Finotech</div>
                                        <div class="row">
                                            <div class="col-md-6 form-group mb-3">
                                                <label>API Key</label>
                                                <div class="input-group">
                                                    <input type="password" name="FinotechKey" id="FinotechKey"
                                                           class="form-control text-center ltr-dir"
                                                           placeholder="Finotech API Key" value="{{$result->FinotechKey ?? ''}}"/>
                                                    <span class="input-group-text password-toggle" onclick="togglePassword('FinotechKey')">
                                                        <i class="mdi mdi-eye"></i>
                                                    </span>
                                                </div>
                                            </div>
                                            <div class="col-md-6 form-group mb-3">
                                                <label>کد ملی</label>
                                                <input type="text" name="FinotechCodemeli" id="FinotechCodemeli"
                                                       class="form-control text-center ltr-dir"
                                                       placeholder="کد ملی" value="{{$result->FinotechCodemeli ?? ''}}"/>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="api-section">
                                        <div class="api-section-title">تنظیمات دسترسی</div>
                                        <div class="row">
                                            <div class="col-md-6 form-group mb-3">
                                                <label>کنترل دسترسی IP</label>
                                                <select class="form-control text-center" name="IP_Access">
                                                    <option value="true" @if(($result->IP_Access ?? '') == 'true') selected @endif>فعال</option>
                                                    <option value="false" @if(($result->IP_Access ?? '') == 'false') selected @endif>غیرفعال</option>
                                                </select>
                                            </div>
                                            <div class="col-md-6 form-group mb-3">
                                                <label>محدودیت IP ایران</label>
                                                <select class="form-control text-center" name="IP_Iran">
                                                    <option value="true" @if(($result->IP_Iran ?? '') == 'true') selected @endif>فعال</option>
                                                    <option value="false" @if(($result->IP_Iran ?? '') == 'false') selected @endif>غیرفعال</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="api-section">
                                        <div class="api-section-title">کارمزدها</div>
                                        <div class="row">
                                            <div class="col-md-6 form-group mb-3">
                                                <label>کارمزد سفارش خرید (%)</label>
                                                <input type="text" name="buy_order_fee" id="buy_order_fee"
                                                       class="form-control text-center ltr-dir"
                                                       placeholder="درصد کارمزد" value="{{$result->buy_order_fee ?? '0'}}"/>
                                            </div>
                                            <div class="col-md-6 form-group mb-3">
                                                <label>کارمزد سفارش فروش (%)</label>
                                                <input type="text" name="sell_order_fee" id="sell_order_fee"
                                                       class="form-control text-center ltr-dir"
                                                       placeholder="درصد کارمزد" value="{{$result->sell_order_fee ?? '0'}}"/>
                                            </div>
                                        </div>
                                    </div>

                                </div>
                            </div>

                        </div>
                        <div class="text-center">
                            <button type="submit" class="btn btn-primary btn-block btn" id="ScrollButton">ذخیره تنظیمات API</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
@stop

@section('script')
    <script>
        // Toggle password visibility
        function togglePassword(fieldId) {
            const field = document.getElementById(fieldId);
            const icon = field.nextElementSibling.querySelector('i');
            
            if (field.type === 'password') {
                field.type = 'text';
                icon.classList.remove('mdi-eye');
                icon.classList.add('mdi-eye-off');
            } else {
                field.type = 'password';
                icon.classList.remove('mdi-eye-off');
                icon.classList.add('mdi-eye');
            }
        }

        // Test Tetherland API connection
        function testTetherlandAPI() {
            const statusEl = document.getElementById('tetherland-status');
            const privateKey = document.getElementById('tetherland_private_key').value;
            const apiUrl = document.getElementById('tetherland_api_url').value;
            
            statusEl.innerHTML = '<span class="text-info"><i class="mdi mdi-loading mdi-spin"></i> در حال تست...</span>';
            
            // Prepare headers
            const headers = {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            };
            
            // Add private key to headers if provided
            if (privateKey && privateKey.trim() !== '') {
                headers['Authorization'] = 'Bearer ' + privateKey.trim();
                headers['X-API-Key'] = privateKey.trim();
                headers['Api-Key'] = privateKey.trim();
            }
            
            // Try GET request first
            fetch(apiUrl || 'https://service.tetherland.com/api/v5/user/converter/exchange', {
                method: 'GET',
                headers: headers,
                mode: 'cors'
            })
            .then(response => {
                if (!response.ok) {
                    // If GET fails with 401, try POST
                    if (response.status === 401 || response.status === 405) {
                        return fetch(apiUrl || 'https://service.tetherland.com/api/v5/user/converter/exchange', {
                            method: 'POST',
                            headers: headers,
                            body: JSON.stringify({}),
                            mode: 'cors'
                        });
                    } else if (response.status === 403) {
                        statusEl.innerHTML = '<span class="text-danger"><i class="mdi mdi-close-circle"></i> دسترسی رد شد - Private Key صحیح نیست یا منقضی شده</span>';
                        return null;
                    } else {
                        throw new Error('HTTP ' + response.status);
                    }
                }
                return response.json();
            })
            .then(data => {
                if (!data) return; // Already handled error
                
                if (data.status === true && data.data && data.data.coinPrice) {
                    const price = parseFloat(data.data.coinPrice).toLocaleString('fa-IR');
                    statusEl.innerHTML = `<span class="text-success"><i class="mdi mdi-check-circle"></i> موفق! قیمت فعلی USDT: ${price} تومان</span>`;
                } else if (data.status === false) {
                    statusEl.innerHTML = '<span class="text-warning"><i class="mdi mdi-alert"></i> پاسخ نامعتبر - بررسی کنید که Private Key صحیح باشد</span>';
                }
            })
            .catch(error => {
                // CORS or network error
                if (privateKey && privateKey.trim() !== '') {
                    statusEl.innerHTML = '<span class="text-info"><i class="mdi mdi-information"></i> تست از مرورگر ممکن نیست (CORS) - Private Key ذخیره می‌شود و در سمت سرور تست خواهد شد</span>';
                } else {
                    statusEl.innerHTML = '<span class="text-warning"><i class="mdi mdi-information"></i> تست از مرورگر ممکن نیست (CORS) - Private Key را وارد کنید و ذخیره کنید</span>';
                }
                console.log('Tetherland API test (CORS expected):', error.message);
            });
        }

        // Test Iranian Exchange API connection
        function testIranianExchangeAPI() {
            const statusEl = document.getElementById('iranian-exchange-status');
            const exchangeName = document.querySelector('select[name="iranian_exchange_name"]').value;
            
            statusEl.innerHTML = '<span class="text-info"><i class="mdi mdi-loading mdi-spin"></i> در حال تست...</span>';
            
            // API endpoints for different Iranian exchanges
            const apiEndpoints = {
                'nobitex': 'https://api.nobitex.ir/v2/orderbook/USDTIRT',
                'wallex': 'https://api.wallex.ir/v1/markets',
                'exnovin': 'https://api.exnovin.com/api/v1/market/stats',
                'ramzinex': 'https://publicapi.ramzinex.com/exchange/api/v1.0/exchange/pairs'
            };
            
            const endpoint = apiEndpoints[exchangeName];
            
            fetch(endpoint, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                // Parse price based on exchange
                let price = 0;
                if (exchangeName === 'nobitex' && data.lastTradePrice) {
                    price = parseFloat(data.lastTradePrice) / 10; // Nobitex returns in Rials
                } else if (exchangeName === 'wallex' && data.result && data.result.symbols) {
                    const usdtMarket = data.result.symbols['USDTTMN'];
                    price = usdtMarket ? parseFloat(usdtMarket.stats.lastPrice) : 0;
                }
                
                if (price > 0) {
                    const priceFormatted = price.toLocaleString('fa-IR');
                    statusEl.innerHTML = `<span class="text-success"><i class="mdi mdi-check-circle"></i> موفق! قیمت فعلی USDT: ${priceFormatted} تومان</span>`;
                } else {
                    statusEl.innerHTML = '<span class="text-success"><i class="mdi mdi-check-circle"></i> اتصال موفق - API در دسترس است</span>';
                }
            })
            .catch(error => {
                statusEl.innerHTML = '<span class="text-danger"><i class="mdi mdi-close-circle"></i> خطا در اتصال به صرافی</span>';
                console.error('Iranian Exchange API Error:', error);
            });
        }

        // Toggle settings based on USDT price source
        function toggleUSDTSettings() {
            const source = document.getElementById('usdt_price_source').value;
            const tetherlandSettings = document.getElementById('tetherland-settings');
            const iranianSettings = document.getElementById('iranian-exchange-settings');
            
            if (source === 'tetherland') {
                tetherlandSettings.style.display = 'block';
                iranianSettings.style.display = 'none';
            } else if (source === 'iranian_exchange') {
                tetherlandSettings.style.display = 'none';
                iranianSettings.style.display = 'block';
            } else {
                tetherlandSettings.style.display = 'none';
                iranianSettings.style.display = 'none';
            }
        }

        $(document).ready(function () {
            // Initialize USDT settings toggle
            toggleUSDTSettings();
            
            // Add event listener for source change
            $('#usdt_price_source').on('change', toggleUSDTSettings);
            
            $('form').ajaxForm({
                beforeSend: function () {
                    loading();
                },
                complete: function (data) {
                    data = data.responseJSON;
                    if (data.status == true) {
                        swal.fire({
                            icon: 'success',
                            title: "انجام شد",
                            html: data.message,
                            confirmButtonText: "تایید",
                        }).then(function () {
                            location.reload();
                        });
                    } else {
                        swal.fire({
                            icon: 'error',
                            title: "توجه",
                            html: data.message,
                            confirmButtonText: "تایید",
                        })
                    }
                    unloading();
                }
            });
        });
    </script>
@stop
