<?php session_start();
// bank_linking.php
include 'includes/head.php';

// Get all FAQ categories with their items
$categories_sql = "SELECT fc.*, COUNT(fi.id) as faq_count 
                   FROM faq_categories fc 
                   LEFT JOIN faq_items fi ON fc.id = fi.category_id AND fi.is_active = 1 
                   WHERE fc.is_active = 1 
                   GROUP BY fc.id 
                   ORDER BY fc.name";
$categories_result = mysqli_query($conn, $categories_sql);

// Get all FAQs for search functionality
$all_faqs_sql = "SELECT fi.*, fc.name as category_name 
                 FROM faq_items fi 
                 JOIN faq_categories fc ON fi.category_id = fc.id 
                 WHERE fi.is_active = 1 
                 ORDER BY fc.name, fi.id";
$all_faqs_result = mysqli_query($conn, $all_faqs_sql);

$search_results = array();
$search_query = '';

// Handle search
if (isset($_GET['search']) && !empty($_GET['search'])) {
    $search_query = $conn->real_escape_string($_GET['search']);
    $search_sql = "SELECT fi.*, fc.name as category_name 
                   FROM faq_items fi 
                   JOIN faq_categories fc ON fi.category_id = fc.id 
                   WHERE fi.is_active = 1 
                   AND (fi.question LIKE '%$search_query%' OR fi.answer LIKE '%$search_query%')
                   ORDER BY fc.name, fi.id";
    $search_result = mysqli_query($conn, $search_sql);
    
    while ($faq = mysqli_fetch_assoc($search_result)) {
        $search_results[] = $faq;
    }
}
?>
<!DOCTYPE html>
<html lang="en">


<style>
    .faq-category-card {
        border: none;
        border-radius: 15px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        margin-bottom: 30px;
        transition: all 0.3s ease;
    }
    .faq-category-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 15px rgba(0,0,0,0.2);
    }
    .faq-item {
        border-bottom: 1px solid #eee;
        padding: 20px 0;
    }
    .faq-item:last-child {
        border-bottom: none;
    }
    .faq-question {
        font-weight: 600;
        cursor: pointer;
        margin: 0;
        padding-right: 30px;
        position: relative;
    }
    .faq-question:after {
        content: '+';
        position: absolute;
        right: 0;
        top: 0;
        font-size: 1.5em;
        color: #4CAF50;
        transition: all 0.3s ease;
    }
    .faq-question.active:after {
        content: '-';
        color: #dc3545;
    }
    .faq-answer {
        display: none;
        padding-top: 15px;
        color: #666;
        line-height: 1.6;
    }
    .search-box {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 15px;
        padding: 40px 30px;
        color: white;
        margin-bottom: 30px;
    }
    .category-badge {
        background: rgba(76, 175, 80, 0.1);
        color: #4CAF50;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 0.8em;
        font-weight: 600;
    }
    .helpful-buttons {
        margin-top: 20px;
        padding-top: 15px;
        border-top: 1px solid #eee;
    }
    .search-result-item {
        background: #121213ff;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 15px;
        border-left: 4px solid #4CAF50;
    }
</style>



