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

    $referrals = $db_connect->select("users", [
        "id",
        "name",
        "regdate"
    ], [
        "referrer_id" => $user["id"]
    ]);

    $referralsCount = count($referrals);

    foreach ($referrals as &$referral) {
        $transactions = $db_connect->select("transactions", "*", ["user_id" => $referral['id'], "status" => "succeeded"]);
        $referral['total_spent'] = 0;

        foreach ($transactions as $transaction) {
            if (!empty($transaction["sum"]) && !empty($transaction["currency"])) {
                $referral["total_spent"] += convertAmount($transaction["sum"], $transaction["currency"], getCurrentCurrency());
            }
        }
    }

    $referralsTotalReward = 0;
    foreach ($referrals as &$referral) {
        $referral['total_reward'] = $db_connect->sum("referral_rewards", "reward_amount", [
            "referrer_id" => $user["id"],
            "referred_user_id" => $referral['id']
        ]);
        if ($referral['total_reward'] == "") {
            $referral['total_reward'] = 0;
        }
        $referral['reward_percentage'] = $db_connect->avg("referral_rewards", "reward_percentage", [
            "referrer_id" => $user["id"],
            "referred_user_id" => $referral['id']
        ]);
        if ($referral['reward_percentage'] == "") {
            $referral['reward_percentage'] = 0;
        }
    }

    $seven_days_ago = date('Y-m-d H:i:s', strtotime('-7 days'));
    $days_ago_30 = date('Y-m-d H:i:s', strtotime('-30 days'));

    $total_reward_last_7_days = $db_connect->sum("referral_rewards", "reward_amount", [
        "referrer_id" => $user["id"],
        "created_at[>=]" => $seven_days_ago
    ]);

    $l7 = $total_reward_last_7_days;
    $total_reward_last_7_days = convertAmount($total_reward_last_7_days, $config["payment_info"]["default_currency"], getCurrentCurrency()). " " . getCurrentCurrency();

    $fourteen_days_ago = date('Y-m-d H:i:s', strtotime('-14 days'));
    $total_reward_previous_7_days = $db_connect->sum("referral_rewards", "reward_amount", [
        "referrer_id" => $user["id"],
        "created_at[>=]" => $fourteen_days_ago,
        "created_at[<]" => $seven_days_ago
    ]);

    $ll7 = $total_reward_previous_7_days;
    $total_reward_previous_7_days = convertAmount($total_reward_previous_7_days, $config["payment_info"]["default_currency"], getCurrentCurrency()). " " . getCurrentCurrency();

    if ($ll7 > 0 && $l7 > 0) {
        @$percentage_change_7 = (($l7 - $ll7) / $ll7) * 100;
    } else {
        $percentage_change_7 = $l7 > 0 ? 100 : 0;
    }

    $total_reward_last_30_days = $db_connect->sum("referral_rewards", "reward_amount", [
        "referrer_id" => $user["id"],
        "created_at[>=]" => $days_ago_30
    ]);

    $tr30 = $total_reward_last_30_days;
    $total_reward_last_30_days = convertAmount($total_reward_last_30_days, $config["payment_info"]["default_currency"], getCurrentCurrency()). " " . getCurrentCurrency();

    $days_ago_60 = date('Y-m-d H:i:s', strtotime('-60 days'));
    $total_reward_previous_30_days = $db_connect->sum("referral_rewards", "reward_amount", [
        "referrer_id" => $user["id"],
        "created_at[>=]" => $days_ago_60,
        "created_at[<]" => $days_ago_30
    ]);

    $trr30 = $total_reward_previous_30_days;
    $total_reward_previous_30_days = convertAmount($total_reward_previous_30_days, $config["payment_info"]["default_currency"], getCurrentCurrency()). " " . getCurrentCurrency();

    if ($trr30 > 0 && $tr30 > 0) {
        @$percentage_change_30 = (($tr30 - $trr30) / $trr30) * 100;
    } else {
        $percentage_change_30 = $tr30 > 0 ? 100 : 0;
    }
    $percentage_change_7 = round($percentage_change_7, 2);
    $percentage_change_30 = round($percentage_change_30, 2);

    $allPercentage = $db_connect->avg("referral_rewards", "reward_percentage", [
        "referrer_id" => $user["id"],
    ]);

    foreach ($referrals as &$referral) {
        $referral["ID"] = $referral["id"];
        $referral[$lang["widgets"]["reg_date"]] = $referral["regdate"];
        $referral[$lang["widgets"]["name"]] = $referral["name"];
        $referral[$lang["widgets"]["all_sum_count"]] = $referral["total_spent"] ." ". getCurrentCurrency();
        $referral[$lang["widgets"]["percent"]] = round($referral["reward_percentage"], 2). "%";
        $referral[$lang["widgets"]["reward_amount"]] = convertAmount($referral["total_reward"], $config["payment_info"]["default_currency"], getCurrentCurrency()). " " . getCurrentCurrency();

        $referralsTotalReward += convertAmount($referral["total_reward"], $config["payment_info"]["default_currency"], getCurrentCurrency());
    }

    $referralUrl = $_SERVER["SERVER_NAME"]."/?referrer/uid&code=" . $user["referral_code"];

    $referralFixSum = 0;
    if (!empty($config['referral_fix_sum'])) {
        $referralFixSum = convertAmount($config['referral_fix_sum'], $config["payment_info"]["default_currency"], getCurrentCurrency())." ".getCurrentCurrency();
    }

    $refSettings = $db_connect->get("referral_settings", "*", ["object_type" => "groups", "object_id" => $user["group"]]);
    if (!empty($refSettings)) {
        if(!empty($refSettings["discount_percent"]) && $refSettings["discount_percent"] > 0) {
            $refSettings["discount"] = round($refSettings["discount_percent"]);
            $refSettings["type"] = "percent";
        } elseif (!empty($refSettings["discount_sum"]) && $refSettings["discount_sum"] > 0) {
            $refSettings["discount"] = round($refSettings["discount_sum"]) ." ". $config["payment_info"]["default_currency"];
            $refSettings["type"] = "sum";
        } else {
            $refSettings["discount"] = 0;
        }
    } else {
        $refSettings = [];
    }

    $smarty->assign('refSettings', $refSettings);
    $smarty->assign('referralFixSum', $referralFixSum);
    $smarty->assign('referrals', $referrals);
    $smarty->assign('referralsCount', $referralsCount);
    $smarty->assign('referralsTotalReward', $referralsTotalReward . " " . getCurrentCurrency());
    $smarty->assign('referralUrl', $referralUrl);
    $smarty->assign('total_reward_last_7_days', $total_reward_last_7_days);
    $smarty->assign('total_reward_last_30_days', $total_reward_last_30_days);
    $smarty->assign('percentage_change_7', $percentage_change_7 > 0 ? "+".$percentage_change_7 : $percentage_change_7);
    $smarty->assign('percentage_change_30', $percentage_change_30 > 0 ? "+".$percentage_change_30 : $percentage_change_30);
    $smarty->assign('allPercentage', !empty($allPercentage) ? round($allPercentage, 2) : 0);
    $smarty->assign('referralCode', $user["referral_code"]);

