@extends('layouts.admin')

@section('title', 'System Configuration')

@section('content')
<div class="container-fluid py-4">
    <!-- Alert Container -->
    <div id="alertContainer"></div>

    <!-- Header -->
    <div class="row mb-4">
        <div class="col-md-8">
            <h1 class="h3 mb-0">
                <i class="bi bi-gear"></i> System Configuration
            </h1>
            <p class="text-muted">Manage all system settings and notification channels</p>
            <small class="badge bg-info mt-2">
                <i class="bi bi-info-circle me-1"></i>Each field auto-saves on blur for quick updates
            </small>
        </div>
        <div class="col-md-4 text-end">
            <button type="button" class="btn btn-success" onclick="saveAllChanges()">
                <i class="bi bi-check-circle"></i> Save All Changes
            </button>
            <button type="button" class="btn btn-outline-secondary" onclick="location.reload()">
                <i class="bi bi-arrow-clockwise"></i> Refresh
            </button>
        </div>
    </div>

    <!-- Tabs Navigation -->
    <ul class="nav nav-tabs mb-4" role="tablist">
        <li class="nav-item">
            <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#notifications">
                <i class="bi bi-bell"></i> Notifications
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#email">
                <i class="bi bi-envelope"></i> Email
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#sms">
                <i class="bi bi-telephone"></i> SMS
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#payment">
                <i class="bi bi-credit-card"></i> Payment
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#business">
                <i class="bi bi-building"></i> Business
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#security">
                <i class="bi bi-shield-lock"></i> Security
            </button>
        </li>
    </ul>

    <form id="configForm" method="POST" action="{{ route('admin.configuration.bulk-update') }}" onsubmit="return saveAllChanges();">
        @csrf
        <div class="tab-content">

            <!-- NOTIFICATIONS TAB -->
            <div class="tab-pane fade show active" id="notifications">
                <div class="card border-0 shadow-sm mb-3">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0">
                            <i class="bi bi-bell"></i> Notification Settings
                        </h5>
                    </div>
                    <div class="card-body">
                        <!-- Email Notifications -->
                        <div class="mb-4">
                            <h6 class="fw-bold mb-3">
                                <i class="bi bi-envelope"></i> Email Notifications
                            </h6>
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">Enable Email Notifications</label>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="emailEnabled"
                                               name="notifications[email][enabled]" value="1" checked>
                                        <label class="form-check-label" for="emailEnabled">
                                            Send notifications via email
                                        </label>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">From Email Address</label>
                                    <input type="email" class="form-control" name="notifications[email][from]"
                                           value="noreply@privasee.com" placeholder="noreply@privasee.com">
                                </div>
                            </div>
                        </div>

                        <hr>

                        <!-- SMS Notifications -->
                        <div class="mb-4">
                            <h6 class="fw-bold mb-3">
                                <i class="bi bi-telephone"></i> SMS Notifications
                            </h6>
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">Enable SMS Notifications</label>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="smsEnabled"
                                               name="notifications[sms][enabled]" value="1">
                                        <label class="form-check-label" for="smsEnabled">
                                            Send notifications via SMS
                                        </label>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">SMS Provider</label>
                                    <select class="form-select" name="notifications[sms][provider]">
                                        <option value="twilio">Twilio</option>
                                        <option value="nexmo">Nexmo/Vonage</option>
                                        <option value="aws">AWS SNS</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <hr>

                        <!-- Push Notifications -->
                        <div class="mb-4">
                            <h6 class="fw-bold mb-3">
                                <i class="bi bi-chat-dots"></i> Push Notifications
                            </h6>
                            <div class="row g-3">
                                <div class="col-md-12">
                                    <label class="form-label">Enable Push Notifications</label>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="pushEnabled"
                                               name="notifications[push][enabled]" value="1" checked>
                                        <label class="form-check-label" for="pushEnabled">
                                            Send push notifications to mobile apps
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <hr>

                        <!-- Notification Channels Configuration -->
                        <div>
                            <h6 class="fw-bold mb-3">
                                <i class="bi bi-diagram-3"></i> Notification Channels
                            </h6>
                            <p class="text-muted small">Select which channels each notification type should use</p>

                            <div class="table-responsive">
                                <table class="table table-sm table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Notification Type</th>
                                            <th style="width: 200px;">
                                                <span class="badge bg-primary">Database</span>
                                            </th>
                                            <th style="width: 200px;">
                                                <span class="badge bg-info">Email</span>
                                            </th>
                                            <th style="width: 200px;">
                                                <span class="badge bg-warning">SMS</span>
                                            </th>
                                            <th style="width: 200px;">
                                                <span class="badge bg-success">Push</span>
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- Offer Redeemed -->
                                        <tr>
                                            <td>
                                                <strong>Offer Redeemed</strong>
                                                <br><small class="text-muted">When user redeems an offer</small>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[offer_redeemed][]" value="database" checked>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[offer_redeemed][]" value="email">
                                                </div>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[offer_redeemed][]" value="sms">
                                                </div>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[offer_redeemed][]" value="push">
                                                </div>
                                            </td>
                                        </tr>

                                        <!-- Staff Invited -->
                                        <tr>
                                            <td>
                                                <strong>Staff Invited</strong>
                                                <br><small class="text-muted">When new staff is invited</small>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[staff_invited][]" value="database" checked>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[staff_invited][]" value="email" checked>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[staff_invited][]" value="sms">
                                                </div>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[staff_invited][]" value="push">
                                                </div>
                                            </td>
                                        </tr>

                                        <!-- Business Verified -->
                                        <tr>
                                            <td>
                                                <strong>Business Verified</strong>
                                                <br><small class="text-muted">When business is approved</small>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[business_verified][]" value="database" checked>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[business_verified][]" value="email" checked>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[business_verified][]" value="sms">
                                                </div>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[business_verified][]" value="push">
                                                </div>
                                            </td>
                                        </tr>

                                        <!-- Payment Confirmed -->
                                        <tr>
                                            <td>
                                                <strong>Payment Confirmed</strong>
                                                <br><small class="text-muted">When payment is processed</small>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[payment_confirmed][]" value="database" checked>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[payment_confirmed][]" value="email" checked>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[payment_confirmed][]" value="sms">
                                                </div>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[payment_confirmed][]" value="push">
                                                </div>
                                            </td>
                                        </tr>

                                        <!-- User Status Changed -->
                                        <tr>
                                            <td>
                                                <strong>User Status Changed</strong>
                                                <br><small class="text-muted">When user is suspended/activated</small>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[user_status_changed][]" value="database" checked>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[user_status_changed][]" value="email" checked>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[user_status_changed][]" value="sms">
                                                </div>
                                            </td>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           name="channels[user_status_changed][]" value="push">
                                                </div>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- EMAIL TAB -->
            <div class="tab-pane fade" id="email">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-info text-white">
                        <h5 class="mb-0">
                            <i class="bi bi-envelope"></i> Email Configuration
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Email Driver</label>
                                <select class="form-select" name="email[driver]">
                                    <option value="smtp">SMTP</option>
                                    <option value="mailgun">Mailgun</option>
                                    <option value="sendgrid">SendGrid</option>
                                    <option value="ses">AWS SES</option>
                                </select>
                                <small class="text-muted">Select your email service provider</small>
                            </div>

                            <div class="col-md-6">
                                <label class="form-label fw-semibold">SMTP Host</label>
                                <input type="text" class="form-control" name="email[host]"
                                       placeholder="smtp.mailtrap.io" value="smtp.mailtrap.io">
                            </div>

                            <div class="col-md-6">
                                <label class="form-label fw-semibold">SMTP Port</label>
                                <input type="number" class="form-control" name="email[port]"
                                       placeholder="2525" value="2525">
                            </div>

                            <div class="col-md-6">
                                <label class="form-label fw-semibold">SMTP Username</label>
                                <input type="text" class="form-control" name="email[username]"
                                       placeholder="username">
                            </div>

                            <div class="col-md-6">
                                <label class="form-label fw-semibold">SMTP Password</label>
                                <input type="password" class="form-control" name="email[password]"
                                       placeholder="••••••••">
                            </div>

                            <div class="col-md-6">
                                <label class="form-label fw-semibold">From Email Address</label>
                                <input type="email" class="form-control" name="email[from]"
                                       value="noreply@privasee.com">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- SMS TAB -->
            <div class="tab-pane fade" id="sms">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-warning text-white">
                        <h5 class="mb-0">
                            <i class="bi bi-telephone"></i> SMS Configuration
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">SMS Provider</label>
                                <select class="form-select" name="sms[provider]" onchange="updateSmsProvider(this.value)">
                                    <option value="twilio" selected>Twilio</option>
                                    <option value="nexmo">Nexmo/Vonage</option>
                                    <option value="aws">AWS SNS</option>
                                </select>
                                <small class="text-muted">Choose your SMS service provider</small>
                            </div>

                            <div class="col-md-12" id="twilio-settings">
                                <h6 class="fw-bold mb-3">Twilio Credentials</h6>
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Account SID</label>
                                        <input type="text" class="form-control" name="sms[twilio][account_sid]"
                                               placeholder="Your Twilio Account SID">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Auth Token</label>
                                        <input type="password" class="form-control" name="sms[twilio][auth_token]"
                                               placeholder="Your Twilio Auth Token">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">From Number</label>
                                        <input type="text" class="form-control" name="sms[twilio][from_number]"
                                               placeholder="+1234567890">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- PAYMENT TAB -->
            <div class="tab-pane fade" id="payment">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-success text-white">
                        <h5 class="mb-0">
                            <i class="bi bi-credit-card"></i> Payment Configuration
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Enable Stripe</label>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox"
                                           name="payment[stripe][enabled]" value="1" checked>
                                    <label class="form-check-label">
                                        Allow Stripe payments
                                    </label>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Enable PayPal</label>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox"
                                           name="payment[paypal][enabled]" value="1" checked>
                                    <label class="form-check-label">
                                        Allow PayPal payments
                                    </label>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Stripe Public Key</label>
                                <input type="text" class="form-control" name="payment[stripe][public_key]"
                                       placeholder="pk_live_...">
                            </div>

                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Stripe Secret Key</label>
                                <input type="password" class="form-control" name="payment[stripe][secret_key]"
                                       placeholder="sk_live_...">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- BUSINESS TAB -->
            <div class="tab-pane fade" id="business">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0">
                            <i class="bi bi-building"></i> Business Settings
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Business Verification</label>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox"
                                           name="business[verification][auto_approve]" value="1">
                                    <label class="form-check-label">
                                        Auto-approve businesses (requires manual if unchecked)
                                    </label>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Require Documents</label>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox"
                                           name="business[verification][require_documents]" value="1" checked>
                                    <label class="form-check-label">
                                        Require trade license for verification
                                    </label>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Default Max Offers per Business</label>
                                <input type="number" class="form-control" name="business[max_offers]"
                                       value="50" min="1">
                            </div>

                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Default Max Venues per Business</label>
                                <input type="number" class="form-control" name="business[max_venues]"
                                       value="10" min="1">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- SECURITY TAB -->
            <div class="tab-pane fade" id="security">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-danger text-white">
                        <h5 class="mb-0">
                            <i class="bi bi-shield-lock"></i> Security Settings
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Minimum Password Length</label>
                                <input type="number" class="form-control" name="security[password_min_length]"
                                       value="8" min="6">
                            </div>

                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Session Timeout (minutes)</label>
                                <input type="number" class="form-control" name="security[session_timeout]"
                                       value="120" min="15">
                            </div>

                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Multi-Factor Authentication</label>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox"
                                           name="security[mfa_enabled]" value="1" checked>
                                    <label class="form-check-label">
                                        Enable MFA for admin users
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>

        <!-- Form Actions -->
        <div class="row mt-4">
            <div class="col-12 text-end">
                <button type="reset" class="btn btn-secondary me-2">
                    <i class="bi bi-arrow-counterclockwise"></i> Reset
                </button>
                <button type="button" class="btn btn-success" onclick="saveAllChanges()">
                    <i class="bi bi-check-circle"></i> Save Configuration
                </button>
            </div>
        </div>
    </form>