<body class="dashboard">
    <div id="main-wrapper">
        
        <?php include('includes/header.php');?>
        <?php include('includes/sidebar.php');?>


        <div class="content-body">
            <div class="container">
                <div class="row">
                    <div class="col-12">
                        <div class="page-title">
                            <div class="row align-items-center justify-content-between">
                                <div class="col-xl-4">
                                    <div class="page-title-content">
                                        <h3>Frequently Asked Questions</h3>
                                        <p class="mb-2">Find quick answers to common questions about our loan services</p>
                                    </div>
                                </div>
                                <div class="col-auto">
                                    <div class="breadcrumbs">
                                        <a href="dashboard.php">Home</a>
                                        <span><i class="fi fi-rr-angle-small-right"></i></span>
                                        <a href="support.php">Support</a>
                                        <span><i class="fi fi-rr-angle-small-right"></i></span>
                                        <a href="#">FAQs</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- SEARCH SECTION -->
                <div class="row">
                    <div class="col-12">
                        <div class="search-box">
                            <h4 class="text-white mb-3">How can we help you today?</h4>
                            <p class="text-white-50 mb-4">Search through our knowledge base or browse categories below</p>
                            <form action="faq.php" method="GET">
                                <div class="input-group input-group-lg">
                                    <input type="text" class="form-control" name="search" placeholder="Type your question here..." value="<?php echo htmlspecialchars($search_query); ?>">
                                    <button class="btn btn-light" type="submit">
                                        <i class="fi fi-br-search"></i> Search
                                    </button>
                                </div>
                            </form>
                            <div class="row mt-4 text-center">
                                <div class="col-md-3">
                                    <div class="text-white-50">
                                        <i class="fi fi-rr-document fs-2 d-block mb-2"></i>
                                        <small>100+ Articles</small>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="text-white-50">
                                        <i class="fi fi-rr-time-fast fs-2 d-block mb-2"></i>
                                        <small>Instant Answers</small>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="text-white-50">
                                        <i class="fi fi-rr-user-headset fs-2 d-block mb-2"></i>
                                        <small>Expert Content</small>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="text-white-50">
                                        <i class="fi fi-rr-calendar fs-2 d-block mb-2"></i>
                                        <small>Regularly Updated</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- SEARCH RESULTS -->
                <?php if (!empty($search_query)): ?>
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h4 class="card-title mb-0">Search Results for "<?php echo htmlspecialchars($search_query); ?>"</h4>
                                <span class="badge bg-primary"><?php echo count($search_results); ?> results</span>
                            </div>
                            <div class="card-body">
                                <?php if (!empty($search_results)): ?>
                                    <?php foreach ($search_results as $faq): ?>
                                    <div class="search-result-item">
                                        <div class="d-flex justify-content-between align-items-start mb-2">
                                            <h6 class="mb-0"><?php echo htmlspecialchars($faq['question']); ?></h6>
                                            <span class="category-badge"><?php echo htmlspecialchars($faq['category_name']); ?></span>
                                        </div>
                                        <p class="text-muted mb-0"><?php echo nl2br(htmlspecialchars($faq['answer'])); ?></p>
                                    </div>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <div class="text-center py-5">
                                        <i class="fi fi-rr-search fs-1 text-muted mb-3"></i>
                                        <h5 class="text-muted">No results found</h5>
                                        <p class="text-muted">Try different keywords or browse the categories below</p>
                                        <a href="faq.php" class="btn btn-primary">View All FAQs</a>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- FAQ CATEGORIES -->
                <?php if (empty($search_query) || empty($search_results)): ?>
                <div class="row">
                    <div class="col-12">
                        <h4 class="mb-4">Browse by Category</h4>
                    </div>
                </div>

                <?php while ($category = mysqli_fetch_assoc($categories_result)): 
                    // Get FAQs for this category
                    $faq_sql = "SELECT * FROM faq_items WHERE category_id = '{$category['id']}' AND is_active = 1 ORDER BY id";
                    $faq_result = mysqli_query($conn, $faq_sql);
                    $faq_count = mysqli_num_rows($faq_result);
                ?>
                <div class="row">
                    <div class="col-12">
                        <div class="card faq-category-card">
                            <div class="card-header bg-transparent">
                                <div class="d-flex justify-content-between align-items-center">
                                    <h5 class="card-title mb-0">
                                        <i class="fi fi-rr-folder me-2 text-primary"></i>
                                        <?php echo htmlspecialchars($category['name']); ?>
                                    </h5>
                                    <span class="badge bg-primary"><?php echo $faq_count; ?> questions</span>
                                </div>
                                <?php if (!empty($category['description'])): ?>
                                <p class="text-muted mb-0 mt-2"><?php echo htmlspecialchars($category['description']); ?></p>
                                <?php endif; ?>
                            </div>
                            <div class="card-body">
                                <?php if ($faq_count > 0): ?>
                                    <?php while ($faq = mysqli_fetch_assoc($faq_result)): ?>
                                    <div class="faq-item">
                                        <div class="faq-question" onclick="toggleFAQ(this)">
                                            <?php echo htmlspecialchars($faq['question']); ?>
                                        </div>
                                        <div class="faq-answer">
                                            <?php echo $faq['answer']; ?> 
                                            <div class="helpful-buttons">
                                                <small class="text-muted">Was this helpful?</small>
                                                <button class="btn btn-sm btn-outline-success me-2" onclick="markHelpful(this)">
                                                    <i class="fi fi-rr-thumbs-up me-1"></i> Yes
                                                </button>
                                                <button class="btn btn-sm btn-outline-danger" onclick="markUnhelpful(this)">
                                                    <i class="fi fi-rr-thumbs-down me-1"></i> No
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <div class="text-center py-4">
                                        <i class="fi fi-rr-document fs-1 text-muted mb-3"></i>
                                        <p class="text-muted">No FAQs available in this category yet.</p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endwhile; ?>
                <?php endif; ?>

                <!-- CONTACT SUPPORT CTA -->
                <div class="row">
                    <div class="col-12">
                        <div class="card bg-dark">
                            <div class="card-body text-center py-5">
                                <i class="fi fi-rr-user-headset fs-1 text-primary mb-3"></i>
                                <h4 class="text-primary mb-3">Still need help?</h4>
                                <p class="text-muted mb-4">Can't find the answer you're looking for? Our support team is here to help you.</p>
                                <div class="d-flex justify-content-center gap-3 flex-wrap">
                                    <a href="create_ticket.php" class="btn btn-primary">
                                        <i class="fi fi-rr-paper-plane me-2"></i>Create Support Ticket
                                    </a>
                                    <a href="support.php" class="btn btn-outline-primary">
                                        <i class="fi fi-rr-phone-call me-2"></i>Contact Support
                                    </a>
                                    <a href="feedback.php" class="btn btn-outline-secondary">
                                        <i class="fi fi-rr-comment-alt me-2"></i>Give Feedback
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php include('includes/footer.php');?>

    </div>
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>


