@extends('layouts.app')

@section('title', 'Company Settings')
@section('page-title', 'Company Settings')
@section('page-subtitle', 'Profile, notifications, WhatsApp, payment gateway, and member website')

@section('content')
@php
    $tenantPortalUrl = route('public.tenant.show', ['tenant' => $tenant->slug]);
    $setting = fn (string $key, mixed $default = null) => old($key, $tenant->settings[$key] ?? $default);
    $platformMailSettings = $platformMailSettings ?? app(\App\Services\PlatformSettings::class)->platformMailSettings();
    $platformSmsSettings = $platformSmsSettings ?? app(\App\Services\PlatformSettings::class)->platformSmsSettings();
    $platformWhatsappSettings = $platformWhatsappSettings ?? app(\App\Services\PlatformSettings::class)->platformWhatsappSettings();
    $platformBillPaymentSettings = $platformBillPaymentSettings ?? app(\App\Services\PlatformSettings::class)->billPaymentSettings();
    $platformBillPaymentConfigured = $platformBillPaymentConfigured ?? app(\App\Services\PlatformSettings::class)->billPaymentConfigured();
    $tenantUsesPlatformMail = filter_var(old('mail_use_platform_defaults', $tenantUsesPlatformMail ?? ($tenant->settings['mail_use_platform_defaults'] ?? true)), FILTER_VALIDATE_BOOLEAN);
    $tenantUsesPlatformSms = filter_var(old('sms_use_platform_defaults', $tenantUsesPlatformSms ?? ($tenant->settings['sms_use_platform_defaults'] ?? true)), FILTER_VALIDATE_BOOLEAN);
    $tenantUsesPlatformWhatsapp = filter_var(old('whatsapp_use_platform_defaults', $tenantUsesPlatformWhatsapp ?? ($tenant->settings['whatsapp_use_platform_defaults'] ?? true)), FILTER_VALIDATE_BOOLEAN);
    $isSuperAdminTenantPortal = session()->has('impersonating_super_admin_id') && filter_var(session('can_manage_tenant_communication_gateways'), FILTER_VALIDATE_BOOLEAN);
    $mailSetting = fn (string $key, mixed $default = null) => old($key, $tenant->settings[$key] ?? ($platformMailSettings[$key] ?? $default));
    $smsSetting = fn (string $key, mixed $default = null) => old($key, $tenant->settings[$key] ?? ($platformSmsSettings[$key] ?? $default));
    $whatsappSetting = fn (string $key, mixed $default = null) => old($key, $tenant->settings[$key] ?? ($platformWhatsappSettings[$key] ?? $default));
    $currencies = [
        'NGN' => 'Nigerian Naira (NGN)',
        'GHS' => 'Ghanaian Cedi (GHS)',
        'KES' => 'Kenyan Shilling (KES)',
        'UGX' => 'Ugandan Shilling (UGX)',
        'TZS' => 'Tanzanian Shilling (TZS)',
        'ZAR' => 'South African Rand (ZAR)',
        'XOF' => 'West African CFA Franc (XOF)',
        'XAF' => 'Central African CFA Franc (XAF)',
        'USD' => 'US Dollar (USD)',
        'GBP' => 'British Pound (GBP)',
        'EUR' => 'Euro (EUR)',
    ];
    $automationCatalog = \App\Services\MemberNotificationAutomationService::catalog();
    $automationChannels = \App\Services\MemberNotificationAutomationService::channels();
    $automationPlaceholders = \App\Services\MemberNotificationAutomationService::placeholders();
    $automationSettings = old('member_notification_automations', $tenant->settings['member_notification_automations'] ?? \App\Services\MemberNotificationAutomationService::defaultSettings());
    $billPaymentServiceTypes = \App\Services\BillPaymentService::serviceTypes();
@endphp

<section class="section-hero mb-4">
    <div class="section-hero-copy">
        <span>Company setup</span>
        <h2>Settings workspace</h2>
        <p>Manage branding, currency, member account numbers, KYC, notifications, payment gateway, and public portal links from a clearer tabbed screen.</p>
    </div>
    <div class="section-hero-panel">
        <span>Member website</span>
        <strong>{{ $tenant->slug }}</strong>
        <small>{{ $tenantPortalUrl }}</small>
    </div>
</section>

<div class="section-stat-grid mb-4">
    <div class="section-stat-card">
        <i class="bi bi-building"></i>
        <span>Company</span>
        <strong>{{ $tenant->name }}</strong>
        <small>{{ $tenant->phone ?: 'No phone saved' }}</small>
    </div>
    <div class="section-stat-card">
        <i class="bi bi-currency-exchange"></i>
        <span>Currency</span>
        <strong>{{ $setting('currency', 'NGN') }}</strong>
        <small>Default transaction currency</small>
    </div>
    <div class="section-stat-card">
        <i class="bi bi-shield-check"></i>
        <span>KYC</span>
        <strong>{{ ucfirst($setting('kyc_provider', 'local')) }}</strong>
        <small>Verification provider</small>
    </div>
    <div class="section-stat-card">
        <i class="bi bi-credit-card"></i>
        <span>Payments</span>
        <strong>{{ ucfirst(str_replace('_', ' ', $setting('payment_gateway_provider', 'none'))) }}</strong>
        <small>Tenant preferred gateway</small>
    </div>
</div>