</div>

<style>
    /* Tab Navigation Styling */
    .nav-tabs .nav-link {
        color: #666;
        border-bottom: 2px solid transparent;
        transition: all 0.3s ease;
    }

    .nav-tabs .nav-link:hover {
        border-bottom-color: #0d6efd;
        color: #0d6efd;
    }

    .nav-tabs .nav-link.active {
        border-bottom-color: #0d6efd;
        color: #0d6efd;
        background-color: transparent;
    }

    /* Card Styling */
    .card-header {
        border-radius: 0.375rem 0.375rem 0 0 !important;
    }

    .form-check-input:checked {
        background-color: #0d6efd;
        border-color: #0d6efd;
    }

    /* Badge Styling */
    .badge {
        font-size: 0.8rem;
        font-weight: 600;
    }

    /* Table Styling */
    table.table-hover tbody tr:hover {
        background-color: #f8f9fa;
    }

    /* Single Field Update Styling */
    .form-control,
    .form-select,
    .form-check-input {
        transition: all 0.3s ease;
    }

    /* Field with changes indicator */
    .form-control.has-changes,
    .form-select.has-changes {
        border-color: #ffc107;
        box-shadow: 0 0 0 0.2rem rgba(255, 193, 7, 0.25);
    }

    /* Saving state */
    .form-control:disabled,
    .form-select:disabled {
        opacity: 0.7;
    }

    /* Success feedback */
    input:valid {
        border-left: 3px solid #28a745 !important;
    }

    /* Error feedback */
    input:invalid:not(:placeholder-shown) {
        border-left: 3px solid #dc3545 !important;
    }

    /* Alert Styling */
    .alert {
        border-radius: 0.5rem;
        border: none;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        animation: slideInDown 0.3s ease-out;
    }

    .alert-success {
        background-color: #d4edda;
        color: #155724;
        border-left: 4px solid #28a745;
    }

    .alert-danger {
        background-color: #f8d7da;
        color: #721c24;
        border-left: 4px solid #dc3545;
    }

    .alert-info {
        background-color: #d1ecf1;
        color: #0c5460;
        border-left: 4px solid #17a2b8;
    }

    /* Animation */
    @keyframes slideInDown {
        from {
            opacity: 0;
            transform: translateY(-20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    /* Loading spinner */
    .spinner-border-sm {
        width: 1rem;
        height: 1rem;
        border-width: 0.25em;
        animation: spinner 0.75s linear infinite;
    }

    @keyframes spinner {
        to {
            transform: rotate(360deg);
        }
    }

    /* Input focus state */
    .form-control:focus,
    .form-select:focus {
        border-color: #0d6efd;
        box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
    }

    /* Improved label styling */
    .form-label {
        font-weight: 500;
        color: #333;
        margin-bottom: 0.5rem;
    }

    .form-label.fw-semibold {
        font-weight: 600;
    }

    /* Field status indicators */
    .field-status {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 12px;
    }

    .field-status.saving {
        color: #ffc107;
    }

    .field-status.saved {
        color: #28a745;
    }

    .field-status.error {
        color: #dc3545;
    }

    /* Responsive adjustments */
    @media (max-width: 768px) {
        .nav-tabs {
            flex-wrap: wrap;
        }

        .nav-tabs .nav-link {
            font-size: 0.9rem;
        }

        .form-label {
            font-size: 0.95rem;
        }
    }
</style>

<script>
    // Single field update with blur event
    document.addEventListener('DOMContentLoaded', function() {
        const smsProviderSelect = document.querySelector('select[name="sms[provider]"]');
        if (smsProviderSelect) {
            updateSmsProvider(smsProviderSelect.value);
        }

        // Add blur event listeners to all form fields for single updates
        setupSingleFieldUpdates();
    });

    /**
     * Setup single field auto-save on blur
     */
    function setupSingleFieldUpdates() {
        const form = document.getElementById('configForm');
        const inputs = form.querySelectorAll('input[type="text"], input[type="email"], input[type="password"], input[type="number"], select');

        inputs.forEach(input => {
            // Skip nested arrays for now (handle via bulk update)
            if (!input.name.includes('[')) return;

            // Add blur event for single update
            input.addEventListener('blur', function() {
                const key = this.name;
                const value = this.value;

                // Skip empty values
                if (!value || !value.trim()) return;

                // Update on blur with debounce
                clearTimeout(input.updateTimeout);
                input.updateTimeout = setTimeout(() => {
                    updateSingleField(key, value, input);
                }, 500);
            });

            // Show visual feedback on change
            input.addEventListener('change', function() {
                this.classList.add('has-changes');
            });
        });

        // Add blur event to checkboxes
        const checkboxes = form.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach(checkbox => {
            if (!checkbox.name.includes('[')) return;

            checkbox.addEventListener('change', function() {
                const key = this.name;
                const value = this.checked ? '1' : '0';
                updateSingleField(key, value, this);
            });
        });
    }

    /**
     * Update single configuration field
     */
    function updateSingleField(key, value, element) {
        // Convert nested array name to dot notation
        if (key.includes('[')) {
            const parts = key.replace(/\]/g, '').split('[');
            key = parts.join('.');
        }

        // Show saving state
        const originalBg = element.style.backgroundColor;
        element.style.backgroundColor = '#fff3cd';
        const icon = document.createElement('i');
        icon.className = 'bi bi-hourglass-split spinner-border spinner-border-sm';

        fetch('{{ route("admin.configuration.update") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                'Accept': 'application/json',
            },
            body: JSON.stringify({
                key: key,
                value: value
            })
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(data => {
                    throw new Error(data.message || 'Error updating configuration');
                });
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                // Success - green background
                element.style.backgroundColor = '#d4edda';
                element.classList.remove('has-changes');

                showAlert('success',
                    '<i class="bi bi-check-circle"></i> Saved',
                    `${key.replace(/\./g, ' → ')} updated successfully`,
                    'inline');

                // Reset background after 2 seconds
                setTimeout(() => {
                    element.style.backgroundColor = originalBg;
                }, 2000);

                console.log('Updated:', { key, value });
            } else {
                throw new Error(data.message || 'Update failed');
            }
        })
        .catch(error => {
            // Error - red background
            element.style.backgroundColor = '#f8d7da';
            console.error('Update error:', error);

            showAlert('danger',
                '<i class="bi bi-exclamation-circle"></i> Error',
                error.message || 'Failed to update configuration',
                'inline');

            // Reset background after 3 seconds
            setTimeout(() => {
                element.style.backgroundColor = originalBg;
            }, 3000);
        });
    }

    function updateSmsProvider(provider) {
        // Show/hide provider-specific settings
        document.getElementById('twilio-settings').style.display = provider === 'twilio' ? 'block' : 'none';
    }

    /**
     * Save all changes at once
     */
    function saveAllChanges() {
        const form = document.getElementById('configForm');
        const formData = new FormData(form);

        // Fix checkbox values - send '1' for checked, '0' for unchecked
        const checkboxes = form.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach(checkbox => {
            const key = checkbox.name;
            formData.delete(key);
            if (checkbox.checked) {
                formData.set(key, '1');
            } else {
                formData.set(key, '0');
            }
        });

        // Get the button that was clicked
        const btn = event ? event.target.closest('button') : document.querySelector('button[onclick="saveAllChanges()"]');
        const originalText = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<i class="bi bi-hourglass-split"></i> Saving all...';

        fetch(form.action, {
            method: 'POST',
            body: formData,
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(data => {
                    throw new Error(data.message || 'Error updating configuration');
                });
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                showAlert('success',
                    '<i class="bi bi-check-circle"></i> All Changes Saved',
                    `${data.updated_count} configuration(s) updated successfully`,
                    'main');
                console.log('Updated configurations:', data.data);

                // Clear has-changes class
                form.querySelectorAll('.has-changes').forEach(el => {
                    el.classList.remove('has-changes');
                });
            } else {
                throw new Error(data.message || 'Save failed');
            }
        })
        .catch(error => {
            console.error('Configuration error:', error);
            showAlert('danger',
                '<i class="bi bi-exclamation-circle"></i> Save Error',
                error.message || 'Error updating configuration',
                'main');
        })
        .finally(() => {
            btn.disabled = false;
            btn.innerHTML = originalText;
        });

        return false;
    }

    /**
     * Show alert message
     */
    function showAlert(type, title, message, position = 'main') {
        let alertHtml;

        if (position === 'inline') {
            // Small inline alert for single field updates
            alertHtml = `
                <div class="alert alert-${type} alert-dismissible fade show d-inline-block" role="alert" style="position: fixed; top: 20px; right: 20px; z-index: 9999; max-width: 400px;">
                    <div class="d-flex align-items-center">
                        <div>${title} ${message}</div>
                        <button type="button" class="btn-close ms-2" data-bs-dismiss="alert" style="margin: -0.5rem -0.5rem -0.5rem auto;"></button>
                    </div>
                </div>
            `;
        } else {
            // Main alert for bulk operations
            alertHtml = `
                <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                    <h5 class="alert-heading">${title}</h5>
                    <p class="mb-0">${message}</p>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `;
        }

        if (position === 'inline') {
            // Show inline alert
            const alertElement = document.createElement('div');
            alertElement.innerHTML = alertHtml;
            document.body.appendChild(alertElement.firstElementChild);

            // Auto-dismiss after 3 seconds
            setTimeout(() => {
                const alert = document.querySelector('.alert');
                if (alert) {
                    const bsAlert = new bootstrap.Alert(alert);
                    bsAlert.close();
                }
            }, 3000);
        } else {
            // Show main alert
            const container = document.getElementById('alertContainer') || document.querySelector('.container-fluid');
            const alertElement = document.createElement('div');
            alertElement.innerHTML = alertHtml;
            container.insertBefore(alertElement.firstElementChild, container.firstChild);

            // Auto-dismiss after 5 seconds
            setTimeout(() => {
                const alert = document.querySelector('.alert');
                if (alert) {
                    const bsAlert = new bootstrap.Alert(alert);
                    bsAlert.close();
                }
            }, 5000);
        }
    }
</script>
@endsection

