<?php
header('Content-Type: application/json');

require_once __DIR__ . '/../classes/Database.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../classes/Messaging.php';

try {
    session_start();
    if (empty($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => 'Login required.']);
        exit;
    }

    $userId = (int)$_SESSION['user_id'];
    $messageId = (int)($_POST['message_id'] ?? 0);

    if (!$messageId) {
        echo json_encode(['success' => false, 'message' => 'Message not found.']);
        exit;
    }

    $database = new Database();
    $conn = $database->getConnection();

    $messaging = new Messaging($conn);
    $messaging->deleteMessageForUser($messageId, $userId);

    echo json_encode(['success' => true]);
} catch (InvalidArgumentException $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
} catch (Throwable $e) {
    error_log('Deleting message failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Unable to delete message.']);
}
