
<?php
require_once 'config.php';
header('Content-Type: application/json; charset=utf-8');
$input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
$userId = miniapp_require_admin();
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS faq_items (id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, question VARCHAR(255) NOT NULL, answer MEDIUMTEXT NOT NULL, is_active TINYINT(1) NOT NULL DEFAULT 1, display_order INT NOT NULL DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, KEY idx_faq_active_order (is_active, display_order, id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $rows=$pdo->query("SELECT * FROM faq_items ORDER BY display_order ASC, id ASC LIMIT 100")->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['ok'=>true,'data'=>['items'=>$rows]], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); exit;
    }
    $action = $input['action'] ?? 'save';
    if ($action === 'delete') {
        $id=(int)($input['id']??0); $pdo->prepare("DELETE FROM faq_items WHERE id=?")->execute([$id]);
        gemaccAdminActionNotify('سوال متداول حذف شد', ['شناسه'=>$id], $userId);
        echo json_encode(['ok'=>true,'message'=>'حذف شد'], JSON_UNESCAPED_UNICODE); exit;
    }
    if ($action === 'toggle') {
        $id=(int)($input['id']??0); $pdo->prepare("UPDATE faq_items SET is_active=IF(is_active=1,0,1) WHERE id=?")->execute([$id]);
        gemaccAdminActionNotify('وضعیت سوال متداول تغییر کرد', ['شناسه'=>$id], $userId);
        echo json_encode(['ok'=>true,'message'=>'تغییر وضعیت انجام شد'], JSON_UNESCAPED_UNICODE); exit;
    }
    $id=(int)($input['id']??0); $q=trim((string)($input['question']??'')); $ans=trim((string)($input['answer']??'')); $active=(int)($input['is_active']??1); $order=(int)($input['display_order']??0);
    if ($q==='' || $ans==='') { echo json_encode(['ok'=>false,'error'=>'سوال و جواب الزامی است'], JSON_UNESCAPED_UNICODE); exit; }
    if ($id>0) $pdo->prepare("UPDATE faq_items SET question=?, answer=?, is_active=?, display_order=?, updated_at=NOW() WHERE id=?")->execute([$q,$ans,$active?1:0,$order,$id]);
    else $pdo->prepare("INSERT INTO faq_items(question,answer,is_active,display_order) VALUES(?,?,?,?)")->execute([$q,$ans,$active?1:0,$order]);
    gemaccAdminActionNotify($id>0 ? 'سوال متداول ویرایش شد' : 'سوال متداول اضافه شد', ['شناسه'=>$id>0?$id:$pdo->lastInsertId(), 'سوال'=>$q, 'فعال'=>$active?1:0], $userId);
    echo json_encode(['ok'=>true,'message'=>'ذخیره شد'], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) { echo json_encode(['ok'=>false,'error'=>$e->getMessage()], JSON_UNESCAPED_UNICODE); }
