@extends('backoffice.layouts.app')
@section('title', 'Sistem Ayarlari')

@section('content')
<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-12">
            <h2 class="mb-1"><i class="bi bi-gear me-2"></i>Sistem Ayarları</h2>
        </div>
    </div>

    <ul class="nav nav-pills settings-tabs mb-4" id="settingsTabs" role="tablist">
        <li class="nav-item" role="presentation"><button class="nav-link active" id="tab-general-btn" data-bs-toggle="tab" data-bs-target="#tab-general" type="button" role="tab"><i class="bi bi-sliders2 me-2"></i>Genel</button></li>
        <li class="nav-item" role="presentation"><button class="nav-link" id="tab-security-btn" data-bs-toggle="tab" data-bs-target="#tab-security" type="button" role="tab"><i class="bi bi-shield-lock me-2"></i>Guvenlik</button></li>
        <li class="nav-item" role="presentation"><button class="nav-link" id="tab-coins-btn" data-bs-toggle="tab" data-bs-target="#tab-coins" type="button" role="tab"><i class="bi bi-currency-bitcoin me-2"></i>Kripto Coinler</button></li>
        <li class="nav-item" role="presentation"><button class="nav-link" id="tab-system-btn" data-bs-toggle="tab" data-bs-target="#tab-system" type="button" role="tab"><i class="bi bi-info-circle me-2"></i>Sistem</button></li>
    </ul>

    @php
        $notificationSound = $settings['notification_sound'] ?? 'enabled';
        $backoffice2fa = $settings['backoffice_2fa_enabled'] ?? 'enabled';
        $finance2fa = $settings['finance_2fa_enabled'] ?? 'enabled';
        $paymentDeposit = $settings['payment_deposit_enabled'] ?? 'enabled';
    @endphp

    <div class="tab-content">
        <div class="tab-pane fade show active" id="tab-general" role="tabpanel">
            <form id="settingsForm">
                <div class="row g-4">
                    <div class="col-xl-8">
                        <div class="card border-0 shadow-sm mb-4">
                            <div class="card-header bg-white border-bottom-0 pb-0"><h5 class="mb-0"><i class="bi bi-building me-2"></i>Genel Bilgiler</h5></div>
                            <div class="card-body"><div class="row g-3">
                                <div class="col-md-6"><label class="form-label">Site Adi <span class="text-danger">*</span></label><input type="text" name="site_name" class="form-control" value="{{ $settings['site_name'] ?? 'Finance Panel' }}" required></div>
                                <div class="col-md-6"><label class="form-label">Iletisim E-posta <span class="text-danger">*</span></label><input type="email" name="site_email" class="form-control" value="{{ $settings['site_email'] ?? 'info@financepanel.com' }}" required></div>
                                <div class="col-md-6"><label class="form-label">Sunucu Yenileme Tarihi</label><input type="text" class="form-control" value="10/06/2026" readonly><small class="text-muted">Yenileme tarihi salt okunur.</small></div>
                            </div></div>
                        </div>

                        <div class="card border-0 shadow-sm mb-4">
                            <div class="card-header bg-white border-bottom-0 pb-0"><h5 class="mb-0"><i class="bi bi-toggles2 me-2"></i>Ozellik Durumlari</h5></div>
                            <div class="card-body">
                                <div class="setting-toggle-row"><div><div class="fw-semibold">Bildirim Sesi</div><small class="text-muted">Yeni islem geldiginde ses bildirimi</small></div><div class="d-flex align-items-center gap-2"><span id="state_notification_sound" class="badge {{ $notificationSound === 'enabled' ? 'bg-success-subtle text-success-emphasis' : 'bg-secondary-subtle text-secondary-emphasis' }}">{{ $notificationSound === 'enabled' ? 'Aktif' : 'Pasif' }}</span><input type="hidden" name="notification_sound" id="setting_notification_sound" value="{{ $notificationSound }}"><div class="form-check form-switch setting-switch m-0"><input class="form-check-input setting-toggle" type="checkbox" data-hidden="#setting_notification_sound" data-state="#state_notification_sound" {{ $notificationSound === 'enabled' ? 'checked' : '' }}></div></div></div>
                                <div class="setting-toggle-row"><div><div class="fw-semibold">Backoffice 2FA</div><small class="text-muted">Pasif secilirse backoffice girisinde 2FA sorulmaz</small></div><div class="d-flex align-items-center gap-2"><span id="state_backoffice_2fa" class="badge {{ $backoffice2fa === 'enabled' ? 'bg-success-subtle text-success-emphasis' : 'bg-secondary-subtle text-secondary-emphasis' }}">{{ $backoffice2fa === 'enabled' ? 'Aktif' : 'Pasif' }}</span><input type="hidden" name="backoffice_2fa_enabled" id="setting_backoffice_2fa" value="{{ $backoffice2fa }}"><div class="form-check form-switch setting-switch m-0"><input class="form-check-input setting-toggle" type="checkbox" data-hidden="#setting_backoffice_2fa" data-state="#state_backoffice_2fa" {{ $backoffice2fa === 'enabled' ? 'checked' : '' }}></div></div></div>
                                <div class="setting-toggle-row"><div><div class="fw-semibold">Finans Panel 2FA</div><small class="text-muted">Pasif secilirse finans panel girisinde 2FA sorulmaz</small></div><div class="d-flex align-items-center gap-2"><span id="state_finance_2fa" class="badge {{ $finance2fa === 'enabled' ? 'bg-success-subtle text-success-emphasis' : 'bg-secondary-subtle text-secondary-emphasis' }}">{{ $finance2fa === 'enabled' ? 'Aktif' : 'Pasif' }}</span><input type="hidden" name="finance_2fa_enabled" id="setting_finance_2fa" value="{{ $finance2fa }}"><div class="form-check form-switch setting-switch m-0"><input class="form-check-input setting-toggle" type="checkbox" data-hidden="#setting_finance_2fa" data-state="#state_finance_2fa" {{ $finance2fa === 'enabled' ? 'checked' : '' }}></div></div></div>
                                <div class="setting-toggle-row mb-0 border-0 pb-0"><div><div class="fw-semibold">Payment Deposit</div><small class="text-muted">Pasif secilirse yatirim sayfasi bakim moduna alinir</small></div><div class="d-flex align-items-center gap-2"><span id="state_payment_deposit" class="badge {{ $paymentDeposit === 'enabled' ? 'bg-success-subtle text-success-emphasis' : 'bg-secondary-subtle text-secondary-emphasis' }}">{{ $paymentDeposit === 'enabled' ? 'Aktif' : 'Pasif' }}</span><input type="hidden" name="payment_deposit_enabled" id="setting_payment_deposit" value="{{ $paymentDeposit }}"><div class="form-check form-switch setting-switch m-0"><input class="form-check-input setting-toggle" type="checkbox" data-hidden="#setting_payment_deposit" data-state="#state_payment_deposit" {{ $paymentDeposit === 'enabled' ? 'checked' : '' }}></div></div></div>
                            </div>
                        </div>

                        <div class="card border-0 shadow-sm mb-0">
                            <div class="card-header bg-white border-bottom-0 pb-0"><h5 class="mb-0"><i class="bi bi-cash-stack me-2"></i>Islem Limitleri</h5></div>
                            <div class="card-body"><div class="row g-3">
                                <div class="col-md-6"><label class="form-label">Min Yatirim Tutari (TL)</label><input type="text" name="min_deposit_amount" class="form-control number-input" value="{{ number_format($settings['min_deposit_amount'] ?? 10, 0, ',', '.') }}"></div>
                                <div class="col-md-6"><label class="form-label">Max Yatirim Tutari (TL)</label><input type="text" name="max_deposit_amount" class="form-control number-input" value="{{ number_format($settings['max_deposit_amount'] ?? 1000000, 0, ',', '.') }}"></div>
                                <div class="col-md-6"><label class="form-label">Min Cekim Tutari (TL)</label><input type="text" name="min_withdrawal_amount" class="form-control number-input" value="{{ number_format($settings['min_withdrawal_amount'] ?? 10, 0, ',', '.') }}"></div>
                                <div class="col-md-6"><label class="form-label">Max Cekim Tutari (TL)</label><input type="text" name="max_withdrawal_amount" class="form-control number-input" value="{{ number_format($settings['max_withdrawal_amount'] ?? 1000000, 0, ',', '.') }}"></div>
                            </div></div>
                        </div>
                    </div>
                    <div class="col-xl-4">
                        <div class="card border-0 shadow-sm mb-4"><div class="card-header bg-white"><h5 class="mb-0"><i class="bi bi-lightning-charge me-2"></i>Hizli Bilgi</h5></div><div class="card-body"><p class="text-muted mb-3">Degisiklikler canli sistemi etkiler.</p><ul class="small text-muted mb-0"><li>2FA degisiklikleri aninda etkilenir.</li><li>Limitler yeni islemlerde uygulanir.</li><li>Kaydetmeden once degerleri kontrol edin.</li></ul></div></div>
                        <div class="card border-0 shadow-sm"><div class="card-header bg-white"><h5 class="mb-0"><i class="bi bi-save me-2"></i>Kayit</h5></div><div class="card-body d-grid"><button type="submit" class="btn btn-primary btn-lg"><i class="bi bi-check2-circle me-2"></i>Ayarlari Kaydet</button></div></div>
                    </div>
                </div>
            </form>
        </div>

        <div class="tab-pane fade" id="tab-security" role="tabpanel">
            <form id="securitySettingsForm">
                <div class="row g-4">
                    <div class="col-xl-8">
                        <div class="card border-0 shadow-sm mb-4"><div class="card-header bg-white border-bottom-0 pb-0"><h5 class="mb-0"><i class="bi bi-shield-lock me-2"></i>IP Guvenlik</h5></div><div class="card-body"><div class="mb-3"><label class="form-label">API IP Whitelist</label><textarea name="api_ip_whitelist" class="form-control" rows="4">{{ $settings['api_ip_whitelist'] ?? '' }}</textarea><small class="text-muted">API erisimine izin verilen IP adresleri (her satira bir IP)</small></div><div class="mb-0"><label class="form-label">Backoffice IP Whitelist</label><textarea name="backoffice_ip_whitelist" class="form-control" rows="4">{{ $settings['backoffice_ip_whitelist'] ?? '' }}</textarea><small class="text-muted">Backoffice erisimine izin verilen IP adresleri (her satira bir IP)</small></div></div></div>
                        <div class="card border-0 shadow-sm mb-0"><div class="card-header bg-white border-bottom-0 pb-0"><h5 class="mb-0"><i class="bi bi-shield-exclamation me-2"></i>Advanced Security</h5></div><div class="card-body"><p class="text-muted">Yetki/Kullanici ekranlarinda gizlenecek izin gruplarini yonetir.</p><button type="button" class="btn btn-outline-dark" id="openAdvancedSecurityBtn"><i class="bi bi-lock me-2"></i>Advanced Security Paneli</button></div></div>
                    </div>
                    <div class="col-xl-4"><div class="card border-0 shadow-sm"><div class="card-header bg-white"><h5 class="mb-0"><i class="bi bi-save me-2"></i>Kayit</h5></div><div class="card-body d-grid"><button type="submit" class="btn btn-primary btn-lg"><i class="bi bi-check2-circle me-2"></i>Guvenlik Ayarlarini Kaydet</button></div></div></div>
                </div>
            </form>
        </div>

        <div class="tab-pane fade" id="tab-coins" role="tabpanel">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="bi bi-currency-bitcoin me-2"></i>Kripto Coin Yonetimi</h5>
                    <button type="button" class="btn btn-primary btn-sm" id="addCoinBtn"><i class="bi bi-plus-circle me-1"></i>Coin Ekle</button>
                </div>
                <div class="card-body">
                    <p class="text-muted mb-3">Coin ekleme, duzenleme ve silme islemlerini bu sekmeden yonetin.</p>
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0" id="cryptoCoinsTable">
                            <thead class="table-light"><tr><th style="width:70px">#</th><th>Coin</th><th style="width:260px">Icon</th><th class="text-end" style="width:150px">Bagli Hesap</th><th style="width:160px">Olusturma</th><th class="text-end" style="width:170px">Islemler</th></tr></thead>
                            <tbody>
                                @forelse($cryptoCoins as $coin)
                                    @php
                                        $iconValue = trim((string) ($coin->icon ?? ''));
                                        if ($iconValue === '') { $iconUrl = null; }
                                        elseif (preg_match('/^https?:\/\//i', $iconValue)) { $iconUrl = $iconValue; }
                                        elseif (str_starts_with($iconValue, '/')) { $iconUrl = $iconValue; }
                                        elseif (!str_contains($iconValue, '/')) { $iconUrl = '/coins/' . ltrim($iconValue, '/'); }
                                        else { $iconUrl = '/' . ltrim($iconValue, '/'); }
                                    @endphp
                                    <tr id="coinRow_{{ $coin->id }}" data-id="{{ $coin->id }}" data-name="{{ $coin->name }}" data-icon="{{ $coin->icon }}" data-accounts="{{ (int) $coin->crypto_accounts_count }}" data-created="{{ optional($coin->created_at)->format('d.m.Y H:i') }}">
                                        <td class="fw-semibold">{{ $coin->id }}</td>
                                        <td><span class="fw-semibold">{{ $coin->name }}</span></td>
                                        <td>@if($iconUrl)<div class="coin-icon-wrap"><img src="{{ $iconUrl }}" alt="{{ $coin->name }}" class="coin-icon-thumb"><small class="text-muted">{{ $coin->icon }}</small></div>@else<span class="text-muted"><i class="bi bi-currency-bitcoin me-1"></i>Icon tanimli degil</span>@endif</td>
                                        <td class="text-end"><span class="badge {{ (int) $coin->crypto_accounts_count > 0 ? 'bg-warning-subtle text-warning-emphasis' : 'bg-secondary-subtle text-secondary-emphasis' }}">{{ (int) $coin->crypto_accounts_count }}</span></td>
                                        <td><small class="text-muted">{{ optional($coin->created_at)->format('d.m.Y H:i') }}</small></td>
                                        <td class="text-end"><div class="btn-group btn-group-sm"><button type="button" class="btn btn-outline-primary btn-edit-coin" data-id="{{ $coin->id }}"><i class="bi bi-pencil-square"></i></button><button type="button" class="btn btn-outline-danger btn-delete-coin" data-id="{{ $coin->id }}" {{ (int) $coin->crypto_accounts_count > 0 ? 'disabled' : '' }}><i class="bi bi-trash"></i></button></div></td>
                                    </tr>
                                @empty
                                    <tr id="coinEmptyRow"><td colspan="6" class="text-center py-4 text-muted">Kayitli coin bulunmuyor.</td></tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <div class="tab-pane fade" id="tab-system" role="tabpanel">
            <div class="row g-4">
                <div class="col-xl-6">
                    <div class="card border-0 shadow-sm h-100"><div class="card-header bg-white"><h5 class="mb-0"><i class="bi bi-info-square me-2"></i>Sistem Bilgileri</h5></div><div class="card-body"><div class="mb-3"><small class="text-muted">Laravel Versiyon</small><div class="fw-bold">{{ app()->version() }}</div></div><div class="mb-3"><small class="text-muted">PHP Versiyon</small><div class="fw-bold">{{ PHP_VERSION }}</div></div><div class="mb-3"><small class="text-muted">Timezone</small><div class="fw-bold">{{ config('app.timezone') }}</div></div><div class="mb-0"><small class="text-muted">Ortam</small><div class="fw-bold">@if(app()->environment('production'))<span class="badge bg-success">Production</span>@else<span class="badge bg-warning">{{ app()->environment() }}</span>@endif</div></div></div></div>
                </div>
                <div class="col-xl-6">
                    <div class="card border-0 shadow-sm h-100"><div class="card-header bg-white"><h5 class="mb-0"><i class="bi bi-calendar-event me-2"></i>Yenileme Bilgisi</h5></div><div class="card-body">
                        @php
                            $dueDate = \Carbon\Carbon::createFromFormat('d/m/Y', '10/06/2026')->startOfDay();
                            $now = now()->startOfDay();
                            if ($now->greaterThan($dueDate)) { $monthsLeft = 0; $daysLeft = 0; }
                            else { $monthsLeft = $now->diffInMonths($dueDate); $daysLeft = $now->copy()->addMonths($monthsLeft)->diffInDays($dueDate); }
                        @endphp
                        <div class="mb-2"><small class="text-muted">Kalan Sure</small><div class="fw-bold">{{ $monthsLeft }} ay {{ $daysLeft }} gun</div></div><div class="mb-0"><small class="text-muted">Yenileme Tarihi</small><div class="fw-bold">10/06/2026</div></div>
                    </div></div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="coinModal" tabindex="-1" aria-hidden="true"><div class="modal-dialog modal-dialog-centered"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="coinModalLabel"><i class="bi bi-currency-bitcoin me-2"></i>Coin Ekle</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><form id="coinForm"><div class="modal-body"><input type="hidden" id="coinId" value=""><div class="mb-3"><label class="form-label">Coin Adi <span class="text-danger">*</span></label><input type="text" class="form-control" id="coinName" maxlength="120" required></div><div class="mb-2"><label class="form-label">Icon (URL veya dosya adi)</label><input type="text" class="form-control" id="coinIcon" maxlength="255" placeholder="ornek: btc.png veya /coins/btc.png veya https://..."><small class="text-muted">Sadece dosya adi yazarsaniz sistem /coins/ klasorunu otomatik kullanir.</small></div><div class="coin-preview mt-3"><div class="coin-preview-icon" id="coinPreviewIcon"><i class="bi bi-currency-bitcoin"></i></div><div><div class="fw-semibold" id="coinPreviewName">Coin Onizleme</div><small class="text-muted" id="coinPreviewPath">Icon tanimli degil</small></div></div></div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Iptal</button><button type="submit" class="btn btn-primary" id="coinSubmitBtn"><i class="bi bi-check-circle me-1"></i>Kaydet</button></div></form></div></div></div>

    <div class="modal fade" id="advancedSecurityModal" tabindex="-1" aria-labelledby="advancedSecurityModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-scrollable"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="advancedSecurityModalLabel"><i class="bi bi-shield-lock me-2"></i>Advanced Security</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <form id="advancedSecurityForm">
                <div class="modal-body">
                    <div class="mb-3"><label class="form-label">Advanced Security Sifresi <span class="text-danger">*</span></label><div class="input-group"><input type="password" name="password" id="advancedSecurityPassword" class="form-control" required autocomplete="off"><button type="button" class="btn btn-outline-secondary" id="toggleAdvancedPassword"><i class="bi bi-eye"></i></button></div><small class="text-muted">Degisiklikleri kaydetmek icin sifre zorunludur.</small></div>
                    <ul class="nav nav-tabs mb-3" role="tablist"><li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#advancedPermissionsTab" type="button" role="tab">Backoffice Permissions</button></li><li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#advancedUsersTab" type="button" role="tab">Backoffice Users</button></li><li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#advancedHiddenModulesTab" type="button" role="tab">Hidden Modules</button></li></ul>
                    <div class="tab-content">
                        <div class="tab-pane fade show active" id="advancedPermissionsTab" role="tabpanel"><p class="text-muted small mb-2">Secilen gruplar <strong>Backoffice Yetkileri</strong> sayfasinda gizlenir.</p><div class="advanced-list">@foreach($permissionGroups as $group)<div class="form-check"><input class="form-check-input" type="checkbox" name="hidden_permission_group_ids[]" value="{{ $group->id }}" id="hiddenPermissionGroup{{ $group->id }}" {{ in_array((int) $group->id, $hiddenPermissionGroupIds, true) ? 'checked' : '' }}><label class="form-check-label" for="hiddenPermissionGroup{{ $group->id }}">{{ $group->name }} <small class="text-muted">#{{ $group->id }}</small></label></div>@endforeach</div></div>
                        <div class="tab-pane fade" id="advancedUsersTab" role="tabpanel"><p class="text-muted small mb-2">Secilen gruplar <strong>Backoffice Kullanicilari</strong> sayfasinda gizlenir.</p><div class="advanced-list">@foreach($permissionGroups as $group)<div class="form-check"><input class="form-check-input" type="checkbox" name="hidden_user_group_ids[]" value="{{ $group->id }}" id="hiddenUserGroup{{ $group->id }}" {{ in_array((int) $group->id, $hiddenUserGroupIds, true) ? 'checked' : '' }}><label class="form-check-label" for="hiddenUserGroup{{ $group->id }}">{{ $group->name }} <small class="text-muted">#{{ $group->id }}</small></label></div>@endforeach</div></div>
                        <div class="tab-pane fade" id="advancedHiddenModulesTab" role="tabpanel">
                            <p class="text-muted small mb-2">Buradaki moduller <strong>Backoffice Yetkileri</strong> ekraninda listelenmez. Sadece gizli gruplar icin yonetilir. Gizli grup listesini degistirirseniz bu sekme kaydetme sonrasi yenilenir.</p>
                            @if(empty($hiddenPermissionGroupIds))
                                <div class="alert alert-light border mb-0">Once <strong>Backoffice Permissions</strong> sekmesinden en az bir gizli grup secin.</div>
                            @elseif(empty($advancedHiddenModules))
                                <div class="alert alert-light border mb-0">Tanimli gizli modul bulunmuyor.</div>
                            @else
                                <div class="advanced-hidden-modules-list">
                                    @foreach($advancedHiddenModulePermissions as $groupId => $groupModules)
                                        @php
                                            $groupMeta = $permissionGroups->firstWhere('id', (int) $groupId);
                                        @endphp
                                        <div class="advanced-module-group-card">
                                            <div class="advanced-module-group-head">
                                                <div class="fw-semibold">{{ $groupMeta?->name ?? ('Grup #' . $groupId) }}</div>
                                                <small class="text-muted">#{{ $groupId }}</small>
                                            </div>
                                            <div class="table-responsive">
                                                <table class="table table-sm align-middle advanced-modules-table mb-0">
                                                    <thead>
                                                        <tr>
                                                            <th>Modul</th>
                                                            @foreach(($advancedHiddenModules[array_key_first($advancedHiddenModules)]['actions'] ?? []) as $actionKey => $actionLabel)
                                                                <th class="text-center">{{ $actionLabel }}</th>
                                                            @endforeach
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        @foreach($advancedHiddenModules as $moduleKey => $moduleMeta)
                                                            <tr>
                                                                <td>
                                                                    <div class="fw-semibold">{{ $moduleMeta['label'] }}</div>
                                                                    @if(!empty($moduleMeta['description']))
                                                                        <small class="text-muted">{{ $moduleMeta['description'] }}</small>
                                                                    @endif
                                                                </td>
                                                                @foreach($moduleMeta['actions'] as $actionKey => $actionLabel)
                                                                    <td class="text-center">
                                                                        <input
                                                                            type="checkbox"
                                                                            class="form-check-input"
                                                                            name="hidden_module_permissions[{{ $groupId }}][{{ $moduleKey }}][{{ $actionKey }}]"
                                                                            value="1"
                                                                            {{ !empty($groupModules[$moduleKey][$actionKey]) ? 'checked' : '' }}
                                                                        >
                                                                    </td>
                                                                @endforeach
                                                            </tr>
                                                        @endforeach
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    @endforeach
                                </div>
                            @endif
                        </div>
                    </div>
                </div>
                <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Iptal</button><button type="submit" class="btn btn-dark"><i class="bi bi-check-circle me-2"></i>Kaydet</button></div>
            </form>
        </div></div>
    </div>
