<?php
/**
 * FAQs Page - Dynamic with AJAX Category Tabs
 * File: faqs.php (ROOT)
 */

require_once __DIR__ . '/app/Core/init.php';

// Initialize models
$faqModel = new Faq();
$categoryModel = new Category();

// Set page variables
$page_title = 'Frequently Asked Questions - ' . APP_NAME;
$body_class = '';

// Get all FAQ categories with counts
$categories = $faqModel->getCategories();

// Get featured FAQs for initial display
$featured_faqs = $faqModel->getFeatured(6);

// Get all active FAQs grouped by category for search
$all_faqs = $faqModel->getAll(['is_active' => 1]);

// Include header template
include __DIR__ . '/templates/layouts/frontend/header.php';
?>

<!-- start hero section -->
<div class="py-5 bg-light">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-8 text-center">
                <h1 class="display-4 fw-bold mb-4">Frequently Asked Questions</h1>
                <p class="lead text-muted">Find answers to common questions about <?= APP_NAME ?>. Can't find what you're looking for? <a href="contact-us.php">Contact our support team</a>.</p>
                
                <!-- Search FAQs -->
                <div class="mt-4">
                    <div class="input-group input-group-lg">
                        <input type="text" 
                               id="faqSearch" 
                               class="form-control" 
                               placeholder="Search FAQs..." 
                               aria-label="Search FAQs">
                        <button class="btn btn-primary" type="button" onclick="searchFAQs()">
                            <i class="fas fa-search"></i> Search
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- end hero section -->

<!-- start FAQ categories tabs -->
<div class="py-5">
    <div class="container">
        <div class="row">
            <!-- Left Sidebar - Category Tabs -->
            <div class="col-lg-3">
                <div class="sticky-top" style="top: 100px;">
                    <h5 class="mb-3 fw-bold">Categories</h5>
                    <div class="nav flex-column nav-pills gap-2" id="faqCategoryTabs" role="tablist">
                        <button class="nav-link active text-start" 
                                id="featured-tab" 
                                data-category="featured"
                                onclick="loadFAQs('featured')" 
                                type="button">
                            <i class="fas fa-star me-2"></i>Featured
                        </button>
                        <?php foreach ($categories as $cat): ?>
                            <button class="nav-link text-start" style="border-radius: 8px; border: 1px solid rgba(0,0,0,0.1);"
                                    id="<?= $cat['category'] ?>-tab" 
                                    data-category="<?= $cat['category'] ?>"
                                    onclick="loadFAQs('<?= $cat['category'] ?>')" 
                                    type="button">
                                <i class="fas fa-folder me-2"></i><?= ucfirst($cat['category']) ?>
                                <span class="badge bg-secondary float-end"><?= $cat['count'] ?></span>
                            </button>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <!-- Right Content - FAQs -->
            <div class="col-lg-9">
                <!-- Loading Indicator -->
                <div id="loadingIndicator" class="text-center my-5" style="display: none;">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="text-muted mt-2">Loading FAQs...</p>
                </div>

                <!-- FAQ Content -->
                <div id="faqContent">
                    <!-- Featured FAQs loaded by default -->
                    <?php if (!empty($featured_faqs)): ?>
                        <div class="accordion" id="faqAccordion">
                            <?php foreach ($featured_faqs as $index => $faq): ?>
                                <div class="accordion-item mb-3 rounded-4 border shadow-sm">
                                    <h2 class="accordion-header">
                                        <button class="accordion-button <?= $index > 0 ? 'collapsed' : '' ?> fs-5 p-4 text-dark" 
                                                type="button" 
                                                data-bs-toggle="collapse" 
                                                data-bs-target="#faq<?= $faq['id'] ?>" 
                                                aria-expanded="<?= $index === 0 ? 'true' : 'false' ?>" 
                                                aria-controls="faq<?= $faq['id'] ?>">
                                            <span class="badge bg-warning text-dark me-3">
                                                <i class="fas fa-star"></i>
                                            </span>
                                            <?= htmlspecialchars($faq['question']) ?>
                                        </button>
                                    </h2>
                                    <div id="faq<?= $faq['id'] ?>" 
                                         class="accordion-collapse collapse <?= $index === 0 ? 'show' : '' ?>" 
                                         data-bs-parent="#faqAccordion">
                                        <div class="accordion-body p-4 pt-0">
                                            <p class="text-muted mb-0"><?= nl2br(htmlspecialchars($faq['answer'])) ?></p>
                                            <div class="mt-3 pt-3 border-top">
                                                <small class="text-muted">
                                                    <i class="fas fa-tag me-1"></i>
                                                    Category: <span class="badge bg-secondary"><?= ucfirst($faq['category']) ?></span>
                                                </small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="text-center py-5">
                            <i class="fas fa-question-circle fa-3x text-muted mb-3"></i>
                            <h4>No FAQs Available</h4>
                            <p class="text-muted">Check back soon for frequently asked questions.</p>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Search Results -->
                <div id="searchResults" style="display: none;">
                    <!-- Search results will be displayed here -->
                </div>
            </div>
        </div>
    </div>
