<?php
require_once 'config/database.php';
require_once 'includes/visitor_counter.php';

// Set page variables
$current_page = 'tanya-cici';
$page_title = 'Tanya Cici - Chatbot BBWS Cilicis';

// Get FAQ data from database with statistics
$pdo = getConnection();
$stmt = $pdo->prepare("
    SELECT f.*, 
           COALESCE(s.ask_count, 0) as ask_count,
           s.last_asked
    FROM faq f 
    LEFT JOIN faq_stats s ON f.id = s.faq_id 
    WHERE f.status = 'aktif' 
    ORDER BY COALESCE(s.ask_count, 0) DESC, f.urutan ASC, f.id ASC
");
$stmt->execute();
$faqs = $stmt->fetchAll();

// Include header
include 'includes/header.php';
?>

<!-- Main Content -->
<section class="py-4">
    <div class="container-fluid" style="padding: 15px 150px 100px; margin-top: -12px;">
        <div class="row g-4">
            <!-- Main Content -->
            <div class="col-12">
                <div class="col-md-12" style="padding: 0;">
                    <div class="chatbot-container">
                        <div class="chatbot-header">
                            <div class="chatbot-title">
                                <div class="cici-avatar">
                                    <img src="assets/logo/Tanya Cici.png" alt="Tanya Cici" class="cici-image">
                                </div>
                                <div class="chatbot-info">
                                    <h2>Tanya Cici</h2>
                                    <p>Asisten Virtual BBWS Cilicis</p>
                                    <span class="status-indicator">
                                        <span class="status-dot"></span>
                                        Online
                                    </span>
                                </div>
                            </div>
                        </div>

                        <div class="chatbot-body">
                            <div class="chat-messages" id="chatMessages">
                                <!-- Welcome Message -->
                                <div class="message cici-message">
                                    <div class="message-avatar">
                                        <img src="<?php echo getAssetUrl('logo/Tanya Cici.png'); ?>" alt="Tanya Cici" class="message-avatar-img">
                                    </div>
                                    <div class="message-content">
                                        <div class="message-bubble">
                                            <p>Halo! Saya Cici, asisten virtual BBWS Cilicis. Saya siap membantu menjawab pertanyaan Anda tentang layanan dan informasi BBWS Cilicis. Silakan pilih salah satu pertanyaan di bawah ini atau ketik pertanyaan Anda sendiri.</p>
                                        </div>
                                        <div class="message-time"><?php echo date('H:i'); ?></div>
                                    </div>
                                </div>

                                <!-- Quick Questions -->
                                <div class="message cici-message">
                                    <div class="message-avatar">
                                        <img src="<?php echo getAssetUrl('logo/Tanya Cici.png'); ?>" alt="Tanya Cici" class="message-avatar-img">
                                    </div>
                                    <div class="message-content">
                                        <div class="message-bubble">
                                            <p><strong>Pertanyaan yang sering diajukan:</strong></p>
                                            <div class="quick-questions">
                                                <?php 
                                                $topFaqs = array_slice($faqs, 0, 4); // Ambil 4 pertanyaan teratas
                                                foreach ($topFaqs as $index => $faq): 
                                                ?>
                                                    <button class="quick-question-btn" onclick="sendQuickQuestion('<?php echo htmlspecialchars($faq['pertanyaan']); ?>', <?php echo $faq['id']; ?>)">
                                                        <?php echo htmlspecialchars($faq['pertanyaan']); ?>
                                                        <?php if ($faq['ask_count'] > 0): ?>
                                                            <span class="ask-count">(<?php echo $faq['ask_count']; ?>x)</span>
                                                        <?php endif; ?>
                                                    </button>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                        <div class="message-time"><?php echo date('H:i'); ?></div>
                                    </div>
                                </div>
                            </div>

                            <div class="chat-input-container">
                                <div class="chat-input">
                                    <select id="questionSelect" class="form-select">
                                        <option value="">Pilih pertanyaan</option>
                                        <?php foreach ($faqs as $faq): ?>
                                            <option value="<?php echo htmlspecialchars($faq['pertanyaan']); ?>" data-faq-id="<?php echo $faq['id']; ?>">
                                                <?php echo htmlspecialchars($faq['pertanyaan']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <button id="sendButton" onclick="sendSelectedQuestion()">
                                        <i class="fas fa-paper-plane"></i>
                                    </button>
                                </div>
                                <div class="chat-suggestions">
                                    <span class="suggestion-label">Saran:</span>
                                    <button class="suggestion-btn" onclick="sendSuggestion('Apa itu BBWS Cilicis?')">Apa itu BBWS Cilicis?</button>
                                    <button class="suggestion-btn" onclick="sendSuggestion('Bagaimana cara mengajukan permohonan?')">Cara mengajukan permohonan</button>
                                    <button class="suggestion-btn" onclick="sendSuggestion('Kontak BBWS Cilicis')">Kontak BBWS Cilicis</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<style>
.chatbot-container {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
    backdrop-filter: blur(10px);
    height: 80vh;
    display: flex;
    flex-direction: column;
}

.chatbot-header {
    background-color: #1f3368;
    padding: 20px;
    color: white;
}

.chatbot-title {
    display: flex;
    align-items: center;
    gap: 15px;
}

.cici-avatar {
    width: 60px;
    height: 60px;
    background: rgba(255,255,255,0.2);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.8rem;
    overflow: hidden;
}

.cici-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 50%;
}

.chatbot-info h2 {
    margin: 0;
    font-size: 1.5rem;
    font-weight: 700;
}

.chatbot-info p {
    margin: 5px 0;
    opacity: 0.9;
    font-size: 0.9rem;
}

.status-indicator {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 0.8rem;
    opacity: 0.8;
}

.status-dot {
    width: 8px;
    height: 8px;
    background: #4ade80;
    border-radius: 50%;
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.5; }
}

