query("SELECT id, title, mode, created_at FROM chats ORDER BY created_at DESC LIMIT 20"); $chats = $stmt->fetchAll(); echo json_encode(['success' => true, 'chats' => $chats]); } elseif ($action === 'messages') { $chatId = $_GET['chat_id'] ?? null; if (!$chatId) { echo json_encode(['error' => 'Chat ID is required']); exit; } // Fetch all messages for this chat $stmt = db()->prepare("SELECT role, content, created_at FROM messages WHERE chat_id = ? ORDER BY id ASC"); $stmt->execute([$chatId]); $messages = $stmt->fetchAll(); // Also fetch chat details (to restore mode) $stmt = db()->prepare("SELECT mode FROM chats WHERE id = ?"); $stmt->execute([$chatId]); $chat = $stmt->fetch(); echo json_encode([ 'success' => true, 'messages' => $messages, 'mode' => $chat['mode'] ?? 'regular' ]); } elseif ($action === 'delete') { $chatId = $_GET['chat_id'] ?? null; if (!$chatId) { echo json_encode(['error' => 'Chat ID is required']); exit; } $stmt = db()->prepare("DELETE FROM chats WHERE id = ?"); $stmt->execute([$chatId]); echo json_encode(['success' => true]); } else { echo json_encode(['error' => 'Invalid action']); } } catch (Exception $e) { echo json_encode(['error' => $e->getMessage()]); }