<?php
include 'includes/header.php';
$page_title = $lang_frontend['PAGE_TITLE_FAQ'] ?? 'FAQ';
?>

<?php

// Fetch FAQs from database grouped by category
try {
    $stmt = $pdo->prepare("SELECT * FROM faqs ORDER BY 
                          CASE WHEN category IS NULL OR category = '' THEN 1 ELSE 0 END,
                          category ASC, 
                          created_at DESC");
    $stmt->execute();
    $all_faqs = $stmt->fetchAll();

    // Group FAQs by category
    $faqs_by_category = [];
    foreach ($all_faqs as $faq) {
        $category = !empty($faq['category']) ? $faq['category'] : ($lang_frontend['FAQ_CATEGORY_GENERAL'] ?? 'General');
        if (!isset($faqs_by_category[$category])) {
            $faqs_by_category[$category] = [];
        }
        $faqs_by_category[$category][] = $faq;
    }
} catch (PDOException $e) {
    $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_ERROR_LOADING_FAQS'] ?? 'Error loading FAQs: %s', $e->getMessage()), 'danger');
    $faqs_by_category = [];
}
?>

<div class="card mb-4">

    <div class="card-body">
        <?php if (isLoggedIn() && isAdmin()): ?>
            <div class="mb-4">
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addFaqModal">
                    <i class="bi bi-plus"></i> <?php echo $lang_frontend['FAQ_BUTTON_ADD_NEW'] ?? 'Add New FAQ'; ?>
                </button>
            </div>
        <?php endif; ?>

        <?php if (!empty($faqs_by_category)): ?>
            <!-- Search Field -->
            <div class="faq-search-container">
                <div class="row justify-content-center">
                    <div class="col-md-10 col-lg-8">
                        <div class="text-center mb-3">
                            <h5 class="text-muted mb-1"><?php echo $lang_frontend['FAQ_SEARCH_HEADING'] ?? 'Search FAQs'; ?>
                            </h5>
                            <small
                                class="text-muted"><?php echo $lang_frontend['FAQ_SEARCH_SUBTEXT'] ?? 'Find answers by searching questions, answers, or categories'; ?></small>
                        </div>
                        <div class="input-group faq-search-input-group">
                            <span class="input-group-text">
                                <i class="bi bi-search text-primary"></i>
                            </span>
                            <input type="text" id="faqSearch" class="form-control"
                                placeholder="<?php echo $lang_frontend['FAQ_SEARCH_PLACEHOLDER'] ?? 'Type your search here...'; ?>"
                                autocomplete="off">
                            <button class="btn btn-light" type="button" id="clearSearch"
                                title="<?php echo $lang_frontend['FAQ_SEARCH_CLEAR_TITLE'] ?? 'Clear search'; ?>"
                                style="display: none;">
                                <i class="bi bi-x-lg text-muted"></i>
                            </button>
                        </div>
                        <div id="searchResults" class="mt-3 text-center search-results-text"></div>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <?php if (empty($faqs_by_category)): ?>
            <div class="alert alert-info">
                <i class="bi bi-info-circle"></i>
                <?php echo $lang_frontend['FAQ_NO_FAQS_AVAILABLE'] ?? 'No FAQs available yet. Check back later.'; ?>
            </div>
        <?php else: ?>
            <div id="faqContainer">
                <?php foreach ($faqs_by_category as $category => $faqs): ?>
                    <div class="mb-5 faq-category" data-category="<?php echo htmlspecialchars($category); ?>">
                        <h4 class="text-primary mb-3 border-bottom pb-2 category-header">
                            <i class="bi bi-folder"></i> <?php echo htmlspecialchars($category); ?>
                            <span class="badge rounded-pill bg-secondary ms-1 category-count"><?php echo count($faqs); ?></span>
                        </h4>

                        <div class="accordion" id="faqAccordion<?php echo preg_replace('/[^a-zA-Z0-9]/', '', $category); ?>">
                            <?php foreach ($faqs as $index => $faq): ?>
                                <div class="accordion-item faq-item"
                                    data-question="<?php echo htmlspecialchars(strtolower($faq['question'])); ?>"
                                    data-answer="<?php echo htmlspecialchars(strtolower($faq['answer'])); ?>"
                                    data-category="<?php echo htmlspecialchars(strtolower($category)); ?>">
                                    <h2 class="accordion-header" id="heading<?php echo $faq['id']; ?>">
                                        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse"
                                            data-bs-target="#collapse<?php echo $faq['id']; ?>" aria-expanded="false"
                                            aria-controls="collapse<?php echo $faq['id']; ?>">
                                            <?php echo htmlspecialchars($faq['question']); ?>
                                        </button>
                                    </h2>
                                    <div id="collapse<?php echo $faq['id']; ?>" class="accordion-collapse collapse"
                                        aria-labelledby="heading<?php echo $faq['id']; ?>"
                                        data-bs-parent="#faqAccordion<?php echo preg_replace('/[^a-zA-Z0-9]/', '', $category); ?>">
                                        <div class="accordion-body">
                                            <div class="faq-content">
                                                <div class="faq-answer mb-3">
                                                    <?php echo makeLinksClickable(cleanHTML(html_entity_decode($faq['answer'], ENT_QUOTES | ENT_HTML5, 'UTF-8'))); ?>
                                                </div>

                                                <?php if (isLoggedIn() && isAdmin()): ?>
                                                    <div class="admin-actions d-flex gap-2 justify-content-end border-top pt-3">
                                                        <button type="button" class="btn btn-sm btn-outline-primary edit-faq-btn"
                                                            data-id="<?php echo $faq['id']; ?>"
                                                            data-question="<?php echo htmlspecialchars($faq['question']); ?>"
                                                            data-answer="<?php echo htmlspecialchars($faq['answer']); ?>"
                                                            data-category="<?php echo htmlspecialchars($faq['category'] ?? ''); ?>">
                                                            <i class="bi bi-pencil"></i>
                                                            <?php echo $lang_frontend['BUTTON_EDIT'] ?? 'Edit'; ?>
                                                        </button>
                                                        <button type="button" class="btn btn-sm btn-outline-danger delete-faq-btn"
                                                            data-id="<?php echo $faq['id']; ?>">
                                                            <i class="bi bi-trash"></i>
                                                            <?php echo $lang_frontend['BUTTON_DELETE'] ?? 'Delete'; ?>
                                                        </button>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php if (isLoggedIn() && isAdmin()): ?>
    <!-- Add FAQ Modal -->
    <div class="modal fade" id="addFaqModal" tabindex="-1" aria-labelledby="addFaqModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addFaqModalLabel">
                        <?php echo $lang_frontend['FAQ_MODAL_TITLE_ADD'] ?? 'Add New FAQ'; ?>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"
                        aria-label="<?php echo $lang_frontend['ARIA_LABEL_CLOSE'] ?? 'Close'; ?>"></button>
                </div>
                <form action="<?php echo getCleanUrl('faq_update'); ?>" method="post">
                    <div class="modal-body">
                        <?php echo get_csrf_input_field(); ?>
                        <input type="hidden" name="action" value="add">
                        <div class="mb-3">
                            <label for="question"
                                class="form-label"><?php echo $lang_frontend['FORM_LABEL_QUESTION'] ?? 'Question'; ?></label>
                            <input type="text" class="form-control" id="question" name="question" required>
                        </div>
                        <div class="mb-3">
                            <label for="answer"
                                class="form-label"><?php echo $lang_frontend['FORM_LABEL_ANSWER'] ?? 'Answer'; ?></label>
                            <textarea class="form-control" id="answer" name="answer" rows="5" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="category"
                                class="form-label"><?php echo $lang_frontend['FORM_LABEL_CATEGORY'] ?? 'Category'; ?></label>
                            <input type="text" class="form-control" id="category" name="category">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary"
                            data-bs-dismiss="modal"><?php echo $lang_frontend['BUTTON_CANCEL'] ?? 'Cancel'; ?></button>
                        <button type="submit"
                            class="btn btn-primary"><?php echo $lang_frontend['FAQ_MODAL_BUTTON_ADD'] ?? 'Add FAQ'; ?></button>
                    </div>
                </form>


            </div>
        </div>
    </div>

    <!-- Edit FAQ Modal -->
    <div class="modal fade" id="editFaqModal" tabindex="-1" aria-labelledby="editFaqModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editFaqModalLabel">
                        <?php echo $lang_frontend['FAQ_MODAL_TITLE_EDIT'] ?? 'Edit FAQ'; ?>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"
                        aria-label="<?php echo $lang_frontend['ARIA_LABEL_CLOSE'] ?? 'Close'; ?>"></button>
                </div>
                <form action="<?php echo getCleanUrl('faq_update'); ?>" method="post">
                    <div class="modal-body">
                        <?php echo get_csrf_input_field(); ?>
                        <input type="hidden" name="action" value="edit">
                        <input type="hidden" name="id" id="edit-id">
                        <div class="mb-3">
                            <label for="edit-question"
                                class="form-label"><?php echo $lang_frontend['FORM_LABEL_QUESTION'] ?? 'Question'; ?></label>
                            <input type="text" class="form-control" id="edit-question" name="question" required>
                        </div>
                        <div class="mb-3">
                            <label for="edit-answer"
                                class="form-label"><?php echo $lang_frontend['FORM_LABEL_ANSWER'] ?? 'Answer'; ?></label>
                            <textarea class="form-control" id="edit-answer" name="answer" rows="5" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="edit-category"
                                class="form-label"><?php echo $lang_frontend['FORM_LABEL_CATEGORY'] ?? 'Category'; ?></label>
                            <input type="text" class="form-control" id="edit-category" name="category">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary"
                            data-bs-dismiss="modal"><?php echo $lang_frontend['BUTTON_CANCEL'] ?? 'Cancel'; ?></button>
                        <button type="submit"
                            class="btn btn-primary"><?php echo $lang_frontend['FAQ_MODAL_BUTTON_UPDATE'] ?? 'Update FAQ'; ?></button>
                    </div>
                </form>

            </div>
        </div>
    </div>

    <!-- Delete FAQ Modal -->
    <div class="modal fade" id="deleteFaqModal" tabindex="-1" aria-labelledby="deleteFaqModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteFaqModalLabel">
                        <?php echo $lang_frontend['FAQ_MODAL_TITLE_CONFIRM_DELETE'] ?? 'Confirm Delete'; ?>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"
                        aria-label="<?php echo $lang_frontend['ARIA_LABEL_CLOSE'] ?? 'Close'; ?>"></button>
                </div>
                <form action="<?php echo getCleanUrl('faq_update'); ?>" method="post">
                    <div class="modal-body">
                        <?php echo get_csrf_input_field(); ?>
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" id="delete-id">
                        <p><?php echo $lang_frontend['FAQ_DELETE_CONFIRMATION_MESSAGE'] ?? 'Are you sure you want to delete this FAQ? This action cannot be undone.'; ?>
                        </p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary"
                            data-bs-dismiss="modal"><?php echo $lang_frontend['BUTTON_CANCEL'] ?? 'Cancel'; ?></button>
                        <button type="submit"
                            class="btn btn-danger"><?php echo $lang_frontend['BUTTON_DELETE'] ?? 'Delete'; ?></button>
                    </div>
                </form>
            </div>
        </div>
    </div>

<?php endif; ?>
<script>
    window.magicAIConfig = {
        AI_OPENAI: '<?php echo AI_OPENAI; ?>',
        AI_CLAUDE: '<?php echo AI_CLAUDE; ?>',
        AI_GEMINI: '<?php echo AI_GEMINI; ?>',
        AI_MISTRAL: '<?php echo AI_MISTRAL; ?>',
        AI_DEEPSEEK: '<?php echo AI_DEEPSEEK; ?>'
    };
</script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        // Decode HTML entities - fixes content that was double-encoded (e.g. &lt;p&gt; -> <p>)
        function decodeHtmlEntities(str) {
            if (!str) return '';
            var txt = document.createElement('textarea');
            txt.innerHTML = str;
            return txt.value;
        }

        // Set up edit FAQ modal (only if admin)
        <?php if (isLoggedIn() && isAdmin()): ?>
            document.querySelectorAll('.edit-faq-btn').forEach(button => {
                button.addEventListener('click', function (e) {
                    e.preventDefault();
                    e.stopPropagation(); // Prevent accordion from toggling

                    const id = this.getAttribute('data-id');
                    const question = this.getAttribute('data-question');
                    // Decode entities so Summernote receives proper HTML for WYSIWYG rendering
                    const answer = decodeHtmlEntities(this.getAttribute('data-answer') || '');
                    const category = this.getAttribute('data-category');

                    document.getElementById('edit-id').value = id;
                    document.getElementById('edit-question').value = question;
                    document.getElementById('edit-category').value = category || '';
                    // Don't set edit-answer via .value - Summernote can misread it and show raw HTML.
                    // We set content via summernote('code', answer) after init instead.

                    // Show the modal
                    var editFaqModal = new bootstrap.Modal(document.getElementById('editFaqModal'));
                    editFaqModal.show();

                    // Initialize Summernote after the modal is shown
                    $('#editFaqModal').on('shown.bs.modal', function () {
                        $('#edit-answer').summernote({
                            toolbar: [
                                ['style', ['bold', 'italic', 'underline', 'clear']],
                                ['para', ['ul', 'ol']],
                                ['insert', ['link']],
                                ['magic', ['SummernoteMagic']]
                            ],
                            height: 300,
                            minHeight: 150,
                            maxHeight: null,
                            dialogsFade: true,
                            dialogsInBody: true,
                            tabDisable: false,
                            spellCheck: true,
                            focus: true
                        });
                        $('#edit-answer').summernote('code', answer);
                        // Ensure WYSIWYG mode - in case code view was somehow active
                        if ($('#edit-answer').summernote('codeview.isActivated')) {
                            $('#edit-answer').summernote('codeview.deactivate');
                        }
                    });
                });
            });

            // Clean up Summernote when the modal is hidden
            $('#editFaqModal').on('hidden.bs.modal', function () {
                $('#edit-answer').summernote('destroy');
                // Remove the shown.bs.modal event handler to prevent multiple bindings
                $('#editFaqModal').off('shown.bs.modal');
            });

            // Set up delete FAQ modal
            document.querySelectorAll('.delete-faq-btn').forEach(button => {
                button.addEventListener('click', function (e) {
                    e.preventDefault();
                    e.stopPropagation(); // Prevent accordion from toggling

                    const id = this.getAttribute('data-id');
                    document.getElementById('delete-id').value = id;

                    // Show the modal
                    new bootstrap.Modal(document.getElementById('deleteFaqModal')).show();
                });
            });
        <?php endif; ?>
    });