</div>
<!-- end FAQ categories tabs -->

<!-- start CTA section -->
<div class="py-5 bg-primary text-white">
    <div class="container">
        <div class="row justify-content-center text-center">
            <div class="col-lg-8">
                <h2 class="mb-3">Still Have Questions?</h2>
                <p class="lead mb-4">Can't find the answer you're looking for? Our friendly customer support team is here to help.</p>
                <div class="d-flex gap-3 justify-content-center flex-wrap">
                    <a href="contact-us.php" class="btn btn-light btn-lg">
                        <i class="fas fa-envelope me-2"></i>Contact Support
                    </a>
                    <a href="items.php" class="btn btn-outline-light btn-lg">
                        <i class="fas fa-search me-2"></i>Browse Items
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- end CTA section -->

<script>
// All FAQs data for search (from PHP)
const allFAQs = <?= json_encode($all_faqs) ?>;
let currentCategory = 'featured';

// Load FAQs by category via AJAX
function loadFAQs(category) {
    if (currentCategory === category) return;
    currentCategory = category;
    
    // Update active tab
    document.querySelectorAll('#faqCategoryTabs .nav-link').forEach(btn => {
        btn.classList.remove('active');
    });
    document.getElementById(category + '-tab').classList.add('active');
    
    // Hide search results if visible
    document.getElementById('searchResults').style.display = 'none';
    document.getElementById('faqContent').style.display = 'block';
    document.getElementById('faqSearch').value = '';
    
    // Show loading
    document.getElementById('loadingIndicator').style.display = 'block';
    document.getElementById('faqContent').style.display = 'none';
    
    // Fetch FAQs via AJAX
    fetch(`ajax/get-faqs.php?category=${category}`)
        .then(response => response.json())
        .then(data => {
            document.getElementById('loadingIndicator').style.display = 'none';
            document.getElementById('faqContent').style.display = 'block';
            
            if (data.success && data.faqs.length > 0) {
                renderFAQs(data.faqs);
            } else {
                document.getElementById('faqContent').innerHTML = `
                    <div class="text-center py-5">
                        <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                        <h4>No FAQs Found</h4>
                        <p class="text-muted">There are no FAQs in this category yet.</p>
                    </div>
                `;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('loadingIndicator').style.display = 'none';
            document.getElementById('faqContent').innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle me-2"></i>
                    Error loading FAQs. Please try again.
                </div>
            `;
        });
}

// Render FAQs accordion
function renderFAQs(faqs) {
    let html = '<div class="accordion" id="faqAccordion">';
    
    faqs.forEach((faq, index) => {
        const isFirst = index === 0;
        const badgeHtml = faq.is_featured == 1 ? 
            '<span class="badge bg-warning text-dark me-3"><i class="fas fa-star"></i></span>' : 
            '';
        
        html += `
            <div class="accordion-item mb-3 rounded-4 border shadow-sm">
                <h2 class="accordion-header">
                    <button class="accordion-button ${!isFirst ? 'collapsed' : ''} fs-5 p-4 text-dark" 
                            type="button" 
                            data-bs-toggle="collapse" 
                            data-bs-target="#faq${faq.id}" 
                            aria-expanded="${isFirst ? 'true' : 'false'}" 
                            aria-controls="faq${faq.id}">
                        ${badgeHtml}
                        ${escapeHtml(faq.question)}
                    </button>
                </h2>
                <div id="faq${faq.id}" 
                     class="accordion-collapse collapse ${isFirst ? 'show' : ''}" 
                     data-bs-parent="#faqAccordion">
                    <div class="accordion-body p-4 pt-0">
                        <p class="text-muted mb-0">${nl2br(escapeHtml(faq.answer))}</p>
                        <div class="mt-3 pt-3 border-top">
                            <small class="text-muted">
                                <i class="fas fa-tag me-1"></i>
                                Category: <span class="badge bg-secondary">${capitalize(faq.category)}</span>
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        `;
    });
    
    html += '</div>';
    document.getElementById('faqContent').innerHTML = html;
}

// Search FAQs
function searchFAQs() {
    const keyword = document.getElementById('faqSearch').value.trim().toLowerCase();
    
    if (keyword.length < 2) {
        alert('Please enter at least 2 characters to search');
        return;
    }
    
    // Filter FAQs
    const results = allFAQs.filter(faq => 
        faq.question.toLowerCase().includes(keyword) || 
        faq.answer.toLowerCase().includes(keyword)
    );
    
    // Hide category content, show search results
    document.getElementById('faqContent').style.display = 'none';
    document.getElementById('searchResults').style.display = 'block';
    
    // Remove active tab
    document.querySelectorAll('#faqCategoryTabs .nav-link').forEach(btn => {
        btn.classList.remove('active');
    });
    
    if (results.length > 0) {
        let html = `
            <div class="alert alert-info mb-4">
                <i class="fas fa-search me-2"></i>
                Found <strong>${results.length}</strong> result(s) for "<strong>${escapeHtml(keyword)}</strong>"
                <button type="button" class="btn btn-sm btn-outline-primary ms-3" onclick="clearSearch()">
                    Clear Search
                </button>
            </div>
            <div class="accordion" id="searchAccordion">
        `;
        
        results.forEach((faq, index) => {
            html += `
                <div class="accordion-item mb-3 rounded-4 border shadow-sm">
                    <h2 class="accordion-header">
                        <button class="accordion-button ${index > 0 ? 'collapsed' : ''} fs-5 p-4 text-dark" 
                                type="button" 
                                data-bs-toggle="collapse" 
                                data-bs-target="#search${faq.id}" 
                                aria-expanded="${index === 0 ? 'true' : 'false'}" 
                                aria-controls="search${faq.id}">
                            ${escapeHtml(faq.question)}
                        </button>
                    </h2>
                    <div id="search${faq.id}" 
                         class="accordion-collapse collapse ${index === 0 ? 'show' : ''}" 
                         data-bs-parent="#searchAccordion">
                        <div class="accordion-body p-4 pt-0">
                            <p class="text-muted mb-0">${nl2br(escapeHtml(faq.answer))}</p>
                            <div class="mt-3 pt-3 border-top">
                                <small class="text-muted">
                                    <i class="fas fa-tag me-1"></i>
                                    Category: <span class="badge bg-secondary">${capitalize(faq.category)}</span>
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        });
        
        html += '</div>';
        document.getElementById('searchResults').innerHTML = html;
    } else {
        document.getElementById('searchResults').innerHTML = `
            <div class="alert alert-warning">
                <i class="fas fa-search me-2"></i>
                No results found for "<strong>${escapeHtml(keyword)}</strong>"
                <button type="button" class="btn btn-sm btn-outline-primary ms-3" onclick="clearSearch()">
                    Clear Search
                </button>
            </div>
        `;
    }
}

