<?php
$chat = new Chat();

if ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    if (!isset($input['session_id']) || !isset($input['message'])) {
        json_response(['error' => 'Missing required parameters'], 400);
    }

    $sessionId = sanitize_input($input['session_id']);
    $message = sanitize_input($input['message']);

    $response = $chat->processMessage($sessionId, $message);

    json_response([
        'success' => true,
        'response' => $response
    ]);

} elseif ($method === 'GET') {
    if (!isset($_GET['session_id'])) {
        json_response(['error' => 'Missing session_id'], 400);
    }

    $sessionId = sanitize_input($_GET['session_id']);
    $action = $_GET['action'] ?? 'history';

    if ($action === 'history') {
        $messages = $chat->getChatHistory($sessionId);
        json_response([
            'success' => true,
            'messages' => $messages
        ]);
    }

} elseif ($method === 'DELETE') {
    $input = json_decode(file_get_contents('php://input'), true);

    if (!isset($input['session_id'])) {
        json_response(['error' => 'Missing session_id'], 400);
    }

    $sessionId = sanitize_input($input['session_id']);
    $result = $chat->clearHistory($sessionId);

    json_response([
        'success' => $result
    ]);

} else {
    json_response(['error' => 'Method not allowed'], 405);
}
?>