<?php
// Start session
session_start();

// Include database connection
require_once "../config/connection.php";

// Redirect if not borrower user - using functions from connection.php
if (!is_logged_in() || !is_user_type('borrower')) {
    header("Location: ../login.php");
    exit();
}

// Get borrower data
$borrower_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM borrower_users WHERE id = ?");
$stmt->bind_param("i", $borrower_id);
$stmt->execute();
$borrower_data = $stmt->get_result()->fetch_assoc();
$stmt->close();

// Check if account is active, redirect to logout if not
if ($borrower_data['status'] == 'nonactive') {
    // Log this attempt
    error_log("Nonactive borrower attempted to access help center: " . $_SESSION['username']);
    
    // Clear all session variables
    $_SESSION = array();
    
    // Destroy the session
    session_destroy();
    
    // Redirect to login with message
    header("Location: ../login.php?error=inactive");
    exit();
}

// Fetch all questions from the database
$query = "SELECT * FROM chatbot_qa ORDER BY display_order ASC";
$result = $conn->query($query);
$questions = [];

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $questions[] = $row;
    }
}

// Group questions by category if it exists in the database
$grouped_questions = [];
foreach ($questions as $question) {
    $category = isset($question['category']) ? $question['category'] : 'Umum';
    if (!isset($grouped_questions[$category])) {
        $grouped_questions[$category] = [];
    }
    $grouped_questions[$category][] = $question;
}

// Set page title
$page_title = "Pusat Bantuan";

// Log activity
log_activity($conn, $borrower_id, 'borrower', 'Help Center Access', 'borrower user accessed help center');

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