// Clear search
function clearSearch() {
    document.getElementById('faqSearch').value = '';
    document.getElementById('searchResults').style.display = 'none';
    document.getElementById('faqContent').style.display = 'block';
    loadFAQs('featured');
}

// Helper functions
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function nl2br(text) {
    return text.replace(/\n/g, '<br>');
}

function capitalize(text) {
    return text.charAt(0).toUpperCase() + text.slice(1);
}

// Allow Enter key to search
document.getElementById('faqSearch')?.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        searchFAQs();
    }
});
</script>

<style>
/* Vertical Sidebar Navigation */
.nav-pills .nav-link {
    border-radius: 8px;
    padding: 12px 16px;
    font-weight: 500;
    transition: all 0.3s ease;
    position: relative;
}

.nav-pills .nav-link:hover {
    background-color: rgba(var(--bs-primary-rgb), 0.1);
    transform: translateX(5px);
}

.nav-pills .nav-link.active {
    background-color: var(--bs-primary);
    color: white;
}

.nav-pills .nav-link.active .badge {
    background-color: white !important;
    color: var(--bs-primary) !important;
}

.nav-pills .nav-link i {
    width: 20px;
}

/* Accordion Styles */
.accordion-button:not(.collapsed) {
    background-color: rgba(var(--bs-primary-rgb), 0.05);
    color: var(--bs-primary);
}

.accordion-button:focus {
    box-shadow: none;
    border-color: rgba(var(--bs-primary-rgb), 0.25);
}

/* Sticky Sidebar */
@media (min-width: 992px) {
    .sticky-top {
        position: sticky;
        z-index: 1020;
    }
}

/* Mobile responsive */
@media (max-width: 991px) {
    .sticky-top {
        position: relative !important;
        top: auto !important;
        margin-bottom: 30px;
    }
}
</style>

<?php
// Include footer template
include __DIR__ . '/templates/layouts/frontend/footer.php';
?>