</script>
<script>
    $(document).ready(function () {
        $('#answer').summernote({
            toolbar: [
                ['style', ['bold', 'italic', 'underline', 'clear']],
                ['para', ['ul', 'ol']],
                ['insert', ['link']],
                ['magic', ['SummernoteMagic']]
            ],
            height: 300,
            minHeight: 150,
            maxHeight: null,
            dialogsFade: true,
            dialogsInBody: true,
            tabDisable: false,
            spellCheck: true
        });
    });
</script>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const searchInput = document.getElementById('faqSearch');
        const clearBtn = document.getElementById('clearSearch');
        const faqItems = document.querySelectorAll('.faq-item');
        const faqCategories = document.querySelectorAll('.faq-category');
        const searchResults = document.getElementById('searchResults');

        function filterFaqs() {
            const query = searchInput.value.trim().toLowerCase();
            let anyVisible = false;

            faqCategories.forEach(cat => {
                let catVisible = false;
                cat.querySelectorAll('.faq-item').forEach(item => {
                    const question = item.getAttribute('data-question') || '';
                    const answer = item.getAttribute('data-answer') || '';
                    const category = item.getAttribute('data-category') || '';
                    if (
                        query === '' ||
                        question.includes(query) ||
                        answer.includes(query) ||
                        category.includes(query)
                    ) {
                        item.style.display = '';
                        catVisible = true;
                        anyVisible = true;
                    } else {
                        item.style.display = 'none';
                    }
                });
                cat.style.display = catVisible ? '' : 'none';
            });

            if (query && !anyVisible) {
                searchResults.textContent = 'No FAQs match your search.';
            } else {
                searchResults.textContent = '';
            }
            clearBtn.style.display = query ? '' : 'none';
        }

        if (searchInput) {
            searchInput.addEventListener('input', filterFaqs);
        }
        if (clearBtn) {
            clearBtn.addEventListener('click', function () {
                searchInput.value = '';
                filterFaqs();
            });
        }
    });
</script>
<?php include 'includes/footer.php'; ?>