<!-- Main Content Area -->
<main class="flex-1 p-4 md:p-6 overflow-auto bg-gradient-to-br from-blue-50 via-teal-50 to-green-50">
    <!-- Help Center Card -->
    <div class="bg-white rounded-xl shadow-lg p-5 mb-6 border border-blue-100 transition-all duration-300 hover:shadow-xl max-w-5xl mx-auto">
        <div class="flex items-center mb-5">
            <div class="bg-gradient-to-r from-blue-600 to-teal-500 p-3 rounded-lg shadow-md mr-4">
                <i class="fas fa-headset text-white text-xl"></i>
            </div>
            <div>
                <h2 class="text-2xl font-bold bg-gradient-to-r from-blue-600 to-teal-500 bg-clip-text text-transparent">Pusat Bantuan Color Code</h2>
                <p class="text-gray-600">Pilih pertanyaan dalam chat untuk mendapatkan jawaban cepat seputar peminjaman Color Code</p>
            </div>
        </div>
        
        <!-- Chat Container -->
        <div class="border border-blue-200 rounded-xl overflow-hidden shadow-md transition-all duration-300 hover:shadow-lg">
            <!-- Chat Header -->
            <div class="bg-gradient-to-r from-blue-600 to-teal-500 text-white p-4 flex items-center">
                <div class="flex items-center">
                    <div class="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center mr-3 shadow-inner animate-pulse">
                        <i class="fas fa-robot text-xl"></i>
                    </div>
                    <div>
                        <h3 class="font-semibold">Color Code Assistant</h3>
                        <p class="text-xs text-blue-100 flex items-center">
                            <span class="inline-block w-2 h-2 bg-green-400 rounded-full mr-2 shadow"></span>
                            Online - Siap Membantu
                        </p>
                    </div>
                </div>
            </div>
            
            <!-- Chat Messages -->
            <div id="chat-messages" class="bg-gray-50 p-4 h-[450px] overflow-y-auto flex flex-col space-y-4 scroll-smooth">
                <!-- Welcome Message -->
                <div class="flex items-start reveal-message">
                    <div class="w-10 h-10 rounded-full bg-gradient-to-r from-blue-600 to-teal-500 flex items-center justify-center text-white mr-2 mt-1 flex-shrink-0 shadow-md">
                        <i class="fas fa-robot text-sm"></i>
                    </div>
                    <div class="bg-white rounded-2xl p-4 shadow-sm max-w-xs sm:max-w-md border-l-4 border-blue-500 transform transition-all duration-300">
                        <p class="text-gray-800">Halo, <span class="font-semibold text-blue-600"><?php echo htmlspecialchars($borrower_data['username']); ?></span>! 👋</p>
                        <p class="text-gray-800 mt-2">Saya adalah Color Code Assistant yang siap membantu Anda. Silakan pilih pertanyaan di bawah ini:</p>
                    </div>
                </div>
                
                <!-- Category tabs if grouped -->
                <?php if (count($grouped_questions) > 1): ?>
                <div class="flex flex-wrap mb-2 px-2 mt-4 gap-2 category-tabs">
                    <button class="category-tab active px-4 py-2 rounded-full text-sm font-medium text-blue-700 bg-blue-100 hover:bg-blue-200 transition-colors" data-category="all">
                        Semua
                    </button>
                    <?php foreach (array_keys($grouped_questions) as $category): ?>
                    <button class="category-tab px-4 py-2 rounded-full text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 transition-colors" data-category="<?php echo htmlspecialchars($category); ?>">
                        <?php echo htmlspecialchars($category); ?>
                    </button>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
                
                <!-- Questions as Bot Messages -->
                <?php 
                $delay = 0;
                foreach ($grouped_questions as $category => $category_questions): 
                ?>
                <div class="category-section" data-category="<?php echo htmlspecialchars($category); ?>">
                    <?php foreach ($category_questions as $question): 
                        $delay += 100; // Increase delay for each question
                    ?>
                    <div class="flex items-start assistant-question mb-3 reveal-message" style="animation-delay: <?php echo $delay; ?>ms;">
                        <div class="w-10 h-10 rounded-full bg-gradient-to-r from-blue-600 to-teal-500 flex items-center justify-center text-white mr-2 mt-1 flex-shrink-0 shadow-md">
                            <i class="fas fa-robot text-sm"></i>
                        </div>
                        <button 
                            class="text-left bg-white hover:bg-blue-50 rounded-2xl p-4 shadow-sm transition-all duration-300 max-w-xs sm:max-w-md border border-gray-100 hover:border-blue-200 question-btn transform hover:-translate-y-1 hover:shadow-md"
                            data-id="<?php echo $question['id']; ?>"
                            data-question="<?php echo htmlspecialchars($question['question']); ?>"
                            data-answer="<?php echo htmlspecialchars($question['answer']); ?>"
                            data-category="<?php echo htmlspecialchars($category); ?>">
                            <p class="text-gray-800"><?php echo htmlspecialchars($question['question']); ?></p>
                        </button>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endforeach; ?>
                
                <!-- No results message -->
                <div id="no-results" class="hidden text-center py-8 reveal-message">
                    <div class="mx-auto w-16 h-16 mb-4 text-gray-300 flex items-center justify-center rounded-full bg-gray-100">
                        <i class="fas fa-search text-2xl"></i>
                    </div>
                    <p class="text-gray-500 font-medium">Tidak ada pertanyaan yang cocok dengan pencarian Anda.</p>
                    <p class="text-gray-400 text-sm mt-1">Coba gunakan kata kunci lain atau lihat semua kategori.</p>
                </div>
            </div>
            
            <!-- Chat Footer -->
            <div class="bg-gray-50 border-t border-gray-200 p-3 flex items-center justify-center">
                <img src="../images/logo.png" alt="Logo Perusahaan" class="h-6 mr-2">
                <div class="text-xs text-gray-500">Powered by <span class="font-medium">Kayu Mebel Indonesia (Color Panel)</span></div>
            </div>
        </div>
    </div>
    
    <!-- Modal untuk jawaban -->
    <div id="answer-modal" class="fixed inset-0 bg-black bg-opacity-50 backdrop-blur-sm z-50 flex items-center justify-center hidden">
        <div class="bg-white rounded-xl shadow-2xl w-full max-w-2xl mx-4 transform transition-all scale-95 opacity-0 overflow-hidden" id="modal-content">
            <div class="bg-gradient-to-r from-blue-600 to-teal-500 text-white p-4 flex justify-between items-center">
                <h3 class="text-xl font-bold" id="modal-question"></h3>
                <button id="close-modal" class="text-white hover:text-gray-200 bg-white/10 hover:bg-white/20 rounded-full w-8 h-8 flex items-center justify-center transition-colors">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="p-6 max-h-[70vh] overflow-y-auto prose prose-blue" id="modal-answer">
                <!-- Jawaban akan ditampilkan di sini -->
            </div>
            <div class="border-t p-4 flex justify-between items-center bg-gray-50">
                <div class="flex gap-2">
                    <button id="copy-answer" class="bg-gray-100 hover:bg-gray-200 text-gray-700 py-2 px-4 rounded-lg transition-colors text-sm flex items-center">
                        <i class="far fa-copy mr-2"></i> Salin
                    </button>
                    <button id="share-answer" class="bg-gray-100 hover:bg-gray-200 text-gray-700 py-2 px-4 rounded-lg transition-colors text-sm flex items-center">
                        <i class="fas fa-share-alt mr-2"></i> Bagikan
                    </button>
                </div>
                <button id="close-modal-btn" class="bg-gradient-to-r from-blue-600 to-teal-500 hover:from-blue-700 hover:to-teal-600 text-white py-2 px-6 rounded-lg transition-colors shadow-md hover:shadow-lg">
                    Tutup
                </button>
            </div>
        </div>
    </div>
    
    <!-- Snackbar for notifications -->
    <div id="snackbar" class="fixed bottom-4 right-4 bg-gray-800 text-white py-2 px-4 rounded-lg shadow-lg transform translate-y-10 opacity-0 transition-all duration-300">
        Teks disalin ke clipboard!
    </div>
