<?php
    /*
        *****************************************************************************
        * MEGA Digital Space - by MEGA Digital Studio                               *
        * ------------------------------------------------------------------------- *
        * CMS Website:  https://megadigital.space                                   *
        * License:  https://megadigital.space/license                               *
        * Owner:  Giorgi Basharuli                                                  *
        * Contact:  online@megadigital.studio                                       *
        * MEGA Digital Studio – Official Development Studio for MEGA Digital Space  *
        * Website:  https://megadigital.studio                                      *
        * ------------------------------------------------------------------------- *
        * Description: This file is a part of the MEGA Digital Space CMS system.    *
        * Unauthorized distribution, modification, or commercial use is strictly -  *
        * prohibited without prior written permission.                              *
        * ------------------------------------------------------------------------- *
        * Copyright (c) 2023-2025 MEGA Digital Studio.                              *
        * All rights reserved.                                                      *
        *****************************************************************************
    */

    require_once($_SERVER["DOCUMENT_ROOT"] . '/engine/data/config.php');
    require_once($_SERVER["DOCUMENT_ROOT"] . "/engine/data/dbconfig.php");


    if (!empty($_GET["wall_id"])) {
        $wall = $db_connect->get("walls", "*", ["id" => $_GET["wall_id"]]);
        $posts = [];
        if (!empty($wall)) {

            $wallFollowers = $db_connect->select("wall_followers", "*", ["wall_id" => $wall["id"]]);
            $posts = $db_connect->select("posts", "*", [
                "wall_id" => $_GET['wall_id'],
                "ORDER" => ["created_at" => "DESC"],
                "LIMIT" => [(int)$_GET['offset'], (int)$_GET['limit']]
            ]);

            foreach ($posts as &$post) {
                $post["author_data"] = $db_connect->get("users", "*", ["id" => $post["author_id"]]) ?? [];
                if ($wall["owner_id"] == $post["author_id"]) {
                    $post["author_data"]["is_owner"] = true;
                } else {
                    $post["author_data"]["is_owner"] = false;
                }
                $post["media"] = $db_connect->get("post_media", "*", ["post_id" => $post["id"]]) ?? [];
                $post["comments"][$post["id"]] = getCommentsTreeMedoo($db_connect, $post["id"], "wall_post");

                $post["likes"] = $db_connect->count("likes", "*", ["post_id" => $post["id"]]) ?? 0;
                $post["commentsCount"] = $db_connect->count("comments", "*", ["entity_id" => $post["id"], "entity_type" => "wall_post"]) ?? 0;
            }
        }

        echo json_encode($posts);
    }

    function getCommentsTreeMedoo($db_connect, $entityId, $entityType = 'wall_post', $parentId = null)
    {
        $comments = $db_connect->select("comments", "*", [
            "AND" => [
                "entity_id" => $entityId,
                "entity_type" => $entityType,
                "parent_id" => $parentId
            ],
            "ORDER" => ["created_at" => "ASC"]
        ]);

        $result = [];

        foreach ($comments as $comment) {
            $result[] = [
                "id" => (int)$comment["id"],
                "parentId" => $comment["parent_id"] !== null ? (int)$comment["parent_id"] : null,
                "author" => $comment["author"],
                "date" => formatTimeAgo($comment["created_at"]),
                "text" => $comment["comment_text"],
                "avatar" => $db_connect->get("users", "avatar", ["id" => $comment["user_id"]]),
                "replies" => getCommentsTreeMedoo($db_connect, $entityId, $entityType, $comment["id"])
            ];
        }

        return $result;
    }

    function formatTimeAgo($datetime)
    {
        $time = strtotime($datetime);
        $diff = time() - $time;

        if ($diff < 60) return $diff . ' секунд назад';
        if ($diff < 3600) return floor($diff / 60) . ' минут назад';
        if ($diff < 86400) return floor($diff / 3600) . ' часов назад';

        return date('Y-m-d H:i', $time); // fallback
    }