<form method="POST" action="{{ route('tenant.settings.update') }}" enctype="multipart/form-data" class="settings-form-shell">
    @csrf

    <div class="section-workspace settings-workspace">
        <div class="section-tabbar">
            <ul class="nav section-tabs" id="tenantSettingsTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="company-tab" data-bs-toggle="tab" data-bs-target="#company-pane" type="button" role="tab" aria-controls="company-pane" aria-selected="true">
                        <i class="bi bi-building me-1"></i> Company
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="account-numbers-tab" data-bs-toggle="tab" data-bs-target="#account-numbers-pane" type="button" role="tab" aria-controls="account-numbers-pane" aria-selected="false">
                        <i class="bi bi-123 me-1"></i> Account Numbers
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="kyc-provider-tab" data-bs-toggle="tab" data-bs-target="#kyc-provider-pane" type="button" role="tab" aria-controls="kyc-provider-pane" aria-selected="false">
                        <i class="bi bi-shield-check me-1"></i> KYC
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="approval-tab" data-bs-toggle="tab" data-bs-target="#approval-pane" type="button" role="tab" aria-controls="approval-pane" aria-selected="false">
                        <i class="bi bi-check2-square me-1"></i> Approvals
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="email-tab" data-bs-toggle="tab" data-bs-target="#email-pane" type="button" role="tab" aria-controls="email-pane" aria-selected="false">
                        <i class="bi bi-envelope me-1"></i> Email
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="sms-tab" data-bs-toggle="tab" data-bs-target="#sms-pane" type="button" role="tab" aria-controls="sms-pane" aria-selected="false">
                        <i class="bi bi-phone me-1"></i> SMS
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="whatsapp-tab" data-bs-toggle="tab" data-bs-target="#whatsapp-pane" type="button" role="tab" aria-controls="whatsapp-pane" aria-selected="false">
                        <i class="bi bi-whatsapp me-1"></i> WhatsApp
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="automation-tab" data-bs-toggle="tab" data-bs-target="#automation-pane" type="button" role="tab" aria-controls="automation-pane" aria-selected="false">
                        <i class="bi bi-broadcast me-1"></i> Automation
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="payment-tab" data-bs-toggle="tab" data-bs-target="#payment-pane" type="button" role="tab" aria-controls="payment-pane" aria-selected="false">
                        <i class="bi bi-credit-card me-1"></i> Payment Gateway
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="bill-payment-tab" data-bs-toggle="tab" data-bs-target="#bill-payment-pane" type="button" role="tab" aria-controls="bill-payment-pane" aria-selected="false">
                        <i class="bi bi-phone-vibrate me-1"></i> Bill Payments
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="portal-tab" data-bs-toggle="tab" data-bs-target="#portal-pane" type="button" role="tab" aria-controls="portal-pane" aria-selected="false">
                        <i class="bi bi-link-45deg me-1"></i> Portal
                    </button>
                </li>
            </ul>
        </div>

        <div class="settings-tab-body">
            <div class="tab-content" id="tenantSettingsTabsContent">
                <div class="tab-pane fade show active" id="company-pane" role="tabpanel" aria-labelledby="company-tab" tabindex="0">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Company name</label>
                            <input name="name" value="{{ old('name', $tenant->name) }}" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Phone</label>
                            <input name="phone" value="{{ old('phone', $tenant->phone) }}" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Public WhatsApp number</label>
                            <input name="public_whatsapp_number" value="{{ $setting('public_whatsapp_number', $tenant->phone) }}" class="form-control" placeholder="Example: 08012345678 or 2348012345678">
                            <div class="form-text">Leave empty to use the company phone. Nigerian local numbers are converted to 234 format for WhatsApp links.</div>
                        </div>
                        <div class="col-12">
                            <label class="form-label">Address</label>
                            <textarea name="address" class="form-control">{{ old('address', $tenant->address) }}</textarea>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Brand color</label>
                            <input name="primary_color" type="color" value="{{ old('primary_color', $tenant->primary_color) }}" class="form-control form-control-color">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Currency</label>
                            <select name="currency" class="form-select" required>
                                @foreach($currencies as $code => $label)
                                    <option value="{{ $code }}" @selected($setting('currency', 'NGN') === $code)>{{ $label }}</option>
                                @endforeach
                            </select>
                            <div class="form-text">Naira is the default for new tenants.</div>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Logo</label>
                            <input name="logo" type="file" class="form-control" accept="image/*">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Default interest %</label>
                            <input name="interest_rate" type="number" step="0.01" value="{{ $setting('interest_rate', 5) }}" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Default penalty %</label>
                            <input name="penalty_rate" type="number" step="0.01" value="{{ $setting('penalty_rate', 1) }}" class="form-control" required>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="account-numbers-pane" role="tabpanel" aria-labelledby="account-numbers-tab" tabindex="0">
                    <div class="row g-3">
                        <div class="col-12">
                            <h2 class="h5 mb-1">Member Account Numbers</h2>
                            <div class="text-muted small">Choose how new member 10-digit account numbers should be generated. Existing member numbers are not changed.</div>
                        </div>
                        <div class="col-lg-4">
                            <label class="form-label">Generation mode</label>
                            <select name="account_number_mode" class="form-select" data-account-number-mode>
                                <option value="random" @selected($setting('account_number_mode', 'random') === 'random')>Random 10 digits</option>
                                <option value="prefix_random" @selected($setting('account_number_mode', 'random') === 'prefix_random')>Random with starting digits</option>
                            </select>
                        </div>
                        <div class="col-lg-8">
                            <div class="p-3 rounded border bg-light h-100">
                                <div class="fw-semibold mb-1">How this affects new members</div>
                                <div class="small text-muted">Random mode hides member volume. Starting digits let a tenant request numbers like 2xxxxxxxxx, 5xxxxxxxxx, or 7xxxxxxxxx while the system still checks global uniqueness.</div>
                            </div>
                        </div>
                        <div class="col-lg-6" data-account-number-prefix-settings>
                            <label class="form-label">Allowed first digits</label>
                            <input name="account_number_prefixes" value="{{ $setting('account_number_prefixes') }}" class="form-control" placeholder="Example: 2 or 2,5,7">
                            <div class="form-text">Use digits separated by commas. Example: 2,5,7 generates numbers like 2381947206, 5810264492, or 7290051834.</div>
                        </div>
                        <div class="col-lg-6" data-account-number-prefix-settings>
                            <label class="form-label">Prefix example</label>
                            <div class="form-control bg-light">2xxxxxxxxx, 5xxxxxxxxx, 7xxxxxxxxx</div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="kyc-provider-pane" role="tabpanel" aria-labelledby="kyc-provider-tab" tabindex="0">
                    <div class="row g-3">
                        <div class="col-12">
                            <h2 class="h5 mb-1">KYC Verification</h2>
                            <div class="text-muted small">Choose how member identity verification should run. Local mode keeps the existing profile plus 11-digit BVN/NIN check. Didit creates hosted KYC links and locks verified identity fields after approval.</div>
                        </div>
                        <div class="col-lg-4">
                            <label class="form-label">KYC provider</label>
                            <select name="kyc_provider" class="form-select" data-kyc-provider>
                                <option value="local" @selected($setting('kyc_provider', 'local') === 'local')>Local auto check</option>
                                <option value="didit" @selected($setting('kyc_provider', 'local') === 'didit')>Didit hosted KYC</option>
                            </select>
                        </div>
                        <div class="col-lg-8">
                            <div class="p-3 rounded border bg-light h-100">
                                <div class="fw-semibold mb-1">Recommended for production</div>
                                <div class="small text-muted">Use Didit for hosted document, liveness, and workflow-based identity checks. Keep local mode while testing or when external KYC credentials are not available.</div>
                            </div>
                        </div>
                        <div class="col-12" data-kyc-provider-settings="didit">
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <label class="form-label">Didit API key</label>
                                    <input name="didit_api_key" type="password" value="{{ $setting('didit_api_key') }}" class="form-control" autocomplete="new-password">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Didit KYC workflow ID</label>
                                    <input name="didit_workflow_id" value="{{ $setting('didit_workflow_id') }}" class="form-control" placeholder="Workflow ID from Didit console">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Didit base URL</label>
                                    <input name="didit_base_url" value="{{ $setting('didit_base_url', 'https://verification.didit.me') }}" class="form-control">
                                </div>
                                <div class="col-12">
                                    <div class="alert alert-info mb-0 small">Didit hosted sessions redirect members back to the member portal after completion. Final approval still depends on the Didit workflow status returned by the provider.</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="approval-pane" role="tabpanel" aria-labelledby="approval-tab" tabindex="0">
                    <div class="settings-pane-intro mb-3">
                        <div>
                            <h2 class="h5 mb-1">Transaction Approval Rules</h2>
                            <p class="text-muted mb-0">Approvals are enabled by default. Turn any item off when this company wants transactions to post directly without an approval queue.</p>
                        </div>
                    </div>
                    <div class="row g-3">
                        @foreach([
                            'deposit' => ['Savings deposits', 'Deposits update savings balances only after approval.'],
                            'withdrawal' => ['Savings withdrawals', 'Withdrawals reduce balances only after approval.'],
                            'repayment' => ['Loan repayments', 'Repayments update loan schedules, balances, receipts, and accounting only after approval.'],
                            'transfer' => ['Member transfers', 'Internal and bank transfers post only after approval.'],
                        ] as $approvalKey => [$approvalLabel, $approvalDescription])
                            @php
                                $approvalField = $approvalKey.'_approval_required';
                                $approvalEnabled = filter_var($setting($approvalField, true), FILTER_VALIDATE_BOOLEAN);
                            @endphp
                            <div class="col-lg-3">
                                <div class="approval-setting-card">
                                    <div>
                                        <strong>{{ $approvalLabel }}</strong>
                                        <span>{{ $approvalDescription }}</span>
                                    </div>
                                    <div class="form-check form-switch mb-0">
                                        <input type="hidden" name="{{ $approvalField }}" value="0">
                                        <input class="form-check-input" type="checkbox" role="switch" name="{{ $approvalField }}" value="1" @checked($approvalEnabled)>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>
                    <div class="alert alert-warning small mt-3 mb-0">
                        If approval is turned off, new transactions post immediately. Existing pending transactions should still be reviewed before changing the rule.
                    </div>
                </div>

                <div class="tab-pane fade" id="email-pane" role="tabpanel" aria-labelledby="email-tab" tabindex="0">
                    <div class="d-flex justify-content-between align-items-start gap-3 mb-3">
                        <div>
                            <h2 class="h5 mb-1">Email Setup</h2>
                            <div class="text-muted small">Tenants use the Super Admin email setup by default. Turn this off only when this company wants its own SMTP account.</div>
                        </div>
                        <div class="form-check form-switch">
                            <input type="hidden" name="mail_use_platform_defaults" value="0">
                            <input class="form-check-input" type="checkbox" role="switch" name="mail_use_platform_defaults" value="1" id="mail_use_platform_defaults" @checked($tenantUsesPlatformMail)>
                            <label class="form-check-label fw-semibold" for="mail_use_platform_defaults">Use platform email</label>
                        </div>
                    </div>
                    <div class="alert alert-info small">
                        Platform default: {{ $platformMailSettings['mail_from_name'] ?? config('app.name') }} &lt;{{ $platformMailSettings['mail_from_address'] ?? config('mail.from.address') }}&gt; via {{ $platformMailSettings['mail_host'] ?? 'platform SMTP' }}.
                    </div>
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label">Mailer</label>
                            <select name="mail_mailer" class="form-select">
                                <option value="log" @selected($mailSetting('mail_mailer', 'log') === 'log')>Log only</option>
                                <option value="smtp" @selected($mailSetting('mail_mailer', 'log') === 'smtp')>SMTP</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">SMTP host</label>
                            <input name="mail_host" value="{{ $mailSetting('mail_host') }}" class="form-control" placeholder="mail.company.com">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">Port</label>
                            <input name="mail_port" type="number" value="{{ $mailSetting('mail_port', 465) }}" class="form-control">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">Security</label>
                            <select name="mail_scheme" class="form-select">
                                <option value="" @selected($mailSetting('mail_scheme') === null || $mailSetting('mail_scheme') === '')>None</option>
                                <option value="tls" @selected($mailSetting('mail_scheme') === 'tls')>TLS</option>
                                <option value="ssl" @selected($mailSetting('mail_scheme') === 'ssl')>SSL</option>
                                <option value="smtps" @selected($mailSetting('mail_scheme') === 'smtps')>SMTPS</option>
                            </select>
                        </div>
                        <div class="col-12">
                            <div class="email-safety-option border rounded-3 p-3 bg-light">
                                <div class="form-check form-switch mb-1">
                                    <input type="hidden" name="mail_verify_peer" value="0">
                                    <input class="form-check-input" type="checkbox" role="switch" name="mail_verify_peer" value="1" id="mail_verify_peer" @checked(filter_var($mailSetting('mail_verify_peer', true), FILTER_VALIDATE_BOOLEAN))>
                                    <label class="form-check-label fw-semibold" for="mail_verify_peer">Verify SMTP SSL certificate</label>
                                </div>
                                <div class="form-text">Recommended for live mail. If a shared host certificate does not match the mail host, use the server hostname that matches the certificate or temporarily turn this off.</div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">SMTP username</label>
                            <input name="mail_username" value="{{ $mailSetting('mail_username') }}" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">SMTP password</label>
                            <input name="mail_password" type="password" value="" class="form-control" autocomplete="new-password" placeholder="{{ filled($tenant->settings['mail_password'] ?? null) ? 'Saved - leave blank to keep current password' : 'Leave blank to use platform password' }}">
                            <div class="form-text">Password is hidden for security. Leave blank unless this tenant is replacing its own SMTP password.</div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">From email</label>
                            <input name="mail_from_address" type="email" value="{{ $mailSetting('mail_from_address', $tenant->email) }}" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">From name</label>
                            <input name="mail_from_name" value="{{ $mailSetting('mail_from_name', $tenant->name) }}" class="form-control">
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="sms-pane" role="tabpanel" aria-labelledby="sms-tab" tabindex="0">
                    <div class="d-flex justify-content-between align-items-start gap-3 mb-3">
                        <div>
                            <h2 class="h5 mb-1">SMS Setup</h2>
                            <div class="text-muted small">
                                @if($isSuperAdminTenantPortal)
                                    Tenants use the Super Admin SMS gateway by default. Turn this off only when this company wants its own SMS provider.
                                @else
                                    SMS gateway access follows the platform configuration. Message cost settings can still be managed here.
                                @endif
                            </div>
                        </div>
                        @if($isSuperAdminTenantPortal)
                            <div class="form-check form-switch">
                                <input type="hidden" name="sms_use_platform_defaults" value="0">
                                <input class="form-check-input" type="checkbox" role="switch" name="sms_use_platform_defaults" value="1" id="sms_use_platform_defaults" @checked($tenantUsesPlatformSms)>
                                <label class="form-check-label fw-semibold" for="sms_use_platform_defaults">Use platform SMS</label>
                            </div>
                        @else
                            <input type="hidden" name="sms_use_platform_defaults" value="{{ $tenantUsesPlatformSms ? '1' : '0' }}">
                        @endif
                    </div>
                    <div class="alert alert-info small">
                        Platform default: {{ strtoupper($platformSmsSettings['sms_gateway_method'] ?? 'POST') }} {{ $platformSmsSettings['sms_gateway_url'] ?: 'No platform SMS gateway URL set yet' }}.
                        SMS unit purchase price: {{ $setting('currency', 'NGN') }} {{ number_format((float) ($platformSmsSettings['sms_unit_price'] ?? 0), 2) }}.
                    </div>
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label">Who pays member SMS cost?</label>
                            <select name="sms_notification_cost_payer" class="form-select">
                                <option value="member" @selected($setting('sms_notification_cost_payer', 'member') === 'member')>Member account balance</option>
                                <option value="tenant" @selected($setting('sms_notification_cost_payer', 'member') === 'tenant')>Company bears the cost</option>
                            </select>
                            <div class="form-text">If member pays and balance is insufficient, the SMS will not be sent.</div>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Member charge per SMS unit</label>
                            <input name="sms_member_charge" type="number" min="0" step="0.01" value="{{ $setting('sms_member_charge', $platformSmsSettings['default_sms_member_charge'] ?? $platformSmsSettings['sms_unit_price'] ?? 5) }}" class="form-control">
                            <div class="form-text">1 unit covers up to 160 characters. Longer SMS uses 153 characters per extra page.</div>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Tenant purchase price</label>
                            <input value="{{ $setting('currency', 'NGN') }} {{ number_format((float) ($platformSmsSettings['sms_unit_price'] ?? 0), 2) }} per unit" class="form-control bg-light" readonly>
                            <div class="form-text">Set by the Super Admin.</div>
                        </div>
                        @if($isSuperAdminTenantPortal)
                            <div class="col-md-3">
                                <label class="form-label">SMS driver</label>
                                <select name="sms_driver" class="form-select">
                                    <option value="log" @selected($smsSetting('sms_driver', 'log') === 'log')>Log only</option>
                                    <option value="http" @selected($smsSetting('sms_driver', 'log') === 'http')>HTTP gateway</option>
                                    <option value="ebulksms" @selected($smsSetting('sms_driver', 'log') === 'ebulksms')>eBulkSMS</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Method</label>
                                <select name="sms_gateway_method" class="form-select">
                                    <option value="POST" @selected($smsSetting('sms_gateway_method', 'POST') === 'POST')>POST</option>
                                    <option value="GET" @selected($smsSetting('sms_gateway_method', 'POST') === 'GET')>GET</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Gateway URL</label>
                                <input name="sms_gateway_url" value="{{ $smsSetting('sms_gateway_url', 'https://api.ebulksms.com/sendsms') }}" class="form-control" placeholder="https://api.ebulksms.com/sendsms">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">eBulkSMS username/email</label>
                                <input name="sms_gateway_username" value="{{ $smsSetting('sms_gateway_username') }}" class="form-control" placeholder="your-ebulksms-email@example.com">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">API token / eBulkSMS API key</label>
                                <input name="sms_gateway_token" type="password" value="" class="form-control" autocomplete="new-password" placeholder="{{ filled($tenant->settings['sms_gateway_token'] ?? null) ? 'Saved - leave blank to keep current token' : 'Leave blank to use platform token' }}">
                                <div class="form-text">Token is hidden for security. Leave blank unless this tenant is replacing its own SMS token.</div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Tenant SMS sender name</label>
                                <input name="sms_from" value="{{ $smsSetting('sms_from', $tenant->name) }}" class="form-control">
                                <div class="form-text">Super Admin can set a different approved sender name for this tenant while still using the platform SMS gateway.</div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">eBulkSMS DND sender</label>
                                <select name="sms_dnd_sender" class="form-select">
                                    <option value="1" @selected((string) $smsSetting('sms_dnd_sender', '1') === '1')>Enabled - deliver to DND numbers</option>
                                    <option value="0" @selected((string) $smsSetting('sms_dnd_sender', '1') === '0')>Disabled</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Phone field</label>
                                <input name="sms_to_param" value="{{ $smsSetting('sms_to_param', 'to') }}" class="form-control" required>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Message field</label>
                                <input name="sms_message_param" value="{{ $smsSetting('sms_message_param', 'message') }}" class="form-control" required>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Sender field</label>
                                <input name="sms_sender_param" value="{{ $smsSetting('sms_sender_param', 'from') }}" class="form-control" required>
                            </div>
                        @else
                            <div class="col-12">
                                <div class="alert alert-light border small mb-0">
                                    <strong>SMS gateway locked.</strong> Driver, method, gateway URL, API token, sender name, and provider field mapping are managed by the platform/Super Admin.
                                </div>
                            </div>
                        @endif
                    </div>
                </div>

                <div class="tab-pane fade" id="whatsapp-pane" role="tabpanel" aria-labelledby="whatsapp-tab" tabindex="0">
                    <div class="d-flex justify-content-between align-items-start gap-3 mb-3">
                        <div>
                            <h2 class="h5 mb-1">WhatsApp Setup</h2>
                            <div class="text-muted small">
                                @if($isSuperAdminTenantPortal)
                                    Tenants use the Super Admin WhatsApp gateway by default. Turn this off only when this company wants its own provider.
                                @else
                                    WhatsApp gateway access follows the platform configuration. Message cost settings can still be managed here.
                                @endif
                            </div>
                        </div>
                        @if($isSuperAdminTenantPortal)
                            <div class="form-check form-switch">
                                <input type="hidden" name="whatsapp_use_platform_defaults" value="0">
                                <input class="form-check-input" type="checkbox" role="switch" name="whatsapp_use_platform_defaults" value="1" id="whatsapp_use_platform_defaults" @checked($tenantUsesPlatformWhatsapp)>
                                <label class="form-check-label fw-semibold" for="whatsapp_use_platform_defaults">Use platform WhatsApp</label>
                            </div>
                        @else
                            <input type="hidden" name="whatsapp_use_platform_defaults" value="{{ $tenantUsesPlatformWhatsapp ? '1' : '0' }}">
                        @endif
                    </div>
                    <div class="alert alert-info small">
                        Platform default: {{ strtoupper($platformWhatsappSettings['whatsapp_gateway_method'] ?? 'POST') }} {{ $platformWhatsappSettings['whatsapp_gateway_url'] ?: 'No platform WhatsApp gateway URL set yet' }}.
                        WhatsApp unit purchase price: {{ $setting('currency', 'NGN') }} {{ number_format((float) ($platformWhatsappSettings['whatsapp_unit_price'] ?? 0), 2) }}.
                    </div>
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label">Who pays member WhatsApp cost?</label>
                            <select name="whatsapp_notification_cost_payer" class="form-select">
                                <option value="member" @selected($setting('whatsapp_notification_cost_payer', 'member') === 'member')>Member account balance</option>
                                <option value="tenant" @selected($setting('whatsapp_notification_cost_payer', 'member') === 'tenant')>Company bears the cost</option>
                            </select>
                            <div class="form-text">If member pays and balance is insufficient, WhatsApp will not be sent.</div>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Member charge per WhatsApp message</label>
                            <input name="whatsapp_member_charge" type="number" min="0" step="0.01" value="{{ $setting('whatsapp_member_charge', $platformWhatsappSettings['default_whatsapp_member_charge'] ?? $platformWhatsappSettings['whatsapp_unit_price'] ?? 15) }}" class="form-control">
                            <div class="form-text">WhatsApp is counted as one unit per message.</div>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Tenant purchase price</label>
                            <input value="{{ $setting('currency', 'NGN') }} {{ number_format((float) ($platformWhatsappSettings['whatsapp_unit_price'] ?? 0), 2) }} per unit" class="form-control bg-light" readonly>
                            <div class="form-text">Set by the Super Admin.</div>
                        </div>
                        @if($isSuperAdminTenantPortal)
                            <div class="col-md-3">
                                <label class="form-label">WhatsApp driver</label>
                                <select name="whatsapp_driver" class="form-select">
                                    <option value="log" @selected($whatsappSetting('whatsapp_driver', 'log') === 'log')>Log only</option>
                                    <option value="http" @selected($whatsappSetting('whatsapp_driver', 'log') === 'http')>HTTP gateway</option>
                                    <option value="ebulksms" @selected($whatsappSetting('whatsapp_driver', 'log') === 'ebulksms')>eBulkSMS</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Method</label>
                                <select name="whatsapp_gateway_method" class="form-select">
                                    <option value="POST" @selected($whatsappSetting('whatsapp_gateway_method', 'POST') === 'POST')>POST</option>
                                    <option value="GET" @selected($whatsappSetting('whatsapp_gateway_method', 'POST') === 'GET')>GET</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Gateway URL</label>
                                <input name="whatsapp_gateway_url" value="{{ $whatsappSetting('whatsapp_gateway_url', 'https://api.ebulksms.com/sendwhatsapp.json') }}" class="form-control" placeholder="https://api.ebulksms.com/sendwhatsapp.json">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">eBulkSMS username/email</label>
                                <input name="whatsapp_gateway_username" value="{{ $whatsappSetting('whatsapp_gateway_username') }}" class="form-control" placeholder="your-ebulksms-email@example.com">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">API token / eBulkSMS API key</label>
                                <input name="whatsapp_gateway_token" type="password" value="" class="form-control" autocomplete="new-password" placeholder="{{ filled($tenant->settings['whatsapp_gateway_token'] ?? null) ? 'Saved - leave blank to keep current token' : 'Leave blank to use platform token' }}">
                                <div class="form-text">Token is hidden for security. Leave blank unless this tenant is replacing its own WhatsApp token.</div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Tenant WhatsApp subject</label>
                                <input name="whatsapp_from" value="{{ $whatsappSetting('whatsapp_from', $tenant->name) }}" class="form-control">
                                <div class="form-text">Super Admin can set a different eBulkSMS WhatsApp subject/title for this tenant while still using the platform gateway.</div>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Phone field</label>
                                <input name="whatsapp_to_param" value="{{ $whatsappSetting('whatsapp_to_param', 'to') }}" class="form-control" required>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Message field</label>
                                <input name="whatsapp_message_param" value="{{ $whatsappSetting('whatsapp_message_param', 'message') }}" class="form-control" required>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Sender field</label>
                                <input name="whatsapp_sender_param" value="{{ $whatsappSetting('whatsapp_sender_param', 'from') }}" class="form-control" required>
                            </div>
                        @else
                            <div class="col-12">
                                <div class="alert alert-light border small mb-0">
                                    <strong>WhatsApp gateway locked.</strong> Driver, method, gateway URL, API token, subject, and provider field mapping are managed by the platform/Super Admin.
                                </div>
                            </div>
                        @endif
                    </div>
                </div>

                <div class="tab-pane fade" id="automation-pane" role="tabpanel" aria-labelledby="automation-tab" tabindex="0">
                    <div class="settings-pane-intro mb-3">
                        <div>
                            <h2 class="h5 mb-1">Automatic Member Notifications</h2>
                            <p class="text-muted mb-0">Choose the account events members should receive automatically, then edit the subject and message text for each alert. Portal alerts work for members with login access; email, SMS, and WhatsApp use the channel setup saved in these settings.</p>
                        </div>
                    </div>
                    <div class="automation-placeholders mb-3">
                        <strong>Available placeholders</strong>
                        <div>
                            @foreach($automationPlaceholders as $placeholder => $description)
                                <span title="{{ $description }}">{{ $placeholder }}</span>
                            @endforeach
                        </div>
                    </div>
                    <div class="automation-settings-grid">
                        @foreach($automationCatalog as $eventKey => $event)
                            @php
                                $eventEnabled = filter_var(data_get($automationSettings, $eventKey.'.enabled', $event['default_enabled']), FILTER_VALIDATE_BOOLEAN);
                                $selectedChannels = data_get($automationSettings, $eventKey.'.channels', $event['default_channels']);
                                $selectedChannels = is_array($selectedChannels) ? $selectedChannels : [];
                                $selectedChannelLabels = collect($automationChannels)->only($selectedChannels)->pluck('label')->implode(', ');
                                $eventSubject = data_get($automationSettings, $eventKey.'.subject', $event['default_subject']);
                                $eventBody = data_get($automationSettings, $eventKey.'.body', $event['default_body']);
                                $channelsCollapseId = 'automation-channels-'.$eventKey;
                                $templateCollapseId = 'automation-template-'.$eventKey;
                            @endphp
                            <article class="automation-card">
                                <div class="automation-card-head">
                                    <div>
                                        <strong>{{ $event['label'] }}</strong>
                                        <span>{{ $event['description'] }}</span>
                                    </div>
                                    <div class="form-check form-switch mb-0">
                                        <input type="hidden" name="member_notification_automations[{{ $eventKey }}][enabled]" value="0">
                                        <input class="form-check-input" type="checkbox" role="switch" name="member_notification_automations[{{ $eventKey }}][enabled]" value="1" @checked($eventEnabled)>
                                    </div>
                                </div>
                                <div>
                                    <div class="automation-template-summary automation-channel-summary">
                                        <div>
                                            <span>Delivery channels</span>
                                            <strong>{{ $selectedChannelLabels ?: 'No channel selected' }}</strong>
                                        </div>
                                        <button class="btn btn-sm btn-outline-secondary automation-collapse-button" type="button" data-bs-toggle="collapse" data-bs-target="#{{ $channelsCollapseId }}" aria-expanded="false" aria-controls="{{ $channelsCollapseId }}">
                                            <i class="bi bi-chevron-right me-1"></i> Choose channels
                                        </button>
                                    </div>
                                    <div class="collapse" id="{{ $channelsCollapseId }}">
                                        <div class="automation-channel-grid automation-channel-grid-collapsed">
                                            @foreach($automationChannels as $channelKey => $channel)
                                                <label class="automation-channel-option">
                                                    <input class="form-check-input" type="checkbox" name="member_notification_automations[{{ $eventKey }}][channels][]" value="{{ $channelKey }}" @checked(in_array($channelKey, $selectedChannels, true))>
                                                    <span><i class="bi {{ $channel['icon'] }}"></i> {{ $channel['label'] }}</span>
                                                </label>
                                            @endforeach
                                        </div>
                                    </div>
                                </div>
                                <div class="automation-template-summary">
                                    <div>
                                        <span>Message template</span>
                                        <strong>{{ $eventSubject }}</strong>
                                    </div>
                                    <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#{{ $templateCollapseId }}" aria-expanded="false" aria-controls="{{ $templateCollapseId }}">
                                        <i class="bi bi-pencil-square me-1"></i> Edit message
                                    </button>
                                </div>
                                <div class="collapse" id="{{ $templateCollapseId }}">
                                    <div class="automation-template-grid">
                                        <div>
                                            <label class="form-label">Subject</label>
                                            <input name="member_notification_automations[{{ $eventKey }}][subject]" value="{{ $eventSubject }}" class="form-control" maxlength="160">
                                        </div>
                                        <div>
                                            <label class="form-label">Message</label>
                                            <textarea name="member_notification_automations[{{ $eventKey }}][body]" class="form-control" rows="3" maxlength="1000">{{ $eventBody }}</textarea>
                                            <div class="form-text">Use placeholders above to auto-fill member, amount, reference, balance, due date, maturity date, and company details.</div>
                                        </div>
                                    </div>
                                </div>
                            </article>
                        @endforeach
                    </div>
                </div>

                <div class="tab-pane fade" id="payment-pane" role="tabpanel" aria-labelledby="payment-tab" tabindex="0">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label">Provider</label>
                            <select name="payment_gateway_provider" class="form-select" data-payment-provider>
                                <option value="none" @selected($setting('payment_gateway_provider', 'none') === 'none')>None</option>
                                <option value="paystack" @selected($setting('payment_gateway_provider', 'none') === 'paystack')>Paystack</option>
                                <option value="monnify" @selected($setting('payment_gateway_provider', 'none') === 'monnify')>Monnify</option>
                                <option value="flutterwave" @selected($setting('payment_gateway_provider', 'none') === 'flutterwave')>Flutterwave</option>
                                <option value="providus_bank" @selected($setting('payment_gateway_provider', 'none') === 'providus_bank')>Providus Bank</option>
                                <option value="wema_bank" @selected($setting('payment_gateway_provider', 'none') === 'wema_bank')>Wema Bank</option>
                            </select>
                            <div class="form-text">This is the tenant's preferred provider for member payments and virtual accounts.</div>
                        </div>

                        <div class="col-12" data-provider-settings="none">
                            <div class="alert alert-light border mb-0">Online member payments are disabled until a provider is selected and saved.</div>
                        </div>

                        <div class="col-12" data-provider-settings="paystack">
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <label class="form-label">Paystack secret key</label>
                                    <input name="paystack_secret_key" type="password" value="" class="form-control" autocomplete="new-password" placeholder="{{ filled($setting('paystack_secret_key')) ? 'Saved - leave blank to keep current key' : 'sk_live_xxxxx' }}">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Paystack base URL</label>
                                    <input name="paystack_base_url" value="{{ $setting('paystack_base_url', 'https://api.paystack.co') }}" class="form-control">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Preferred virtual account bank</label>
                                    <input name="paystack_preferred_bank" value="{{ $setting('paystack_preferred_bank') }}" class="form-control" placeholder="wema-bank or titan-paystack">
                                </div>
                                <div class="col-12">
                                    <label class="form-label">Paystack webhook URL</label>
                                    <input value="{{ route('webhooks.paystack') }}" class="form-control" readonly>
                                    <div class="form-text">Add this URL in Paystack so dedicated virtual account transfers can credit member savings automatically.</div>
                                </div>
                            </div>
                        </div>

                        <div class="col-12" data-provider-settings="monnify">
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <label class="form-label">Monnify API key</label>
                                    <input name="monnify_api_key" type="password" value="" class="form-control" autocomplete="new-password" placeholder="{{ filled($setting('monnify_api_key')) ? 'Saved - leave blank to keep current key' : 'Monnify API key' }}">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Monnify secret key</label>
                                    <input name="monnify_secret_key" type="password" value="" class="form-control" autocomplete="new-password" placeholder="{{ filled($setting('monnify_secret_key')) ? 'Saved - leave blank to keep current secret' : 'Monnify secret key' }}">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Contract code</label>
                                    <input name="monnify_contract_code" value="{{ $setting('monnify_contract_code') }}" class="form-control">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Monnify base URL</label>
                                    <input name="monnify_base_url" value="{{ $setting('monnify_base_url', 'https://api.monnify.com') }}" class="form-control">
                                </div>
                                <div class="col-md-6">
                                    <div class="alert alert-info mb-0 small">Monnify supports hosted checkout and reserved virtual accounts. Reserved accounts require BVN or NIN on the member profile.</div>
                                </div>
                            </div>
                        </div>

                        <div class="col-12" data-provider-settings="flutterwave">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">Flutterwave secret key</label>
                                    <input name="flutterwave_secret_key" type="password" value="" class="form-control" autocomplete="new-password" placeholder="{{ filled($setting('flutterwave_secret_key')) ? 'Saved - leave blank to keep current key' : 'FLWSECK_xxxxx' }}">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Flutterwave base URL</label>
                                    <input name="flutterwave_base_url" value="{{ $setting('flutterwave_base_url', 'https://api.flutterwave.com/v3') }}" class="form-control">
                                </div>
                                <div class="col-12">
                                    <div class="alert alert-info mb-0 small">Flutterwave is used for hosted checkout. Dedicated virtual account creation remains Paystack or Monnify in this build.</div>
                                </div>
                            </div>
                        </div>

                        <div class="col-12" data-provider-settings="providus_bank">
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <label class="form-label">Providus client ID</label>
                                    <input name="providus_client_id" value="{{ $setting('providus_client_id') }}" class="form-control">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Providus client secret</label>
                                    <input name="providus_client_secret" type="password" value="" class="form-control" autocomplete="new-password" placeholder="{{ filled($setting('providus_client_secret')) ? 'Saved - leave blank to keep current secret' : 'Provided by Providus' }}">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Providus base URL</label>
                                    <input name="providus_base_url" value="{{ $setting('providus_base_url') }}" class="form-control" placeholder="Provided by Providus">
                                </div>
                                <div class="col-12">
                                    <div class="alert alert-warning mb-0 small">Providus direct bank APIs require bank-issued production credentials and endpoint documentation. The credentials are stored here for the bank adapter.</div>
                                </div>
                            </div>
                        </div>

                        <div class="col-12" data-provider-settings="wema_bank">
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <label class="form-label">Wema client ID</label>
                                    <input name="wema_client_id" value="{{ $setting('wema_client_id') }}" class="form-control">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Wema client secret</label>
                                    <input name="wema_client_secret" type="password" value="" class="form-control" autocomplete="new-password" placeholder="{{ filled($setting('wema_client_secret')) ? 'Saved - leave blank to keep current secret' : 'Provided by Wema' }}">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Wema base URL</label>
                                    <input name="wema_base_url" value="{{ $setting('wema_base_url') }}" class="form-control" placeholder="Provided by Wema">
                                </div>
                                <div class="col-12">
                                    <div class="alert alert-warning mb-0 small">For Wema virtual accounts through Paystack, choose Paystack and use the preferred bank slug. Direct Wema APIs require bank-issued credentials.</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="bill-payment-pane" role="tabpanel" aria-labelledby="bill-payment-tab" tabindex="0">
                    <div class="settings-pane-intro mb-3">
                        <div>
                            <h2 class="h5 mb-1">Bill Payment Provider</h2>
                            <p class="text-muted mb-0">Super Admin controls the live VTU provider. Tenants set their service fees and markups here.</p>
                        </div>
                    </div>
                    <div class="row g-3">
                        <div class="col-lg-4">
                            <div class="vtu-provider-summary h-100">
                                <span>Platform provider</span>
                                <strong>{{ strtoupper(str_replace('_', ' ', $platformBillPaymentSettings['driver'] ?? 'manual_provider')) }}</strong>
                                <small>{{ $platformBillPaymentConfigured ? 'Configured by Super Admin' : 'Waiting for Super Admin setup' }}</small>
                            </div>
                        </div>
                        <div class="col-lg-4">
                            <label class="form-label">Default service fee</label>
                            <input name="bill_payment_fee" type="number" step="0.01" min="0" value="{{ $setting('bill_payment_fee', 0) }}" class="form-control">
                            <div class="form-text">Flat fee added to the member/staff payment.</div>
                        </div>
                        <div class="col-lg-4">
                            <label class="form-label">Default markup %</label>
                            <input name="bill_payment_commission_rate" type="number" step="0.01" min="0" max="100" value="{{ $setting('bill_payment_commission_rate', 0) }}" class="form-control">
                            <div class="form-text">Percentage added to the customer's bill amount as tenant VTU earning.</div>
                        </div>
                        <div class="col-12">
                            <div class="alert {{ $platformBillPaymentConfigured ? 'alert-info' : 'alert-warning' }} mb-0 small">
                                Bill-payment provider credentials are controlled by Super Admin. Tenants can only set service charges and commissions here.
                                @if(($platformBillPaymentSettings['driver'] ?? 'manual_provider') === 'vtpass')
                                    Current VTpass mode: {{ ucfirst($platformBillPaymentSettings['vtpass_environment'] ?? 'sandbox') }}.
                                @elseif(($platformBillPaymentSettings['driver'] ?? 'manual_provider') === 'flutterwave')
                                    Current provider: Flutterwave Bills.
                                @endif
                            </div>
                        </div>

                        <div class="col-12">
                            <div class="section-data-card p-3">
                                <div class="section-card-title mb-3">
                                    <span><i class="bi bi-sliders"></i></span>
                                    <div>
                                        <strong>Service fees and commissions</strong>
                                        <small>Leave a service row empty to use the default fee and default markup above.</small>
                                    </div>
                                </div>
                                <div class="table-responsive">
                                    <table class="table section-table align-middle mb-0">
                                        <thead><tr><th>Service</th><th>Flat fee</th><th>Markup %</th></tr></thead>
                                        <tbody>
                                            @foreach($billPaymentServiceTypes as $serviceKey => $service)
                                                <tr>
                                                    <td>
                                                        <div class="fw-semibold"><i class="bi {{ $service['icon'] }} me-1"></i>{{ $service['label'] }}</div>
                                                        <small class="text-muted">{{ ucfirst(str_replace('_', ' ', $serviceKey)) }}</small>
                                                    </td>
                                                    <td>
                                                        <input name="bill_payment_fee_{{ $serviceKey }}" type="number" step="0.01" min="0" value="{{ $setting('bill_payment_fee_'.$serviceKey) }}" class="form-control form-control-sm" placeholder="Use default">
                                                    </td>
                                                    <td>
                                                        <input name="bill_payment_commission_{{ $serviceKey }}" type="number" step="0.01" min="0" max="100" value="{{ $setting('bill_payment_commission_'.$serviceKey) }}" class="form-control form-control-sm" placeholder="Use default">
                                                    </td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="portal-pane" role="tabpanel" aria-labelledby="portal-tab" tabindex="0">
                    <div class="row g-3">
                        <div class="col-lg-8">
                            <label class="form-label">Portal slug</label>
                            <div class="input-group">
                                <span class="input-group-text">{{ url('/t') }}/</span>
                                <input name="slug" value="{{ old('slug', $tenant->slug) }}" class="form-control" required>
                            </div>
                            <div class="form-text">This controls the public member website link.</div>
                        </div>
                        <div class="col-lg-4 d-flex align-items-end">
                            <button class="btn btn-primary w-100"><i class="bi bi-save me-1"></i> Save slug</button>
                        </div>
                        <div class="col-lg-8">
                            <label class="form-label">Current member website link</label>
                            <input class="form-control" value="{{ $tenantPortalUrl }}" readonly>
                        </div>
                        <div class="col-lg-4 d-flex align-items-end">
                            <a class="btn btn-outline-primary w-100" target="_blank" href="{{ $tenantPortalUrl }}">Open public portal</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="settings-save-bar">
            <button class="btn btn-primary"><i class="bi bi-save me-1"></i> Save settings</button>
        </div>
    </div>