</main>

<!-- JavaScript for ChatBot -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    const chatMessages = document.getElementById('chat-messages');
    const questionButtons = document.querySelectorAll('.question-btn');
    const modal = document.getElementById('answer-modal');
    const modalContent = document.getElementById('modal-content');
    const modalQuestion = document.getElementById('modal-question');
    const modalAnswer = document.getElementById('modal-answer');
    const closeModal = document.getElementById('close-modal');
    const closeModalBtn = document.getElementById('close-modal-btn');
    const assistantQuestions = document.querySelectorAll('.assistant-question');
    const copyAnswerBtn = document.getElementById('copy-answer');
    const shareAnswerBtn = document.getElementById('share-answer');
    const snackbar = document.getElementById('snackbar');
    const categoryTabs = document.querySelectorAll('.category-tab');
    
    // Function to add message to chat
    function addMessage(sender, content, isTyping = false) {
        const messageDiv = document.createElement('div');
        messageDiv.className = sender === 'user' ? 
            'flex items-start justify-end reveal-message' : 
            'flex items-start reveal-message';
        
        let iconClass = sender === 'user' ? 'fa-user' : 'fa-robot';
        let bgColor = sender === 'user' ? 'bg-gradient-to-r from-teal-500 to-blue-500' : 'bg-gradient-to-r from-blue-600 to-teal-500';
        let msgBgColor = sender === 'user' ? 'bg-gradient-to-r from-teal-500 to-blue-500 text-white' : 'bg-white text-gray-800';
        let alignment = sender === 'user' ? 'ml-2' : 'mr-2';
        
        if (isTyping) {
            content = '<div class="typing-indicator"><span></span><span></span><span></span></div>';
        }
        
        const html = `
            ${sender === 'user' ? '' : `<div class="w-10 h-10 rounded-full ${bgColor} flex items-center justify-center text-white ${alignment} mt-1 flex-shrink-0 shadow-md">
                <i class="fas ${iconClass} text-sm"></i>
            </div>`}
            <div class="${sender === 'user' ? msgBgColor : 'bg-white border-l-4 border-blue-500'} rounded-2xl p-4 shadow-sm max-w-xs sm:max-w-md ${isTyping ? 'typing-message' : ''} transform transition-all">
                ${isTyping ? content : `<p>${content}</p>`}
            </div>
            ${sender === 'user' ? `<div class="w-10 h-10 rounded-full ${bgColor} flex items-center justify-center text-white ${alignment} mt-1 flex-shrink-0 shadow-md">
                <i class="fas ${iconClass} text-sm"></i>
            </div>` : ''}
        `;
        
        messageDiv.innerHTML = html;
        chatMessages.appendChild(messageDiv);
        
        // Trigger animation
        setTimeout(() => {
            messageDiv.classList.add('is-visible');
        }, 10);
        
        // Scroll to bottom with smooth animation
        chatMessages.scrollTo({
            top: chatMessages.scrollHeight,
            behavior: 'smooth'
        });
        
        return messageDiv;
    }
    
    // Function to show modal
    function showModal(question, answer) {
        modalQuestion.textContent = question;
        // Convert newlines to <br> and apply some formatting
        const formattedAnswer = answer.replace(/\n/g, '<br>').replace(
            /(CATATAN PENTING|PERHATIAN|PENTING|NOTE):(.*?)(?=\n|$)/gi, 
            '<div class="bg-yellow-50 border-l-4 border-yellow-400 p-3 my-2 rounded"><strong>$1:</strong>$2</div>'
        );
        modalAnswer.innerHTML = formattedAnswer;
        modal.classList.remove('hidden');
        
        // Animation
        setTimeout(() => {
            modalContent.classList.remove('scale-95', 'opacity-0');
            modalContent.classList.add('scale-100', 'opacity-100');
        }, 10);
    }
    
    // Function to hide modal
    function hideModal() {
        // Animation
        modalContent.classList.remove('scale-100', 'opacity-100');
        modalContent.classList.add('scale-95', 'opacity-0');
        
        setTimeout(() => {
            modal.classList.add('hidden');
        }, 300);
    }
    

    
    // Function to filter by category
    function filterByCategory(category) {
        const categorySections = document.querySelectorAll('.category-section');
        
        // Update active tab
        categoryTabs.forEach(tab => {
            if (tab.dataset.category === category) {
                tab.classList.add('active', 'text-blue-700', 'bg-blue-100');
                tab.classList.remove('text-gray-700', 'bg-gray-100');
            } else {
                tab.classList.remove('active', 'text-blue-700', 'bg-blue-100');
                tab.classList.add('text-gray-700', 'bg-gray-100');
            }
        });
        
        if (category === 'all') {
            categorySections.forEach(section => {
                section.classList.remove('hidden');
            });
            
            // Show all questions
            assistantQuestions.forEach(question => {
                question.classList.remove('hidden');
            });
        } else {
            categorySections.forEach(section => {
                if (section.dataset.category === category) {
                    section.classList.remove('hidden');
                } else {
                    section.classList.add('hidden');
                }
            });
        }
        
        // Reset search
        searchInput.value = '';
        noResults.classList.add('hidden');
    }
    
    // Function to show snackbar
    function showSnackbar(message) {
        snackbar.textContent = message;
        snackbar.classList.remove('translate-y-10', 'opacity-0');
        snackbar.classList.add('translate-y-0', 'opacity-100');
        
        setTimeout(() => {
            snackbar.classList.remove('translate-y-0', 'opacity-100');
            snackbar.classList.add('translate-y-10', 'opacity-0');
        }, 3000);
    }
    
    // Copy answer to clipboard
    copyAnswerBtn.addEventListener('click', function() {
        const answerText = modalAnswer.textContent;
        navigator.clipboard.writeText(answerText).then(() => {
            showSnackbar('Teks berhasil disalin ke clipboard!');
        }).catch(err => {
            showSnackbar('Gagal menyalin teks: ' + err);
        });
    });
    
    // Share answer (just a demo)
    shareAnswerBtn.addEventListener('click', function() {
        showSnackbar('Fitur berbagi akan segera hadir!');
    });
    

    
    // Add event listeners to category tabs
    categoryTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            const category = this.dataset.category;
            filterByCategory(category);
        });
    });
    
    // Add event listeners to question buttons
    questionButtons.forEach(button => {
        button.addEventListener('click', function() {
            const questionText = this.getAttribute('data-question');
            const answerText = this.getAttribute('data-answer');
            
            // Add user question to chat
            addMessage('user', questionText);
            
            // Add "typing" message
            const typingMessage = addMessage('assistant', '', true);
            
            // Simulate typing delay
            setTimeout(() => {
                // Remove typing message
                typingMessage.remove();
                
                // Show answer in modal
                showModal(questionText, answerText);
            }, 1000); // 1 second delay
        });
    });
    
    // Close modal event listeners
    closeModal.addEventListener('click', hideModal);
    closeModalBtn.addEventListener('click', hideModal);
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            hideModal();
        }
    });
    

    
    // Keyboard events
    document.addEventListener('keydown', function(e) {
        // Close modal on ESC key
        if (e.key === 'Escape' && !modal.classList.contains('hidden')) {
            hideModal();
        }
    });
    
    // Initially make sure all questions are visible and scroll to top
    chatMessages.scrollTop = 0;
    
    // Add animation to all reveal-message elements
    document.querySelectorAll('.reveal-message').forEach((el, index) => {
        setTimeout(() => {
            el.classList.add('is-visible');
        }, 100 * index);
    });
});
</script>

