<?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.                                                      *
        *****************************************************************************
    */

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

    session_start();
    global $db_connect;

    $tickets = [];
    if (!empty($_SESSION["user_id"])) {

        $groupName = $db_connect->get("roles", "name", ["id" => $_SESSION["user_group_id"]]);
        $fieldName = $groupName === "Support" ? "support_u_id" : "user_id";

        $tickets = $db_connect->select("tickets", "*", [/*$fieldName => $_SESSION["user_id"], */"status" => "open"]);

        $newTickets = [];
        foreach ($tickets as &$ticket) {

            $ticket["messages"] = $db_connect->select("messages", "*", ["ticket_id" => $ticket["id"]]);

            foreach ($ticket["messages"] as &$message) {
                if ($message["sender_id"] == $_SESSION["user_id"]) {
                    $message["from"] = "support";
                } else {
                    $message["from"] = "user";
                }
            }

            $newTickets[$ticket["id"]] = $ticket;

        }


    }

    echo json_encode($newTickets);
