<template :key="$route.meta.name">
    <div class="main_component settings-page">
        <!-- Page Header -->
        <div class="card shadow-sm border-0 mb-3">
            <div class="card-body p-4">
                <div class="d-flex align-items-center justify-content-between flex-wrap gap-3">
                    <div>
                        <h4 class="fw-bold text-dark mb-1 d-flex align-items-center gap-2">
                            <i class="fa fa-sliders text-primary"></i> System Settings & Configurations
                        </h4>
                        <p class="text-muted mb-0 small">
                            Manage brand identity, SMS character rules, scheduler options, and gateway parameters.
                        </p>
                    </div>
                    <div class="d-flex gap-2">
                        <button
                            type="button"
                            class="btn btn-outline-secondary btn-sm px-3"
                            @click="fetchSettings"
                            :disabled="loading"
                        >
                            <i class="fa fa-refresh me-1" :class="{ 'fa-spin': loading }"></i> Reload
                        </button>
                        <button
                            type="button"
                            class="btn btn-primary btn-sm px-4 fw-semibold shadow-sm"
                            @click="saveAllSettings"
                            :disabled="saving"
                        >
                            <i v-if="saving" class="fa fa-spinner fa-spin me-1"></i>
                            <i v-else class="fa fa-check-circle me-1"></i>
                            {{ saving ? 'Saving Changes...' : 'Save Settings' }}
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main Content Area with Navigation Tabs -->
        <div class="row g-3">
            <!-- Left Sidebar Navigation Tabs -->
            <div class="col-lg-3 col-md-4">
                <div class="card shadow-sm border-0 sticky-nav">
                    <div class="card-body p-2">
                        <nav class="nav nav-pills flex-column settings-nav">
                            <button
                                type="button"
                                class="nav-link text-start d-flex align-items-center gap-3 py-3 px-3"
                                :class="{ active: activeTab === 'general' }"
                                @click="activeTab = 'general'"
                            >
                                <div class="nav-icon-box bg-primary-subtle text-primary">
                                    <i class="fa fa-building-o"></i>
                                </div>
                                <div>
                                    <strong class="d-block">General & Branding</strong>
                                    <small class="nav-subtitle text-muted">App Name, Logo, Contacts</small>
                                </div>
                            </button>

                            <button
                                type="button"
                                class="nav-link text-start d-flex align-items-center gap-3 py-3 px-3"
                                :class="{ active: activeTab === 'sms' }"
                                @click="activeTab = 'sms'"
                            >
                                <div class="nav-icon-box bg-success-subtle text-success">
                                    <i class="fa fa-commenting-o"></i>
                                </div>
                                <div>
                                    <strong class="d-block">SMS Engine & Limits</strong>
                                    <small class="nav-subtitle text-muted">Character counts, batch sizes</small>
                                </div>
                            </button>

                            <button
                                type="button"
                                class="nav-link text-start d-flex align-items-center gap-3 py-3 px-3"
                                :class="{ active: activeTab === 'scheduler' }"
                                @click="activeTab = 'scheduler'"
                            >
                                <div class="nav-icon-box bg-warning-subtle text-warning">
                                    <i class="fa fa-clock-o"></i>
                                </div>
                                <div>
                                    <strong class="d-block">Cron & Scheduler</strong>
                                    <small class="nav-subtitle text-muted">Background queue timers</small>
                                </div>
                            </button>

                            <button
                                type="button"
                                class="nav-link text-start d-flex align-items-center gap-3 py-3 px-3"
                                :class="{ active: activeTab === 'status' }"
                                @click="activeTab = 'status'"
                            >
                                <div class="nav-icon-box bg-info-subtle text-info">
                                    <i class="fa fa-server"></i>
                                </div>
                                <div>
                                    <strong class="d-block">Gateway & Status</strong>
                                    <small class="nav-subtitle text-muted">Server & FCM device health</small>
                                </div>
                            </button>

                            <button
                                type="button"
                                class="nav-link text-start d-flex align-items-center gap-3 py-3 px-3"
                                :class="{ active: activeTab === 'raw' }"
                                @click="activeTab = 'raw'"
                            >
                                <div class="nav-icon-box bg-secondary-subtle text-secondary">
                                    <i class="fa fa-code"></i>
                                </div>
                                <div>
                                    <strong class="d-block">Raw Key-Value</strong>
                                    <small class="nav-subtitle text-muted">Direct database keys</small>
                                </div>
                            </button>
                        </nav>
                    </div>
                </div>
            </div>

            <!-- Right Content Panels -->
            <div class="col-lg-9 col-md-8">
                <!-- TAB 1: General & Branding -->
                <div v-show="activeTab === 'general'" class="card shadow-sm border-0">
                    <div class="card-header bg-transparent border-bottom py-3">
                        <h5 class="card-title mb-0 fw-bold">
                            <i class="fa fa-building-o text-primary me-2"></i> General & Brand Identity
                        </h5>
                    </div>
                    <div class="card-body p-4">
                        <div class="row g-4">
                            <!-- Logo Upload -->
                            <div class="col-12">
                                <label class="form-label fw-bold">Application Logo</label>
                                <div class="d-flex align-items-center gap-4 flex-wrap">
                                    <div class="logo-preview-box rounded border bg-light p-2 text-center">
                                        <img
                                            v-if="settings.logo"
                                            :src="getLogoSrc(settings.logo)"
                                            alt="Logo Preview"
                                            class="img-fluid logo-img"
                                        />
                                        <div v-else class="text-muted small py-3">
                                            <i class="fa fa-image fa-2x mb-1 d-block"></i>
                                            No Logo Uploaded
                                        </div>
                                    </div>
                                    <div>
                                        <input
                                            type="file"
                                            ref="logoFileInput"
                                            class="d-none"
                                            accept="image/*"
                                            @change="handleLogoUpload"
                                        />
                                        <button
                                            type="button"
                                            class="btn btn-outline-primary btn-sm me-2"
                                            @click="$refs.logoFileInput.click()"
                                            :disabled="uploadingLogo"
                                        >
                                            <i v-if="uploadingLogo" class="fa fa-spinner fa-spin me-1"></i>
                                            <i v-else class="fa fa-upload me-1"></i>
                                            {{ settings.logo ? 'Change Logo' : 'Upload Logo' }}
                                        </button>
                                        <button
                                            v-if="settings.logo"
                                            type="button"
                                            class="btn btn-outline-danger btn-sm"
                                            @click="settings.logo = ''"
                                        >
                                            <i class="fa fa-trash me-1"></i> Remove
                                        </button>
                                        <small class="text-muted d-block mt-2">
                                            Recommended size: 240x60px. Supported formats: PNG, JPG, SVG, WebP. Max 2MB.
                                        </small>
                                    </div>
                                </div>
                            </div>

                            <hr class="my-0">

                            <!-- App Name -->
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Application Name <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fa fa-cube text-muted"></i></span>
                                    <input
                                        type="text"
                                        class="form-control"
                                        v-model="settings.name"
                                        placeholder="e.g. T-SMS SERVICE"
                                    />
                                </div>
                                <small class="text-muted">Displayed in sidebar, navbar, and page headers.</small>
                            </div>

                            <!-- System Tagline -->
                            <div class="col-md-6">
                                <label class="form-label fw-bold">System Tagline</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fa fa-tag text-muted"></i></span>
                                    <input
                                        type="text"
                                        class="form-control"
                                        v-model="settings.tagline"
                                        placeholder="e.g. High Performance SMS Gateway"
                                    />
                                </div>
                                <small class="text-muted">Short subtitle displayed across portal interfaces.</small>
                            </div>

                            <!-- Support Phone -->
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Support / Contact Phone</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fa fa-phone text-muted"></i></span>
                                    <input
                                        type="text"
                                        class="form-control"
                                        v-model="settings.phone_configuration"
                                        placeholder="e.g. +8801725785256"
                                    />
                                </div>
                            </div>

                            <!-- Support Email -->
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Support Email</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fa fa-envelope text-muted"></i></span>
                                    <input
                                        type="email"
                                        class="form-control"
                                        v-model="settings.email_configuration"
                                        placeholder="e.g. support@sms-gateway.com"
                                    />
                                </div>
                            </div>

                            <!-- Office Address -->
                            <div class="col-12">
                                <label class="form-label fw-bold">Headquarters / Office Address</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fa fa-map-marker text-muted"></i></span>
                                    <textarea
                                        class="form-control"
                                        rows="2"
                                        v-model="settings.address_configuration"
                                        placeholder="e.g. TMSS Bhaban (5th Floor), West Kazipara, Mirpur-10, Dhaka-1216."
                                    ></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- TAB 2: SMS Engine & Limits -->
                <div v-show="activeTab === 'sms'" class="card shadow-sm border-0">
                    <div class="card-header bg-transparent border-bottom py-3">
                        <h5 class="card-title mb-0 fw-bold">
                            <i class="fa fa-commenting-o text-success me-2"></i> SMS Engine Rules & Limits
                        </h5>
                    </div>
                    <div class="card-body p-4">
                        <div class="row g-4">
                            <!-- English Character Limit -->
                            <div class="col-md-6">
                                <label class="form-label fw-bold">English (GSM-7) Single SMS Length</label>
                                <div class="input-group">
                                    <input
                                        type="number"
                                        class="form-control"
                                        v-model="settings.english_one_sms_count"
                                        placeholder="160"
                                        min="1"
                                    />
                                    <span class="input-group-text">Characters</span>
                                </div>
                                <small class="text-muted">Standard GSM 7-bit character count per single SMS part (Default: 160).</small>
                            </div>

                            <!-- Unicode Character Limit -->
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Unicode (Bangla / Arabic) Single SMS Length</label>
                                <div class="input-group">
                                    <input
                                        type="number"
                                        class="form-control"
                                        v-model="settings.unicode_one_sms_count"
                                        placeholder="70"
                                        min="1"
                                    />
                                    <span class="input-group-text">Characters</span>
                                </div>
                                <small class="text-muted">Unicode character count for non-Latin languages per single SMS part (Default: 70).</small>
                            </div>

                            <!-- Transactional Batch Size -->
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Transactional SMS Batch Chunk Size</label>
                                <div class="input-group">
                                    <input
                                        type="number"
                                        class="form-control"
                                        v-model="settings.transactional_sms_chunk_size"
                                        placeholder="100"
                                        min="1"
                                    />
                                    <span class="input-group-text">Messages / Batch</span>
                                </div>
                                <small class="text-muted">Number of messages sent concurrently in one transactional dispatch queue.</small>
                            </div>

                            <!-- Promotional Batch Size -->
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Promotional / Bulk SMS Batch Size</label>
                                <div class="input-group">
                                    <input
                                        type="number"
                                        class="form-control"
                                        v-model="settings.promotional_sms_chunk_size"
                                        placeholder="50"
                                        min="1"
                                    />
                                    <span class="input-group-text">Messages / Batch</span>
                                </div>
                                <small class="text-muted">Number of messages queued per promotional chunk to avoid mobile carrier throttling.</small>
                            </div>

                            <!-- Default Country Code -->
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Default Country Dialing Code</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fa fa-globe text-muted"></i></span>
                                    <input
                                        type="text"
                                        class="form-control"
                                        v-model="settings.country_code"
                                        placeholder="880"
                                    />
                                </div>
                                <small class="text-muted">Automatically prepended to local numbers if no country prefix is supplied.</small>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- TAB 3: Cron & Scheduler -->
                <div v-show="activeTab === 'scheduler'" class="card shadow-sm border-0">
                    <div class="card-header bg-transparent border-bottom py-3">
                        <h5 class="card-title mb-0 fw-bold">
                            <i class="fa fa-clock-o text-warning me-2"></i> Cron & Background Job Scheduler
                        </h5>
                    </div>
                    <div class="card-body p-4">
                        <div class="row g-4">
                            <!-- Scheduler Check Interval -->
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Schedule Poller Interval</label>
                                <div class="input-group">
                                    <input
                                        type="number"
                                        class="form-control"
                                        v-model="settings.scheduler_check_time"
                                        placeholder="20"
                                        min="1"
                                    />
                                    <span class="input-group-text">Minutes</span>
                                </div>
                                <small class="text-muted">Frequency interval for checking pending and scheduled SMS jobs.</small>
                            </div>

                            <!-- Auto Retry Failed -->
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Auto Retry Failed Messages</label>
                                <select class="form-select form-control" v-model="settings.auto_retry_failed">
                                    <option value="1">Enabled (Automatic)</option>
                                    <option value="0">Disabled (Manual Only)</option>
                                </select>
                                <small class="text-muted">Whether failed gateway messages should automatically return to queue.</small>
                            </div>

                            <!-- Max Retry Attempts -->
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Maximum Retry Attempts</label>
                                <div class="input-group">
                                    <input
                                        type="number"
                                        class="form-control"
                                        v-model="settings.max_retry_attempts"
                                        placeholder="3"
                                        min="1"
                                        max="10"
                                    />
                                    <span class="input-group-text">Attempts</span>
                                </div>
                                <small class="text-muted">Upper attempt ceiling before an SMS is marked permanently failed.</small>
                            </div>

                            <!-- Cron Command Helper -->
                            <div class="col-12">
                                <div class="p-3 bg-light rounded border">
                                    <h6 class="fw-bold mb-2 text-dark"><i class="fa fa-terminal text-primary me-1"></i> System Cron Command</h6>
                                    <p class="text-muted small mb-2">Ensure your server's crontab includes the Laravel scheduler entry below:</p>
                                    <div class="d-flex align-items-center justify-content-between bg-dark text-white p-2 rounded font-monospace small">
                                        <code>* * * * * cd /var/www/PHPProjects/SMS_Gateway && php artisan schedule:run >> /dev/null 2>&1</code>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- TAB 4: Gateway & System Status -->
                <div v-show="activeTab === 'status'" class="card shadow-sm border-0">
                    <div class="card-header bg-transparent border-bottom py-3">
                        <h5 class="card-title mb-0 fw-bold">
                            <i class="fa fa-server text-info me-2"></i> Gateway & Environment Status
                        </h5>
                    </div>
                    <div class="card-body p-4">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <div class="status-card p-3 rounded border bg-light d-flex align-items-center justify-content-between">
                                    <div>
                                        <small class="text-muted d-block">PHP Runtime Version</small>
                                        <strong class="text-dark fs-16">{{ systemInfo.php_version || '-' }}</strong>
                                    </div>
                                    <span class="badge bg-success-subtle text-success fs-12">Active</span>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="status-card p-3 rounded border bg-light d-flex align-items-center justify-content-between">
                                    <div>
                                        <small class="text-muted d-block">Laravel Framework</small>
                                        <strong class="text-dark fs-16">v{{ systemInfo.laravel_version || '-' }}</strong>
                                    </div>
                                    <span class="badge bg-primary-subtle text-primary fs-12">{{ systemInfo.environment || 'Production' }}</span>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="status-card p-3 rounded border bg-light d-flex align-items-center justify-content-between">
                                    <div>
                                        <small class="text-muted d-block">Firebase FCM Push Service</small>
                                        <strong class="text-dark fs-16">
                                            {{ systemInfo.fcm_configured ? 'Configured & Ready' : 'Simulated / Not Linked' }}
                                        </strong>
                                    </div>
                                    <span
                                        class="badge fs-12"
                                        :class="systemInfo.fcm_configured ? 'bg-success-subtle text-success' : 'bg-warning-subtle text-warning'"
                                    >
                                        {{ systemInfo.fcm_configured ? 'Online' : 'Pending Key' }}
                                    </span>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="status-card p-3 rounded border bg-light d-flex align-items-center justify-content-between">
                                    <div>
                                        <small class="text-muted d-block">Active Gateway Android Devices</small>
                                        <strong class="text-dark fs-16">{{ systemInfo.active_devices_count || 0 }} Device(s)</strong>
                                    </div>
                                    <span class="badge bg-info-subtle text-info fs-12">Synced</span>
                                </div>
                            </div>

                            <div class="col-12">
                                <div class="status-card p-3 rounded border bg-light d-flex align-items-center justify-content-between">
                                    <div>
                                        <small class="text-muted d-block">Server Time (Current Sync)</small>
                                        <strong class="text-dark fs-15">{{ systemInfo.server_time || '-' }}</strong>
                                    </div>
                                    <span class="badge bg-secondary-subtle text-secondary fs-12">UTC Synchronized</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- TAB 5: Raw Key-Value Database Table -->
                <div v-show="activeTab === 'raw'" class="card shadow-sm border-0">
                    <div class="card-header bg-transparent border-bottom py-3 d-flex align-items-center justify-content-between">
                        <h5 class="card-title mb-0 fw-bold">
                            <i class="fa fa-code text-secondary me-2"></i> Database Configuration Keys
                        </h5>
                        <button
                            type="button"
                            class="btn btn-sm btn-outline-primary"
                            @click="openAddRawModal"
                        >
                            <i class="fa fa-plus-circle me-1"></i> Add Custom Key
                        </button>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th>#ID</th>
                                        <th>Key</th>
                                        <th>Display Name</th>
                                        <th>Type</th>
                                        <th>Value</th>
                                        <th class="text-end">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="item in rawList" :key="item.id">
                                        <td class="text-muted small">#{{ item.id }}</td>
                                        <td><code>{{ item.key }}</code></td>
                                        <td><strong>{{ item.display_name }}</strong></td>
                                        <td><span class="badge bg-light text-dark border">{{ item.type || 'text' }}</span></td>
                                        <td>
                                            <div class="text-truncate" style="max-width: 200px;" :title="item.value">
                                                {{ item.value }}
                                            </div>
                                        </td>
                                        <td class="text-end">
                                            <div class="hstack gap-2 justify-content-end">
                                                <button
                                                    type="button"
                                                    class="btn btn-sm btn-icon btn-light text-primary"
                                                    @click="editRawItem(item)"
                                                    title="Edit Key"
                                                >
                                                    <i class="fa fa-edit"></i>
                                                </button>
                                                <button
                                                    type="button"
                                                    class="btn btn-sm btn-icon btn-light text-danger"
                                                    @click="deleteRawItem(item)"
                                                    title="Delete Key"
                                                >
                                                    <i class="fa fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    <tr v-if="rawList.length === 0">
                                        <td colspan="6" class="text-center py-4 text-muted">
                                            No configuration rows found.
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Bottom Floating / Sticky Save Bar -->
                <div class="card shadow-sm border-0 mt-3" v-if="activeTab !== 'raw'">
                    <div class="card-body p-3 d-flex align-items-center justify-content-between bg-light rounded">
                        <div class="text-muted small">
                            <i class="fa fa-info-circle text-primary me-1"></i>
                            Changes apply immediately across the entire SMS Gateway system.
                        </div>
                        <button
                            type="button"
                            class="btn btn-primary px-4 fw-semibold shadow-sm"
                            @click="saveAllSettings"
                            :disabled="saving"
                        >
                            <i v-if="saving" class="fa fa-spinner fa-spin me-1"></i>
                            <i v-else class="fa fa-save me-1"></i>
                            {{ saving ? 'Saving Changes...' : 'Save Settings' }}
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Add / Edit Raw Key Modal -->
        <general-modal modal-id="rawConfigModal" modal-size="modal-md">
            <template v-slot:title>
                <span>{{ rawForm.id ? 'Edit Configuration Key' : 'Add New Configuration Key' }}</span>
            </template>
            <template v-slot:body>
                <form @submit.prevent="submitRawForm">
                    <div class="mb-3">
                        <label class="form-label fw-bold">Configuration Key <span class="text-danger">*</span></label>
                        <input
                            type="text"
                            class="form-control"
                            v-model="rawForm.key"
                            placeholder="e.g. custom_gateway_token"
                            required
                        />
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Display Name <span class="text-danger">*</span></label>
                        <input
                            type="text"
                            class="form-control"
                            v-model="rawForm.display_name"
                            placeholder="e.g. Custom Gateway Token"
                            required
                        />
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Type</label>
                        <select class="form-select form-control" v-model="rawForm.type">
                            <option value="text">Text</option>
                            <option value="number">Number</option>
                            <option value="textarea">Textarea</option>
                            <option value="select">Select / Toggle</option>
                            <option value="file">File / Image</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Value <span class="text-danger">*</span></label>
                        <textarea
                            class="form-control"
                            rows="3"
                            v-model="rawForm.value"
                            placeholder="Enter configuration value"
                            required
                        ></textarea>
                    </div>
                    <div class="d-flex justify-content-end gap-2">
                        <button type="button" class="btn btn-secondary" @click="closeModal('rawConfigModal')">
                            Cancel
                        </button>
                        <button type="submit" class="btn btn-primary" :disabled="savingRaw">
                            <i v-if="savingRaw" class="fa fa-spinner fa-spin me-1"></i>
                            <i v-else class="fa fa-save me-1"></i>
                            Save Key
                        </button>
                    </div>
                </form>
            </template>
        </general-modal>
    </div>
