<?php
session_start();
include 'session_check.php';
/*include 'get_user_info.php';*/
include 'include/functions.php';

//  fetch total balance,bv,member,register members
$qr="select * from wallet_balance where balance_user_id='$got_unique_id' ";
$connection=mysqli_query($conn,$qr);
if(mysqli_num_rows($connection)>0)
{
    while($rw=mysqli_fetch_array($connection))
    {
        $total_balance=$rw['total_balance'];
        $total_bv=$rw['bv_balance'];
    }
}

//  Get direct joinings
$direct = "select count(unique_user_id) AS direct_user from registration AS R  WHERE R.refferance_id = '$got_unique_id' ";
$con = mysqli_query($conn,$direct);
$direct_data = mysqli_fetch_assoc($con);

// Get total users
$total_users = getAllDownlines(array($got_unique_id));
$total_downline_users = !empty($total_users) && count($total_users)>0 ? count($total_users) : 0;

// Get total registered users
$users = !empty($total_users) && count($total_users)>0 ? $total_users : array();
$total_downline_register_users = getCountPurchasedUsers($users);

// Get total left users
$total_left_users = get_left_or_right_downlines(array($got_unique_id), 'left');
$total_downline_left_users = !empty($total_left_users) && count($total_left_users)>0 ? count($total_left_users) : 0;

$total_downline_left_purchased_users = getCountPurchasedUsers($total_left_users);

// Get total downline right users
$total_downline_right_users = ($total_downline_users-$total_downline_left_users);

$total_right_users = get_left_or_right_downlines(array($got_unique_id), 'right');
$total_downline_right_purchased_users = getCountPurchasedUsers($total_right_users);

// Get total paired user 

//echo $total_downline_right_purchased_users; die;
if((int)$total_downline_left_purchased_users >= (int)$total_downline_right_purchased_users)
{
	$total_carry_user = ((int)$total_downline_users - ((int)$total_downline_right_purchased_users * 2));
	$total_pair_user = $total_downline_right_purchased_users;
}
else
{
	$total_carry_user = ((int)$total_downline_users - ((int)$total_downline_left_purchased_users * 2 ));
	$total_pair_user = $total_downline_left_purchased_users;
}


$percentage = 0;
$referrer_details = get_user_details($got_unique_id);
if($referrer_details !='' && (int)$referrer_details['bonus_percentage'] >0)
{
	$percentage = $referrer_details['bonus_percentage'];
}

// GET THE PRODUCT PRICE TO CALCULATE PERCENTAGE FOR PAIRING. HERE WE ARE TAKING PRICE FROM ANY PRODUCT BECAUSE AS PER THE CLIENT PRODUCT PRICE WILL SAME FOR ALL PRODUCTS
$product_price_to_calculate = 1000;
$product_sql = "SELECT product_price FROM product LIMIT 1";
$connection = mysqli_query($conn, $product_sql);
if(mysqli_num_rows($connection) > 0) {
	$product_details =mysqli_fetch_assoc($connection);
	if(isset($product_details['product_price'])) {
		$product_price_to_calculate = (int)$product_details['product_price'];
	}
}

$commission = ($product_price_to_calculate * $percentage)/100;
$check_prev_pair_reward = "SELECT user_id FROM rewards WHERE LOWER(user_id) = '".strtolower(trim($got_unique_id))."' AND UPPER(user_id) != '".ADMIN_ID."' AND reward_type = 2 ORDER BY id ";
$connection = mysqli_query($conn, $check_prev_pair_reward);
$num_of_pair_already_got = mysqli_num_rows($connection);
$result =mysqli_fetch_assoc($connection);

