<x-app-layout>
<x-slot name="header">
    <div class="d-flex flex-wrap gap-3 align-items-center justify-content-between">
        <div><h2 class="h4 mb-1">Settings Control Center</h2></div>
        <a href="{{ url('/') }}" target="_blank" class="btn btn-outline-primary"><i class="fas fa-external-link-alt me-1"></i> View Website</a>
    </div>
</x-slot>

<form id="settingsControlForm" enctype="multipart/form-data">
    @csrf
    <div class="settings-layout">
        <aside class="settings-nav card border-0 shadow-sm">
            <div class="card-body p-2">
                <button type="button" class="settings-tab active" data-target="business"><i class="fas fa-building"></i><span>Business</span></button>
                <button type="button" class="settings-tab" data-target="automation"><i class="fas fa-robot"></i><span>Automation</span></button>
                <button type="button" class="settings-tab" data-target="integrations"><i class="fas fa-plug"></i><span>Integration</span></button>
                <button type="button" class="settings-tab" data-target="maintenance"><i class="fas fa-tools"></i><span>Maintenance</span></button>
            </div>
        </aside>

        <main class="min-w-0">
            <section class="settings-pane active" id="settings-business">
                <div class="card border-0 shadow-sm"><div class="card-body p-3 p-lg-4">
                    <div class="setting-heading"><span class="setting-icon bg-primary-subtle text-primary"><i class="fas fa-building"></i></span><div><h3>Business Settings</h3></div></div>
                    <div class="row g-3">
                        <div class="col-md-6"><label class="form-label">ISP/Business Name</label><input class="form-control" name="settings[business.name]" value="{{ $settings['business.name'] }}" required></div>
                        <div class="col-md-6"><label class="form-label">Short Tagline</label><input class="form-control" name="settings[business.tagline]" value="{{ $settings['business.tagline'] }}"></div>
                        <div class="col-md-6"><label class="form-label">Phone</label><input class="form-control" name="settings[business.phone]" value="{{ $settings['business.phone'] }}"></div>
                        <div class="col-md-6"><label class="form-label">Email</label><input type="email" class="form-control" name="settings[business.email]" value="{{ $settings['business.email'] }}"></div>
                        <div class="col-md-9"><label class="form-label">Office address</label><input class="form-control" name="settings[business.address]" value="{{ $settings['business.address'] }}"></div>
                        <div class="col-12"><hr><h4 class="h6">{{ __('ui.currency_language') }}</h4></div>
                        <div class="col-md-3"><label class="form-label">{{ __('ui.currency_code') }}</label><select id="currencyCode" class="form-select" name="settings[currency.code]">@foreach(['BDT'=>'Bangladeshi Taka','USD'=>'US Dollar','EUR'=>'Euro','GBP'=>'British Pound','INR'=>'Indian Rupee','JPY'=>'Japanese Yen','AED'=>'UAE Dirham','SAR'=>'Saudi Riyal'] as $code=>$name)<option value="{{ $code }}" @selected($settings['currency.code']===$code)>{{ $code }} — {{ $name }}</option>@endforeach</select></div>
                        <div class="col-md-3"><label class="form-label">{{ __('ui.currency_symbol') }}</label><input id="currencySymbol" class="form-control" name="settings[currency.symbol]" value="{{ $settings['currency.symbol'] }}" maxlength="10"></div>
                        <div class="col-md-2"><label class="form-label">{{ __('ui.symbol_position') }}</label><select class="form-select" name="settings[currency.position]"><option value="before" @selected($settings['currency.position']==='before')>{{ __('ui.before') }}</option><option value="after" @selected($settings['currency.position']==='after')>{{ __('ui.after') }}</option></select></div>
                        <div class="col-md-2"><label class="form-label">{{ __('ui.decimals') }}</label><select class="form-select" name="settings[currency.decimals]">@foreach([0,2,3,4] as $decimal)<option value="{{ $decimal }}" @selected((int)$settings['currency.decimals']===$decimal)>{{ $decimal }}</option>@endforeach</select></div>
                        <div class="col-md-2"><label class="form-label">{{ __('ui.default_language') }}</label><select class="form-select" name="settings[language.default]"><option value="en" @selected($settings['language.default']==='en')>English</option></select></div>
                        <input type="hidden" name="settings[business.currency]" value="{{ $settings['currency.symbol'] }}">
                        <div class="col-12"><label class="form-label">Logo <small class="text-muted">PNG/JPG/WebP/SVG, max 2MB</small></label><input type="file" class="form-control" name="logo" accept="image/*"></div>
                    </div>
                </div></div>
            </section>

            <section class="settings-pane" id="settings-automation">
                <div class="card border-0 shadow-sm"><div class="card-body p-3 p-lg-4">
                    <div class="setting-heading"><span class="setting-icon bg-warning-subtle text-warning"><i class="fas fa-clock"></i></span><div><h3>Cron & Automation</h3></div></div>
                    @foreach([['automation.daily_billing','Daily billing','Generate missing monthly bills at midnight'],['automation.mikrotik_sync','MikroTik sync','Background RouterOS data refresh'],['automation.auto_backup','Automatic backup','Create database backup at the scheduled time'],['mikrotik.auto_connect','MikroTik auto-connect','Router connection background check']] as $option)
                        @php($switchId = 'setting-'.str_replace('.', '-', $option[0]))
                        <div class="setting-switch">
                            <label class="setting-switch-label" for="{{ $switchId }}"><strong>{{ $option[1] }}</strong><small>{{ $option[2] }}</small></label>
                            <input type="hidden" name="settings[{{ $option[0] }}]" value="0">
                            <div class="form-check form-switch app-toggle">
                                <input id="{{ $switchId }}" class="form-check-input" type="checkbox" name="settings[{{ $option[0] }}]" value="1" aria-label="{{ $option[1] }}" {{ $settings[$option[0]] === '1' ? 'checked' : '' }}>
                            </div>
                        </div>
                    @endforeach
                    <div class="setting-switch">
                        <label class="setting-switch-label" for="setting-automation-mikrotik-disconnect"><strong>Date-wise line disconnect</strong><small>Disconnect expired customers from MikroTik at the selected time</small></label>
                        <input type="hidden" name="settings[automation.mikrotik_disconnect]" value="0">
                        <div class="form-check form-switch app-toggle"><input id="setting-automation-mikrotik-disconnect" class="form-check-input" type="checkbox" name="settings[automation.mikrotik_disconnect]" value="1" @checked($settings['automation.mikrotik_disconnect'] === '1')></div>
                    </div>
                    <div class="setting-switch">
                        <label class="setting-switch-label" for="setting-automation-olt-sync"><strong>OLT gateway sync</strong><small>Refresh OLT data in the background every 5 minutes</small></label>
                        <input type="hidden" name="settings[automation.olt_sync]" value="0">
                        <div class="form-check form-switch app-toggle"><input id="setting-automation-olt-sync" class="form-check-input" type="checkbox" name="settings[automation.olt_sync]" value="1" @checked($settings['automation.olt_sync'] === '1')></div>
                    </div>
                    <div class="row g-3 mt-2">
                        <div class="col-md-6"><label class="form-label fw-semibold">Customer disconnect time</label><input type="time" class="form-control" name="settings[automation.disconnect_time]" value="{{ $settings['automation.disconnect_time'] }}" required><div class="form-text">The PPPoE secret of due customers will be disabled at this time every day. Server timezone: {{ config('app.timezone') }}.</div></div>
                        <div class="col-md-6"><label class="form-label fw-semibold">Auto backup time</label><input type="time" class="form-control" name="settings[automation.backup_time]" value="{{ $settings['automation.backup_time'] }}"></div>
                        <div class="col-md-6"><label class="form-label fw-semibold">Monthly billing time</label><input type="time" class="form-control" name="settings[automation.billing_time]" value="{{ $settings['automation.billing_time'] }}"></div>
                        <div class="col-md-6"><label class="form-label fw-semibold">Due reminder SMS time</label><input type="time" class="form-control" name="settings[automation.due_sms_time]" value="{{ $settings['automation.due_sms_time'] }}"></div>
                        @foreach([['automation.mikrotik_sync_interval','MikroTik sync interval',[1,2,5,10,15,30]],['automation.olt_sync_interval','OLT sync interval',[1,2,5,10,15,30,60]],['automation.auto_connect_interval','Router connection check interval',[1,2,5,10,15,30,60]]] as $interval)
                            <div class="col-md-4"><label class="form-label fw-semibold">{{ $interval[1] }}</label><select class="form-select" name="settings[{{ $interval[0] }}]">@foreach($interval[2] as $minute)<option value="{{ $minute }}" @selected((string)$settings[$interval[0]]===(string)$minute)>Every {{ $minute }} minute{{ $minute>1?'s':'' }}</option>@endforeach</select></div>
                        @endforeach
                        <div class="col-md-4"><label class="form-label fw-semibold">Due SMS before</label><div class="input-group"><input type="number" min="1" max="30" class="form-control" name="settings[automation.due_sms_days]" value="{{ $settings['automation.due_sms_days'] }}"><span class="input-group-text">days</span></div></div>
                        <div class="col-md-4"><label class="form-label fw-semibold">Log retention</label><div class="input-group"><input type="number" min="1" max="3650" class="form-control" name="settings[automation.log_retention_days]" value="{{ $settings['automation.log_retention_days'] }}"><span class="input-group-text">days</span></div></div>
                        <div class="col-md-4"><label class="form-label fw-semibold">Backup retention</label><div class="input-group"><input type="number" min="1" max="3650" class="form-control" name="settings[automation.backup_retention_days]" value="{{ $settings['automation.backup_retention_days'] }}"><span class="input-group-text">days</span></div></div>
                    </div>
                    <hr class="my-4"><h4 class="h6 mb-3">Payment & SMS Event Automation</h4>
                    @foreach([['automation.payment_activation','Payment activation','Successful payment instantly enables the exact MikroTik customer'],['automation.sms_new_customer','New customer SMS','Send the active New Customer template'],['automation.sms_payment','Payment SMS','Send the active Paid SMS template'],['automation.sms_due_reminder','Due reminder SMS','Send before the configured disconnect date'],['automation.sms_disconnect','Disconnect SMS','Send after successful MikroTik disconnect'],['automation.sms_activation','Activation SMS','Send after successful MikroTik activation']] as $option)
                        @php($switchId = 'setting-'.str_replace('.', '-', $option[0]))
                        <div class="setting-switch"><label class="setting-switch-label" for="{{ $switchId }}"><strong>{{ $option[1] }}</strong><small>{{ $option[2] }}</small></label><input type="hidden" name="settings[{{ $option[0] }}]" value="0"><div class="form-check form-switch app-toggle"><input id="{{ $switchId }}" class="form-check-input" type="checkbox" name="settings[{{ $option[0] }}]" value="1" @checked($settings[$option[0]] === '1')></div></div>
                    @endforeach
                    <hr class="my-4">
                    <h4 class="h6 mb-1">Expired Customer & Payment Redirect</h4>
                    <p class="small text-muted mb-3">All values will be managed from the software. No action will run without an exact router/customer match.</p>
                    <div class="row g-3">
                        <div class="col-md-6"><label class="form-label">Expiry action</label><select class="form-select" name="settings[billing.expiry_action]"><option value="hard_disconnect" {{ $settings['billing.expiry_action']==='hard_disconnect'?'selected':'' }}>Hard Disconnect</option><option value="payment_redirect" {{ $settings['billing.expiry_action']==='payment_redirect'?'selected':'' }}>Payment Redirect Profile</option></select></div>
                        <div class="col-md-6"><label class="form-label">Connection type</label><select class="form-select" name="settings[billing.connection_type]"><option value="pppoe" {{ $settings['billing.connection_type']==='pppoe'?'selected':'' }}>PPPoE</option><option value="hotspot" {{ $settings['billing.connection_type']==='hotspot'?'selected':'' }}>HotSpot</option></select></div>
                        <div class="col-12"><label class="form-label">Payment page full URL</label><input type="url" class="form-control" name="settings[billing.payment_url]" value="{{ $settings['billing.payment_url'] }}" placeholder="https://example.com/pay"></div>
                        <div class="col-md-6"><label class="form-label">Payment domain</label><input class="form-control" name="settings[billing.payment_domain]" value="{{ $settings['billing.payment_domain'] }}" placeholder="example.com"></div>
                        <div class="col-md-6"><label class="form-label">Payment server IP</label><input class="form-control" name="settings[billing.payment_ip]" value="{{ $settings['billing.payment_ip'] }}" placeholder="203.0.113.10"></div>
                        <div class="col-md-6"><label class="form-label">Expired profile name</label><input class="form-control" name="settings[billing.expired_profile]" value="{{ $settings['billing.expired_profile'] }}" placeholder="EXPIRED-PAYMENT"></div>
                        <div class="col-md-6"><label class="form-label">Expired IP pool/range</label><input class="form-control" name="settings[billing.expired_pool]" value="{{ $settings['billing.expired_pool'] }}" placeholder="10.99.0.2-10.99.0.254"></div>
                        <div class="col-12"><button type="button" class="btn btn-outline-primary" id="applyPaymentRedirect"><i class="fas fa-network-wired me-1"></i> Apply Saved Configuration to MikroTik</button></div>
                    </div>
                </div></div>
            </section>

            <section class="settings-pane" id="settings-integrations">
                <div class="row g-3">
                    <div class="col-md-6"><a class="manage-card" href="{{ route('admin.sms-gateways.index') }}"><span class="setting-icon bg-primary-subtle text-primary"><i class="fas fa-sms"></i></span><div><h3>SMS API</h3><p>Gateway, credentials and API status manage </p></div><i class="fas fa-chevron-right ms-auto"></i></a></div>
                    <div class="col-md-6"><a class="manage-card" href="{{ route('admin.mikrotiks.index') }}"><span class="setting-icon bg-success-subtle text-success"><i class="fas fa-network-wired"></i></span><div><h3>MikroTik</h3><p>Router connection and realtime sync manage </p></div><i class="fas fa-chevron-right ms-auto"></i></a></div>
                </div>

                <div class="card border-0 shadow-sm mt-3"><div class="card-body p-3 p-lg-4">
                    <div class="setting-heading"><span class="setting-icon bg-success-subtle text-success"><i class="fas fa-credit-card"></i></span><div><h3>UddoktaPay</h3><p>Customer Portal online payment and verified MikroTik activation.</p></div></div>
                    <div class="setting-switch"><label class="setting-switch-label" for="uddoktapayEnabled"><strong>Enable online payment</strong><small>Pay Now is shown only after URL and API key are configured.</small></label><input type="hidden" name="settings[uddoktapay.enabled]" value="0"><div class="form-check form-switch app-toggle"><input id="uddoktapayEnabled" class="form-check-input" type="checkbox" name="settings[uddoktapay.enabled]" value="1" @checked($settings['uddoktapay.enabled']==='1')></div></div>
                    <div class="row g-3 mt-1"><div class="col-md-6"><label class="form-label">UddoktaPay Base URL</label><input type="url" class="form-control" name="settings[uddoktapay.base_url]" value="{{ $settings['uddoktapay.base_url'] }}" placeholder="https://pay.your-domain.com"></div><div class="col-md-6"><label class="form-label">API Key</label><input type="password" class="form-control" name="settings[uddoktapay.api_key]" placeholder="{{ $settings['uddoktapay.api_key'] ? 'Configured - leave blank to keep it' : 'Paste API key' }}" autocomplete="new-password"><div class="form-text">Requires payment:checkout and payment:verify abilities.</div></div></div>
                </div></div>
                <div class="card border-0 shadow-sm mt-3"><div class="card-body p-3 p-lg-4">
                    <div class="setting-heading"><span class="setting-icon bg-info-subtle text-info"><i class="fas fa-project-diagram"></i></span><div><h3>OLT API Gateway</h3><p>VPS gateway to interface, device condition and diagram data will be fetched.</p></div></div>
                    <div class="row g-3">
                        <div class="col-md-6"><label class="form-label">Gateway URL</label><input type="url" class="form-control" name="settings[olt_gateway.url]" value="{{ $settings['olt_gateway.url'] }}" placeholder="https://olt-api.example.com"></div>
                        <div class="col-md-6"><label class="form-label">API Key</label><input type="password" class="form-control" name="settings[olt_gateway.api_key]" placeholder="{{ $settings['olt_gateway.api_key'] ? 'Configured - leave blank to keep it' : 'Paste one-time API key' }}" autocomplete="new-password"><div class="form-text">The key will not be stored in the browser or in the OLT record; it will remain encrypted in Settings.</div></div>
                    </div>
                </div></div>
                <div class="card border-0 shadow-sm mt-3"><div class="card-body p-3 p-lg-4"><div class="setting-heading"><span class="setting-icon bg-primary-subtle text-primary"><i class="fas fa-user-shield"></i></span><div><h3>Customer Portal Login</h3><p>Customer portal is payment-only. Verification can be enabled whenever required.</p></div></div><div class="row g-3"><div class="col-md-6"><label class="form-label">Customer login identifier</label><select class="form-select" name="settings[customer_portal.identifier_mode]"><option value="code_or_pppoe" @selected($settings['customer_portal.identifier_mode']==='code_or_pppoe')>Customer Code or PPPoE Username</option><option value="pppoe_only" @selected($settings['customer_portal.identifier_mode']==='pppoe_only')>PPPoE Username only</option><option value="code_only" @selected($settings['customer_portal.identifier_mode']==='code_only')>Customer Code only</option></select></div><div class="col-md-6"><label class="form-label">Verification method</label><select class="form-select" name="settings[customer_portal.verification_mode]"><option value="none" @selected($settings['customer_portal.verification_mode']==='none')>No OTP verification</option><option value="sms" @selected($settings['customer_portal.verification_mode']==='sms')>SMS OTP</option><option value="email" @selected($settings['customer_portal.verification_mode']==='email')>Email OTP</option><option value="sms_or_email" @selected($settings['customer_portal.verification_mode']==='sms_or_email')>Customer chooses SMS or Email</option></select></div><div class="col-12"><div class="alert alert-warning mb-0">Without OTP, an exact identifier match opens the payment portal. Enable SMS/Email OTP whenever stronger verification is required.</div></div></div></div></div>
            </section>

            <section class="settings-pane" id="settings-maintenance">
                <div class="row g-3">
                    <div class="col-md-6"><a class="manage-card" href="{{ route('admin.backups.index') }}"><span class="setting-icon bg-primary-subtle text-primary"><i class="fas fa-database"></i></span><div><h3>Database Backup</h3></div><i class="fas fa-chevron-right ms-auto"></i></a></div>
                    <div class="col-md-6"><a class="manage-card" href="{{ route('admin.activity-logs.index') }}"><span class="setting-icon bg-info-subtle text-info"><i class="fas fa-history"></i></span><div><h3>Activity Logs</h3></div><i class="fas fa-chevron-right ms-auto"></i></a></div>
                    <div class="col-md-6"><a class="manage-card" href="{{ route('admin.scheduler.index') }}"><span class="setting-icon bg-warning-subtle text-warning"><i class="fas fa-tasks"></i></span><div><h3>Scheduler Test</h3></div><i class="fas fa-chevron-right ms-auto"></i></a></div>
                    <div class="col-md-6"><button type="button" id="clearCache" class="manage-card w-100 text-start"><span class="setting-icon bg-danger-subtle text-danger"><i class="fas fa-broom"></i></span><div><h3>Clear Cache</h3></div><i class="fas fa-chevron-right ms-auto"></i></button></div>
                </div>
                <div class="alert alert-danger mt-3 mb-0"><strong>Security:</strong> </div>
            </section>

            <div class="settings-savebar"><button class="btn btn-primary px-4" type="submit" id="saveSettings"><i class="fas fa-save me-1"></i>Settings Save </button></div>
        </main>
    </div>
