<?php
	define('thisscript','network');

	require_once "global.php";
	
	if (empty($userid)){
		redirecting('home');
	}
	
	require_once "class/User.php";
	$user = new User();  
	
	$max_level = 3;
	$max_child = 2;
	
 	/* sanitize post, get, request */
	$_POST['do'] = ((empty($_POST['do']))?"":$_POST['do']);
	$_POST['regpassword'] = ((empty($_POST['regpassword']))?"":$_POST['regpassword']);
	$_REQUEST['upline'] = ((empty($_REQUEST['upline']))?"":$_REQUEST['upline']);
	$_GET['type'] = ((empty($_GET['type']))?"":$_GET['type']);
	/* end sanitize */
 	
 	if (!empty($_POST)){
		$do = $_POST['do'];
 		if ($do == "getPendingDownline"){
			$downline = '';
			
			$downline_db = $db->fetch_all("SELECT userid, firstname, email FROM user WHERE parentid = '".$db->clean($userid)."' AND parent_tree = 0 AND deposit_status = 1 ORDER BY userid");
			
			if(sizeof($downline_db) > 0){
				$downline .= '<ul>';
				foreach($downline_db as $row){
					$downline .= '<li><a href="" class="chooseDownline" data-target="'.$row['userid'].'">'.$row['firstname'].' ('.$row['email'].')</a></li>';
				}
				$downline .= '</ul>';
			}
			else{
				$downline .= '<p class="margin-0 padding-0">There is no downline</p>';
			}

			echo json_encode(array('err' => false, 'list' => $downline));
			exit;
 		}		
		else if ($do == "setDownlinePosition"){
			$parentid = $_POST['parentid'];
			$level = $_POST['level'];
			$position = $_POST['position'];
			$id = $_POST['id'];
			
			$db->beginTransaction();
			
			if(!empty($parentid) && !empty($level) && !empty($position) && !empty($id)){
				if ($position != 'left' && $position != 'right'){
					exit;
				}
			
				$detail = $db->fetch_one("SELECT userid, firstname, email, deposit, deposit_status, parentid, pending_point FROM user WHERE userid = '".$db->clean($id)."'");
				
				if(!empty($detail['userid']) && $detail['deposit_status'] == 1 && $detail['parentid'] == $userid){
					$level_parent = $db->fetch_one("SELECT level, `".$position."` AS position FROM user WHERE userid = '".$db->clean($parentid)."'");
					$current_level = empty($level_parent['level']) ? 1 : ($level_parent['level'] + 1);
					if (!empty($level_parent['position'])){
						exit;
					}
					
					if ($parentid != $userid){
						$verified = false;
						$user->isTreeDownline($parentid);
						if (!$verified){
							exit;
						}
					}
				
					$db->query("UPDATE user SET level = ".$db->clean($current_level).", parent_tree = ".$db->clean($parentid)." WHERE userid = '".$db->clean($id)."'");
					$db->query("UPDATE user SET `".$position."` = ".$db->clean($id)." WHERE userid = '".$db->clean($parentid)."'");
					
					$user->setUplineTotalDownlineTree($id);
					//$user->setUplinePoint($detail['userid'], $detail['deposit']);
					
					if ($detail['pending_point'] > 0){
						$db->query("UPDATE user SET pending_point = 0 WHERE userid = ".$db->clean($detail['userid']));
						$user->setUplineTotalTopup($detail['pending_point'], $detail['userid']);
					}
					
					$downline = '<a href="network/'.$detail['userid'].'"><i class="fa fa-user"></i><br>'.$detail['firstname'].'<br><small>'.$detail['email'].'</small></a>';
					
					/* $level++;
					if($level <= $max_level){
						$downline .= $user->getDownline($id, $max_level, $max_child, $level);
					} */
					
					echo json_encode(array('err' => false, 'downline' => $downline));
				}
			}
			
			$db->endTransaction();
			exit;
 		}
		else if($do == 'getDownline'){
			$id = $_POST['id'];
			
			$next_downline = '';
			if(!empty($id)){
				$verified = false;
				$user->isReferralDownline($id);
				if (!$verified){
					exit;
				}
			
				$next_downline_db = $db->fetch_all("SELECT u.userid, u.firstname, u.lastname, u.email, u.deposit_status, u.activated_date, (SELECT count( userid ) AS total_downline FROM user WHERE parentid = u.userid) total_downline FROM user u WHERE parentid = '".$db->clean($id)."'");
				if(sizeof($next_downline_db) > 0){
					foreach($next_downline_db as $row){
						$tooltip_text = '';
						$text_color = '';
						if ($row['deposit_status'] == 1){
							$tooltip_text = 'Activated on '.date('d M Y, H:i:s', $row['activated_date']);
						}
						else{
							$tooltip_text = 'Pending Account Activation';
							$text_color = ' style="color:#f4cd03;"';
						}
						
						$next_downline .= '<li>
											'.($row['total_downline'] > 0?'<a href="#" class="toggle" userid="'.$row['userid'].'"></a>&nbsp;&nbsp;':'').'
											<span data-toggle="tooltip" data-placement="right" title="'.$tooltip_text.'"'.$text_color.'>'.$row['firstname'].' ('.$row['email'].')</span>
										</li>';
					}
				}
				
				if(!empty($next_downline)){
					$next_downline = '<div class="tree-wrapper"><ul>'.$next_downline.'</ul></div>';
				}
			}
			
			echo json_encode(array("downline" => $next_downline));
			exit;
		}
	}
	
	$outer_verified = true;
	$outer_mode = 'both';
	if(!empty($_REQUEST['upline'])){
		$parentid = $_REQUEST['upline'];
		$is_expand = true;
		
		if ($parentid != $userid){
			$verified = false;
			$user->isTreeDownline($parentid);
			if (!$verified){
				redirecting('../network');
			}
			
			$initial = '';
			$user->isTreeOuter($parentid);
			$outer_mode = $initial;
		}
	}
	else{
		$parentid = $userid;
		$is_expand = false;
	}
	
	//echo $outer_verified;exit;
	
	$user->setId($parentid);
	$detail = $user->getUserDetail();
	
	if(!empty($detail['parent_tree'])){
		$empty_box = array();
		$level_point = array(0, 0, 0, 0);
	
		$downline = $user->getDownline($parentid, $max_level, $max_child);/* echo $downline;exit; */
		
		$upline_box = '';
		if ($is_expand && $parentid != $userid){
			$upline = $db->fetch_one("SELECT firstname, email, package FROM user WHERE userid = '".$db->clean($detail['parent_tree'])."'");
			if (!empty($upline['email'])){
				$add_label = '';
				if ($upline['package'] == 'gold'){
					$add_label = ' gold-label';
				}
				if ($upline['package'] == 'silver'){
					$add_label = ' silver-label';
				}
				
				$upline_box = '<span class="parent-box' . $add_label . '"><i class="fa fa-user"></i><br><a href="network/'.$detail['parent_tree'].'">'.$upline['firstname'].'<br><small>'.$upline['email'].'</small></a></span>';
			}
		}
		
		//echo $outer_verified.'-'.$outer_mode;
		//print_r($empty_box);
		
		if (sizeof($empty_box) > 0){
			foreach($empty_box as $k1 => $v1){
				foreach($v1 as $k2 => $v2){
					if ($outer_verified){
						if ($k1 == 2){
							if ($outer_mode == 'both'){
								$get_parent = explode(':', $v2);
								$get_parent[1] = str_replace(']', '', $get_parent[1]);
								$downline = str_replace($v2, '<li><a href="" class="new" data-toggle="modal" data-target="#myModal" data-level="' . $k1 . '" data-parent="' . $get_parent[1] . '" data-position="'.(($k2 % 2 == 0)?'left':'right').'"><i class="fa fa-plus"></i></a>', $downline);
							}
							else if ($outer_mode == 'left'){
								if ($k2 == 0){
									$get_parent = explode(':', $v2);
									$get_parent[1] = str_replace(']', '', $get_parent[1]);
									$downline = str_replace($v2, '<li><a href="" class="new" data-toggle="modal" data-target="#myModal" data-level="' . $k1 . '" data-parent="' . $get_parent[1] . '" data-position="'.(($k2 % 2 == 0)?'left':'right').'"><i class="fa fa-plus"></i></a>', $downline);
								}
								else{
									$downline = str_replace($v2, '<li><span class="empty"><i class="fa fa-minus"></i></span>', $downline);
								}
							}
							else if ($outer_mode == 'right'){
								if ($k2 == 1){
									$get_parent = explode(':', $v2);
									$get_parent[1] = str_replace(']', '', $get_parent[1]);
									$downline = str_replace($v2, '<li><a href="" class="new" data-toggle="modal" data-target="#myModal" data-level="' . $k1 . '" data-parent="' . $get_parent[1] . '" data-position="'.(($k2 % 2 == 0)?'left':'right').'"><i class="fa fa-plus"></i></a>', $downline);
								}
								else{
									$downline = str_replace($v2, '<li><span class="empty"><i class="fa fa-minus"></i></span>', $downline);
								}
							}
						}
						else if ($k1 == 3){
							if ($outer_mode == 'both'){
								if ($k2 == 0 || $k2 == 3){
									$get_parent = explode(':', $v2);
									$get_parent[1] = str_replace(']', '', $get_parent[1]);
									$downline = str_replace($v2, '<li><a href="" class="new" data-toggle="modal" data-target="#myModal" data-level="' . $k1 . '" data-parent="' . $get_parent[1] . '" data-position="'.(($k2 % 2 == 0)?'left':'right').'"><i class="fa fa-plus"></i></a>', $downline);
								}
								else{
									$downline = str_replace($v2, '<li><span class="empty"><i class="fa fa-minus"></i></span>', $downline);
								}
							}
							else if ($outer_mode == 'left'){
								if ($k2 == 0){
									$get_parent = explode(':', $v2);
									$get_parent[1] = str_replace(']', '', $get_parent[1]);
									$downline = str_replace($v2, '<li><a href="" class="new" data-toggle="modal" data-target="#myModal" data-level="' . $k1 . '" data-parent="' . $get_parent[1] . '" data-position="'.(($k2 % 2 == 0)?'left':'right').'"><i class="fa fa-plus"></i></a>', $downline);
								}
								else{
									$downline = str_replace($v2, '<li><span class="empty"><i class="fa fa-minus"></i></span>', $downline);
								}
							}
							else if ($outer_mode == 'right'){
								if ($k2 == 3){
									$get_parent = explode(':', $v2);
									$get_parent[1] = str_replace(']', '', $get_parent[1]);
									$downline = str_replace($v2, '<li><a href="" class="new" data-toggle="modal" data-target="#myModal" data-level="' . $k1 . '" data-parent="' . $get_parent[1] . '" data-position="'.(($k2 % 2 == 0)?'left':'right').'"><i class="fa fa-plus"></i></a>', $downline);
								}
								else{
									$downline = str_replace($v2, '<li><span class="empty"><i class="fa fa-minus"></i></span>', $downline);
								}
							}
						}
					}
					else{
						$downline = str_replace($v2, '<li><span class="empty"><i class="fa fa-minus"></i></span>', $downline);
					}	
				}
			}
		}
		
		$add_label = '';
		if ($detail['package'] == 'gold'){
			$add_label = ' class="gold-label"';
		}
		if ($detail['package'] == 'silver'){
			$add_label = ' class="silver-label"';
		}
		
		$downline = '<ul class="downline-diagram">
						<li>
							'.$upline_box.'
							<span'.$add_label.'><i class="fa fa-user"></i><br>'.$detail['firstname'].'<br><small>'.$detail['email'].'</small></span>
							'.$downline.'
						</li>
					</ul>';
	}
	else{
		if(!empty($_REQUEST['upline'])){
			$downline = '<h6>'.$detail['firstname'].' has not been assigned in our system</h6>';
		}
		else{
			$downline = '<h6>You have not been assigned in our system</h6>';
		}	
	}
	
	//Tree
	$first_level_downline = '';
	$first_level_downline_db = $db->fetch_all("SELECT u.userid, u.firstname, u.lastname, u.email, u.deposit_status, u.activated_date, (SELECT count( userid ) AS total_downline FROM user WHERE parentid = u.userid) total_downline FROM user u WHERE parentid = '".$db->clean($userid)."' ORDER BY userid ASC");
	if(sizeof($first_level_downline_db) > 0){
		foreach($first_level_downline_db as $row){
			$tooltip_text = '';
			$text_color = '';
			if ($row['deposit_status'] == 1){
				$tooltip_text = 'Activated on '.date('d M Y, H:i:s', $row['activated_date']);
			}
			else{
				$tooltip_text = 'Pending Account Activation';
				$text_color = ' style="color:#f4cd03;"';
			}
			
			$first_level_downline .= '<li>
										'.($row['total_downline'] > 0?'<a href="#" class="toggle" userid="'.$row['userid'].'"></a>&nbsp;&nbsp;':'').'
										<span data-toggle="tooltip" data-placement="right" title="'.$tooltip_text.'"'.$text_color.'>'.$row['firstname'].' ('.$row['email'].')</span>
									</li>';
		}
	}
	
	if(!empty($first_level_downline)){
		$first_level_downline = '<div class="tree-wrapper"><ul>'.$first_level_downline.'</ul></div>';
	}
	
	$user->setId($userid);
	$usrdtl = $user->getUserDetail();
	
	$usrdtl['parentid'] = empty($usrdtl['parentid']) ? 0 : $usrdtl['parentid'];
	$userdeposit = empty($usrdtl['deposit'])?0:number_format($usrdtl['deposit'], 2, $decimalseparator, $thousandseparator);
	$stars_level = empty($usrdtl['stars_level'])?0:number_format($usrdtl['stars_level'], 0, $decimalseparator, $thousandseparator);
	$bonus_sharing = empty($usrdtl['bonus_sharing'])?0:number_format($usrdtl['bonus_sharing'], 2, $decimalseparator, $thousandseparator);
	$point_left = empty($usrdtl['point_left'])?0:number_format($usrdtl['point_left'], 2, $decimalseparator, $thousandseparator);
	$point_right = empty($usrdtl['point_right'])?0:number_format($usrdtl['point_right'], 2, $decimalseparator, $thousandseparator);
	$point_used = empty($usrdtl['point_used'])?0:number_format($usrdtl['point_used'], 0, $decimalseparator, $thousandseparator);
	$bonus_point = empty($usrdtl['bonus_point'])?0:number_format($usrdtl['bonus_point'], 2, $decimalseparator, $thousandseparator);
	
	$min_point = $usrdtl['point_left'];
	if($usrdtl['point_right'] < $min_point){
		$min_point = $usrdtl['point_right'];
	}
	
	$remaining_point = $min_point - $usrdtl['point_used'];
	$remaining_point = number_format($remaining_point, 0, $decimalseparator, $thousandseparator) . ' <small>($'.$bonus_point.')</small>';
	
	$upline = $db->fetch_one("SELECT firstname, email FROM user WHERE userid = '".$db->clean($usrdtl['parentid'])."'");
	$upline_name = empty($upline['firstname']) ? '' : $upline['firstname'];
	$upline_email = empty($upline['email']) ? '' : $upline['email'];
	
	require_once "incl/global_template.php";
	
	if ($_GET['type'] == 'point'){
		$tmpl = gettemplate('network-tree');
	}
	else{
		$tmpl = gettemplate('network-referral');
	}
	eval("\$template = \"$tmpl\";");
	echo $template;
?>