<?php
session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';
header('Content-Type: application/json; charset=utf-8');

$auth = new Auth();
if (!$auth->check() || !$auth->isSuperAdmin()) { jsonResponse(false, 'Unauthorized', [], 401); }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { jsonResponse(false, 'Invalid method.'); }

$csrf = new CSRF();
if (!$csrf->verify($_POST['csrf_token'] ?? '')) { jsonResponse(false, 'Invalid CSRF token.'); }

$db = Database::getInstance();
$action = $_POST['action'] ?? 'save';
$faqId = (int) ($_POST['faq_id'] ?? 0);

if ($action === 'delete') {
    $db->delete('faqs', 'id = ?', [$faqId]);
    jsonResponse(true, 'FAQ deleted.');
}

$question = trim($_POST['question'] ?? '');
$answer = trim($_POST['answer'] ?? '');
if (empty($question) || empty($answer)) { jsonResponse(false, 'Question and answer are required.'); }

$data = [
    'question' => $question,
    'answer' => $answer,
    'category' => trim($_POST['category'] ?? 'general'),
    'sort_order' => (int) ($_POST['sort_order'] ?? 0),
    'is_active' => isset($_POST['is_active']) ? 1 : 0,
];

if ($faqId > 0) {
    $db->update('faqs', $data, 'id = ?', [$faqId]);
    jsonResponse(true, 'FAQ updated.');
} else {
    $data['created_at'] = date('Y-m-d H:i:s');
    $db->insert('faqs', $data);
    jsonResponse(true, 'FAQ created.');
}