</form>

@push('scripts')
<style>
.settings-layout{display:grid;grid-template-columns:230px minmax(0,1fr);gap:1.25rem;align-items:start}.settings-nav{position:sticky;top:82px}.settings-tab{width:100%;display:flex;align-items:center;gap:.75rem;border:0;background:transparent;padding:.8rem .9rem;border-radius:.75rem;color:#475569;font-weight:600;text-align:left}.settings-tab:hover,.settings-tab.active{background:#eef2ff;color:#1d4ed8}.settings-tab i{width:20px}.settings-pane{display:none}.settings-pane.active{display:block}.setting-heading{display:flex;gap:.9rem;align-items:center;margin-bottom:1.15rem}.setting-heading h3,.manage-card h3{font-size:clamp(1rem,.94rem + .22vw,1.15rem);font-weight:700;line-height:1.2;margin:0 0 .12rem}.setting-heading p,.manage-card p{font-size:.78rem;line-height:1.4;color:#64748b;margin:0}.setting-icon{width:40px;height:40px;border-radius:12px;display:grid;place-items:center;flex:0 0 40px}.setting-switch{display:flex;gap:1rem;align-items:center;justify-content:space-between;padding:1rem 0;border-bottom:1px solid #eef2f7}.setting-switch-label{min-width:0;cursor:pointer}.setting-switch small{display:block;color:#64748b;margin-top:.2rem}.manage-card{display:flex;align-items:center;gap:.85rem;width:100%;min-height:92px;padding:.95rem 1rem;background:#fff;border:1px solid #e5eaf0;border-radius:1rem;text-decoration:none;color:#0f172a;transition:.2s}.manage-card:hover{transform:translateY(-2px);box-shadow:0 .7rem 1.5rem rgba(15,23,42,.08);border-color:#bfdbfe}.settings-savebar{position:sticky;bottom:0;margin-top:1rem;padding:1rem;background:rgba(255,255,255,.94);backdrop-filter:blur(10px);border:1px solid #e5eaf0;border-radius:1rem;display:flex;align-items:center;justify-content:space-between;z-index:5}.min-w-0{min-width:0}@media(max-width:767.98px){.settings-layout{grid-template-columns:1fr}.settings-nav{position:static;overflow:auto}.settings-nav .card-body{display:flex;min-width:max-content}.settings-tab{width:auto}.settings-tab span{white-space:nowrap}.settings-savebar{justify-content:stretch}.settings-savebar .btn{width:100%}}
</style>
<script>
document.addEventListener('DOMContentLoaded',()=>{
 const symbols={BDT:'৳',USD:'$',EUR:'€',GBP:'£',INR:'₹',JPY:'¥',AED:'د.إ',SAR:'ر.س'};document.getElementById('currencyCode')?.addEventListener('change',e=>document.getElementById('currencySymbol').value=symbols[e.target.value]||e.target.value);
 document.querySelectorAll('.settings-tab').forEach(tab=>tab.addEventListener('click',()=>{document.querySelectorAll('.settings-tab,.settings-pane').forEach(el=>el.classList.remove('active'));tab.classList.add('active');document.getElementById('settings-'+tab.dataset.target).classList.add('active')}));
 document.getElementById('settingsControlForm').addEventListener('submit',async e=>{e.preventDefault();const btn=document.getElementById('saveSettings');btn.disabled=true;try{await axios.post(@json(route('admin.settings.control-center')),new FormData(e.target));showToast('All settings save ','success')}catch(error){showToast(error.response?.data?.message||'Settings save ','error')}finally{btn.disabled=false}});
 document.getElementById('clearCache').addEventListener('click',async()=>{const ask=await Swal.fire({title:'Clear cache?',icon:'question',showCancelButton:true,confirmButtonText:'Yes'});if(!ask.isConfirmed)return;try{const r=await axios.post(@json(route('admin.settings.clear-cache')));Swal.fire('Done',r.data.message,'success')}catch(e){Swal.fire('Error',e.response?.data?.message||'Cache could not be cleared','error')}});
 document.getElementById('applyPaymentRedirect').addEventListener('click',async()=>{const ask=await Swal.fire({title:'Apply to all active MikroTik routers?',text:'Expired profile, pool and payment-only firewall rules will be created.',icon:'warning',showCancelButton:true,confirmButtonText:'Apply'});if(!ask.isConfirmed)return;Swal.fire({title:'Applying router configuration...',allowOutsideClick:false,didOpen:()=>Swal.showLoading()});try{const r=await axios.post(@json(route('admin.settings.apply-payment-redirect')));const d=r.data.data;Swal.fire(d.failed?'Partially completed':'Completed',`Configured: ${d.configured}, Failed: ${d.failed}${d.messages.length?'\n'+d.messages.join('\n'):''}`,d.failed?'warning':'success')}catch(e){Swal.fire('Apply failed',e.response?.data?.message||'Router configuration failed','error')}});
});
</script>
@endpush
</x-app-layout>