<script>
   // Enhanced FAQ functionality
function toggleFAQ(element) {
    const answer = element.nextElementSibling;
    const isActive = element.classList.contains('active');
    
    // Close all other FAQs in the same category
    const categoryCard = element.closest('.card');
    categoryCard.querySelectorAll('.faq-question.active').forEach(activeElement => {
        if (activeElement !== element) {
            activeElement.classList.remove('active');
            activeElement.nextElementSibling.style.display = 'none';
        }
    });
    
    // Toggle current FAQ
    if (isActive) {
        element.classList.remove('active');
        answer.style.display = 'none';
    } else {
        element.classList.add('active');
        answer.style.display = 'block';
        
        // Scroll to the question if it's not fully visible
        const rect = element.getBoundingClientRect();
        if (rect.top < 100 || rect.bottom > window.innerHeight - 100) {
            element.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
        
        // Track FAQ views (for analytics)
        trackFAQView(element.textContent.trim());
    }
}

function trackFAQView(question) {
    // In a real application, send this to your analytics
    console.log('FAQ viewed: ' + question);
    
    // You can implement Google Analytics or custom tracking here
    // Example: ga('send', 'event', 'FAQ', 'view', question);
}

function markHelpful(button) {
    const question = button.closest('.faq-item').querySelector('.faq-question').textContent;
    const buttonsContainer = button.parentElement;
    
    // Disable both buttons
    buttonsContainer.querySelectorAll('button').forEach(btn => {
        btn.disabled = true;
    });
    
    // Update the clicked button
    button.innerHTML = '<i class="fi fi-rr-check me-1"></i> Thank you for your feedback!';
    button.classList.remove('btn-outline-success', 'btn-outline-danger');
    button.classList.add('btn-success');
    
    // Send feedback to server (pseudo-code)
    sendFeedback(question, 'helpful');
}

function markUnhelpful(button) {
    const question = button.closest('.faq-item').querySelector('.faq-question').textContent;
    const buttonsContainer = button.parentElement;
    
    // Disable both buttons
    buttonsContainer.querySelectorAll('button').forEach(btn => {
        btn.disabled = true;
    });
    
    // Update the clicked button
    button.innerHTML = '<i class="fi fi-rr-check me-1"></i> We will improve this answer';
    button.classList.remove('btn-outline-success', 'btn-outline-danger');
    button.classList.add('btn-danger');
    
    // Show feedback form for unhelpful answers
    setTimeout(() => {
        showFeedbackForm(question);
    }, 1000);
    
    // Send feedback to server (pseudo-code)
    sendFeedback(question, 'unhelpful');
}

function sendFeedback(question, feedback) {
    // In a real application, send this to your backend
    console.log('Feedback: ' + feedback + ' for question: ' + question);
    
    // Example AJAX call:
    /*
    $.post('/api/faq-feedback', {
        question: question,
        feedback: feedback,
        timestamp: new Date().toISOString()
    });
    */
}

function showFeedbackForm(question) {
    // Simple feedback form
    const feedback = prompt('Please tell us what information was missing or unclear for: "' + question + '"');
    if (feedback) {
        console.log('User feedback: ' + feedback);
        alert('Thank you for your detailed feedback! We will use it to improve our answers.');
        
        // Send detailed feedback to server
        // $.post('/api/detailed-feedback', { question: question, feedback: feedback });
    }
}

// Keyboard navigation for FAQs
document.addEventListener('keydown', function(e) {
    if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
        const activeElement = document.activeElement;
        if (activeElement.classList.contains('faq-question')) {
            e.preventDefault();
            const allQuestions = Array.from(document.querySelectorAll('.faq-question'));
            const currentIndex = allQuestions.indexOf(activeElement);
            let nextIndex;
            
            if (e.key === 'ArrowDown') {
                nextIndex = (currentIndex + 1) % allQuestions.length;
            } else {
                nextIndex = (currentIndex - 1 + allQuestions.length) % allQuestions.length;
            }
            
            allQuestions[nextIndex].focus();
            toggleFAQ(allQuestions[nextIndex]);
        }
    }
});