</form>

<style>
.approval-setting-card {
    min-height: 160px;
    display: flex;
    justify-content: space-between;
    gap: 1rem;
    padding: 1rem;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    background: #f8fafc;
}
.approval-setting-card strong,
.approval-setting-card span {
    display: block;
}
.approval-setting-card strong {
    color: #0f172a;
    font-size: 1rem;
}
.approval-setting-card span {
    margin-top: .35rem;
    color: #64748b;
    font-size: .86rem;
}
.vtu-provider-card {
    border: 1px solid #dbeafe;
    border-radius: 12px;
    padding: 1rem;
    background: linear-gradient(135deg, #eff6ff, #ffffff);
}
.vtu-provider-head {
    display: flex;
    align-items: center;
    gap: .8rem;
    margin-bottom: 1rem;
}
.vtu-provider-head > span {
    width: 44px;
    height: 44px;
    border-radius: 12px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    background: #0f766e;
}
.vtu-provider-head strong,
.vtu-provider-head small {
    display: block;
}
.vtu-provider-head small {
    color: #64748b;
}
.vtu-provider-summary {
    border: 1px solid #dbeafe;
    border-radius: 12px;
    padding: 1rem;
    background: linear-gradient(135deg, #eff6ff, #ffffff);
}
.vtu-provider-summary span,
.vtu-provider-summary strong,
.vtu-provider-summary small {
    display: block;
}
.vtu-provider-summary span {
    color: #64748b;
    font-size: .82rem;
    text-transform: uppercase;
    letter-spacing: .04em;
}
.vtu-provider-summary strong {
    color: #0f172a;
    margin-top: .35rem;
}
.vtu-provider-summary small {
    color: #0f766e;
    margin-top: .25rem;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const mode = document.querySelector('[data-account-number-mode]');
    const prefixFields = document.querySelectorAll('[data-account-number-prefix-settings]');
    const provider = document.querySelector('[data-payment-provider]');
    const providerSettings = document.querySelectorAll('[data-provider-settings]');
    const kycProvider = document.querySelector('[data-kyc-provider]');
    const kycProviderSettings = document.querySelectorAll('[data-kyc-provider-settings]');
    const tabButtons = document.querySelectorAll('#tenantSettingsTabs [data-bs-toggle="tab"]');

    const activateHashTab = () => {
        const hash = window.location.hash;

        if (! /^#[A-Za-z0-9_-]+$/.test(hash)) {
            return;
        }

        const trigger = document.querySelector(`#tenantSettingsTabs [data-bs-target="${hash}"]`);

        if (trigger && window.bootstrap) {
            window.bootstrap.Tab.getOrCreateInstance(trigger).show();
        }
    };

    tabButtons.forEach((button) => {
        button.addEventListener('shown.bs.tab', () => {
            if (button.dataset.bsTarget) {
                history.replaceState(null, '', button.dataset.bsTarget);
            }
        });
    });

    activateHashTab();
    window.addEventListener('hashchange', activateHashTab);

    const syncAccountNumberFields = () => {
        prefixFields.forEach((field) => field.classList.toggle('d-none', mode?.value !== 'prefix_random'));
    };

    mode?.addEventListener('change', syncAccountNumberFields);
    syncAccountNumberFields();

    const syncProviderFields = () => {
        providerSettings.forEach((section) => {
            section.classList.toggle('d-none', section.dataset.providerSettings !== provider?.value);
        });
    };

    provider?.addEventListener('change', syncProviderFields);
    syncProviderFields();

    const syncKycProviderFields = () => {
        kycProviderSettings.forEach((section) => {
            section.classList.toggle('d-none', section.dataset.kycProviderSettings !== kycProvider?.value);
        });
    };

    kycProvider?.addEventListener('change', syncKycProviderFields);
    syncKycProviderFields();
});
</script>
@endsection
