<?php

class Network extends controller
{
    public function detail($id)
    {
        $qry = $this->DB->dbFetchAssoc("SELECT T.*, DATE_FORMAT(registration_date, '%d-%m-%Y %H:%i') AS join_date,  P.package, (SELECT name FROM member WHERE uid=T.sponsor_id) AS sponsor_name, (SELECT name FROM member WHERE uid=T.upline_id) AS upline_name FROM member AS T JOIN (package AS P) ON (T.package_id=P.package_id) WHERE T.uid=?", [$id]);
        echo json_encode($qry);
    }

    public function child($id, $i)
    {
        $data = [];
        if ($i < 7) {
            $qry = $this->DB->dbQuery("SELECT uid, package_id FROM member WHERE upline_id=? ORDER BY foot ASC", [$id]);
            while ($obj = $this->DB->dbFetchObject($qry)) {                
                $tmp = $this->child($obj->uid, $i+1);

                if ($tmp)
                    $data[] = ['name' => $obj->uid, 'package' => $obj->package_id, 'children' => $tmp];
                else

                    $data[] = ['name' => $obj->uid, 'package' => $obj->package_id];
            }
        }
        return $data;
    }

    public function downline($id = '')
    {
        $data = [];

        if ($id && $id != 'undefined') {
            $obj = $this->DB->dbFetchObject("SELECT uid, package_id FROM member WHERE uid=?", [$id]);
        } else {
            $obj = $this->DB->dbFetchObject("SELECT uid, package_id FROM member ORDER BY registration_date ASC LIMIT 1");
        }

        $i = 1;
        $data = $this->child($obj->uid, $i);
        $data = ['name' => $obj->uid, 'package' => $obj->package_id, 'children' => [...$data]];

        echo json_encode($data, JSON_PRETTY_PRINT);
    }
}
