<div class="row">
    <div class="col-lg-12">
        <div class="card">
            <div class="card-header">
                <h4 class="card-title">Live Chat Settings</h4>
                <p class="card-category">Configure live chat widget for your website</p>
            </div>
            <div class="card-body">
                <form id="liveChatForm">
                    @csrf
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label class="form-label">Enable Live Chat</label>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="live_chat_enabled" 
                                           name="live_chat_enabled" value="1" 
                                           {{ $settings->live_chat_enabled ? 'checked' : '' }}>
                                    <label class="form-check-label" for="live_chat_enabled">
                                        Enable live chat widget on website
                                    </label>
                                </div>
                                <small class="form-text text-muted">
                                    When enabled, the live chat widget will be displayed on all pages of your website.
                                </small>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label class="form-label">Live Chat Code</label>
                                <textarea class="form-control" id="live_chat_code" name="live_chat_code" 
                                          rows="8" placeholder="Paste your live chat script code here...">{{ $settings->live_chat_code }}</textarea>
                                <small class="form-text text-muted">
                                    Paste the complete script code from your live chat provider (e.g., Smartsupp, Tawk.to, Intercom, etc.)
                                </small>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-12">
                            <div class="alert alert-info">
                                <h5><i class="fas fa-info-circle mr-2"></i>How to get your live chat code:</h5>
                                <ol class="mb-0">
                                    <li>Sign up with a live chat provider (Smartsupp, Tawk.to, Intercom, etc.)</li>
                                    <li>Get your installation script from their dashboard</li>
                                    <li>Copy the complete script code (including &lt;script&gt; tags)</li>
                                    <li>Paste it in the textarea above</li>
                                    <li>Enable the live chat and save settings</li>
                                </ol>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-12">
                            <div class="alert alert-warning">
                                <h5><i class="fas fa-exclamation-triangle mr-2"></i>Important Notes:</h5>
                                <ul class="mb-0">
                                    <li>Make sure to include the complete script code with opening and closing &lt;script&gt; tags</li>
                                    <li>The chat widget will appear on all pages of your website when enabled</li>
                                    <li>Test the chat functionality after saving to ensure it works correctly</li>
                                    <li>Some chat providers may require additional configuration in their dashboard</li>
                                </ul>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-12">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save mr-2"></i>Save Live Chat Settings
                            </button>
                            <button type="button" class="btn btn-secondary ml-2" onclick="testLiveChat()">
                                <i class="fas fa-test-tube mr-2"></i>Test Live Chat
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
document.getElementById('liveChatForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const liveChatEnabled = document.getElementById('live_chat_enabled').checked;

    // Laravel route is PUT — spoof method (POST + _method) so the request matches the route
    formData.append('_method', 'PUT');

    if (liveChatEnabled) {
        formData.append('live_chat_enabled', '1');
    }

    const csrfMeta = document.querySelector('meta[name="csrf-token"]');
    const csrfToken = csrfMeta ? csrfMeta.getAttribute('content') : '';

    // Show loading state
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Saving...';
    submitBtn.disabled = true;

    fetch('{{ route("update.live.chat") }}', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRF-TOKEN': csrfToken,
            'Accept': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        credentials: 'same-origin'
    })
    .then(async response => {
        let data = {};
        try {
            data = await response.json();
        } catch (e) {
            /* non-JSON body */
        }
        if (response.ok && data.status === 200) {
            showAlert('success', data.success || 'Settings saved');
            return;
        }
        let msg = data.message || 'Failed to save live chat settings';
        if (data.errors && typeof data.errors === 'object') {
            const first = Object.values(data.errors)[0];
            if (Array.isArray(first) && first[0]) {
                msg = first[0];
            }
        }
        showAlert('error', msg);
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('error', 'An error occurred while saving settings');
    })
    .finally(() => {
        // Reset button state
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
});

function testLiveChat() {
    const chatCode = document.getElementById('live_chat_code').value;
    const isEnabled = document.getElementById('live_chat_enabled').checked;
    
    if (!isEnabled) {
        showAlert('warning', 'Please enable live chat first');
        return;
    }
    
    if (!chatCode.trim()) {
        showAlert('warning', 'Please enter live chat code first');
        return;
    }
    
    // Open a new window to test the chat
    const testWindow = window.open('{{ route("home") }}', '_blank');
    if (testWindow) {
        showAlert('info', 'Test window opened. Check if the live chat widget appears on the homepage.');
    } else {
        showAlert('error', 'Please allow popups to test the live chat');
    }
}

function showAlert(type, message) {
    // Create alert element
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type === 'error' ? 'danger' : type} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : type === 'warning' ? 'exclamation-triangle' : 'info-circle'} mr-2"></i>
        ${message}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    `;
    
    // Insert at the top of the form
    const form = document.getElementById('liveChatForm');
    form.insertBefore(alertDiv, form.firstChild);
    
    // Auto remove after 5 seconds
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.remove();
        }
    }, 5000);
}
</script>