</template>

<script>
import axios from 'axios';
import GeneralModal from "../../components/generalModal";

export default {
    name: "configurationList",
    components: { GeneralModal },
    data() {
        return {
            activeTab: 'general',
            loading: false,
            saving: false,
            uploadingLogo: false,
            savingRaw: false,
            settings: {
                name: 'T-SMS SERVICE',
                logo: '',
                tagline: 'High Performance SMS Gateway Platform',
                phone_configuration: '01725785256',
                address_configuration: 'TMSS Bhaban (5th Floor), West Kazipara, Mirpur-10, Dhaka-1216.',
                email_configuration: 'support@sms-gateway.com',
                country_code: '880',
                english_one_sms_count: '160',
                unicode_one_sms_count: '70',
                transactional_sms_chunk_size: '100',
                promotional_sms_chunk_size: '50',
                scheduler_check_time: '20',
                auto_retry_failed: '1',
                max_retry_attempts: '3',
            },
            rawList: [],
            systemInfo: {
                php_version: '',
                laravel_version: '',
                server_time: '',
                environment: '',
                fcm_configured: false,
                active_devices_count: 0
            },
            rawForm: {
                id: null,
                key: '',
                display_name: '',
                type: 'text',
                value: ''
            }
        };
    },
    methods: {
        async fetchSettings() {
            this.loading = true;
            try {
                const response = await axios.get('/api/settings');
                if (response.data && response.data.status === 2000) {
                    const res = response.data;
                    if (res.settings) {
                        this.settings = Object.assign({}, this.settings, res.settings);
                    }
                    if (res.system_info) {
                        this.systemInfo = res.system_info;
                    }
                    if (res.result && res.result.data) {
                        this.rawList = res.result.data;
                    } else if (Array.isArray(res.data)) {
                        this.rawList = res.data;
                    }
                }
            } catch (error) {
                console.error('Failed to load configurations:', error);
                this.toastMsg('error', 'Could not load system configurations.');
            } finally {
                this.loading = false;
            }
        },

        async saveAllSettings() {
            this.saving = true;
            try {
                const response = await axios.post('/api/settings', {
                    settings: this.settings
                });

                if (response.data && response.data.status === 2000) {
                    this.toastMsg('success', 'System settings saved successfully!');
                    this.fetchSettings();
                } else {
                    this.toastMsg('error', response.data.message || 'Failed to save settings.');
                }
            } catch (error) {
                console.error('Save error:', error);
                this.toastMsg('error', error.response?.data?.message || 'Error saving settings.');
            } finally {
                this.saving = false;
            }
        },

        async handleLogoUpload(event) {
            const file = event.target.files[0];
            if (!file) return;

            const formData = new FormData();
            formData.append('file', file);

            this.uploadingLogo = true;
            try {
                const response = await axios.post('/api/file_upload', formData, {
                    headers: { 'Content-Type': 'multipart/form-data' }
                });

                if (response.data && response.data.status === 2000) {
                    this.settings.logo = response.data.result;
                    this.toastMsg('success', 'Logo uploaded. Remember to click "Save Settings".');
                } else {
                    this.toastMsg('error', response.data.message || 'Logo upload failed.');
                }
            } catch (err) {
                console.error('Logo upload error:', err);
                this.toastMsg('error', 'Failed to upload logo.');
            } finally {
                this.uploadingLogo = false;
                event.target.value = '';
            }
        },

        getLogoSrc(path) {
            if (!path) return '';
            if (path.startsWith('http') || path.startsWith('/')) return path;
            if (typeof this.getImage === 'function') {
                return this.getImage(path);
            }
            return `/storage/${path}`;
        },

        openAddRawModal() {
            this.rawForm = {
                id: null,
                key: '',
                display_name: '',
                type: 'text',
                value: ''
            };
            this.openModal('rawConfigModal');
        },

        editRawItem(item) {
            this.rawForm = {
                id: item.id,
                key: item.key,
                display_name: item.display_name,
                type: item.type || 'text',
                value: item.value || ''
            };
            this.openModal('rawConfigModal');
        },

        async submitRawForm() {
            this.savingRaw = true;
            try {
                let response;
                if (this.rawForm.id) {
                    response = await axios.put(`/api/settings/${this.rawForm.id}`, this.rawForm);
                } else {
                    response = await axios.post('/api/settings', this.rawForm);
                }

                if (response.data && response.data.status === 2000) {
                    this.toastMsg('success', 'Configuration key saved.');
                    this.closeModal('rawConfigModal');
                    this.fetchSettings();
                } else {
                    this.toastMsg('error', response.data.message || 'Could not save key.');
                }
            } catch (err) {
                this.toastMsg('error', 'Error saving configuration key.');
            } finally {
                this.savingRaw = false;
            }
        },

        async deleteRawItem(item) {
            if (!confirm(`Are you sure you want to delete configuration key "${item.key}"?`)) return;

            try {
                const response = await axios.delete(`/api/settings/${item.id}`);
                if (response.data && response.data.status === 2000) {
                    this.toastMsg('success', 'Configuration key deleted.');
                    this.fetchSettings();
                } else {
                    this.toastMsg('error', response.data.message || 'Could not delete key.');
                }
            } catch (err) {
                this.toastMsg('error', 'Error deleting configuration key.');
            }
        },

        toastMsg(type, message) {
            if (this.$toastr) {
                this.$toastr(type === 'error' ? 'error' : 'success', message, type.toUpperCase());
            } else {
                alert(message);
            }
        }
    },
    mounted() {
        this.fetchSettings();
    }
};
</script>

<style scoped>
.settings-nav .nav-link {
    border-radius: 10px;
    margin-bottom: 6px;
    color: #495057;
    background: transparent;
    transition: all 0.2s ease;
    border: 1px solid transparent;
}
.settings-nav .nav-link:hover {
    background-color: #f8fafc;
    border-color: #e2e8f0;
}
.settings-nav .nav-link.active {
    background-color: #ffffff;
    color: #0f172a;
    border-color: #cbd5e1;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}
.nav-icon-box {
    width: 38px;
    height: 38px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    flex-shrink: 0;
}
.nav-subtitle {
    font-size: 11px;
}
.logo-preview-box {
    width: 220px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f8fafc;
}
.logo-img {
    max-height: 64px;
    max-width: 100%;
    object-fit: contain;
}
.status-card {
    transition: all 0.2s ease;
}
.status-card:hover {
    border-color: #94a3b8 !important;
}
.sticky-nav {
    position: sticky;
    top: 80px;
}
</style>
