<?php
$postId = $_GET['post_id'] ?? '';
$normalFile = __DIR__ . "/../$postId/data.json";
$userFile   = __DIR__ . "/../user_posts/$postId/data.json";

if (file_exists($normalFile)) {
    $dataFile = $normalFile;
} elseif (file_exists($userFile)) {
    $dataFile = $userFile;
} else {
    exit;
}

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

if (file_exists($dataFile)) {
    $data = json_decode(file_get_contents($dataFile), true);
    $comments = $data['comments'] ?? [];

    foreach ($comments as &$c) {
        $userDir = "../../users/" . ($c['user'] ?? '');
        $c['profile'] = "images/default-avatar.png";
        $c['username'] = $c['user'];

        if (isset($c['user']) && is_dir($userDir)) {
            $userDataFile = "$userDir/data.json";
            if (file_exists($userDataFile)) {
                $userData = json_decode(file_get_contents($userDataFile), true);
                if (isset($userData['username'])) {
                    $c['username'] = $userData['username'];
                }
            }
            
            if (file_exists("$userDir/profile.png")) {
                $c['profile'] = "users/{$c['user']}/profile.png";
            } elseif (file_exists("$userDir/profile.jpg")) {
                $c['profile'] = "users/{$c['user']}/profile.jpg";
            }
        }
    }

    echo json_encode($comments);
} else {
    echo json_encode([]);
}