@extends('admin.layouts.app')
@section('title', 'Settings')
@section('breadcrumb')
    <span class="current">Settings</span>
@endsection

@section('content')
<div class="page-header">
    <h1 class="page-title">
        <span class="title-icon"><i data-lucide="settings" style="width:20px;height:20px;"></i></span>
        System Settings
    </h1>
    <p class="page-subtitle">Application configuration and profile settings</p>
</div>

<div style="display:grid;grid-template-columns:220px 1fr;gap:16px;align-items:start;">

    {{-- Settings Navigation --}}
    <div class="glass-card" style="padding:8px 0;overflow:hidden;">
        @php
            $settingsNav = [
                ['id'=>'profile',      'icon'=>'user',         'label'=>'Profile'],
                ['id'=>'security',     'icon'=>'lock',         'label'=>'Security'],
                ['id'=>'ai',           'icon'=>'cpu',          'label'=>'AI Settings'],
                ['id'=>'application',  'icon'=>'settings',     'label'=>'Application'],
                ['id'=>'email',        'icon'=>'mail',         'label'=>'Email / SMTP'],
                ['id'=>'database',     'icon'=>'database',     'label'=>'Database'],
            ];
        @endphp
        @foreach($settingsNav as $nav)
            <button onclick="showTab('{{ $nav['id'] }}')" id="nav-{{ $nav['id'] }}"
                    class="admin-nav-item settings-tab-btn {{ $loop->first ? 'active' : '' }}"
                    style="width:100%;border:none;background:transparent;cursor:pointer;text-align:left;">
                <span class="nav-icon"><i data-lucide="{{ $nav['icon'] }}" style="width:15px;height:15px;"></i></span>
                <span class="nav-text">{{ $nav['label'] }}</span>
            </button>
        @endforeach
    </div>

    {{-- Settings Content --}}
    <div>

        {{-- Profile --}}
        <div id="tab-profile" class="glass-card settings-tab" style="padding:24px;">
            <div style="font-size:14px;font-weight:600;color:var(--vsc-text-active);margin-bottom:20px;display:flex;align-items:center;gap:8px;">
                <i data-lucide="user" style="width:16px;height:16px;color:var(--vsc-blue);"></i>
                Profile Settings
            </div>
            <form method="POST" action="{{ route('admin.settings.update') }}">
                @csrf @method('PUT')
                <input type="hidden" name="section" value="profile">
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                    <div class="form-group" style="grid-column:1/-1;">
                        <label class="form-label">Full Name</label>
                        <input type="text" name="name" value="{{ auth()->user()->name }}"
                               class="form-control" required>
                    </div>
                    <div class="form-group" style="grid-column:1/-1;">
                        <label class="form-label">Email Address</label>
                        <input type="email" name="email" value="{{ auth()->user()->email }}"
                               class="form-control" required>
                    </div>
                </div>
                <div style="display:flex;justify-content:flex-end;">
                    <button type="submit" class="btn btn-primary">
                        <i data-lucide="save" style="width:13px;height:13px;"></i>
                        Save Profile
                    </button>
                </div>
            </form>
        </div>

        {{-- Security --}}
        <div id="tab-security" class="glass-card settings-tab" style="padding:24px;display:none;">
            <div style="font-size:14px;font-weight:600;color:var(--vsc-text-active);margin-bottom:20px;display:flex;align-items:center;gap:8px;">
                <i data-lucide="lock" style="width:16px;height:16px;color:var(--vsc-orange);"></i>
                Security Settings
            </div>
            <form method="POST" action="{{ route('admin.settings.update') }}">
                @csrf @method('PUT')
                <input type="hidden" name="section" value="security">
                <div class="form-group">
                    <label class="form-label">Current Password</label>
                    <input type="password" name="current_password" class="form-control" placeholder="••••••••">
                </div>
                <div class="form-group">
                    <label class="form-label">New Password</label>
                    <input type="password" name="new_password" class="form-control" placeholder="Min 8 characters">
                </div>
                <div class="form-group">
                    <label class="form-label">Confirm New Password</label>
                    <input type="password" name="new_password_confirmation" class="form-control" placeholder="Repeat password">
                </div>
                <div style="display:flex;justify-content:flex-end;">
                    <button type="submit" class="btn btn-primary">
                        <i data-lucide="shield" style="width:13px;height:13px;"></i>
                        Update Password
                    </button>
                </div>
            </form>
        </div>

        {{-- AI Settings --}}
        <div id="tab-ai" class="glass-card settings-tab" style="padding:24px;display:none;">
            <div style="font-size:14px;font-weight:600;color:var(--vsc-text-active);margin-bottom:6px;display:flex;align-items:center;gap:8px;">
                <i data-lucide="cpu" style="width:16px;height:16px;color:var(--vsc-blue);"></i>
                AI Settings
            </div>
            <p style="font-size:12px;color:var(--vsc-text-secondary);margin:0 0 20px;">
                Configure your OpenAI API key to enable AI-powered regulation extraction, scanned document OCR,
                and plot survey analysis. Each installation uses its own key stored encrypted in the database.
            </p>

            @if(session('success') && session('active_tab') === 'ai')
                <div class="alert alert-success" style="margin-bottom:16px;">{{ session('success') }}</div>
            @endif

            {{-- Status banner --}}
            <div style="display:flex;align-items:center;gap:10px;padding:12px 16px;border-radius:8px;margin-bottom:20px;
                background:{{ $hasApiKey && $aiEnabled ? 'rgba(34,197,94,.1)' : 'rgba(239,68,68,.1)' }};
                border:1px solid {{ $hasApiKey && $aiEnabled ? 'rgba(34,197,94,.3)' : 'rgba(239,68,68,.3)' }};">
                <i data-lucide="{{ $hasApiKey && $aiEnabled ? 'check-circle' : 'alert-circle' }}"
                   style="width:16px;height:16px;color:{{ $hasApiKey && $aiEnabled ? 'var(--vsc-green)' : 'var(--vsc-red)' }};flex-shrink:0;"></i>
                <div style="font-size:12px;">
                    @if($hasApiKey && $aiEnabled)
                        <strong style="color:var(--vsc-green);">AI is active</strong>
                        <span style="color:var(--vsc-text-secondary);margin-left:4px;">— API key configured, features enabled.</span>
                    @elseif($hasApiKey && !$aiEnabled)
                        <strong style="color:var(--vsc-yellow);">API key saved but AI is disabled</strong>
                        <span style="color:var(--vsc-text-secondary);margin-left:4px;">— Enable the master switch below.</span>
                    @else
                        <strong style="color:var(--vsc-red);">AI is not configured</strong>
                        <span style="color:var(--vsc-text-secondary);margin-left:4px;">— Enter your OpenAI API key below to enable AI features.</span>
                    @endif
                </div>
            </div>

            <form method="POST" action="{{ route('admin.settings.update') }}">
                @csrf @method('PUT')
                <input type="hidden" name="section" value="ai">

                {{-- API Key --}}
                <div class="form-group">
                    <label class="form-label">
                        OpenAI API Key
                        <span style="color:var(--vsc-text-muted);font-weight:400;font-size:11px;margin-left:6px;">(stored encrypted in database)</span>
                    </label>

                    @if($hasApiKey)
                    <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;padding:10px 14px;background:var(--vsc-bg-secondary);border:1px solid var(--vsc-border);border-radius:6px;">
                        <i data-lucide="key" style="width:14px;height:14px;color:var(--vsc-green);flex-shrink:0;"></i>
                        <span style="font-family:monospace;font-size:12px;color:var(--vsc-teal);letter-spacing:.05em;">
                            {{ \App\Models\SystemSetting::masked('openai_api_key') }}
                        </span>
                        <span style="font-size:11px;color:var(--vsc-text-muted);margin-left:4px;">• key is saved</span>
                        <form method="POST" action="{{ route('admin.settings.clear-api-key') }}" style="margin-left:auto;" onsubmit="return confirm('Remove this API key?')">
                            @csrf @method('DELETE')
                            <button type="submit" style="background:none;border:none;color:var(--vsc-red);font-size:11px;cursor:pointer;padding:0;">
                                <i data-lucide="trash-2" style="width:12px;height:12px;"></i> Remove key
                            </button>
                        </form>
                    </div>
                    @endif

                    <input type="password" name="openai_api_key" class="form-control"
                           placeholder="{{ $hasApiKey ? 'Enter new key to replace existing one' : 'sk-proj-...' }}"
                           autocomplete="new-password">
                    <div class="form-hint">
                        Get your key at <a href="#" style="color:var(--vsc-blue);">platform.openai.com/api-keys</a>.
                        Leave blank to keep the existing key.
                    </div>
                </div>

                {{-- Master switch --}}
                <div class="form-group" style="display:flex;align-items:center;justify-content:space-between;padding:12px 16px;background:var(--vsc-bg-secondary);border-radius:6px;border:1px solid var(--vsc-border);">
                    <div>
                        <div style="font-size:13px;font-weight:500;color:var(--vsc-text-active);">Enable AI Features</div>
                        <div style="font-size:11px;color:var(--vsc-text-muted);">Master switch — enables regulation extraction, OCR, plot survey analysis.</div>
                    </div>
                    <label style="position:relative;display:inline-block;width:44px;height:24px;flex-shrink:0;">
                        <input type="checkbox" name="openai_enabled" value="1" style="opacity:0;width:0;height:0;"
                               {{ $aiEnabled ? 'checked' : '' }}>
                        <span style="position:absolute;cursor:pointer;inset:0;background:{{ $aiEnabled ? 'var(--vsc-blue)' : '#4b5563' }};border-radius:24px;transition:.3s;">
                            <span style="position:absolute;content:'';height:18px;width:18px;left:{{ $aiEnabled ? '21px' : '3px' }};bottom:3px;background:white;border-radius:50%;transition:.3s;"></span>
                        </span>
                    </label>
                </div>

                <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-top:16px;">
                    {{-- Chat model --}}
                    <div class="form-group" style="margin-bottom:0;">
                        <label class="form-label">Chat Model</label>
                        <select name="openai_model" class="form-control">
                            @foreach(['gpt-4o','gpt-4o-mini','gpt-4-turbo','gpt-4','gpt-3.5-turbo'] as $m)
                                <option value="{{ $m }}" {{ (\App\Models\SystemSetting::get('openai_model','gpt-4o') === $m) ? 'selected' : '' }}>{{ $m }}</option>
                            @endforeach
                        </select>
                        <div class="form-hint">For text-based regulation extraction.</div>
                    </div>
                    {{-- Vision model --}}
                    <div class="form-group" style="margin-bottom:0;">
                        <label class="form-label">Vision Model</label>
                        <select name="openai_vision_model" class="form-control">
                            @foreach(['gpt-4o','gpt-4o-mini','gpt-4-turbo'] as $m)
                                <option value="{{ $m }}" {{ (\App\Models\SystemSetting::get('openai_vision_model','gpt-4o') === $m) ? 'selected' : '' }}>{{ $m }}</option>
                            @endforeach
                        </select>
                        <div class="form-hint">For scanned PDF OCR and plot survey maps.</div>
                    </div>
                </div>

                <div class="form-group" style="margin-top:16px;">
                    <label class="form-label">Max Tokens per Request</label>
                    <input type="number" name="openai_max_tokens" class="form-control"
                           value="{{ \App\Models\SystemSetting::get('openai_max_tokens', '4096') }}"
                           min="512" max="32768" step="256" style="max-width:200px;">
                    <div class="form-hint">Higher value = more detailed AI output, higher cost. Default: 4096.</div>
                </div>

                {{-- Bhulekh toggle --}}
                <div class="form-group" style="display:flex;align-items:center;justify-content:space-between;padding:12px 16px;background:var(--vsc-bg-secondary);border-radius:6px;border:1px solid var(--vsc-border);">
                    <div>
                        <div style="font-size:13px;font-weight:500;color:var(--vsc-text-active);">Show Bhulekh Portal Links</div>
                        <div style="font-size:11px;color:var(--vsc-text-muted);">Show state land record portal links in plot survey results.</div>
                    </div>
                    @php $bhEnabled = \App\Models\SystemSetting::get('bhulekh_enabled','0') === '1'; @endphp
                    <input type="checkbox" name="bhulekh_enabled" value="1" {{ $bhEnabled ? 'checked' : '' }}
                           style="width:18px;height:18px;accent-color:var(--vsc-blue);">
                </div>

                <div style="display:flex;justify-content:flex-end;margin-top:20px;">
                    <button type="submit" class="btn btn-primary">
                        <i data-lucide="save" style="width:13px;height:13px;"></i>
                        Save AI Settings
                    </button>
                </div>
            </form>
        </div>

        {{-- Application --}}
        <div id="tab-application" class="glass-card settings-tab" style="padding:24px;display:none;">
            <div style="font-size:14px;font-weight:600;color:var(--vsc-text-active);margin-bottom:20px;display:flex;align-items:center;gap:8px;">
                <i data-lucide="settings" style="width:16px;height:16px;color:var(--vsc-teal);"></i>
                Application Settings
            </div>
            <div style="display:flex;flex-direction:column;gap:12px;">
                @php
                    $appInfo = [
                        ['label' => 'App Name',     'value' => config('app.name')],
                        ['label' => 'Laravel Version', 'value' => app()->version()],
                        ['label' => 'PHP Version',  'value' => PHP_VERSION],
                        ['label' => 'Environment',  'value' => app()->environment()],
                        ['label' => 'Database',     'value' => config('database.default')],
                        ['label' => 'Cache Driver', 'value' => config('cache.default')],
                        ['label' => 'Queue Driver', 'value' => config('queue.default')],
                        ['label' => 'Timezone',     'value' => config('app.timezone')],
                    ];
                @endphp
                @foreach($appInfo as $item)
                    <div style="display:flex;justify-content:space-between;align-items:center;padding:10px 0;border-bottom:1px solid var(--vsc-border-light);">
                        <span style="font-size:13px;color:var(--vsc-text-secondary);">{{ $item['label'] }}</span>
                        <span style="font-size:12px;font-family:'JetBrains Mono',monospace;color:var(--vsc-teal);">{{ $item['value'] }}</span>
                    </div>
                @endforeach
            </div>
        </div>

        {{-- Email --}}
        <div id="tab-email" class="glass-card settings-tab" style="padding:24px;display:none;">
            <div style="font-size:14px;font-weight:600;color:var(--vsc-text-active);margin-bottom:20px;display:flex;align-items:center;gap:8px;">
                <i data-lucide="mail" style="width:16px;height:16px;color:var(--vsc-purple);"></i>
                Email / SMTP Settings
            </div>
            <div class="alert alert-info" style="margin-bottom:16px;">
                <i data-lucide="info" class="alert-icon" style="width:15px;height:15px;"></i>
                Configure your mail settings in the <code style="color:var(--vsc-teal);">.env</code> file.
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;">
                @php
                    $mailInfo = [
                        ['label'=>'Mail Mailer', 'value'=>config('mail.default')],
                        ['label'=>'SMTP Host',   'value'=>config('mail.mailers.smtp.host','—')],
                        ['label'=>'SMTP Port',   'value'=>config('mail.mailers.smtp.port','—')],
                        ['label'=>'Encryption',  'value'=>config('mail.mailers.smtp.scheme','—')],
                        ['label'=>'From Address','value'=>config('mail.from.address','—')],
                        ['label'=>'From Name',   'value'=>config('mail.from.name','—')],
                    ];
                @endphp
                @foreach($mailInfo as $item)
                    <div style="background:rgba(60,60,60,0.3);border-radius:4px;padding:10px 12px;">
                        <div style="font-size:10px;color:var(--vsc-text-tertiary);text-transform:uppercase;letter-spacing:0.5px;margin-bottom:4px;">{{ $item['label'] }}</div>
                        <div style="font-size:13px;color:var(--vsc-text-active);font-family:monospace;">{{ $item['value'] }}</div>
                    </div>
                @endforeach
            </div>
        </div>

        {{-- Database --}}
        <div id="tab-database" class="glass-card settings-tab" style="padding:24px;display:none;">
            <div style="font-size:14px;font-weight:600;color:var(--vsc-text-active);margin-bottom:20px;display:flex;align-items:center;gap:8px;">
                <i data-lucide="database" style="width:16px;height:16px;color:var(--vsc-green);"></i>
                Database Settings
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;">
                @php
                    $dbInfo = [
                        ['label'=>'Connection',  'value'=>config('database.default')],
                        ['label'=>'Host',        'value'=>config('database.connections.mysql.host','—')],
                        ['label'=>'Port',        'value'=>config('database.connections.mysql.port','—')],
                        ['label'=>'Database',    'value'=>config('database.connections.mysql.database','—')],
                        ['label'=>'Username',    'value'=>config('database.connections.mysql.username','—')],
                        ['label'=>'Charset',     'value'=>config('database.connections.mysql.charset','—')],
                    ];
                @endphp
                @foreach($dbInfo as $item)
                    <div style="background:rgba(60,60,60,0.3);border-radius:4px;padding:10px 12px;">
                        <div style="font-size:10px;color:var(--vsc-text-tertiary);text-transform:uppercase;letter-spacing:0.5px;margin-bottom:4px;">{{ $item['label'] }}</div>
                        <div style="font-size:13px;color:var(--vsc-teal);font-family:monospace;">{{ $item['value'] }}</div>
                    </div>
                @endforeach
            </div>
        </div>

    </div>
</div>

@push('scripts')
<script>
function showTab(tabId) {
    document.querySelectorAll('.settings-tab').forEach(t => t.style.display = 'none');
    document.querySelectorAll('.settings-tab-btn').forEach(b => b.classList.remove('active'));
    document.getElementById('tab-' + tabId).style.display = 'block';
    document.getElementById('nav-' + tabId).classList.add('active');
    lucide.createIcons();
}

// Auto-open tab from server session (after form submit)
const activeTab = '{{ session("active_tab", "profile") }}';
if (activeTab !== 'profile') {
    showTab(activeTab);
}

// AI toggle visual feedback
document.querySelectorAll('[name="openai_enabled"]').forEach(function(cb) {
    cb.addEventListener('change', function() {
        const span = this.nextElementSibling;
        const dot  = span?.querySelector('span');
        if (this.checked) {
            if (span) span.style.background = 'var(--vsc-blue)';
            if (dot)  dot.style.left = '21px';
        } else {
            if (span) span.style.background = '#4b5563';
            if (dot)  dot.style.left = '3px';
        }
    });
});
</script>
@endpush

@endsection
