<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
     
   @hotelSettings
    <title>Settings - {{ config('app.name') }}</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-green: {{ \App\Services\SettingsService::THEME_PRIMARY_GREEN }};
            --secondary-green: {{ \App\Services\SettingsService::THEME_SECONDARY_GREEN }};
            --light-green: {{ \App\Services\SettingsService::THEME_LIGHT_GREEN }};
            --dark-green: {{ \App\Services\SettingsService::THEME_DARK_GREEN }};
            --accent: {{ \App\Services\SettingsService::THEME_ACCENT }};
            --font-family: {{ old('font_family', $settings['font_family'] ?? "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif") }};
            --bs-primary: {{ \App\Services\SettingsService::THEME_PRIMARY_GREEN }};
            --bs-secondary: {{ \App\Services\SettingsService::THEME_SECONDARY_GREEN }};
            --bs-success: {{ \App\Services\SettingsService::THEME_PRIMARY_GREEN }};
            --bs-link-color: {{ \App\Services\SettingsService::THEME_PRIMARY_GREEN }};
            --bs-link-hover-color: {{ \App\Services\SettingsService::THEME_DARK_GREEN }};
        }
        
        body {
            background-color: #f8f9fa;
            font-family: var(--font-family);
        }

        body.theme-dark {
            background-color: #1a1a1a;
            color: #f0f0f0;
        }

        body.theme-dark .card,
        body.theme-dark .settings-card,
        body.theme-dark .sidebar {
            background-color: #2d2d2d;
            color: #f0f0f0;
        }

        body.theme-dark .form-control,
        body.theme-dark .form-select {
            background-color: #222;
            color: #f0f0f0;
            border-color: #444;
        }

        body.theme-dark .text-muted,
        body.theme-dark .form-text {
            color: #b0b0b0 !important;
        }
        
        .navbar {
            background: linear-gradient(90deg, var(--dark-green) 0%, var(--primary-green) 100%);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        
        .sidebar {
            background-color: white;
            box-shadow: 3px 0 10px rgba(0, 0, 0, 0.1);
            height: calc(100vh - 56px);
            position: fixed;
            top: 56px;
            padding: 15px;
            z-index: 1000;
            overflow-y: auto;
            width: 250px;
        }
        
        .sidebar .nav-link {
            color: #495057;
            padding: 15px 20px;
            border-left: 4px solid transparent;
            transition: all 0.3s;
        }
        
        .sidebar .nav-link:hover {
            background-color: #f8f9fa;
            border-left: 4px solid var(--secondary-green);
        }
        
        .sidebar .nav-link.active {
            background-color: var(--light-green);
            color: var(--dark-green);
            border-left: 4px solid var(--primary-green);
            font-weight: 600;
        }
        
        .sidebar .nav-link i {
            margin-right: 10px;
            color: var(--primary-green);
        }
        
        .main-content {
            margin-left: 250px;
            padding: 20px;
            margin-top: 56px;
        }
        
        .settings-card {
            border-radius: 10px;
            transition: transform 0.3s, box-shadow 0.3s;
            border: none;
            margin-bottom: 20px;
        }
        
        .settings-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        .card-header {
            background: linear-gradient(90deg, var(--primary-green) 0%, var(--secondary-green) 100%);
            color: white;
            border-radius: 10px 10px 0 0 !important;
            padding: 1rem 1.5rem;
        }
        
        .card-header h5 {
            margin: 0;
            font-weight: 600;
        }
        
        .bg-primary {
            background-color: var(--primary-green) !important;
        }
        
        .text-primary {
            color: var(--primary-green) !important;
        }
        
        .btn-primary {
            background-color: var(--primary-green);
            border-color: var(--primary-green);
        }
        
        .btn-primary:hover {
            background-color: var(--dark-green);
            border-color: var(--dark-green);
        }
        
        .btn-outline-primary {
            color: var(--primary-green);
            border-color: var(--primary-green);
        }
        
        .btn-outline-primary:hover {
            background-color: var(--primary-green);
            border-color: var(--primary-green);
        }
        
        .settings-section {
            margin-bottom: 30px;
        }
        
        .settings-section h5 {
            border-bottom: 2px solid var(--primary-green);
            padding-bottom: 10px;
            margin-bottom: 20px;
            color: var(--dark-green);
        }
        
        .color-preview {
            width: 30px;
            height: 30px;
            border-radius: 4px;
            display: inline-block;
            margin-right: 10px;
            border: 1px solid #ddd;
        }
        
        .backup-card {
            cursor: pointer;
            transition: all 0.3s;
            height: 100%;
        }
        
        .backup-card:hover {
            background-color: #f8f9fa;
        }
        
        .backup-card .card-body {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 2rem;
        }
        
        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                position: relative;
                height: auto;
                top: 0;
            }
            
            .main-content {
                margin-left: 0;
            }
        }
        
        .tab-pane {
            padding: 20px 0;
        }
        
        .settings-tabs .nav-link {
            color: var(--dark-green);
            padding: 12px 15px;
            border-radius: 5px;
            margin-bottom: 5px;
        }
        
        .settings-tabs .nav-link.active {
            background-color: var(--light-green);
            color: var(--dark-green);
            font-weight: 600;
        }

        .nav-pills .nav-link.active,
        .nav-pills .show > .nav-link {
            background-color: var(--primary-green) !important;
            color: #fff !important;
        }
        
        .settings-tabs .nav-link:hover:not(.active) {
            background-color: #f8f9fa;
        }
        
        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
        }
        
        .form-label {
            font-weight: 500;
            color: var(--dark-green);
            margin-bottom: 0.5rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--primary-green);
            box-shadow: 0 0 0 0.25rem rgba(26, 147, 111, 0.25);
        }
        
        .form-check-input:checked {
            background-color: var(--primary-green);
            border-color: var(--primary-green);
        }
        
        .table th {
            color: var(--dark-green);
            font-weight: 600;
        }
        
        .badge.bg-primary {
            background-color: var(--primary-green) !important;
        }
        
        .badge.bg-success {
            background-color: var(--secondary-green) !important;
            color: var(--dark-green);
        }
        
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.8);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 10000;
        }
        
        .loading-overlay.active {
            display: flex;
        }
        
        .spinner {
            width: 50px;
            height: 50px;
            border: 5px solid var(--light-green);
            border-top-color: var(--primary-green);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .alert {
            border-radius: 10px;
            border: none;
        }
        
        .alert-warning {
            background-color: #fff3cd;
            color: #856404;
        }
        
        .input-group-text.color-preview {
            width: 40px;
            height: 40px;
            padding: 0;
            border: 2px solid #fff;
            box-shadow: 0 0 0 1px #ddd;
        }
        
        .test-smtp-btn {
            margin-top: 32px;
        }
        
        .integration-card {
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
        }
        
        .integration-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .section-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--dark-green);
            margin-bottom: 15px;
        }
        
        .csrf-warning {
            display: none;
        }
    </style>
    <link rel="stylesheet" href="{{ asset('css/admin-elegant-theme.css') }}">