<style>
/* Base animations */
@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

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

/* Reveal message animation */
.reveal-message {
    opacity: 0;
    transform: translateY(20px);
    transition: all 0.3s ease-out;
}

.reveal-message.is-visible {
    opacity: 1;
    transform: translateY(0);
}

/* Fade out animation */
.fade-out {
    animation: fadeOut 0.3s ease-out forwards;
}

/* Typing indicator animation */
.typing-indicator {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    height: 20px;
}

.typing-indicator span {
    height: 8px;
    width: 8px;
    border-radius: 50%;
    background-color: #3b82f6;
    display: inline-block;
    margin-right: 3px;
    animation: bounce 1.3s linear infinite;
    opacity: 0.7;
}

.typing-indicator span:nth-child(2) {
    animation-delay: 0.15s;
}

.typing-indicator span:nth-child(3) {
    animation-delay: 0.3s;
}

@keyframes bounce {
    0%, 100% {
        transform: translateY(0);
    }
    50% {
        transform: translateY(-5px);
    }
}

/* Message styling */
.typing-message {
    min-width: 60px;
}

/* Modal transition */
#modal-content {
    transition: all 0.3s ease-out;
}

/* Question button hover effect */
.question-btn {
    position: relative;
    overflow: hidden;
}

.category-tab.active {
    position: relative;
}

.category-tab.active:after {
    content: '';
    position: absolute;
    bottom: -2px;
    left: 50%;
    transform: translateX(-50%);
    width: 10px;
    height: 2px;
    background-color: #3b82f6;
    border-radius: 2px;
}

/* Custom scrollbar */
#chat-messages::-webkit-scrollbar {
    width: 6px;
}

#chat-messages::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 10px;
}

#chat-messages::-webkit-scrollbar-thumb {
    background: #cbd5e1;
    border-radius: 10px;
}

#chat-messages::-webkit-scrollbar-thumb:hover {
    background: #94a3b8;
}

/* Prose styling for the answer modal */
.prose a {
    color: #3b82f6;
    text-decoration: underline;
}

.prose strong {
    color: #1e40af;
}

.prose h1, .prose h2, .prose h3, .prose h4 {
    color: #1e3a8a;
    margin-top: 1.5em;
    margin-bottom: 0.5em;
}

/* Responsive adjustments */
@media (max-width: 640px) {
    .question-btn {
        max-width: 280px;
    }
}
</style>

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