<?php
session_start();
if (!isset($_SESSION['admin'])) {
    header('HTTP/1.1 403 Forbidden');
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit;
}

$dbFile = '../chat_history.sqlite';
$db = new SQLite3($dbFile);

$action = $_POST['action'] ?? '';

if ($action === 'delete') {
    $id = $_POST['id'] ?? '';
    if (empty($id)) {
        echo json_encode(['success' => false, 'message' => 'Session ID is required']);
        exit;
    }

    $stmt = $db->prepare('DELETE FROM sessions WHERE id = :id');
    $stmt->bindValue(':id', $id, SQLITE3_TEXT);
    $result = $stmt->execute();

    if ($result) {
        // Delete associated messages
        $stmtMessages = $db->prepare('DELETE FROM messages WHERE session_id = :session_id');
        $stmtMessages->bindValue(':session_id', $id, SQLITE3_TEXT);
        $stmtMessages->execute();

        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Database error']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
}