// (int)$percentage >0  check is applicable for pairing bonus
if($num_of_pair_already_got <$total_pair_user && (int)$percentage >0)
{
	for($i=0; $i<($total_pair_user-$num_of_pair_already_got); $i++)
	{
		$check = "SELECT count(id) as today_number_of_paired FROM `rewards` where date(`reward_date`) = '".date('Y-m-d')."' AND user_id = '$got_unique_id' AND reward_type =2 ";
		$con = mysqli_query($conn, $check);
		if(mysqli_num_rows($con)>0)
		{
			$result = mysqli_fetch_assoc($con);
		}
		
		if(isset($result['today_number_of_paired']) && (int)$result['today_number_of_paired'] <= (int)MAX_NUMBER_OF_PAIR_PER_DAY && (int)$commission>0)
		{
			wallet($wallet = array('sender_id'=> ADMIN_ID, 'receiver_id'=>  $got_unique_id, 'amount'=> $commission));
			
			$wallet_arr = array(
				'sender_id'			=>	ADMIN_ID,
				'receiver_id'		=>	$got_unique_id,
				'amount'			=>	$commission,
				'respective_user'	=>	null,
				'transaction_type'	=>	4,  //  Purchasing commission for referrer
				'remarks'			=>  'You have got pairing bonus',
				'status'			=>	1,
				'transaction_id'	=>  get_unique_id('t')
			);
			add_wallet_history($wallet_arr);
		
			// Reward give to referrer user
			
			$reward = array(
				'user_id'			=>	$got_unique_id,
				'reward'			=>	'Rs. '.$commission,
				'reward_desc'		=>	'Congratulations, you have got your pairing bonus',
				'respective_user'	=>	null,
				'reward_type'		=>  2,
				'status'			=>	1, //  received
				'remarks'			=>  'Congratulations, you have got your pairing bonus',
				'status'			=>	1,
				'transaction_id'	=>  get_unique_id('r')
			);
			give_reward($reward);
		}
	}
}

/**  Main pair calculations like [ 100,200,400 ]  pairs */
//  check for pair level
$pair_user_details = get_user_details($got_unique_id);

if((int)$percentage >0 && isset($pair_user_details['pair_count']) && (int)$pair_user_details['pair_count'] < (int)$total_pair_user)
{
	$pair_details = get_pair_msg((int)$total_pair_user);
	if($pair_details !='')
	{	
		//Reward give to referrer user
		$main_reward = array(
			'user_id'			=>	$got_unique_id,
			'reward'			=>	(int)$total_pair_user,
			'reward_desc'		=>	$pair_details,
			'respective_user'	=>	null,
			'reward_type'		=>  3,
			'status'			=>	1, //  received
			'remarks'			=>  'You have completed '.(int)$total_pair_user.' pairs',
			'status'			=>	1,
			'transaction_id'	=>  get_unique_id('r')
		);
		give_reward($main_reward);
		
		
		// Update pair count 100, 200, 500
		$update_pair_count = "UPDATE registration SET pair_count = '".(int)$total_pair_user."' WHERE unique_user_id = '$got_unique_id' ";
		mysqli_query($conn, $update_pair_count);
	}
}

?>
	<head>
    <meta charset="UTF-8">
    <title>AdminLTE 2 | Dashboard</title>
    <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
    <!-- Bootstrap 3.3.2 -->
    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />    
    <!-- FontAwesome 4.3.0 -->
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <!-- Ionicons 2.0.0 -->
    <link href="https://code.ionicframework.com/ionicons/2.0.0/css/ionicons.min.css" rel="stylesheet" type="text/css" />    
    <!-- Theme style -->
    <link href="dist/css/AdminLTE.min.css" rel="stylesheet" type="text/css" />
    <!-- AdminLTE Skins. Choose a skin from the css/skins 
         folder instead of downloading all of them to reduce the load. -->
    <link href="dist/css/skins/_all-skins.min.css" rel="stylesheet" type="text/css" />
    <!-- iCheck -->
    <link href="plugins/iCheck/flat/blue.css" rel="stylesheet" type="text/css" />
    <!-- Morris chart -->
    <link href="plugins/morris/morris.css" rel="stylesheet" type="text/css" />
    <!-- jvectormap -->
    <link href="plugins/jvectormap/jquery-jvectormap-1.2.2.css" rel="stylesheet" type="text/css" />
    <!-- Date Picker -->
    <link href="plugins/datepicker/datepicker3.css" rel="stylesheet" type="text/css" />
    <!-- Daterange picker -->
    <link href="plugins/daterangepicker/daterangepicker-bs3.css" rel="stylesheet" type="text/css" />
    <!-- bootstrap wysihtml5 - text editor -->
    <link href="plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css" rel="stylesheet" type="text/css" />
	
	<!-----		sweet alert css and js link	---->
	<link rel="stylesheet" href="dist/sweetalert.css">
	<script src="dist/sweetalert.min.js"> </script>
   
   
	<link rel="stylesheet" type="text/css" href="custom/custom.css">
	<!---- Ck editor-->
	 <script src="ckeditor/ckeditor.js"></script>
	     <script type="text/javascript" src="js/Chart.min.js"></script>
	 <style>
	    .blur {
		background-size:cover;
		-webkit-filter: blur(6px);
		-moz-filter: blur(6px);
		-ms-filter: blur(6px);
		-o-filter: blur(6px);
		filter: blur(6px);
		}
	 </style>
	 
  </head>

