<?php
/**
 * Admin - FAQ Management
 */
require_once __DIR__ . '/../config.php';
require_admin_login();

$page_title = 'FAQ Management';

// Handle bulk actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action'])) {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        redirect(BASE_URL . 'admin/faqs.php', 'error', 'Invalid security token');
    }
    
    $ids = $_POST['selected_ids'] ?? [];
    $action = $_POST['bulk_action'];
    
    if (!empty($ids)) {
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        try {
            if ($action === 'delete') {
                $stmt = db()->prepare("DELETE FROM faqs WHERE id IN ($placeholders)");
                $stmt->execute($ids);
                redirect(BASE_URL . 'admin/faqs.php', 'success', count($ids) . ' FAQs deleted');
            } elseif ($action === 'activate') {
                $stmt = db()->prepare("UPDATE faqs SET is_active = 1 WHERE id IN ($placeholders)");
                $stmt->execute($ids);
                redirect(BASE_URL . 'admin/faqs.php', 'success', count($ids) . ' FAQs activated');
            } elseif ($action === 'deactivate') {
                $stmt = db()->prepare("UPDATE faqs SET is_active = 0 WHERE id IN ($placeholders)");
                $stmt->execute($ids);
                redirect(BASE_URL . 'admin/faqs.php', 'success', count($ids) . ' FAQs deactivated');
            }
        } catch (PDOException $e) {
            redirect(BASE_URL . 'admin/faqs.php', 'error', 'Action failed: ' . $e->getMessage());
        }
    }
}

// Get FAQs with search/filter
$faqs = [];
$search = sanitize($_GET['search'] ?? '');
$category = sanitize($_GET['category'] ?? '');

$conditions = [];
$params = [];

if ($search) {
    $conditions[] = '(question LIKE ? OR answer LIKE ?)';
    $params[] = '%' . $search . '%';
    $params[] = '%' . $search . '%';
}

if ($category) {
    $conditions[] = 'category = ?';
    $params[] = $category;
}

$sql = "SELECT * FROM faqs";
if ($conditions) {
    $sql .= " WHERE " . implode(' AND ', $conditions);
}
$sql .= " ORDER BY sort_order, category, id DESC";

try {
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    $faqs = $stmt->fetchAll();
} catch (PDOException $e) {}

// Get categories for filter
$categories = [];
try {
    $stmt = db()->query("SELECT DISTINCT category FROM faqs ORDER BY category");
    $categories = $stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (PDOException $e) {}

$csrf_token = generate_csrf_token();
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="fw-bold mb-0">FAQ Management</h2>
    <a href="faq-add.php" class="btn btn-primary"><i class="bi bi-plus-lg me-2"></i>Add FAQ</a>
</div>

<form method="GET" class="row g-3 mb-4">
    <div class="col-md-4">
        <input type="text" name="search" class="form-control" placeholder="Search FAQs..." value="<?php echo $search; ?>">
    </div>
    <div class="col-md-3">
        <select name="category" class="form-select">
            <option value="">All Categories</option>
            <?php foreach ($categories as $cat): ?>
            <option value="<?php echo $cat; ?>" <?php echo $category === $cat ? 'selected' : ''; ?>>
                <?php echo ucfirst($cat); ?>
            </option>
            <?php endforeach; ?>
        </select>
    </div>
    <div class="col-md-2">
        <button type="submit" class="btn btn-outline-primary w-100"><i class="bi bi-search me-2"></i>Filter</button>
    </div>
    <div class="col-md-2">
        <a href="faqs.php" class="btn btn-outline-secondary w-100">Clear</a>
    </div>
</form>

<form method="POST">
    <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
    
    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <span class="fw-bold">FAQs</span>
            <div class="d-flex gap-2">
                <select name="bulk_action" class="form-select form-select-sm" style="width: auto;">
                    <option value="">Bulk Actions</option>
                    <option value="activate">Activate</option>
                    <option value="deactivate">Deactivate</option>
                    <option value="delete">Delete</option>
                </select>
                <button type="submit" class="btn btn-sm btn-outline-secondary">Apply</button>
            </div>
        </div>
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th><input type="checkbox" class="form-check-input" id="selectAll"></th>
                        <th>ID</th>
                        <th>Question</th>
                        <th>Category</th>
                        <th>Views</th>
                        <th>Helpful</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($faqs as $faq): ?>
                    <tr>
                        <td><input type="checkbox" name="selected_ids[]" value="<?php echo $faq['id']; ?>" class="form-check-input row-checkbox"></td>
                        <td><?php echo $faq['id']; ?></td>
                        <td><?php echo truncate_text($faq['question'], 80); ?></td>
                        <td><?php echo ucfirst($faq['category']); ?></td>
                        <td><?php echo $faq['views']; ?></td>
                        <td><?php echo $faq['helpful_count']; ?>/<?php echo $faq['helpful_count'] + $faq['not_helpful_count']; ?></td>
                        <td>
                            <span class="badge bg-<?php echo $faq['is_active'] ? 'success' : 'secondary'; ?>">
                                <?php echo $faq['is_active'] ? 'Active' : 'Inactive'; ?>
                            </span>
                        </td>
                        <td>
                            <a href="faq-edit.php?id=<?php echo $faq['id']; ?>" class="btn btn-sm btn-outline-primary">
                                <i class="bi bi-pencil"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($faqs)): ?>
                    <tr><td colspan="8" class="text-center py-4 text-muted">No FAQs found</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</form>

<script>
document.getElementById('selectAll').addEventListener('change', function() {
    document.querySelectorAll('.row-checkbox').forEach(cb => cb.checked = this.checked);
});
</script>

<?php 
function truncate_text($text, $length) {
    return strlen($text) > $length ? substr($text, 0, $length) . '...' : $text;
}
include __DIR__ . '/includes/footer.php'; 
?>
