false, 'error' => 'Method not allowed']); exit; } // Check authentication via session if (session_status() === PHP_SESSION_NONE) { session_start(); } if (!isset($_SESSION['user']) || !isset($_SESSION['user']['user_id'])) { ob_end_clean(); http_response_code(401); header('Content-Type: application/json'); echo json_encode(['success' => false, 'error' => 'Authentication required']); exit; } // CSRF Protection require_once dirname(__DIR__) . '/middleware/CsrfMiddleware.php'; $csrfToken = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? ''; if (!CsrfMiddleware::validateToken($csrfToken)) { http_response_code(403); header('Content-Type: application/json'); echo json_encode(['success' => false, 'error' => 'Invalid CSRF token', 'csrf_token' => CsrfMiddleware::getToken()]); exit; } $currentUser = $_SESSION['user']; // Use centralized database connection $conn = Database::getConnection(); // Get data - support both POST body and query params $data = json_decode(file_get_contents('php://input'), true); if (!$data || !isset($data['comment_id'])) { // Also check POST params (no GET fallback — prevents CSRF bypass via URL) if (isset($_POST['comment_id'])) { $data = ['comment_id' => $_POST['comment_id']]; } else { ob_end_clean(); http_response_code(400); header('Content-Type: application/json'); echo json_encode(['success' => false, 'error' => 'Missing required field: comment_id']); exit; } } $result = CommentService::deleteComment($conn, $currentUser, $data); if (isset($result['http_status'])) { http_response_code($result['http_status']); unset($result['http_status']); } // Discard any unexpected output ob_end_clean(); header('Content-Type: application/json'); echo json_encode($result); } catch (Exception $e) { ob_end_clean(); error_log("Delete comment API error: " . $e->getMessage()); http_response_code(500); header('Content-Type: application/json'); echo json_encode([ 'success' => false, 'error' => 'An internal error occurred' ]); }