</div>
@endsection

@push('styles')
<style>
    .settings-tabs { gap:.5rem; flex-wrap:wrap; }
    .settings-tabs .nav-link { border-radius:999px; padding:.55rem 1rem; font-weight:600; color:#475569; background:#f8fafc; border:1px solid #e2e8f0; }
    .settings-tabs .nav-link.active { background:#0d6efd; color:#fff; border-color:#0d6efd; }
    .setting-toggle-row { display:flex; align-items:center; justify-content:space-between; gap:14px; padding:12px 0; border-bottom:1px dashed #e5e7eb; }
    .setting-switch .form-check-input { width:3rem; height:1.55rem; cursor:pointer; }
    .setting-switch .form-check-input:checked { background-color:#198754; border-color:#198754; }
    .advanced-list { max-height:320px; overflow:auto; border:1px solid #e5e7eb; border-radius:10px; padding:.75rem; background:#fff; }
    .advanced-list .form-check { padding:.35rem 0 .35rem 1.75rem; border-bottom:1px dashed #f1f5f9; }
    .advanced-list .form-check:last-child { border-bottom:0; }
    .advanced-hidden-modules-list { display:grid; gap:1rem; }
    .advanced-module-group-card { border:1px solid #e5e7eb; border-radius:12px; background:#fff; overflow:hidden; }
    .advanced-module-group-head { display:flex; align-items:center; justify-content:space-between; gap:.75rem; padding:.85rem 1rem; border-bottom:1px solid #eef2f7; background:#f8fafc; }
    .advanced-modules-table th { font-size:.8rem; text-transform:uppercase; letter-spacing:.03em; color:#64748b; background:#fff; }
    .advanced-modules-table td, .advanced-modules-table th { padding:.75rem 1rem; }
    .advanced-modules-table tbody tr:last-child td { border-bottom:0; }
    .advanced-modules-table .form-check-input { cursor:pointer; }
    .coin-icon-wrap { display:flex; align-items:center; gap:.6rem; }
    .coin-icon-thumb { width:26px; height:26px; border-radius:50%; object-fit:cover; border:1px solid #e5e7eb; background:#fff; flex-shrink:0; }
    .coin-preview { display:flex; align-items:center; gap:.75rem; padding:.6rem; border:1px dashed #dbeafe; border-radius:10px; background:#f8fbff; }
    .coin-preview-icon { width:38px; height:38px; border-radius:999px; border:1px solid #dbeafe; background:#fff; display:inline-flex; align-items:center; justify-content:center; overflow:hidden; flex-shrink:0; }
    .coin-preview-icon img { width:100%; height:100%; object-fit:cover; }
    @media (max-width:767.98px) { .setting-toggle-row { align-items:flex-start; flex-direction:column; } }
</style>
@endpush

@push('scripts')
<script>
$(function() {
    const csrfToken = '{{ csrf_token() }}';
    const coinEndpoint = '{{ url('/backoffice/settings/crypto-coins') }}';
    const settingsUpdateUrl = '{{ route("backoffice.settings.update") }}';
    const advVerifyUrl = '{{ route("backoffice.settings.advanced-security.verify") }}';
    const advUpdateUrl = '{{ route("backoffice.settings.advanced-security.update") }}';

    const esc = (v) => $('<div>').text(v == null ? '' : String(v)).html();
    const iconUrl = (v) => {
        v = String(v || '').trim();
        if (!v) return null;
        if (/^https?:\/\//i.test(v)) return v;
        if (v.startsWith('/')) return v;
        if (v.indexOf('/') === -1) return '/coins/' + v.replace(/^\/+/, '');
        return '/' + v.replace(/^\/+/, '');
    };
    const errList = (errors) => {
        let s = '<ul class="text-start">';
        Object.keys(errors).forEach((k) => { s += '<li>' + errors[k][0] + '</li>'; });
        return s + '</ul>';
    };

    $('.setting-toggle').each(function() { syncToggleState($(this)); }).on('change', function() { syncToggleState($(this)); });
    function syncToggleState($t) {
        const en = $t.is(':checked');
        const h = $($t.data('hidden'));
        const st = $($t.data('state'));
        h.val(en ? 'enabled' : 'disabled');
        st.text(en ? 'Aktif' : 'Pasif')
            .removeClass('bg-success-subtle text-success-emphasis bg-secondary-subtle text-secondary-emphasis')
            .addClass(en ? 'bg-success-subtle text-success-emphasis' : 'bg-secondary-subtle text-secondary-emphasis');
    }

    $('#settingsForm').on('submit', function(e) { e.preventDefault(); sendSettings($(this)); });
    $('#securitySettingsForm').on('submit', function(e) {
        e.preventDefault();
        const merged = {};
        $('#settingsForm').serializeArray().concat($(this).serializeArray()).forEach((f) => { merged[f.name] = f.value; });
        const payload = {
            _token: csrfToken,
            site_name: merged.site_name,
            site_email: merged.site_email,
            notification_sound: merged.notification_sound,
            backoffice_2fa_enabled: merged.backoffice_2fa_enabled,
            finance_2fa_enabled: merged.finance_2fa_enabled,
            payment_deposit_enabled: merged.payment_deposit_enabled,
            min_deposit_amount: parseFormattedNumber(merged.min_deposit_amount),
            max_deposit_amount: parseFormattedNumber(merged.max_deposit_amount),
            min_withdrawal_amount: parseFormattedNumber(merged.min_withdrawal_amount),
            max_withdrawal_amount: parseFormattedNumber(merged.max_withdrawal_amount),
            api_ip_whitelist: merged.api_ip_whitelist,
            backoffice_ip_whitelist: merged.backoffice_ip_whitelist
        };
        postSettings(payload);
    });
    function sendSettings($f) {
        const p = { _token: csrfToken };
        $f.serializeArray().forEach((f) => { p[f.name] = f.name.includes('amount') ? parseFormattedNumber(f.value) : f.value; });
        postSettings(p);
    }
    function postSettings(payload) {
        $.ajax({
            url: settingsUpdateUrl,
            method: 'POST',
            data: payload,
            success: (r) => Swal.fire('Basarili!', r.message, 'success'),
            error: (x) => {
                if (x.status === 422 && x.responseJSON && x.responseJSON.errors) return Swal.fire('Dogrulama Hatasi!', errList(x.responseJSON.errors), 'error');
                Swal.fire('Hata!', x.responseJSON?.message || 'Bir hata olustu', 'error');
            }
        });
    }

    function previewCoin() {
        const n = String($('#coinName').val() || '').trim() || 'Coin Onizleme';
        const r = String($('#coinIcon').val() || '').trim();
        const u = iconUrl(r);
        $('#coinPreviewName').text(n);
        $('#coinPreviewPath').text(r || 'Icon tanimli degil');
        $('#coinPreviewIcon').html(u ? '<img src="' + esc(u) + '" alt="' + esc(n) + '">' : '<i class="bi bi-currency-bitcoin"></i>');
    }
    function rowHtml(c) {
        const id = Number(c.id);
        const name = String(c.name || '');
        const raw = String(c.icon || '');
        const url = iconUrl(raw);
        const cnt = Number(c.crypto_accounts_count || 0);
        const created = String(c.created_at || '-');
        const iconCell = url
            ? '<div class="coin-icon-wrap"><img class="coin-icon-thumb" src="' + esc(url) + '" alt="' + esc(name) + '"><small class="text-muted">' + esc(raw) + '</small></div>'
            : '<span class="text-muted"><i class="bi bi-currency-bitcoin me-1"></i>Icon tanimli degil</span>';
        const badgeClass = cnt > 0 ? 'bg-warning-subtle text-warning-emphasis' : 'bg-secondary-subtle text-secondary-emphasis';
        const delDisabled = cnt > 0 ? 'disabled' : '';
        return '<tr id="coinRow_' + id + '" data-id="' + id + '" data-name="' + esc(name) + '" data-icon="' + esc(raw) + '" data-accounts="' + cnt + '" data-created="' + esc(created) + '">' +
            '<td class="fw-semibold">' + id + '</td><td><span class="fw-semibold">' + esc(name) + '</span></td><td>' + iconCell + '</td>' +
            '<td class="text-end"><span class="badge ' + badgeClass + '">' + cnt + '</span></td><td><small class="text-muted">' + esc(created) + '</small></td>' +
            '<td class="text-end"><div class="btn-group btn-group-sm"><button type="button" class="btn btn-outline-primary btn-edit-coin" data-id="' + id + '"><i class="bi bi-pencil-square"></i></button><button type="button" class="btn btn-outline-danger btn-delete-coin" data-id="' + id + '" ' + delDisabled + '><i class="bi bi-trash"></i></button></div></td></tr>';
    }
    function upsert(c) {
        $('#coinEmptyRow').remove();
        const $r = $('#coinRow_' + c.id);
        if ($r.length) $r.replaceWith(rowHtml(c));
        else $('#cryptoCoinsTable tbody').prepend(rowHtml(c));
    }
    function openCoin(mode, data) {
        const edit = mode === 'edit';
        $('#coinId').val(edit ? data.id : '');
        $('#coinName').val(edit ? data.name : '');
        $('#coinIcon').val(edit ? data.icon : '');
        $('#coinModalLabel').html(edit ? '<i class="bi bi-pencil-square me-2"></i>Coin Duzenle' : '<i class="bi bi-currency-bitcoin me-2"></i>Coin Ekle');
        $('#coinSubmitBtn').html(edit ? '<i class="bi bi-check-circle me-1"></i>Guncelle' : '<i class="bi bi-check-circle me-1"></i>Kaydet');
        previewCoin();
        $('#coinModal').modal('show');
    }

    $('#addCoinBtn').on('click', () => openCoin('create', {}));
    $(document).on('click', '.btn-edit-coin', function() {
        const id = Number($(this).data('id'));
        const $r = $('#coinRow_' + id);
        if (!$r.length) return;
        openCoin('edit', { id, name: String($r.data('name') || ''), icon: String($r.data('icon') || '') });
    });
    $('#coinName, #coinIcon').on('input', previewCoin);

    $('#coinForm').on('submit', function(e) {
        e.preventDefault();
        const id = Number($('#coinId').val() || 0);
        const payload = { _token: csrfToken, name: String($('#coinName').val() || '').trim(), icon: String($('#coinIcon').val() || '').trim() };
        if (id > 0) payload._method = 'PUT';
        $.ajax({
            url: id > 0 ? (coinEndpoint + '/' + id) : coinEndpoint,
            method: 'POST',
            data: payload,
            success: (r) => {
                if (!r?.success) return Swal.fire('Hata!', 'Beklenmeyen cevap alindi.', 'error');
                if (r.coin) upsert(r.coin);
                Swal.fire('Basarili!', r.message, 'success');
                $('#coinModal').modal('hide');
            },
            error: (x) => {
                if (x.status === 422 && x.responseJSON?.errors) return Swal.fire('Dogrulama Hatasi!', errList(x.responseJSON.errors), 'error');
                Swal.fire('Hata!', x.responseJSON?.message || 'Islem basarisiz.', 'error');
            }
        });
    });

    $(document).on('click', '.btn-delete-coin', function() {
        const id = Number($(this).data('id'));
        const $r = $('#coinRow_' + id);
        if (!$r.length) return;
        const name = String($r.data('name') || 'Coin');
        const cnt = Number($r.data('accounts') || 0);
        if (cnt > 0) return Swal.fire('Uyari!', 'Bu coin aktif kripto hesaplarda kullanildigi icin silinemez.', 'warning');

        Swal.fire({
            title: 'Coin silinsin mi?',
            text: name + ' kaydi kalici olarak silinecek.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Evet, sil',
            cancelButtonText: 'Iptal'
        }).then((res) => {
            if (!res.isConfirmed) return;
            $.ajax({
                url: coinEndpoint + '/' + id,
                method: 'POST',
                data: { _token: csrfToken, _method: 'DELETE' },
                success: (r) => {
                    if (!r?.success) return Swal.fire('Hata!', 'Beklenmeyen cevap alindi.', 'error');
                    $r.remove();
                    if (!$('#cryptoCoinsTable tbody tr').length) $('#cryptoCoinsTable tbody').append('<tr id="coinEmptyRow"><td colspan="6" class="text-center py-4 text-muted">Kayitli coin bulunmuyor.</td></tr>');
                    Swal.fire('Basarili!', r.message, 'success');
                },
                error: (x) => Swal.fire('Hata!', x.responseJSON?.message || 'Silme islemi basarisiz.', 'error')
            });
        });
    });

    $('#toggleAdvancedPassword').on('click', function() {
        const $p = $('#advancedSecurityPassword');
        const isPwd = $p.attr('type') === 'password';
        $p.attr('type', isPwd ? 'text' : 'password');
        $(this).find('i').toggleClass('bi-eye bi-eye-slash');
    });

    $('#advancedSecurityModal').on('hidden.bs.modal', function() {
        $('#advancedSecurityPassword').val('').attr('type', 'password');
        $('#toggleAdvancedPassword i').removeClass('bi-eye-slash').addClass('bi-eye');
    });

    $('#openAdvancedSecurityBtn').on('click', function() {
        Swal.fire({
            title: 'Advanced Security Password',
            input: 'password',
            inputLabel: 'Sifreyi girin',
            inputPlaceholder: '********',
            inputAttributes: { autocapitalize: 'off', autocorrect: 'off', autocomplete: 'off' },
            showCancelButton: true,
            confirmButtonText: 'Dogrula',
            cancelButtonText: 'Iptal',
            inputValidator: (v) => !v ? 'Sifre zorunludur.' : null
        }).then((res) => {
            if (!res.isConfirmed || !res.value) return;
            $.ajax({
                url: advVerifyUrl,
                method: 'POST',
                data: { _token: csrfToken, password: res.value },
                success: () => { $('#advancedSecurityPassword').val(res.value); $('#advancedSecurityModal').modal('show'); },
                error: (x) => Swal.fire('Hata!', x.responseJSON?.message || 'Sifre dogrulanamadi.', 'error')
            });
        });
    });

    $('#advancedSecurityForm').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url: advUpdateUrl,
            method: 'POST',
            data: $(this).serialize() + '&_token=' + encodeURIComponent(csrfToken),
            success: (r) => { Swal.fire('Basarili!', r.message, 'success'); $('#advancedSecurityModal').modal('hide'); },
            error: (x) => {
                if (x.status === 422 && x.responseJSON?.errors) return Swal.fire('Dogrulama Hatasi!', errList(x.responseJSON.errors), 'error');
                Swal.fire('Hata!', x.responseJSON?.message || 'Bir hata olustu', 'error');
            }
        });
    });

    const tabKey = 'backofficeSettingsActiveTab';
    const savedTab = localStorage.getItem(tabKey);
    if (savedTab) {
        const el = document.querySelector(savedTab);
        if (el) new bootstrap.Tab(el).show();
    }
    document.querySelectorAll('#settingsTabs button[data-bs-toggle="tab"]').forEach((el) => {
        el.addEventListener('shown.bs.tab', (e) => localStorage.setItem(tabKey, '#' + e.target.id));
    });
});
</script>
@endpush