// Print FAQ functionality
function printFAQ(category = null) {
    const originalContents = document.body.innerHTML;
    
    // If specific category, print only that category
    let printContent;
    if (category) {
        const categoryElement = document.querySelector(`[data-category="${category}"]`);
        printContent = categoryElement ? categoryElement.innerHTML : originalContents;
    } else {
        printContent = document.querySelector('.content-body').innerHTML;
    }
    
    document.body.innerHTML = `
        <!DOCTYPE html>
        <html>
        <head>
            <title>E-Finance Loans FAQs</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; }
                .faq-item { margin-bottom: 20px; }
                .faq-question { font-weight: bold; color: #2c5aa0; }
                .faq-answer { margin-top: 10px; color: #333; }
                .category-title { color: #4CAF50; border-bottom: 2px solid #4CAF50; padding-bottom: 10px; }
                @media print {
                    .no-print { display: none; }
                    body { margin: 0; }
                }
            </style>
        </head>
        <body>
            <h1>E-Finance Loans - Frequently Asked Questions</h1>
            <p>Generated on: ${new Date().toLocaleDateString()}</p>
            ${printContent}
        </body>
        </html>
    `;
    
    window.print();
    document.body.innerHTML = originalContents;
    location.reload();
}

// Add print buttons to each category
document.addEventListener('DOMContentLoaded', function() {
    // Add print buttons to category headers
    document.querySelectorAll('.faq-category-card .card-header').forEach(header => {
        const categoryTitle = header.querySelector('.card-title').textContent.trim();
        const printButton = document.createElement('button');
        printButton.className = 'btn btn-sm btn-outline-secondary no-print';
        printButton.innerHTML = '<i class="fi fi-rr-print me-1"></i> Print';
        printButton.onclick = () => printFAQ(categoryTitle);
        header.querySelector('.d-flex').appendChild(printButton);
    });
    
    // Add overall print button
    const overallPrintBtn = document.createElement('button');
    overallPrintBtn.className = 'btn btn-primary no-print';
    overallPrintBtn.innerHTML = '<i class="fi fi-rr-print me-2"></i> Print All FAQs';
    overallPrintBtn.style.marginLeft = '10px';
    overallPrintBtn.onclick = () => printFAQ();
    document.querySelector('.page-title-content').appendChild(overallPrintBtn);
});
</script>

</body>
</html>
<?php mysqli_close($conn); ?>