<div class="chat-icon"><button type="button" class="chat-toggler"><i class="fa fa-comment"></i></button></div>
<!--Chat Popup-->
<div id="chat-popup" class="chat-popup">
    <div class="popup-inner">
        <div class="close-chat"><i class="fa fa-times"></i></div>
        <div class="chat-form">
            <p>Beri penilaian pada website kami sertakan kritik saran yang membangun</p>
            <form id="feedbackForm" class="contact-form-validated">
                <div class="form-group">
                    <input type="text" id="feedbackName" name="name" placeholder="Nama Anda" required>
                </div>
                <div class="form-group">
                    <input type="email" id="feedbackEmail" name="email" placeholder="Email Anda" required>
                </div>
                <!-- rating float 0-10 -->
                <div class="form-group">
                    <input type="number" id="feedbackRating" name="rating" placeholder="Penilaian (0-10)" min="0" max="10" step="0.1" required>
                </div>
                <div class="form-group">
                    <textarea id="feedbackMessage" name="message" placeholder="Pesan Anda" required></textarea>
                </div>
                <div class="form-group message-btn">
                    <button type="submit" class="thm-btn" id="submitFeedbackBtn">
                        <span class="thm-btn-text">Kirim</span>
                        <span class="thm-btn-icon-box"><i class="fas fa-arrow-right"></i></span>
                    </button>
                </div>
                <div class="result"></div>
            </form>
        </div>
    </div>
</div>

<!-- SweetAlert2 for notifications -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const feedbackForm = document.getElementById('feedbackForm');
    const API_URL = '<?php echo e(env('BASE_URL')); ?>/api/public/sites/feedback';
    const SITE_SLUG = '<?php echo e(strtolower(env('DAERAH', 'kota-yogyakarta'))); ?>'; // Ambil dari env DAERAH

    if (feedbackForm) {
        feedbackForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const submitBtn = document.getElementById('submitFeedbackBtn');
            const btnText = submitBtn.querySelector('.thm-btn-text');
            const originalText = btnText.textContent;
            
            // Disable button and show loading
            submitBtn.disabled = true;
            btnText.textContent = 'Mengirim...';
            
            // Get form data
            const formData = {
                name: document.getElementById('feedbackName').value.trim(),
                email: document.getElementById('feedbackEmail').value.trim(),
                rating: parseFloat(document.getElementById('feedbackRating').value),
                substance: document.getElementById('feedbackMessage').value.trim(),
                slug: SITE_SLUG
            };
            
            console.log('Sending feedback to:', API_URL);
            console.log('Data:', formData);
            console.log('Site slug:', SITE_SLUG);
            
            try {
                const response = await fetch(API_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });
                
                console.log('Response status:', response.status);
                console.log('Response headers:', response.headers);
                
                // Check if response is HTML (error page) instead of JSON
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    const text = await response.text();
                    console.error('Received HTML instead of JSON:', text.substring(0, 200));
                    throw new Error('Server mengembalikan format yang tidak valid. Periksa endpoint API.');
                }
                
                const result = await response.json();
                console.log('Response data:', result);
                
                if (response.ok || response.status === 201) {
                    // Success
                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil!',
                        text: 'Terima kasih atas feedback Anda. Feedback Anda telah kami terima.',
                        timer: 3000,
                        showConfirmButton: false
                    });
                    
                    // Reset form
                    feedbackForm.reset();
                    
                    // Close chat popup after 2 seconds
                    setTimeout(() => {
                        document.getElementById('chat-popup').classList.remove('active');
                    }, 2000);
                    
                } else {
                    // Error from server
                    throw new Error(result.error || result.message || `Error ${response.status}: Gagal mengirim feedback`);
                }
                
            } catch (error) {
                console.error('Error submitting feedback:', error);
                
                let errorMessage = 'Terjadi kesalahan saat mengirim feedback.';
                
                if (error.message.includes('Failed to fetch')) {
                    errorMessage = 'Tidak dapat terhubung ke server. Periksa koneksi internet Anda.';
                } else if (error.message.includes('format yang tidak valid')) {
                    errorMessage = 'Endpoint API tidak ditemukan atau tidak valid. Hubungi administrator.';
                } else {
                    errorMessage = error.message;
                }
                
                Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                    text: errorMessage
                });
            } finally {
                // Re-enable button
                submitBtn.disabled = false;
                btnText.textContent = originalText;
            }
        });
    }
});
</script>

<style>
.chat-popup .result {
    margin-top: 10px;
    padding: 10px;
    border-radius: 4px;
    display: none;
}

.chat-popup .result.success {
    background-color: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
    display: block;
}

.chat-popup .result.error {
    background-color: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
    display: block;
}

.thm-btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

#feedbackRating {
    width: 100%;
    padding: 8px;
    padding-left: 16px;
    box-sizing: border-box;
    border-radius: 4px;
    background-color: #393939;
    color: #b7b7b7ff;
    font-size: 13px;
}
</style>
<?php /**PATH D:\laravel\krs-jawa3-template\daerah\resources\views/components/chat_popup.blade.php ENDPATH**/ ?>