<?php
include 'include/header.php';
include 'include/left-nav.php';
?>
      <!-- Right side column. Contains the navbar and content of the page -->
     
	  <div class="content-wrapper <?php echo $is_disabled == TRUE ? 'blur' : ''; ?>">
	   
        <!-- Content Header (Page header) -->
        <section class="content-header">
          <h1>
            Dashboard
            <small>Control panel</small>
          </h1>
          <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
            <li class="active">Dashboard</li>
          </ol>
        </section>

        <!-- Main content -->
        <section class="content">
            <div class="alert alert-warning alert-dismissible fade in" id="warn_msg" style="display: none">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                    <strong>Warning!</strong> This is demo window and a demo user can't make changes any fields.
           </div>
          <!-- Small boxes (Stat box) -->
          <div class="row">
            <div class="col-lg-3 col-xs-6">
              <!-- small box -->
              <div class="small-box bg-aqua">
                <div class="inner">
                  <h3><?php echo isset($total_balance) ? number_format((float)$total_balance, 2, '.', '') : 0.00?></h3>
                  <p>Total balance</p>
                </div>
                <div class="icon">
                  <i class="fa fa-money"></i>
                </div>
               <!--<a href="wallet.php" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a>-->
              </div>
            </div><!-- ./col -->
            <div class="col-lg-3 col-xs-6">
              <!-- small box -->
              <div class="small-box bg-green">
                <div class="inner">
                  <h3><?php echo isset($direct_data['direct_user']) ? $direct_data['direct_user'] : 0?></h3>
                  <p>Direct Joining</p>
                </div>
                <div class="icon">
                  <i class="ion ion-stats-bars"></i>
                </div>
                <!--<a href="direct_joining_report.php" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a>-->
              </div>
            </div><!-- ./col -->
            <div class="col-lg-3 col-xs-6">
              <!-- small box -->
              <div class="small-box bg-yellow">
                <div class="inner">
                  <h3>
					<?php
						echo $total_downline_users;
					?>
				 </h3>
                  <p>Total members</p>
                </div>
                <div class="icon">
                  <i class="ion ion-person-add"></i>
                </div>
                <!--<a href="javascript:void(0)" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a>-->
              </div>
            </div><!-- ./col -->
            <div class="col-lg-3 col-xs-6">
              <!-- small box -->
              <div class="small-box bg-red">
                <div class="inner">
                  <h3><?php echo $total_downline_register_users;?></h3>
                  <p>Total purchased members</p>
                </div>
                <div class="icon">
                  <i class="ion ion-person-add"></i>
                </div>
                <!--<a href="javascript:void(0)" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a>-->
              </div>
            </div><!-- ./col -->
			<div class="col-lg-3 col-xs-6">
              <!-- small box -->
              <div class="small-box bg-aqua">
                <div class="inner">
                  <h3><?php echo $total_downline_left_users;?></h3>
				  <p>Total left user join</p>
                </div>
                <div class="icon">
                  <i class="ion ion-stats-bars"></i>
                </div>
              <!-- <a href="javascript:void(0)" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a>-->
              </div>
            </div><!-- ./col -->
			 <div class="col-lg-3 col-xs-6">
              <!-- small box -->
              <div class="small-box bg-aqua">
                <div class="inner">
                  <h3><?php echo $total_downline_right_users;?></h3>
                  <p>Total right user join</p>
                </div>
                <div class="icon">
                  <i class="ion ion-stats-bars"></i>
                </div>
               <!--<a href="javascript:void(0)" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a>-->
              </div>
            </div><!-- ./col -->
			
			<div class="col-lg-3 col-xs-6">
              <!-- small box -->
              <div class="small-box bg-aqua">
                <div class="inner">
                  <h3><?php echo $total_pair_user;?></h3>
                  <p>Total paired user</p>
                </div>
                <div class="icon">
                   <i class="ion ion-stats-bars"></i>
                </div>
               <!--<a href="javascript:void(0)" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a>-->
              </div>
            </div><!-- ./col -->
			<div class="col-lg-3 col-xs-6">
              <!-- small box -->
              <div class="small-box bg-aqua">
                <div class="inner">
                  <h3><?php echo $total_carry_user;?></h3>
                  <p>Total carry user</p>
                </div>
                <div class="icon">
                  <i class="ion ion-stats-bars"></i>
                </div>
               <!--<a href="javascript:void(0)" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a>-->
              </div>
            </div><!-- ./col -->
			 
          </div><!-- /.row -->
          <!-- Main row -->
    <div class="row">
        <section class="col-lg-6 connectedSortable">
           <div class="row">
				<div class="col-sm-12" style="padding: 25px 20px; font-size: 18px; font-weight: 600">
					NEW REGISTER USER
				</div>
		   </div>
		  <div class="row" style="padding: 5px 20px">
				<div class="box box-info" style="padding: 5px 20px">
					  <div class="">
						  <table class="table table-bordered" style="">
							<thead>
							  <tr>
								<th>user id</th>
								<th> Name </th>
								<th> Purchase status </th>
								<!--<th> Rank </th>-->
								<th>Joining date</th>
							  </tr>
							</thead>
							<tbody>
						  <?php
						       $user_list = is_array($total_users) && $total_users !='' && count($total_users)>0 ? $total_users : array(); 
                                    $result = "'" . implode ( "', '", $user_list ) . "'";
                                   $qr1="select unique_user_id, user_name, active_deactive, created_date  from registration
                                    where unique_user_id  IN ($result)  and unique_user_id NOT IN ('B00001') order by created_date DESC limit 4";
                                    $con1=mysqli_query($conn,$qr1);
                                    
                                    if(mysqli_num_rows($con1)>0)
                                    {
                                        while($rows=mysqli_fetch_array($con1))
                                        {
                            ?>
    							  <tr>
    								<td> <?php echo $rows['unique_user_id'];?> </td>
    								<td><?php echo $rows['user_name'];?></td>
    								<td>
    								    <?php
    								        if($rows['active_deactive'] !=1)
    								        {
    								            echo 'No';
    								        }
    								        else
    								        {
    								            echo 'Yes';
    								        }
    								    ?>
    								</td>
    								<td><?php echo $rows['created_date'];?></td>
    							  </tr>
				              <?php
							            }
							        }
				              ?>
							</tbody>
						  </table>
					</div>
				</div>
			</div>
            </section><!-- /.Left col -->
            
            </div>
            <div class="row">
           
            <div class="row">       
            
           <!-- <section class="col-lg-7 connectedSortable">
             
             <?php
             //include 'fetch_graph_dashboard.php';
             ?>

            </section>--><!-- /.Left col -->
            <!-- right col (We are only adding the ID to make the widgets sortable)-->
            <input type="hidden" value="<?php echo $_SESSION['account_type'];?>" id="fetch_session">
            <section class="col-lg-5 connectedSortable">

              

            </section><!-- right col -->
          </div><!-- /.row (main row) -->

        </section><!-- /.content -->
      </div><!-- /.content-wrapper -->

    
	
	<div class="container">
	<!-- Modal -->
	<div class="modal fade" style="z-index: 9999" id="product_purchase_msg" role="dialog">
	<div class="modal-dialog" style="margin-top: 2%;">

	  <!-- Modal content-->
	  <div class="modal-content col-sm-8 col-sm-offset-2">
	   
		<div class="modal-body">
		<form method="POST">
		
			<div class="row" style="text-align: center; padding-top: 10px">
				<h5 style="font-weight: 400; color: #4f565a; font-size: 17px; font-family: "Brandon Grotesque","proxima-nova","Helvetica Neue",Helvetica,Arial,sans-serif"> 
					System alert <span id="md_user_name">  </span>  
				</h5>
			</div>
			<br>
			<div class="row">
				<div class="form-group">
					<div class="col-sm-8 col-sm-offset-2" style="color: black; font-size: 18px; text-align: center">
						Please purchase any product to continue uninterruptible services.
						<br>
						 <span id="md_msg">  </span>
					</div>
				</div>
			</div>
			<br>
			<div class="row">
				<div class="form-group">
					<div class="text-center">
						<input type="button" class="btn btn-info" id="" data-dismiss="modal" value="Cancel">
					</div>
				</div>
			</div>
		</form>
		</div>
		
	  </div>
	  
	</div>
	</div>
	</div>

  


	
		 <!-- jQuery 2.1.3 -->
    <script src="plugins/jQuery/jQuery-2.1.3.min.js"></script>
    <!-- jQuery UI 1.11.2 -->
    <script src="https://code.jquery.com/ui/1.11.2/jquery-ui.min.js" type="text/javascript"></script>
    <!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
    <?php
    if($status=='Deactive')
    {
        include 'modal_show.php';
    }
    ?>
    
    <script>
      $.widget.bridge('uibutton', $.ui.button);
    </script>
    <!-- Bootstrap 3.3.2 JS -->
    <script src="bootstrap/js/bootstrap.min.js" type="text/javascript"></script>    
    <!-- Morris.js charts -->
   <!-- <script src="http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>-->
    <!---<script src="plugins/morris/morris.min.js" type="text/javascript"></script>-->
    <!-- Sparkline -->
    <script src="plugins/sparkline/jquery.sparkline.min.js" type="text/javascript"></script>
    <!-- jvectormap -->
    <script src="plugins/jvectormap/jquery-jvectormap-1.2.2.min.js" type="text/javascript"></script>
    <script src="plugins/jvectormap/jquery-jvectormap-world-mill-en.js" type="text/javascript"></script>
    <!-- jQuery Knob Chart -->
    <script src="plugins/knob/jquery.knob.js" type="text/javascript"></script>
    <!-- daterangepicker -->
    <script src="plugins/daterangepicker/daterangepicker.js" type="text/javascript"></script>
    <!-- datepicker -->
    <script src="plugins/datepicker/bootstrap-datepicker.js" type="text/javascript"></script>
    <!-- Bootstrap WYSIHTML5 -->
    <script src="plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js" type="text/javascript"></script>
    <!-- iCheck -->
    <script src="plugins/iCheck/icheck.min.js" type="text/javascript"></script>
    <!-- Slimscroll -->
    <script src="plugins/slimScroll/jquery.slimscroll.min.js" type="text/javascript"></script>
    <!-- FastClick -->
    <script src='plugins/fastclick/fastclick.min.js'></script>
    <!-- AdminLTE App -->
    <script src="dist/js/app.min.js" type="text/javascript"></script>
    <script>
	 //$('#example').DataTable();
    </script>
    <script>
        $(document).ready(function () {
		
		var is_product_purchased = '<?php echo $is_disabled ?>';
		if(typeof(is_product_purchased) !='uefined' && is_product_purchased == true)
		{
			$('#product_purchase_msg').modal('show');
		}
		
		$('#product_purchase_msg').on('hidden.bs.modal', function () {    
			window.location.href="buy_products.php";
		});
	
	
            // for demo user warning
            var demo_user=$("#demo_user_id").val();
            if(demo_user=='demo_user')
            {
                $(".disable_btn").attr('disabled',true);
                $("#warn_msg").show();
            }
            
            var xyz=$("#fetch_session").val(); 
            if(xyz=='user')
            {
                var user_id=<?php echo json_encode($get_all_members);?>;
                showGraph('2019',user_id);
                $("#slt_year").change(function(){
                     showGraph(this.value,user_id);
                });
            }
            else
            {
                showGraph_admin('2019');
                $("#slt_year").change(function(){
                     showGraph_admin(this.value);
                });
            }
        });


        function showGraph(year,user_id)
        {
            {
                $.post("data.php?year="+year+"&user_id="+user_id,
                function (data)
                {
                    var xyz= ['January','February','March','April','May','June','July','August','Septepber','October','November','December'];
                   var aa=JSON.parse(data);
                   // alert(data);
                    var chartdata = {
                        labels: xyz,
                        datasets: [
                            {
                                label: 'User joined',
                                backgroundColor: '#49e2ff',
                                borderColor: '#46d5f1',
                                hoverBackgroundColor: '#CCCCCC',
                                hoverBorderColor: '#ffffff',
                                data: aa
                            }
                        ]
                    };
                    var graphTarget = $("#graphCanvas");
                    var barGraph = new Chart(graphTarget, {
                        type: 'line',
                        data: chartdata
                    });
                });
            }
        }
         function showGraph_admin(year)
        {
            {
                $.post("data_admin.php?year="+year,
                function (data)
                {
                    var xyz= ['January','February','March','April','May','June','July','August','Septepber','October','November','December'];
                    var aa=JSON.parse(data);
                    //alert(data);
                    var chartdata = {
                        labels: xyz,
                        datasets: [
                            {
                                label: 'User joined',
                                backgroundColor: '#49e2ff',
                                borderColor: '#46d5f1',
                                hoverBackgroundColor: '#CCCCCC',
                                hoverBorderColor: '#ffffff',
                                data: aa
                            }
                        ]
                    };
                    var graphTarget = $("#graphCanvas");
                    var barGraph = new Chart(graphTarget, {
                        type: 'line',
                        data: chartdata
                    });
                });
            }
        }
        </script>
    <!-- AdminLTE dashboard demo (This is only for demo purposes) -->
   <!-- <script src="dist/js/pages/dashboard.js" type="text/javascript"></script>-->
	<script src="js/custom.js"></script>
	  
<?php
include 'include/footer.php';
?>