<?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");

    session_start();

    global $db_connect;

    $conditions = [];

    if (!empty($_POST["query"])) {
        $conditions = ["id[!]" => $_SESSION["user_id"], "name[~]" => $_POST["query"]];
    } else {
        $conditions = ["id[!]" => $_SESSION["user_id"]];
    }

    $users = $db_connect->select("users", "*", $conditions);

    foreach($users as $key => &$user) {
        $messages = $db_connect->select("messages (m)", [
            "[>]chat_deletions (cd)" => [
                "id" => "chat_id" // без префикса "m." или "cd."
            ]
        ], [
            "m.id",
            "m.sender_id",
            "m.receiver_id",
            "m.file_path",
            "m.img_path",
            "m.message",
            "m.created_at"
        ], [
            //"cd.user_id[!]" => $_SESSION["id"],

            "AND" => [
                "OR" => [
                    "AND #1" => [
                        "m.receiver_id" => $user["id"],
                    ],
                    "AND #2" => [
                        "m.sender_id" => $user["id"],
                    ],
                ],
            ],
        ]);


        $usersRelationship = $db_connect->get("user_relationships", "*", ["user_id_from" => $_SESSION["user_id"], "user_id_to" => $user["id"], "is_support" => 0]) ?? [];

        if (empty($usersRelationship)) {
            unset($users[$key]);
            continue;
        }


        $lastMessage = end($messages);

        if ($lastMessage) {
            $deleted = $db_connect->select("chat_deletions", "*", [
                "user_id" => $_SESSION["user_id"],
                "chat_id" => $lastMessage["id"]
            ]) ?? [];
        }


        if (!empty($deleted) || empty($lastMessage)) {
            $user["lastMessage"] = "No messages";
        } else {
            if (!empty($lastMessage["img_path"])) {
                $user["lastMessage"] = "Вам отправили фото";
            } else if (!empty($lastMessage["file_path"])) {
                $user["lastMessage"] = "Вам отправили файл";
            } else {
                $user["lastMessage"] = $lastMessage["message"] ?? "No messages";
            }
        }

        $user["messages"] = $messages;
        $user["lastMessageTime"] = $lastMessage["created_at"] ?? "";


    }
    $users = array_values($users);

    echo json_encode($users);