.chatbot-body {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.chat-messages {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    background: #f8fafc;
}

.message {
    display: flex;
    margin-bottom: 20px;
    animation: messageSlideIn 0.3s ease;
}

.user-message {
    flex-direction: row-reverse;
}

@keyframes messageSlideIn {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.message-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
    flex-shrink: 0;
}

.user-message .message-avatar {
    margin-right: 0;
    margin-left: 12px;
}

.cici-message .message-avatar {
    background-color: #ffc30c;
    color: white;
}

.user-message .message-avatar {
    background: #e2e8f0;
    color: #64748b;
}

.message-avatar-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 50%;
}

.message-content {
    flex: 1;
    max-width: 70%;
}

.message-bubble {
    background: white;
    padding: 15px 20px;
    border-radius: 18px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    position: relative;
}

.cici-message .message-bubble {
    background: white;
    border-bottom-left-radius: 5px;
}

.user-message .message-bubble {
    background: #3b82f6;
    color: white;
    border-bottom-right-radius: 5px;
}

.message-bubble p {
    margin: 0;
    line-height: 1.5;
}

.message-time {
    font-size: 0.75rem;
    color: #64748b;
    margin-top: 5px;
    text-align: right;
}

.user-message .message-time {
    text-align: left;
}

.quick-questions {
    display: flex;
    flex-direction: column;
    gap: 10px;
    margin-top: 15px;
}

.quick-question-btn {
    background: #f1f5f9;
    border: 1px solid #e2e8f0;
    padding: 12px 16px;
    border-radius: 12px;
    text-align: left;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 0.9rem;
    color: #334155;
}

.quick-question-btn:hover {
    background: #e2e8f0;
    border-color: #3b82f6;
    color: #3b82f6;
    transform: translateX(5px);
}

.ask-count {
    font-size: 0.8rem;
    color: #64748b;
    font-weight: 500;
    margin-left: 5px;
}

.chat-input-container {
    padding: 20px;
    background: white;
    border-top: 1px solid #e2e8f0;
}

.chat-input {
    display: flex;
    gap: 10px;
    margin-bottom: 15px;
}

