<?php
class Matching extends controller
{
    public function bonus($id = '')
    {
        include_once "Bonus.php";

        $bonus = new Bonus();

        // Max Profit
        $package = $this->DB->dbFetchColumn("SELECT P.usd FROM member AS T JOIN(package AS P) ON (T.package_id=P.package_id)  WHERE T.uid=?", [$id]);
        $maxProfit = 3 * (float) $package;
        
        $sponsor = $bonus->totSponsor($id);
        $passive = $bonus->passive($id);
        $pairing = $bonus->pairing($id);

        $tot = $sponsor + $passive + $pairing;

        $data = $bonus->roi($id);

        $now = new DateTime("now");
        $profit = [];
        foreach ($data as $val) {
            if ($tot <= $maxProfit) {
                $start = new DateTime($val['reg']);
                ['level' => $level, 'sponsor' => $sponsor, 'profit' => $usd] = $val;

                while ($start <= $now) {
                    $tot += $usd;
                    if ($tot <= $maxProfit)
                        $profit[] = ['level' => $level, 'sponsor' => $sponsor, 'profit' => $usd, 'date' => $start->format("Y-m-d")];
                    else break;
                    $start->modify("+1 day");
                }
            } else continue;
        }

        usort($profit, function ($a, $b) {
            return strtotime($a['date']) <=> strtotime($b['date']);
        });

        echo json_encode($profit);
    }
}
