<?php
$pageTitle = 'FAQs';
require_once __DIR__ . '/includes/header.php';
$db = Database::getInstance();
$faqs = $db->query("SELECT * FROM faqs ORDER BY sort_order ASC, created_at DESC")->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h6 class="mb-0">Manage FAQs</h6>
    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#faqModal" onclick="resetFaqForm()"><i class="fas fa-plus me-1"></i>Add FAQ</button>
</div>

<div class="table-card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover datatable">
                <thead class="table-light">
                    <tr><th>Sort</th><th>Question</th><th>Category</th><th>Answer</th><th>Active</th><th>Actions</th></tr>
                </thead>
                <tbody>
                    <?php foreach ($faqs as $faq): ?>
                    <tr>
                        <td><?php echo $faq['sort_order']; ?></td>
                        <td><strong><?php echo sanitize($faq['question']); ?></strong></td>
                        <td><span class="badge bg-info"><?php echo sanitize(ucfirst($faq['category'])); ?></span></td>
                        <td><?php echo sanitize(truncate($faq['answer'], 80)); ?></td>
                        <td><span class="badge bg-<?php echo $faq['is_active'] ? 'success' : 'secondary'; ?>"><?php echo $faq['is_active'] ? 'Active' : 'Inactive'; ?></span></td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary btn-action edit-faq-btn" data-id="<?php echo $faq['id']; ?>" title="Edit"><i class="fas fa-edit"></i></button>
                            <button class="btn btn-sm btn-outline-danger btn-action delete-faq-btn" data-id="<?php echo $faq['id']; ?>" title="Delete"><i class="fas fa-trash"></i></button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="faqModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title" id="faqModalTitle">Add FAQ</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <form id="faqForm">
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                    <input type="hidden" name="faq_id" id="faq_id" value="">
                    <div class="mb-3"><label class="form-label">Question <span class="text-danger">*</span></label><input type="text" class="form-control" name="question" id="faq_question" required></div>
                    <div class="mb-3"><label class="form-label">Answer <span class="text-danger">*</span></label><textarea class="form-control" name="answer" id="faq_answer" rows="5" required></textarea></div>
                    <div class="row g-3">
                        <div class="col-md-4"><label class="form-label">Category</label><input type="text" class="form-control" name="category" id="faq_category" placeholder="e.g. general" value="general"></div>
                        <div class="col-md-4"><label class="form-label">Sort Order</label><input type="number" class="form-control" name="sort_order" id="faq_sort" value="0"></div>
                        <div class="col-md-4"><div class="form-check mt-4"><input class="form-check-input" type="checkbox" name="is_active" id="faq_active" value="1" checked><label class="form-check-label">Active</label></div></div>
                    </div>
                </div>
                <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary"><i class="fas fa-save me-1"></i>Save</button></div>
            </form>
        </div>
    </div>
</div>

<script>
var faqData = <?php echo json_encode($faqs, JSON_HEX_TAG | JSON_HEX_AMP); ?>;

function resetFaqForm() {
    document.getElementById('faqModalTitle').textContent = 'Add FAQ';
    document.getElementById('faqForm').reset();
    document.getElementById('faq_id').value = '';
    document.getElementById('faq_active').checked = true;
}

document.querySelectorAll('.edit-faq-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var f = faqData.find(function(x) { return x.id == btn.dataset.id; });
        if (!f) return;
        document.getElementById('faqModalTitle').textContent = 'Edit FAQ';
        document.getElementById('faq_id').value = f.id;
        document.getElementById('faq_question').value = f.question;
        document.getElementById('faq_answer').value = f.answer;
        document.getElementById('faq_category').value = f.category || 'general';
        document.getElementById('faq_sort').value = f.sort_order;
        document.getElementById('faq_active').checked = f.is_active == 1;
        new bootstrap.Modal(document.getElementById('faqModal')).show();
    });
});

document.getElementById('faqForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var fd = new FormData(this);
    fetch(BASE_URL + '/admin/faq_save.php', { method: 'POST', body: new URLSearchParams(fd) })
    .then(function(r) { return r.json(); })
    .then(function(d) { if (d.success) { showAlert('success', d.message); setTimeout(function() { location.reload(); }, 1000); } else { showAlert('danger', d.message); } });
});

document.querySelectorAll('.delete-faq-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        if (confirm('Delete this FAQ?')) {
            ajaxPost(BASE_URL + '/admin/faq_save.php', 'action=delete&faq_id=' + this.dataset.id + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(d) {
                if (d.success) { showAlert('success', d.message); setTimeout(function() { location.reload(); }, 1000); } else { showAlert('danger', d.message); }
            });
        }
    });
});
</script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