.chat-input select {
    flex: 1;
    padding: 12px 16px;
    border: 2px solid #e2e8f0;
    border-radius: 25px;
    font-size: 0.95rem;
    outline: none;
    transition: border-color 0.3s ease;
    background: white;
    cursor: pointer;
}

.chat-input select:focus {
    border-color: #3b82f6;
}

.chat-input button {
    width: 50px;
    height: 50px;
    background: #3b82f6;
    color: white;
    border: none;
    border-radius: 50%;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
}

.chat-input button:hover {
    background: #2563eb;
    transform: scale(1.05);
}

.chat-suggestions {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
}

.suggestion-label {
    font-size: 0.8rem;
    color: #64748b;
    margin-right: 5px;
}

.suggestion-btn {
    background: #f1f5f9;
    border: 1px solid #e2e8f0;
    padding: 6px 12px;
    border-radius: 15px;
    font-size: 0.8rem;
    cursor: pointer;
    transition: all 0.3s ease;
    color: #64748b;
}

.suggestion-btn:hover {
    background: #e2e8f0;
    color: #3b82f6;
}

/* Typing indicator */
.typing-indicator {
    display: flex;
    align-items: center;
    gap: 12px;
    opacity: 0;
    transition: opacity 0.3s ease;
}

.typing-indicator.show {
    opacity: 1;
}

.typing-dots {
    display: flex;
    gap: 4px;
}

.typing-dot {
    width: 8px;
    height: 8px;
    background: #64748b;
    border-radius: 50%;
    animation: typing 1.4s infinite;
}

.typing-dot:nth-child(2) {
    animation-delay: 0.2s;
}

.typing-dot:nth-child(3) {
    animation-delay: 0.4s;
}

@keyframes typing {
    0%, 60%, 100% {
        transform: translateY(0);
    }
    30% {
        transform: translateY(-10px);
    }
}

/* Responsive Design */
@media (max-width: 992px) {
    .container-fluid {
        padding: 15px 50px 100px !important;
    }
    
    .chatbot-container {
        height: 75vh;
    }
    
    .message-content {
        max-width: 85%;
    }
}

@media (max-width: 768px) {
    .container-fluid {
        padding: 15px 20px 50px !important;
    }
    
    .chatbot-container {
        height: 70vh;
        border-radius: 15px;
    }
    
    .chatbot-header {
        padding: 15px;
    }
    
    .cici-avatar {
        width: 50px;
        height: 50px;
        font-size: 1.5rem;
    }
    
    .chatbot-info h2 {
        font-size: 1.3rem;
    }
    
    .chat-messages {
        padding: 15px;
    }
    
    .message-content {
        max-width: 90%;
    }
    
    .message-bubble {
        padding: 12px 16px;
    }
    
    .chat-input-container {
        padding: 15px;
    }
    
    .chat-input select {
        font-size: 0.9rem;
        padding: 10px 14px;
    }
    
    .chat-input button {
        width: 45px;
        height: 45px;
    }
    
    .quick-questions {
        gap: 8px;
    }
    
    .quick-question-btn {
        padding: 10px 14px;
        font-size: 0.85rem;
    }
}
</style>

<script>
// FAQ data from PHP
const faqData = <?php echo json_encode($faqs); ?>;

function sendQuickQuestion(question, faqId) {
    // Add user message
    addMessage('user', question);
    
    // Track FAQ usage
    trackFAQUsage(faqId, question);
    
    // Show typing indicator
    showTypingIndicator();
    
    // Find the answer
    const faq = faqData.find(f => f.id == faqId);
    const answer = faq ? faq.jawaban : 'Maaf, saya tidak dapat menemukan jawaban untuk pertanyaan tersebut.';
    
    // Hide typing indicator and show answer
    setTimeout(() => {
        hideTypingIndicator();
        addMessage('cici', answer);
    }, 1500);
}

function sendSuggestion(suggestion) {
    const select = document.getElementById('questionSelect');
    for (let i = 0; i < select.options.length; i++) {
        if (select.options[i].value === suggestion) {
            select.selectedIndex = i;
            sendSelectedQuestion();
            break;
        }
    }
}