</head>
<body class="hotel-settings-elegant {{ (old('theme_mode', $settings['theme_mode'] ?? 'light') === 'dark') ? 'theme-dark' : 'theme-light' }}">
    <!-- Loading Overlay -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="spinner"></div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-cogs me-2"></i>System Settings</h2>
            <div>
                <a href="{{ route('dashboard') }}" class="btn btn-outline-primary me-2">
                    <i class="fas fa-tachometer-alt me-2"></i>Back to Dashboard
                </a>
                <button class="btn btn-primary" id="saveSettings">
                    <i class="fas fa-save me-2"></i>Save All Settings
                </button>
            </div>
        </div>

        <!-- CSRF Warning Alert (hidden by default) -->
        <div class="alert alert-warning alert-dismissible fade show csrf-warning" id="csrfWarning" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i>
            <strong>CSRF Token Mismatch!</strong> Your session may have expired. 
            <button type="button" class="btn btn-sm btn-outline-warning ms-2" onclick="refreshPage()">Refresh Page</button>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>

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

            <div class="row">
                <div class="col-md-3">
                    <div class="card settings-card sticky-top" style="top: 70px;">
                        <div class="card-body p-0">
                            <div class="nav flex-column nav-pills settings-tabs p-3" id="v-pills-tab" role="tablist">
                                <button class="nav-link active" id="general-tab" data-bs-toggle="pill" data-bs-target="#general" type="button" role="tab">
                                    <i class="fas fa-cog me-2"></i>General
                                </button>
                                <button class="nav-link" id="currency-tab" data-bs-toggle="pill" data-bs-target="#currency" type="button" role="tab">
                                    <i class="fas fa-money-bill me-2"></i>Currency & Rates
                                </button>
                                <button class="nav-link" id="backup-tab" data-bs-toggle="pill" data-bs-target="#backup" type="button" role="tab">
                                    <i class="fas fa-database me-2"></i>Backup & Restore
                                </button>
                                <button class="nav-link" id="notifications-tab" data-bs-toggle="pill" data-bs-target="#notifications" type="button" role="tab">
                                    <i class="fas fa-bell me-2"></i>Notifications
                                </button>
                                <button class="nav-link" id="integration-tab" data-bs-toggle="pill" data-bs-target="#integrations" type="button" role="tab">
                                    <i class="fas fa-plug me-2"></i>Integrations
                                </button>
                                <button class="nav-link" id="users-tab" data-bs-toggle="pill" data-bs-target="#users" type="button" role="tab">
                                    <i class="fas fa-users me-2"></i>Users & Permissions
                                </button>
                                <button class="nav-link" id="payments-tab" data-bs-toggle="pill" data-bs-target="#payments" type="button" role="tab">
                                    <i class="fas fa-credit-card me-2"></i>Payments
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-9">
                    <div class="tab-content" id="v-pills-tabContent">
                        <!-- General Settings -->
                        <div class="tab-pane fade show active" id="general" role="tabpanel">
                            <div class="card settings-card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-cog me-2"></i>General System Settings</h5>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label for="hotel_name" class="form-label">Hotel Name <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" 
                                                   id="hotel_name" name="hotel_name" 
                                                   value="{{ old('hotel_name', $settings['hotel_name'] ?? hotelName()) }}" required>
                                        </div>
                                        <div class="col-md-6">
                                            <label for="hotel_address" class="form-label">Hotel Address <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" 
                                                   id="hotel_address" name="hotel_address" 
                                                   value="{{ old('hotel_address', $settings['hotel_address'] ?? '123 Luxury Street, City') }}" required>
                                        </div>
                                    </div>
                                    
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label for="hotel_phone" class="form-label">Phone Number <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" 
                                                   id="hotel_phone" name="hotel_phone" 
                                                   value="{{ old('hotel_phone', $settings['hotel_phone'] ?? '+1 (555) 123-4567') }}" required>
                                        </div>
                                        <div class="col-md-6">
                                            <label for="hotel_email" class="form-label">Email Address <span class="text-danger">*</span></label>
                                            <input type="email" class="form-control" 
                                                   id="hotel_email" name="hotel_email" 
                                                   value="{{ old('hotel_email', $settings['hotel_email'] ?? 'info@deluxehotel.com') }}" required>
                                        </div>
                                    </div>
                                    
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label for="timezone" class="form-label">Timezone <span class="text-danger">*</span></label>
                                            <select class="form-select" id="timezone" name="timezone" required>
                                                @foreach($timezones as $tz)
                                                    <option value="{{ $tz['value'] }}" {{ (old('timezone', $settings['timezone'] ?? 'Africa/Nairobi') == $tz['value']) ? 'selected' : '' }}>
                                                        {{ $tz['label'] }}
                                                    </option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <div class="col-md-6">
                                            <label for="date_format" class="form-label">Date Format <span class="text-danger">*</span></label>
                                            <select class="form-select" id="date_format" name="date_format" required>
                                                <option value="Y-m-d" {{ (old('date_format', $settings['date_format'] ?? 'Y-m-d') == 'Y-m-d') ? 'selected' : '' }}>YYYY-MM-DD</option>
                                                <option value="m/d/Y" {{ (old('date_format', $settings['date_format'] ?? 'Y-m-d') == 'm/d/Y') ? 'selected' : '' }}>MM/DD/YYYY</option>
                                                <option value="d/m/Y" {{ (old('date_format', $settings['date_format'] ?? 'Y-m-d') == 'd/m/Y') ? 'selected' : '' }}>DD/MM/YYYY</option>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label for="checkin_time" class="form-label">Default Check-in Time <span class="text-danger">*</span></label>
                                            <input type="time" class="form-control" 
                                                   id="checkin_time" name="checkin_time" 
                                                   value="{{ old('checkin_time', $settings['checkin_time'] ?? '14:00') }}" required>
                                        </div>
                                        <div class="col-md-6">
                                            <label for="checkout_time" class="form-label">Default Check-out Time <span class="text-danger">*</span></label>
                                            <input type="time" class="form-control" 
                                                   id="checkout_time" name="checkout_time" 
                                                   value="{{ old('checkout_time', $settings['checkout_time'] ?? '12:00') }}" required>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="hotel_description" class="form-label">Hotel Description</label>
                                        <textarea class="form-control" 
                                                  id="hotel_description" name="hotel_description" rows="3">{{ old('hotel_description', $settings['hotel_description'] ?? 'A luxurious hotel offering premium accommodations and services.') }}</textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Currency & Rates Settings -->
                        <div class="tab-pane fade" id="currency" role="tabpanel">
                            <div class="card settings-card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-money-bill me-2"></i>Currency & Pricing</h5>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label for="base_currency" class="form-label">Base Currency <span class="text-danger">*</span></label>
                                            <select class="form-select" id="base_currency" name="base_currency" required>
                                                @foreach($currencies as $code => $name)
                                                    <option value="{{ $code }}" {{ old('base_currency', $settings['base_currency'] ?? 'UGX') == $code ? 'selected' : '' }}>
                                                        {{ $name }} ({{ $code }})
                                                    </option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <div class="col-md-6">
                                            <label for="currency_position" class="form-label">Currency Position</label>
                                            <select class="form-select" id="currency_position" name="currency_position">
                                                <option value="left" {{ old('currency_position', $settings['currency_position'] ?? 'left') == 'left' ? 'selected' : '' }}>Left (UGX100)</option>
                                                <option value="right" {{ old('currency_position', $settings['currency_position'] ?? 'left') == 'right' ? 'selected' : '' }}>Right (100UGX)</option>
                                                <option value="left_space" {{ old('currency_position', $settings['currency_position'] ?? 'left') == 'left_space' ? 'selected' : '' }}>Left with space (UGX 100)</option>
                                                <option value="right_space" {{ old('currency_position', $settings['currency_position'] ?? 'left') == 'right_space' ? 'selected' : '' }}>Right with space (100 UGX)</option>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label for="thousand_separator" class="form-label">Thousand Separator</label>
                                            <select class="form-select" id="thousand_separator" name="thousand_separator">
                                                <option value="," {{ old('thousand_separator', $settings['thousand_separator'] ?? ',') == ',' ? 'selected' : '' }}>Comma (1,000)</option>
                                                <option value="." {{ old('thousand_separator', $settings['thousand_separator'] ?? ',') == '.' ? 'selected' : '' }}>Dot (1.000)</option>
                                                <option value=" " {{ old('thousand_separator', $settings['thousand_separator'] ?? ',') == ' ' ? 'selected' : '' }}>Space (1 000)</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6">
                                            <label for="decimal_separator" class="form-label">Decimal Separator</label>
                                            <select class="form-select" id="decimal_separator" name="decimal_separator">
                                                <option value="." {{ old('decimal_separator', $settings['decimal_separator'] ?? '.') == '.' ? 'selected' : '' }}>Dot (100.00)</option>
                                                <option value="," {{ old('decimal_separator', $settings['decimal_separator'] ?? '.') == ',' ? 'selected' : '' }}>Comma (100,00)</option>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label for="number_of_decimals" class="form-label">Number of Decimals</label>
                                            <select class="form-select" id="number_of_decimals" name="number_of_decimals">
                                                <option value="0" {{ old('number_of_decimals', $settings['number_of_decimals'] ?? 2) == 0 ? 'selected' : '' }}>0</option>
                                                <option value="2" {{ old('number_of_decimals', $settings['number_of_decimals'] ?? 2) == 2 ? 'selected' : '' }}>2</option>
                                                <option value="3" {{ old('number_of_decimals', $settings['number_of_decimals'] ?? 2) == 3 ? 'selected' : '' }}>3</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6">
                                            <label for="tax_rate" class="form-label">Default Tax Rate (%)</label>
                                            <input type="number" class="form-control" id="tax_rate" name="tax_rate" 
                                                   value="{{ old('tax_rate', $settings['tax_rate'] ?? 10) }}" min="0" max="100" step="0.1">
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" type="checkbox" id="auto_update_rates" name="auto_update_rates" value="1"
                                                   {{ old('auto_update_rates', $settings['auto_update_rates'] ?? false) ? 'checked' : '' }}>
                                            <label class="form-check-label" for="auto_update_rates">Auto-update currency exchange rates</label>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Exchange Rates (to base currency)</label>
                                        <div class="table-responsive">
                                            <table class="table table-sm table-bordered">
                                                <thead class="table-light">
                                                    <tr>
                                                        <th>Currency</th>
                                                        <th>Rate</th>
                                                        <th>Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="exchangeRatesTable">
                                                    @foreach($exchangeRates as $currency => $rate)
                                                        <tr>
                                                            <td>{{ $currency }}</td>
                                                            <td>
                                                                <input type="number" class="form-control form-control-sm" 
                                                                       name="exchange_rates[{{ $currency }}]" value="{{ $rate }}" step="0.000001" min="0">
                                                            </td>
                                                            <td>
                                                                <button type="button" class="btn btn-sm btn-outline-primary update-rate" data-currency="{{ $currency }}">
                                                                    <i class="fas fa-sync-alt"></i>
                                                                </button>
                                                            </td>
                                                        </tr>
                                                    @endforeach
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Backup & Restore Settings -->
                        <div class="tab-pane fade" id="backup" role="tabpanel">
                            <div class="card settings-card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-database me-2"></i>Backup & Restore</h5>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-4">
                                        <div class="col-md-6">
                                            <div class="card backup-card">
                                                <div class="card-body text-center">
                                                    <i class="fas fa-download fa-3x text-primary mb-3"></i>
                                                    <h5>Create Backup</h5>
                                                    <p class="text-muted">Create a full backup of your system data</p>
                                                    <button type="button" class="btn btn-primary" id="createBackup">
                                                        <i class="fas fa-plus me-2"></i>Create Backup Now
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="card backup-card">
                                                <div class="card-body text-center">
                                                    <i class="fas fa-upload fa-3x text-primary mb-3"></i>
                                                    <h5>Restore Backup</h5>
                                                    <p class="text-muted">Restore your system from a backup file</p>
                                                    <div class="d-grid gap-2">
                                                        <input class="form-control" type="file" id="restoreFile" accept=".sql,.txt">
                                                        <button type="button" class="btn btn-outline-primary" id="restoreBackup" disabled>
                                                            <i class="fas fa-upload me-2"></i>Restore
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Auto Backup Settings</label>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-check form-switch mb-2">
                                                    <input class="form-check-input" type="checkbox" id="auto_backup" name="auto_backup" value="1"
                                                           {{ old('auto_backup', $settings['auto_backup'] ?? true) ? 'checked' : '' }}>
                                                    <label class="form-check-label" for="auto_backup">Enable Auto Backup</label>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <label for="backup_frequency" class="form-label">Backup Frequency</label>
                                                <select class="form-select" id="backup_frequency" name="backup_frequency">
                                                    <option value="daily" {{ old('backup_frequency', $settings['backup_frequency'] ?? 'weekly') == 'daily' ? 'selected' : '' }}>Daily</option>
                                                    <option value="weekly" {{ old('backup_frequency', $settings['backup_frequency'] ?? 'weekly') == 'weekly' ? 'selected' : '' }}>Weekly</option>
                                                    <option value="monthly" {{ old('backup_frequency', $settings['backup_frequency'] ?? 'weekly') == 'monthly' ? 'selected' : '' }}>Monthly</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Recent Backups</label>
                                        <div class="table-responsive">
                                            <table class="table table-sm table-hover">
                                                <thead class="table-light">
                                                    <tr>
                                                        <th>Backup Name</th>
                                                        <th>Date</th>
                                                        <th>Size</th>
                                                        <th>Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="backupList">
                                                    @if(isset($backups) && count($backups) > 0)
                                                        @foreach($backups as $backup)
                                                            <tr>
                                                                <td>{{ $backup['name'] }}</td>
                                                                <td>{{ $backup['date'] }}</td>
                                                                <td>{{ $backup['size'] }}</td>
                                                                <td>
                                                                    <a href="{{ route('settings.backup.download', ['filename' => $backup['name']]) }}" class="btn btn-sm btn-outline-primary me-1">
                                                                        <i class="fas fa-download"></i>
                                                                    </a>
                                                                    <button type="button" class="btn btn-sm btn-outline-danger delete-backup" data-backup="{{ $backup['name'] }}">
                                                                        <i class="fas fa-trash"></i>
                                                                    </button>
                                                                </td>
                                                            </tr>
                                                        @endforeach
                                                    @else
                                                        <tr>
                                                            <td colspan="4" class="text-center text-muted">No backups found. Create your first backup above.</td>
                                                        </tr>
                                                    @endif
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                    
                                    <div class="alert alert-warning">
                                        <i class="fas fa-exclamation-triangle me-2"></i>
                                        <strong>Important:</strong> Regularly backup your data and store backups in a secure location. 
                                        Backups contain sensitive information about your hotel operations.
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Notifications Settings -->
                        <div class="tab-pane fade" id="notifications" role="tabpanel">
                            <div class="card settings-card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-bell me-2"></i>Notification Settings</h5>
                                </div>
                                <div class="card-body">
                                    <div class="mb-4">
                                        <h6 class="mb-3">Email Notifications</h6>
                                        <div class="form-check form-switch mb-2">
                                            <input class="form-check-input" type="checkbox" id="email_notifications" name="email_notifications" value="1"
                                                   {{ old('email_notifications', $settings['email_notifications'] ?? true) ? 'checked' : '' }}>
                                            <label class="form-check-label" for="email_notifications">Enable Email Notifications</label>
                                        </div>
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label for="smtp_host" class="form-label">SMTP Host</label>
                                                <input type="text" class="form-control" id="smtp_host" name="smtp_host" 
                                                       value="{{ old('smtp_host', $settings['smtp_host'] ?? 'smtp.gmail.com') }}">
                                            </div>
                                            <div class="col-md-6">
                                                <label for="smtp_port" class="form-label">SMTP Port</label>
                                                <input type="number" class="form-control" id="smtp_port" name="smtp_port" 
                                                       value="{{ old('smtp_port', $settings['smtp_port'] ?? 587) }}">
                                            </div>
                                        </div>
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label for="smtp_username" class="form-label">SMTP Username</label>
                                                <input type="text" class="form-control" id="smtp_username" name="smtp_username" 
                                                       value="{{ old('smtp_username', $settings['smtp_username'] ?? '') }}">
                                            </div>
                                            <div class="col-md-6">
                                                <label for="smtp_password" class="form-label">SMTP Password</label>
                                                <input type="password" class="form-control" id="smtp_password" name="smtp_password" 
                                                       value="{{ old('smtp_password', $settings['smtp_password'] ?? '') }}">
                                            </div>
                                        </div>
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label for="smtp_encryption" class="form-label">Encryption</label>
                                                <select class="form-select" id="smtp_encryption" name="smtp_encryption">
                                                    <option value="tls" {{ old('smtp_encryption', $settings['smtp_encryption'] ?? 'tls') == 'tls' ? 'selected' : '' }}>TLS</option>
                                                    <option value="ssl" {{ old('smtp_encryption', $settings['smtp_encryption'] ?? 'tls') == 'ssl' ? 'selected' : '' }}>SSL</option>
                                                    <option value="none" {{ old('smtp_encryption', $settings['smtp_encryption'] ?? 'tls') == 'none' ? 'selected' : '' }}>None</option>
                                                </select>
                                            </div>
                                            <div class="col-md-6">
                                                <label for="from_email" class="form-label">From Email Address</label>
                                                <input type="email" class="form-control" id="from_email" name="from_email" 
                                                       value="{{ old('from_email', $settings['from_email'] ?? 'noreply@deluxehotel.com') }}">
                                            </div>
                                        </div>
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-8">
                                                <label for="admin_email" class="form-label">Admin Notification Email</label>
                                                <input type="email" class="form-control" id="admin_email" name="admin_email" 
                                                       value="{{ old('admin_email', $settings['admin_email'] ?? 'admin@deluxehotel.com') }}">
                                                <div class="form-text">This email will receive important system notifications</div>
                                            </div>
                                            <div class="col-md-4 d-flex align-items-end">
                                                <button type="button" class="btn btn-outline-primary test-smtp-btn" id="testSmtp">
                                                    <i class="fas fa-paper-plane me-2"></i>Test Connection
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-4">
                                        <h6 class="mb-3">SMS Notifications</h6>
                                        <div class="form-check form-switch mb-2">
                                            <input class="form-check-input" type="checkbox" id="sms_notifications" name="sms_notifications" value="1"
                                                   {{ old('sms_notifications', $settings['sms_notifications'] ?? false) ? 'checked' : '' }}>
                                            <label class="form-check-label" for="sms_notifications">Enable SMS Notifications</label>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <label for="sms_provider" class="form-label">SMS Provider</label>
                                                <select class="form-select" id="sms_provider" name="sms_provider">
                                                    <option value="twilio" {{ old('sms_provider', $settings['sms_provider'] ?? 'twilio') == 'twilio' ? 'selected' : '' }}>Twilio</option>
                                                    <option value="nexmo" {{ old('sms_provider', $settings['sms_provider'] ?? 'twilio') == 'nexmo' ? 'selected' : '' }}>Nexmo</option>
                                                    <option value="plivo" {{ old('sms_provider', $settings['sms_provider'] ?? 'twilio') == 'plivo' ? 'selected' : '' }}>Plivo</option>
                                                    <option value="custom" {{ old('sms_provider', $settings['sms_provider'] ?? 'twilio') == 'custom' ? 'selected' : '' }}>Custom API</option>
                                                </select>
                                            </div>
                                            <div class="col-md-6">
                                                <label for="sms_from" class="form-label">From Number/Name</label>
                                                <input type="text" class="form-control" id="sms_from" name="sms_from" 
                                                       value="{{ old('sms_from', $settings['sms_from'] ?? 'DeluxeHotel') }}">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <h6 class="mb-3">Notification Events</h6>
                                        <div class="table-responsive">
                                            <table class="table table-sm table-bordered">
                                                <thead class="table-light">
                                                    <tr>
                                                        <th>Event</th>
                                                        <th>Email</th>
                                                        <th>System Alert</th>
                                                        <th>SMS</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="notificationEvents">
                                                    @foreach($notificationEvents as $event => $eventSettings)
                                                        <tr>
                                                            <td>{{ ucfirst(str_replace('_', ' ', $event)) }}</td>
                                                            <td class="text-center">
                                                                <div class="form-check form-switch d-inline-block">
                                                                    <input class="form-check-input notification-event" type="checkbox" 
                                                                           name="notification_events[{{ $event }}][email]" value="1"
                                                                           {{ isset($eventSettings['email']) && $eventSettings['email'] ? 'checked' : '' }}>
                                                                </div>
                                                            </td>
                                                            <td class="text-center">
                                                                <div class="form-check form-switch d-inline-block">
                                                                    <input class="form-check-input notification-event" type="checkbox" 
                                                                           name="notification_events[{{ $event }}][system]" value="1"
                                                                           {{ isset($eventSettings['system']) && $eventSettings['system'] ? 'checked' : '' }}>
                                                                </div>
                                                            </td>
                                                            <td class="text-center">
                                                                <div class="form-check form-switch d-inline-block">
                                                                    <input class="form-check-input notification-event" type="checkbox" 
                                                                           name="notification_events[{{ $event }}][sms]" value="1"
                                                                           {{ isset($eventSettings['sms']) && $eventSettings['sms'] ? 'checked' : '' }}>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    @endforeach
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Integrations Settings -->
                        <div class="tab-pane fade" id="integrations" role="tabpanel">
                            <div class="card settings-card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-plug me-2"></i>Third-Party Integrations</h5>
                                </div>
                                <div class="card-body">
                                    <div class="mb-4">
                                        <h6 class="mb-3">Payment Gateways</h6>
                                        
                                        <div class="integration-card">
                                            <div class="integration-header">
                                                <h6 class="mb-0">Stripe</h6>
                                                <div class="form-check form-switch">
                                                    <input class="form-check-input" type="checkbox" id="stripe_enabled" name="integrations_data[stripe][enabled]" value="1"
                                                           {{ isset($integrations['stripe']['enabled']) && $integrations['stripe']['enabled'] ? 'checked' : '' }}>
                                                    <label class="form-check-label" for="stripe_enabled">Enable</label>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <label for="stripe_publishable_key" class="form-label">Publishable Key</label>
                                                    <input type="text" class="form-control" id="stripe_publishable_key" 
                                                           name="integrations_data[stripe][publishable_key]" 
                                                           value="{{ $integrations['stripe']['publishable_key'] ?? '' }}">
                                                </div>
                                                <div class="col-md-6">
                                                    <label for="stripe_secret_key" class="form-label">Secret Key</label>
                                                    <input type="password" class="form-control" id="stripe_secret_key" 
                                                           name="integrations_data[stripe][secret_key]" 
                                                           value="{{ $integrations['stripe']['secret_key'] ?? '' }}">
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="integration-card">
                                            <div class="integration-header">
                                                <h6 class="mb-0">PayPal</h6>
                                                <div class="form-check form-switch">
                                                    <input class="form-check-input" type="checkbox" id="paypal_enabled" name="integrations_data[paypal][enabled]" value="1"
                                                           {{ isset($integrations['paypal']['enabled']) && $integrations['paypal']['enabled'] ? 'checked' : '' }}>
                                                    <label class="form-check-label" for="paypal_enabled">Enable</label>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <label for="paypal_client_id" class="form-label">Client ID</label>
                                                    <input type="text" class="form-control" id="paypal_client_id" 
                                                           name="integrations_data[paypal][client_id]" 
                                                           value="{{ $integrations['paypal']['client_id'] ?? '' }}">
                                                </div>
                                                <div class="col-md-6">
                                                    <label for="paypal_client_secret" class="form-label">Client Secret</label>
                                                    <input type="password" class="form-control" id="paypal_client_secret" 
                                                           name="integrations_data[paypal][client_secret]" 
                                                           value="{{ $integrations['paypal']['client_secret'] ?? '' }}">
                                                </div>
                                            </div>
                                            <div class="mt-2">
                                                <div class="form-check form-check-inline">
                                                    <input class="form-check-input" type="radio" name="integrations_data[paypal][mode]" id="paypal_sandbox" value="sandbox"
                                                           {{ (isset($integrations['paypal']['mode']) && $integrations['paypal']['mode'] == 'sandbox') ? 'checked' : '' }}>
                                                    <label class="form-check-label" for="paypal_sandbox">Sandbox</label>
                                                </div>
                                                <div class="form-check form-check-inline">
                                                    <input class="form-check-input" type="radio" name="integrations_data[paypal][mode]" id="paypal_live" value="live"
                                                           {{ (isset($integrations['paypal']['mode']) && $integrations['paypal']['mode'] == 'live') ? 'checked' : '' }}>
                                                    <label class="form-check-label" for="paypal_live">Live</label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-4">
                                        <h6 class="mb-3">Channel Managers</h6>
                                        
                                        <div class="integration-card">
                                            <div class="integration-header">
                                                <h6 class="mb-0">Booking.com</h6>
                                                <div class="form-check form-switch">
                                                    <input class="form-check-input" type="checkbox" id="booking_enabled" name="integrations_data[booking][enabled]" value="1"
                                                           {{ isset($integrations['booking']['enabled']) && $integrations['booking']['enabled'] ? 'checked' : '' }}>
                                                    <label class="form-check-label" for="booking_enabled">Enable</label>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <label for="booking_username" class="form-label">Username</label>
                                                    <input type="text" class="form-control" id="booking_username" 
                                                           name="integrations_data[booking][username]" 
                                                           value="{{ $integrations['booking']['username'] ?? '' }}">
                                                </div>
                                                <div class="col-md-6">
                                                    <label for="booking_password" class="form-label">Password</label>
                                                    <input type="password" class="form-control" id="booking_password" 
                                                           name="integrations_data[booking][password]" 
                                                           value="{{ $integrations['booking']['password'] ?? '' }}">
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="integration-card">
                                            <div class="integration-header">
                                                <h6 class="mb-0">Expedia</h6>
                                                <div class="form-check form-switch">
                                                    <input class="form-check-input" type="checkbox" id="expedia_enabled" name="integrations_data[expedia][enabled]" value="1"
                                                           {{ isset($integrations['expedia']['enabled']) && $integrations['expedia']['enabled'] ? 'checked' : '' }}>
                                                    <label class="form-check-label" for="expedia_enabled">Enable</label>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <label for="expedia_api_key" class="form-label">API Key</label>
                                                    <input type="text" class="form-control" id="expedia_api_key" 
                                                           name="integrations_data[expedia][api_key]" 
                                                           value="{{ $integrations['expedia']['api_key'] ?? '' }}">
                                                </div>
                                                <div class="col-md-6">
                                                    <label for="expedia_secret" class="form-label">Secret</label>
                                                    <input type="password" class="form-control" id="expedia_secret" 
                                                           name="integrations_data[expedia][secret]" 
                                                           value="{{ $integrations['expedia']['secret'] ?? '' }}">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-4">
                                        <h6 class="mb-3">Other Integrations</h6>
                                        
                                        <div class="integration-card">
                                            <div class="integration-header">
                                                <h6 class="mb-0">Google Analytics</h6>
                                                <div class="form-check form-switch">
                                                    <input class="form-check-input" type="checkbox" id="google_analytics_enabled" name="integrations_data[google_analytics][enabled]" value="1"
                                                           {{ isset($integrations['google_analytics']['enabled']) && $integrations['google_analytics']['enabled'] ? 'checked' : '' }}>
                                                    <label class="form-check-label" for="google_analytics_enabled">Enable</label>
                                                </div>
                                            </div>
                                            <div class="mb-2">
                                                <label for="google_analytics_tracking_id" class="form-label">Tracking ID</label>
                                                <input type="text" class="form-control" id="google_analytics_tracking_id" 
                                                       name="integrations_data[google_analytics][tracking_id]" 
                                                       value="{{ $integrations['google_analytics']['tracking_id'] ?? '' }}">
                                            </div>
                                        </div>
                                        
                                        <div class="integration-card">
                                            <div class="integration-header">
                                                <h6 class="mb-0">Mailchimp</h6>
                                                <div class="form-check form-switch">
                                                    <input class="form-check-input" type="checkbox" id="mailchimp_enabled" name="integrations_data[mailchimp][enabled]" value="1"
                                                           {{ isset($integrations['mailchimp']['enabled']) && $integrations['mailchimp']['enabled'] ? 'checked' : '' }}>
                                                    <label class="form-check-label" for="mailchimp_enabled">Enable</label>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <label for="mailchimp_api_key" class="form-label">API Key</label>
                                                    <input type="text" class="form-control" id="mailchimp_api_key" 
                                                           name="integrations_data[mailchimp][api_key]" 
                                                           value="{{ $integrations['mailchimp']['api_key'] ?? '' }}">
                                                </div>
                                                <div class="col-md-6">
                                                    <label for="mailchimp_list_id" class="form-label">List ID</label>
                                                    <input type="text" class="form-control" id="mailchimp_list_id" 
                                                           name="integrations_data[mailchimp][list_id]" 
                                                           value="{{ $integrations['mailchimp']['list_id'] ?? '' }}">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Users & Permissions Settings -->
                        <div class="tab-pane fade" id="users" role="tabpanel">
                            <div class="card settings-card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-users me-2"></i>Users & Permissions</h5>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-center mb-4">
                                        <h6 class="mb-0">System Users</h6>
                                        <button type="button" class="btn btn-primary btn-sm" id="addUserBtn" data-bs-toggle="modal" data-bs-target="#addUserModal">
                                            <i class="fas fa-plus me-1"></i>Add User
                                        </button>
                                    </div>
                                    
                                    <div class="table-responsive mb-4">
                                        <table class="table table-sm table-hover">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Name</th>
                                                    <th>Email</th>
                                                    <th>Phone</th>
                                                    <th>Role</th>
                                                    <th>Last Login</th>
                                                    <th>Status</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody id="usersTable">
                                                @foreach($users as $user)
                                                    <tr>
                                                        <td>{{ $user['name'] }}</td>
                                                        <td>{{ $user['email'] }}</td>
                                                        <td>{{ $user['phone'] ?? '-' }}</td>
                                                        <td><span class="badge bg-primary">{{ ucfirst($user['role']) }}</span></td>
                                                        <td>{{ $user['last_login'] ?? 'Never' }}</td>
                                                        <td>
                                                            @if($user['status'] == 'active')
                                                                <span class="badge bg-success">Active</span>
                                                            @else
                                                                <span class="badge bg-secondary">Inactive</span>
                                                            @endif
                                                        </td>
                                                        <td>
                                                            <button type="button" class="btn btn-sm btn-outline-primary me-1 edit-user" data-id="{{ $user['id'] }}">
                                                                <i class="fas fa-edit"></i>
                                                            </button>
                                                            @if($user['role'] != 'super_admin')
                                                                <button type="button" class="btn btn-sm btn-outline-danger delete-user" data-id="{{ $user['id'] }}">
                                                                    <i class="fas fa-trash"></i>
                                                                </button>
                                                            @endif
                                                        </td>
                                                    </tr>
                                                @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <div class="mb-4">
                                        <h6 class="mb-3">User Roles & Permissions</h6>
                                        
                                        @foreach($roles as $roleName => $roleData)
                                            <div class="card mb-3 border">
                                                <div class="card-body">
                                                    <h6 class="card-title">{{ ucfirst($roleName) }}</h6>
                                                    <p class="card-text text-muted small">{{ $roleData['description'] ?? '' }}</p>
                                                    <div class="row">
                                                        @foreach($roleData['permissions'] ?? [] as $permission => $enabled)
                                                            <div class="col-md-6">
                                                                <div class="form-check mb-2">
                                                                    <input class="form-check-input" type="checkbox" 
                                                                           name="roles[{{ $roleName }}][{{ $permission }}]" 
                                                                           id="{{ $roleName }}_{{ $permission }}" value="1"
                                                                           {{ $enabled ? 'checked' : '' }}
                                                                           {{ $roleName == 'super_admin' ? 'disabled' : '' }}>
                                                                    <label class="form-check-label" for="{{ $roleName }}_{{ $permission }}">
                                                                        {{ ucfirst(str_replace('_', ' ', $permission)) }}
                                                                    </label>
                                                                </div>
                                                            </div>
                                                        @endforeach
                                                    </div>
                                                </div>
                                            </div>
                                        @endforeach
                                    </div>
                                    
                                    <div class="mb-3">
                                        <h6 class="mb-3">Security Settings</h6>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label for="session_timeout" class="form-label">Session Timeout (minutes)</label>
                                                    <input type="number" class="form-control" id="session_timeout" name="session_timeout" 
                                                           value="{{ old('session_timeout', $settings['session_timeout'] ?? 60) }}" min="5" max="480">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label for="max_login_attempts" class="form-label">Max Login Attempts</label>
                                                    <input type="number" class="form-control" id="max_login_attempts" name="max_login_attempts" 
                                                           value="{{ old('max_login_attempts', $settings['max_login_attempts'] ?? 5) }}" min="1" max="10">
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="form-check form-switch mb-2">
                                            <input class="form-check-input" type="checkbox" id="two_factor_auth" name="two_factor_auth" value="1"
                                                   {{ old('two_factor_auth', $settings['two_factor_auth'] ?? true) ? 'checked' : '' }}>
                                            <label class="form-check-label" for="two_factor_auth">Enable Two-Factor Authentication</label>
                                        </div>
                                        
                                        <div class="form-check form-switch mb-2">
                                            <input class="form-check-input" type="checkbox" id="password_expiry" name="password_expiry" value="1"
                                                   {{ old('password_expiry', $settings['password_expiry'] ?? false) ? 'checked' : '' }}>
                                            <label class="form-check-label" for="password_expiry">Enable Password Expiry (90 days)</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Payments Settings -->
                        <div class="tab-pane fade" id="payments" role="tabpanel">
                            <div class="card settings-card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-credit-card me-2"></i>Subscription Payments</h5>
                                </div>
                                <div class="card-body">
                                    @php
                                        $subscription = $subscriptionPaymentData['subscription'] ?? null;
                                        $latestPayment = $subscriptionPaymentData['latest_payment'] ?? null;
                                        $pendingPayment = $subscriptionPaymentData['pending_payment'] ?? null;
                                        $daysRemaining = $subscription ? $subscription->days_remaining : null;
                                        $paymentActionLabel = 'Pay Early with PesaPal';
                                        $paymentHint = 'You are still safe. You can pay early to avoid service interruptions.';
                                        $paymentToneClass = 'alert-info';

                                        if ($daysRemaining !== null) {
                                            if ($daysRemaining < 0) {
                                                $paymentActionLabel = 'Pay Outstanding with PesaPal';
                                                $paymentHint = 'Your subscription is overdue. Pay now to restore/keep service access.';
                                                $paymentToneClass = 'alert-danger';
                                            } elseif ($daysRemaining <= 7) {
                                                $paymentActionLabel = 'Renew Now with PesaPal';
                                                $paymentHint = 'Your subscription is close to expiry. Renew now to avoid downtime.';
                                                $paymentToneClass = 'alert-warning';
                                            }
                                        }
                                    @endphp

                                    <div class="alert {{ $paymentToneClass }} mb-3">
                                        <i class="fas fa-info-circle me-2"></i>
                                        {{ $paymentHint }}
                                    </div>

                                    @if(!$subscription)
                                        <div class="alert alert-danger">
                                            <i class="fas fa-exclamation-triangle me-2"></i>
                                            No active subscription record found for this hotel.
                                        </div>
                                    @else
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <div class="border rounded p-3 h-100">
                                                    <h6 class="text-primary mb-3">Current Subscription</h6>
                                                    <div class="mb-2"><strong>Plan:</strong> {{ ucfirst((string) $subscription->plan_name) }}</div>
                                                    <div class="mb-2"><strong>Amount:</strong> UGX {{ number_format((float) $subscription->plan_price, 0) }}</div>
                                                    <div class="mb-2"><strong>Status:</strong> {{ ucfirst((string) $subscription->status) }}</div>
                                                    <div class="mb-2"><strong>Expiry:</strong> {{ $subscription->end_date ? \Carbon\Carbon::parse($subscription->end_date)->format('d M Y') : 'N/A' }}</div>
                                                    <div><strong>Days Remaining:</strong>
                                                        @if($daysRemaining !== null)
                                                            <span class="{{ $daysRemaining <= 7 ? 'text-danger' : 'text-success' }}">{{ $daysRemaining }}</span>
                                                        @else
                                                            N/A
                                                        @endif
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="border rounded p-3 h-100">
                                                    <h6 class="text-primary mb-3">Latest Payment</h6>
                                                    @if($latestPayment)
                                                        <div class="mb-2"><strong>Reference:</strong> {{ $latestPayment->payment_number }}</div>
                                                        <div class="mb-2"><strong>Amount:</strong> UGX {{ number_format((float) $latestPayment->amount, 0) }}</div>
                                                        <div class="mb-2"><strong>Status:</strong> {{ ucfirst((string) $latestPayment->status) }}</div>
                                                        <div class="mb-2"><strong>Date:</strong> {{ \Carbon\Carbon::parse($latestPayment->payment_date)->format('d M Y') }}</div>
                                                    @else
                                                        <span class="text-muted">No previous payment found.</span>
                                                    @endif
                                                </div>
                                            </div>
                                        </div>

                                        <div class="d-flex align-items-center gap-2">
                                            <button type="button" class="btn btn-primary" id="paySubscriptionNowBtn">
                                                <i class="fas fa-bolt me-2"></i>{{ $paymentActionLabel }}
                                            </button>
                                            @if($pendingPayment)
                                                <span class="badge bg-warning text-dark">Pending payment exists: {{ $pendingPayment->payment_number }}</span>
                                            @endif
                                        </div>
                                    @endif
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <!-- Add User Modal -->
    <div class="modal fade" id="addUserModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add New User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addUserForm">
                        @csrf
                        <div class="mb-3">
                            <label for="new_user_name" class="form-label">Name</label>
                            <input type="text" class="form-control" id="new_user_name" required>
                        </div>
                        <div class="mb-3">
                            <label for="new_user_email" class="form-label">Email</label>
                            <input type="email" class="form-control" id="new_user_email" required>
                        </div>
                        <div class="mb-3">
                            <label for="new_user_phone" class="form-label">Phone Number</label>
                            <input type="text" class="form-control" id="new_user_phone" placeholder="+256700000000">
                        </div>
                        <div class="mb-3">
                            <label for="new_user_password" class="form-label">Password</label>
                            <div class="input-group">
                                <input type="password" class="form-control" id="new_user_password" required>
                                <button class="btn btn-outline-secondary toggle-password" type="button" data-target="new_user_password">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="new_user_role" class="form-label">Role</label>
                            <select class="form-select" id="new_user_role">
                                @foreach($roles as $roleKey => $roleData)
                                    <option value="{{ $roleKey }}">{{ ucfirst(str_replace('_', ' ', $roleKey)) }}</option>
                                @endforeach
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="saveNewUser">Add User</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit User Modal -->
    <div class="modal fade" id="editUserModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editUserForm">
                        @csrf
                        @method('PUT')
                        <input type="hidden" id="edit_user_id">
                        <div class="mb-3">
                            <label for="edit_user_name" class="form-label">Name</label>
                            <input type="text" class="form-control" id="edit_user_name" required>
                        </div>
                        <div class="mb-3">
                            <label for="edit_user_email" class="form-label">Email</label>
                            <input type="email" class="form-control" id="edit_user_email" required>
                        </div>
                        <div class="mb-3">
                            <label for="edit_user_phone" class="form-label">Phone Number</label>
                            <input type="text" class="form-control" id="edit_user_phone" placeholder="+256700000000">
                        </div>
                        <div class="mb-3">
                            <label for="edit_user_role" class="form-label">Role</label>
                            <select class="form-select" id="edit_user_role">
                                @foreach($roles as $roleKey => $roleData)
                                    <option value="{{ $roleKey }}">{{ ucfirst(str_replace('_', ' ', $roleKey)) }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="form-check form-switch mb-3">
                            <input class="form-check-input" type="checkbox" id="edit_user_status">
                            <label class="form-check-label" for="edit_user_status">Active</label>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="updateUser">Update User</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Toast Container -->
    <div class="toast-container">
        <div class="toast align-items-center text-white bg-success border-0" id="successToast" role="alert">
            <div class="d-flex">
                <div class="toast-body">
                    Settings saved successfully!
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
            </div>
        </div>
        
        <div class="toast align-items-center text-white bg-danger border-0" id="errorToast" role="alert">
            <div class="d-flex">
                <div class="toast-body">
                    An error occurred. Please try again.
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Function to refresh page
            window.refreshPage = function() {
                location.reload();
            };

            // Toggle password visibility
            document.querySelectorAll('.toggle-password').forEach(button => {
                button.addEventListener('click', function() {
                    const targetId = this.getAttribute('data-target');
                    const targetInput = document.getElementById(targetId);
                    const icon = this.querySelector('i');
                    
                    if (targetInput.type === 'password') {
                        targetInput.type = 'text';
                        icon.classList.remove('fa-eye');
                        icon.classList.add('fa-eye-slash');
                    } else {
                        targetInput.type = 'password';
                        icon.classList.remove('fa-eye-slash');
                        icon.classList.add('fa-eye');
                    }
                });
            });

            // Function to check if storage is available
            function isStorageAvailable(type) {
                let storage;
                try {
                    storage = window[type];
                    const x = '__storage_test__';
                    storage.setItem(x, x);
                    storage.removeItem(x);
                    return true;
                } catch (e) {
                    return false;
                }
            }

            // Warn if storage is blocked
            if (!isStorageAvailable('localStorage')) {
                console.warn('localStorage is blocked by browser settings. Some features may not work properly.');
            }

            // Update color previews
            function updateColorPreviews() {
                const primaryColor = document.getElementById('primary_color');
                
                if (primaryColor) document.getElementById('primaryColorPreview').style.backgroundColor = primaryColor.value;
            }

            document.getElementById('primary_color')?.addEventListener('input', updateColorPreviews);

            // Helper function to show toast
            function showToast(type, message) {
                const toastElement = document.getElementById(type === 'success' ? 'successToast' : 'errorToast');
                toastElement.querySelector('.toast-body').textContent = message;
                const toast = new bootstrap.Toast(toastElement);
                toast.show();
            }

            // Save settings
            document.getElementById('saveSettings').addEventListener('click', function() {
                const form = document.getElementById('settingsForm');
                const formData = new FormData(form);
                
                // Show loading
                document.getElementById('loadingOverlay').classList.add('active');
                
                // Get CSRF token from meta tag
                const csrfToken = document.querySelector('meta[name="csrf-token"]').content;
                
                // Log for debugging (remove in production)
                console.log('Saving settings...');
                
                fetch(form.action, {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRF-TOKEN': csrfToken,
                        'Accept': 'application/json'
                    },
                    credentials: 'same-origin'
                })
                .then(response => {
                    console.log('Response status:', response.status);
                    if (!response.ok) {
                        return response.json().then(err => { 
                            console.error('Server error:', err);
                            throw err; 
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('Response data:', data);
                    if (data.success) {
                        showToast('success', data.message || 'Settings saved successfully!');
                        // Reload page after successful save to show updated settings
                        setTimeout(() => location.reload(), 1500);
                    } else {
                        throw new Error(data.message || 'Unknown error occurred');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    let errorMessage = 'Network error. Please try again.';
                    
                    if (error.message && error.message.includes('CSRF')) {
                        errorMessage = 'CSRF token mismatch. Your session may have expired. Please refresh the page and try again.';
                        // Show the CSRF warning
                        document.getElementById('csrfWarning').style.display = 'block';
                    } else if (error.message) {
                        errorMessage = error.message;
                    }
                    
                    showToast('error', errorMessage);
                })
                .finally(() => {
                    document.getElementById('loadingOverlay').classList.remove('active');
                });
            });

            // Create backup
            document.getElementById('createBackup')?.addEventListener('click', function() {
                if (!confirm('Create a new backup? This may take a few moments.')) {
                    return;
                }
                
                document.getElementById('loadingOverlay').classList.add('active');
                
                fetch('{{ route("settings.backup.create") }}', {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    credentials: 'same-origin'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showToast('success', 'Backup created successfully!');
                        setTimeout(() => location.reload(), 1500);
                    } else {
                        showToast('error', 'Failed to create backup: ' + (data.message || 'Unknown error'));
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showToast('error', 'Error creating backup');
                })
                .finally(() => {
                    document.getElementById('loadingOverlay').classList.remove('active');
                });
            });

            // Restore backup
            document.getElementById('restoreFile')?.addEventListener('change', function() {
                document.getElementById('restoreBackup').disabled = !this.files.length;
            });

            document.getElementById('restoreBackup')?.addEventListener('click', function() {
                const fileInput = document.getElementById('restoreFile');
                if (!fileInput.files.length) return;
                
                if (!confirm('WARNING: Restoring a backup will overwrite all current data. This action cannot be undone. Continue?')) {
                    return;
                }
                
                const formData = new FormData();
                formData.append('backup_file', fileInput.files[0]);
                
                document.getElementById('loadingOverlay').classList.add('active');
                
                fetch('{{ route("settings.backup.restore") }}', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Accept': 'application/json'
                    },
                    credentials: 'same-origin'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showToast('success', 'Backup restored successfully. The page will now reload.');
                        setTimeout(() => location.reload(), 2000);
                    } else {
                        showToast('error', 'Failed to restore backup: ' + (data.message || 'Unknown error'));
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showToast('error', 'Error restoring backup');
                })
                .finally(() => {
                    document.getElementById('loadingOverlay').classList.remove('active');
                });
            });

            // Delete backup
            document.querySelectorAll('.delete-backup').forEach(button => {
                button.addEventListener('click', function() {
                    const backupName = this.dataset.backup;
                    if (!backupName) {
                        showToast('error', 'Invalid backup name');
                        return;
                    }
                    
                    if (!confirm(`Delete backup "${backupName}"? This action cannot be undone.`)) return;
                    
                    fetch(`{{ url('settings/backup/delete') }}/${encodeURIComponent(backupName)}`, {
                        method: 'DELETE',
                        headers: {
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                            'Content-Type': 'application/json',
                            'Accept': 'application/json'
                        },
                        credentials: 'same-origin'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            this.closest('tr').remove();
                            showToast('success', 'Backup deleted successfully');
                        } else {
                            showToast('error', 'Failed to delete backup: ' + (data.message || 'Unknown error'));
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        showToast('error', 'Error deleting backup');
                    });
                });
            });

            // Add user
            document.getElementById('saveNewUser')?.addEventListener('click', function() {
                const data = {
                    name: document.getElementById('new_user_name').value,
                    email: document.getElementById('new_user_email').value,
                    phone: document.getElementById('new_user_phone').value,
                    password: document.getElementById('new_user_password').value,
                    role: document.getElementById('new_user_role').value
                };
                
                // Validate
                if (!data.name || !data.email || !data.password) {
                    showToast('error', 'Please fill all fields');
                    return;
                }
                
                document.getElementById('loadingOverlay').classList.add('active');
                
                fetch('{{ route("settings.users.store") }}', {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    credentials: 'same-origin',
                    body: JSON.stringify(data)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Close modal
                        bootstrap.Modal.getInstance(document.getElementById('addUserModal')).hide();
                        showToast('success', 'User added successfully');
                        setTimeout(() => location.reload(), 1500);
                    } else {
                        showToast('error', 'Failed to add user: ' + (data.message || 'Unknown error'));
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showToast('error', 'Error adding user');
                })
                .finally(() => {
                    document.getElementById('loadingOverlay').classList.remove('active');
                });
            });

            // Edit user
            document.querySelectorAll('.edit-user').forEach(button => {
                button.addEventListener('click', function() {
                    const userId = this.dataset.id;
                    
                    fetch(`{{ url('settings/users') }}/${userId}`, {
                        headers: {
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                            'Accept': 'application/json'
                        },
                        credentials: 'same-origin'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            document.getElementById('edit_user_id').value = data.user.id;
                            document.getElementById('edit_user_name').value = data.user.name;
                            document.getElementById('edit_user_email').value = data.user.email;
                            document.getElementById('edit_user_phone').value = data.user.phone || '';
                            document.getElementById('edit_user_role').value = data.user.role;
                            document.getElementById('edit_user_status').checked = data.user.status === 'active';
                            
                            new bootstrap.Modal(document.getElementById('editUserModal')).show();
                        } else {
                            showToast('error', 'Failed to load user data');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        showToast('error', 'Error loading user data');
                    });
                });
            });

            // Update user
            document.getElementById('updateUser')?.addEventListener('click', function() {
                const userId = document.getElementById('edit_user_id').value;
                const data = {
                    name: document.getElementById('edit_user_name').value,
                    email: document.getElementById('edit_user_email').value,
                    phone: document.getElementById('edit_user_phone').value,
                    role: document.getElementById('edit_user_role').value,
                    status: document.getElementById('edit_user_status').checked ? 'active' : 'inactive'
                };
                
                document.getElementById('loadingOverlay').classList.add('active');
                
                fetch(`{{ url('settings/users') }}/${userId}`, {
                    method: 'PUT',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    credentials: 'same-origin',
                    body: JSON.stringify(data)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        bootstrap.Modal.getInstance(document.getElementById('editUserModal')).hide();
                        showToast('success', 'User updated successfully');
                        setTimeout(() => location.reload(), 1500);
                    } else {
                        showToast('error', 'Failed to update user: ' + (data.message || 'Unknown error'));
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showToast('error', 'Error updating user');
                })
                .finally(() => {
                    document.getElementById('loadingOverlay').classList.remove('active');
                });
            });

            // Delete user
            document.querySelectorAll('.delete-user').forEach(button => {
                button.addEventListener('click', function() {
                    const userId = this.dataset.id;
                    if (!confirm('Delete this user? This action cannot be undone.')) return;
                    
                    document.getElementById('loadingOverlay').classList.add('active');
                    
                    fetch(`{{ url('settings/users') }}/${userId}`, {
                        method: 'DELETE',
                        headers: {
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                            'Content-Type': 'application/json',
                            'Accept': 'application/json'
                        },
                        credentials: 'same-origin'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            this.closest('tr').remove();
                            showToast('success', 'User deleted successfully');
                        } else {
                            showToast('error', 'Failed to delete user: ' + (data.message || 'Unknown error'));
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        showToast('error', 'Error deleting user');
                    })
                    .finally(() => {
                        document.getElementById('loadingOverlay').classList.remove('active');
                    });
                });
            });

            // Update exchange rate
            document.querySelectorAll('.update-rate').forEach(button => {
                button.addEventListener('click', function() {
                    const currency = this.dataset.currency;
                    const input = this.closest('tr').querySelector('input[type="number"]');
                    
                    document.getElementById('loadingOverlay').classList.add('active');
                    
                    fetch(`{{ url('settings/currency/rate') }}/${currency}`, {
                        method: 'GET',
                        headers: {
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                            'Accept': 'application/json'
                        },
                        credentials: 'same-origin'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            input.value = data.rate;
                            showToast('success', `Exchange rate for ${currency} updated`);
                        } else {
                            showToast('error', 'Failed to update rate: ' + (data.message || 'Unknown error'));
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        showToast('error', 'Error updating rate');
                    })
                    .finally(() => {
                        document.getElementById('loadingOverlay').classList.remove('active');
                    });
                });
            });

            const payNowBtn = document.getElementById('paySubscriptionNowBtn');
            if (payNowBtn) {
                payNowBtn.addEventListener('click', function() {
                    document.getElementById('loadingOverlay').classList.add('active');

                    fetch('{{ route("settings.payments.pay-now") }}', {
                        method: 'POST',
                        headers: {
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                            'Accept': 'application/json'
                        },
                        credentials: 'same-origin'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success && data.redirect_url) {
                            window.open(data.redirect_url, '_blank');
                            showToast('success', 'PesaPal checkout opened. Complete payment to auto-update subscription.');
                        } else {
                            showToast('error', data.message || 'Could not start payment checkout.');
                        }
                    })
                    .catch(error => {
                        console.error('Payment error:', error);
                        showToast('error', 'Could not start payment.');
                    })
                    .finally(() => {
                        document.getElementById('loadingOverlay').classList.remove('active');
                    });
                });
            }

            // Test SMTP connection
            document.getElementById('testSmtp')?.addEventListener('click', function() {
                const data = {
                    host: document.getElementById('smtp_host').value,
                    port: document.getElementById('smtp_port').value,
                    username: document.getElementById('smtp_username').value,
                    password: document.getElementById('smtp_password').value,
                    encryption: document.getElementById('smtp_encryption').value,
                    from: document.getElementById('from_email').value
                };
                
                // Validate
                if (!data.host || !data.port || !data.from) {
                    showToast('error', 'Please fill in SMTP host, port, and from email');
                    return;
                }
                
                document.getElementById('loadingOverlay').classList.add('active');
                
                fetch('{{ route("settings.test-smtp") }}', {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    credentials: 'same-origin',
                    body: JSON.stringify(data)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showToast('success', data.message);
                    } else {
                        showToast('error', data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showToast('error', 'Error testing SMTP connection');
                })
                .finally(() => {
                    document.getElementById('loadingOverlay').classList.remove('active');
                });
            });
        });
    </script>
    
<script src="{{ asset('js/theme-applier.js') }}?v={{ @filemtime(public_path('js/theme-applier.js')) }}"></script>
</body>
</html>

