<?php
session_start();
require_once 'config.php';
require_once 'functions.php';

if (!isset($_SESSION['user_id'])) { http_response_code(403); exit; }

$userId  = (int)$_SESSION['user_id'];
$msgId   = (int)($_GET['id'] ?? 0);
$circleId = (int)($_SESSION['circle_id'] ?? 1);

if (!$msgId) { http_response_code(400); exit; }

// Vérifier admin ou oracle
$user = getConnectedUser($pdo);
$canDelete = isAdmin($user);
if (!$canDelete) {
    try {
        $stmt = $pdo->prepare("SELECT oracle_id FROM circles WHERE id=?");
        $stmt->execute([$circleId]);
        $circle = $stmt->fetch();
        $canDelete = $circle && (int)$circle['oracle_id'] === $userId;
    } catch (Exception $e) {}
}

if (!$canDelete) { http_response_code(403); exit; }

try {
    $pdo->prepare("DELETE FROM messages WHERE id=?")->execute([$msgId]);
    $pdo->prepare("DELETE FROM chat_reports WHERE message_id=?")->execute([$msgId]);
    echo "ok";
} catch (Exception $e) {
    http_response_code(500);
    echo "Erreur";
}
?>