function sendSelectedQuestion() {
    const select = document.getElementById('questionSelect');
    const selectedOption = select.options[select.selectedIndex];
    
    if (!selectedOption.value) return;
    
    const question = selectedOption.value;
    const faqId = selectedOption.getAttribute('data-faq-id');
    
    // Add user message
    addMessage('user', question);
    
    // Reset select
    select.selectedIndex = 0;
    
    // Track FAQ usage
    trackFAQUsage(faqId, question);
    
    // Show typing indicator
    showTypingIndicator();
    
    // Find the answer
    const faq = faqData.find(f => f.id == faqId);
    const answer = faq ? faq.jawaban : 'Maaf, saya tidak dapat menemukan jawaban untuk pertanyaan tersebut.';
    
    // Hide typing indicator and show answer
    setTimeout(() => {
        hideTypingIndicator();
        addMessage('cici', answer);
    }, 1500);
}

function trackFAQUsage(faqId, question) {
    fetch('api/faq_tracking.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            faq_id: faqId,
            question: question
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            console.log(`FAQ ${faqId} tracked successfully. Count: ${data.ask_count}`);
        }
    })
    .catch(error => {
        console.error('Error tracking FAQ usage:', error);
    });
}

function findBestMatch(query) {
    const queryLower = query.toLowerCase();
    
    // Check for exact matches first
    for (let faq of faqData) {
        if (faq.pertanyaan.toLowerCase().includes(queryLower) || 
            faq.jawaban.toLowerCase().includes(queryLower)) {
            return faq;
        }
    }
    
    // Check for keyword matches
    const keywords = queryLower.split(' ');
    let bestMatch = null;
    let maxScore = 0;
    
    for (let faq of faqData) {
        let score = 0;
        const faqText = (faq.pertanyaan + ' ' + faq.jawaban).toLowerCase();
        
        for (let keyword of keywords) {
            if (faqText.includes(keyword)) {
                score++;
            }
        }
        
        if (score > maxScore) {
            maxScore = score;
            bestMatch = faq;
        }
    }
    
    return maxScore > 0 ? bestMatch : null;
}

function addMessage(sender, content) {
    const messagesContainer = document.getElementById('chatMessages');
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${sender}-message`;
    
    const time = new Date().toLocaleTimeString('id-ID', { 
        hour: '2-digit', 
        minute: '2-digit' 
    });
    
    const avatarContent = sender === 'cici' 
        ? '<img src="<?php echo getAssetUrl('logo/Tanya Cici.png'); ?>" alt="Tanya Cici" class="message-avatar-img">'
        : '<i class="fas fa-user"></i>';
    
    messageDiv.innerHTML = `
        <div class="message-avatar">
            ${avatarContent}
        </div>
        <div class="message-content">
            <div class="message-bubble">
                <p>${content}</p>
            </div>
            <div class="message-time">${time}</div>
        </div>
    `;
    
    messagesContainer.appendChild(messageDiv);
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
}

function showTypingIndicator() {
    const messagesContainer = document.getElementById('chatMessages');
    const typingDiv = document.createElement('div');
    typingDiv.className = 'message cici-message typing-indicator show';
    typingDiv.id = 'typingIndicator';
    
    typingDiv.innerHTML = `
        <div class="message-avatar">
            <img src="<?php echo getAssetUrl('logo/Tanya Cici.png'); ?>" alt="Tanya Cici" class="message-avatar-img">
        </div>
        <div class="message-content">
            <div class="message-bubble">
                <div class="typing-dots">
                    <div class="typing-dot"></div>
                    <div class="typing-dot"></div>
                    <div class="typing-dot"></div>
                </div>
            </div>
        </div>
    `;
    
    messagesContainer.appendChild(typingDiv);
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
}

function hideTypingIndicator() {
    const typingIndicator = document.getElementById('typingIndicator');
    if (typingIndicator) {
        typingIndicator.remove();
    }
}

// Handle Enter key press
document.getElementById('questionSelect').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        sendSelectedQuestion();
    }
});

// Auto-focus select
document.getElementById('questionSelect').focus();
</script>

<?php include 'includes/footer.php'; ?>