<?php
// manage_messages.php - Handle message deletion and moving
session_start();
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit;
}
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if (!$data) {
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON']);
exit;
}
$action = $data['action'] ?? '';
$indices = $data['indices'] ?? [];
if (!is_array($indices) || empty($indices)) {
echo json_encode(['error' => 'No message indices provided']);
exit;
}
// Ensure chat_log exists
if (!isset($_SESSION['chat_log'])) {
$_SESSION['chat_log'] = [];
}
switch ($action) {
case 'delete':
// Sort indices in descending order to avoid index shifting issues
rsort($indices);
foreach ($indices as $index) {
if (isset($_SESSION['chat_log'][$index])) {
unset($_SESSION['chat_log'][$index]);
}
}
// Re-index the array
$_SESSION['chat_log'] = array_values($_SESSION['chat_log']);
echo json_encode(['success' => true, 'message' => 'Messages deleted']);
break;
case 'move':
// Initialize conversations storage if it doesn't exist
if (!isset($_SESSION['conversations'])) {
$_SESSION['conversations'] = [];
}
// Extract selected messages (the ones we want to MOVE)
$movedMessages = [];
$remainingMessages = [];
// Split messages: selected ones go to new conversation, unselected stay
foreach ($_SESSION['chat_log'] as $i => $message) {
if (in_array($i, $indices)) {
// This message was selected - move it
$movedMessages[] = $message;
} else {
// This message was not selected - keep it in current chat
$remainingMessages[] = $message;
}
}
if (!empty($movedMessages)) {
// Create new conversation with the SELECTED messages
$conversationId = 'conv_' . time() . '_' . rand(1000, 9999);
$_SESSION['conversations'][$conversationId] = [
'title' => 'Moved Messages - ' . date('M j, Y g:i A'),
'messages' => $movedMessages,
'created' => time(),
'usage_totals' => ['prompt' => 0, 'completion' => 0, 'total' => 0]
];
// Keep only the UNSELECTED messages in current chat
$_SESSION['chat_log'] = $remainingMessages;
echo json_encode([
'success' => true,
'message' => 'Messages moved to new conversation: ' . $_SESSION['conversations'][$conversationId]['title'],
'conversationId' => $conversationId,
'conversationTitle' => $_SESSION['conversations'][$conversationId]['title'],
'debug' => [
'selected_indices' => $indices,
'moved_count' => count($movedMessages),
'remaining_count' => count($remainingMessages)
]
]);
} else {
echo json_encode(['error' => 'No valid messages found to move']);
}
break;
default:
echo json_encode(['error' => 'Invalid action']);
break;
}
?>