<?php session_start();

include_once('includes/headerincludes.php');
include_once("includes/dbconfig.php");
include_once("functions/allfunctions.php");


if(empty($_SESSION["MEMBER_ID"]) && empty($_SESSION["TYPE"]))
{
    $itemarray = array();
}
else
{
  $memberid = $_SESSION['MEMBER_ID'];
  $type = $_SESSION['TYPE'];
}

//before we store information of our member, we need to start first the session


	//create a new function to check if the session variable member_id is on set
	function logged_in() {
		return isset($_SESSION['MEMBER_ID']);

	}
	//this function if session member is not set then it will be redirected to index.php
	function confirm_logged_in() {
		if (!logged_in()) {

?>
			<script type="text/javascript">
				window.location = "pages/login.php";
			</script>
<?php
		}
	}
	confirm_logged_in();

?>
<html>
<!DOCTYPE html>
<head>
    <title>GBG Enterprise - Dashboard</title>
    <style>body { margin: 0 }
    .sunburst-viz .slice path {
                  cursor: pointer;
              }

              .sunburst-viz text {
                  font-family: sans-serif;
                  font-size: 12px;
                  dominant-baseline: middle;
                  text-anchor: middle;
                  pointer-events: none;
                  fill: #222;
              }

              .sunburst-viz text .text-contour {
                  fill: none;
                  stroke: white;
                  stroke-width: 5;
                  stroke-linejoin: "round";
              }

              .sunburst-viz .main-arc {
                  stroke: white;
                  stroke-width: 5px;
                  transition: opacity .4s;
              }

              .sunburst-viz .main-arc:hover {
                  opacity: 0.85;
                  transition: opacity .05s;
              }

              .sunburst-viz .hidden-arc {
                  fill: none;
              }

              .sunburst-tooltip {
                  display: none;
                  position: absolute;
                  max-width: 320px;
                  white-space: nowrap;
                  padding: 5px;
                  border-radius: 3px;
                  font: 12px sans-serif;
                  color: #eee;
                  background: rgba(0, 0, 0, 0.65);
                  pointer-events: none;
              }

              .sunburst-tooltip .tooltip-title {
                  font-weight: bold;
                  text-align: center;
                  margin-bottom: 5px;
              }
    </style>
</head>

      <body id="page-top">

    <!-- Page Wrapper -->
    <div id="wrapper">

        <!-- Sidebar -->
        <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">

            <!-- Sidebar - Brand -->
            <a class="sidebar-brand d-flex align-items-center justify-content-center" href="index.php">
                <div class="sidebar-brand-icon">
                    <img src="img/gbg.jpg" alt="Company Logo" class="img-thumbnail">
                </div>
                <div class="sidebar-brand-text mx-3">GBG Enterprise</div>
            </a>

            <!-- Divider -->
            <hr class="sidebar-divider my-0">

            <!-- Nav Item - Dashboard -->
            <li class="nav-item active">
                <a class="nav-link" href="index.php">
                    <i class="fas fa-fw fa-tachometer-alt"></i>
                    <span>Dashboard</span></a>
            </li>

            <!-- Divider -->
           <?php echo sidebar(); ?>


            <!-- Divider -->
       <!--     <hr class="sidebar-divider">-->



            <!-- Divider -->
            <hr class="sidebar-divider d-none d-md-block">



        </ul>
        <!-- End of Sidebar -->

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">

            <!-- Main Content -->
            <div id="content">

                <!-- Topbar -->
                <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">

                    <!-- Sidebar Toggle (Topbar) -->
                    <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
                        <i class="fa fa-bars"></i>
                    </button>


                    <!-- Topbar Navbar -->
                    <ul class="navbar-nav ml-auto">




                        <!-- Nav Item - User Information -->
                       <?php echo logindetails(); ?>

                    </ul>

                </nav>
                <!-- End of Topbar -->

                <!-- Begin Page Content -->
                <div class="container-fluid">
				 <?php
				 ?>

         <?php

         $con2 = mysqli_connect(get_dbserver(),get_dbuser(),get_dbpassword(),get_dbname());

         function getTblNumRows2($tbl,$extraCondition)
         {
             $con = mysqli_connect(get_dbserver(),get_dbuser(),get_dbpassword(),get_dbname());
             //$strSQL = 'SELECT count(*) FROM test WHERE parent_id='.$id';
             $strSQL = "SELECT count(*) as total FROM ".$tbl." where ".$extraCondition." ";
             $sqlQuery = mysqli_query($con,$strSQL);
             //$numRows = mysqli_num_rows($sqlQuery);
             while($row = mysqli_fetch_array($sqlQuery,MYSQLI_ASSOC)) {
               if($row['total'] >0)
               {
                 return $row['total'];
               }
               else
               {
                   return 0;
               }
             }
             mysqli_close($con);

         }

         $id = 1;
         $numRows = getTblNumRows2('test','parent_id = "'.$id.'"');
         $index = array();
         $val  = array();


         //retrieve Data from DB
         //$strSQL1 = "SELECT *  FROM test where parent_id=".$id." ";
         $strSQL1 = "SELECT id as id,name as name,parent_id as parent_id,amount as amount FROM test";
         $sqlQuery1 = mysqli_query($con2,$strSQL1);
         //$numRows = mysqli_num_rows($sqlQuery);
         while($rows = mysqli_fetch_array($sqlQuery1,MYSQLI_ASSOC)) {
           //$val = array($rows['id'] => $rows['parent_id']);
           $val[] = $rows;
           //$val[] = array_column($rows, 'name', 'parent_id');
           //var_dump($val);
         }
        print_r($val);
         mysqli_close($con2);

       //JSON Creation
       $results = array();
       $tree = array();
       foreach($val as $item){
            if(!isset($tree[$item['id']])) $tree[$item['id']] = array();
            $tree[$item['id']] = array_merge($tree[$item['id']],$item);
            if(!isset($tree[$item['parent_id']])) $tree[$item['parent_id']] = array();
            if(!isset($tree[$item['parent_id']]['children'])) $tree[$item['parent_id']]['children'] = array();
            $tree[$item['parent_id']]['children'][] = &$tree[$item['id']];
       }

       $result = $tree[0]['children'];

       unset($tree);

       function removeElementWithValue($array, $key, $value){
            foreach($array as $subKey => $subArray){
                 if($subArray[$key] == $value){
                      unset($array[$subKey]);
                 }
            }
            return $array;
       }

       $array2 = removeElementWithValue($result, "id",1);
       //print_r($array2);


       $value = 4;
       foreach ($result as $i => $v) {
           if ($v['id'] == $value) {
               unset($result[$i]);
           }
       }
       //print_r($result);
       //$array3 = removeElementWithValue($array2, "id");

         function buildTree(array $elements, array $branch, $parentId=0) {
             // group elements by parents if it does not comes on the parameters
             if (empty($branch)) {
                 $branch = array();

                 foreach ($elements as $element) {
                     $branch[$element["parent_id"]][$element["name"]] = $element;
                 }
             }

             // echo the childs referenced by the parentId parameter
             if (isset($branch[$parentId])) {
                 echo'<ul>';
                 $total = 0;
                 foreach ($branch[$parentId] as $keyBranch => $itemBranch) {
                     echo '<li> Name: '.$itemBranch['name'];
                     $amount= (int)$itemBranch['amount'];
                     //echo $amount;
                     $total = $total + $amount;
                     //echo $total .'-'. $amount;
                     echo '<li> Referral Amount: '. $itemBranch['amount'];
                     echo '<li> <b>Total Sales Amount: '. $itemBranch['totalamount'].'</b>';
                     //echo '<li> Amount: '. array_sum(intval($itemBranch['amount']));
                     buildTree($elements, $branch, $itemBranch["id"]); // iterate with the actual Id to check if this record have childs
                     echo '</li>';
                 }

                 echo '</ul>';
             }
         }


         function Tablebuild(array $elements, array $branch, $parentId=0) {
             // group elements by parents if it does not comes on the parameters

             if (empty($branch)) {
                 $branch = array();

                 foreach ($elements as $element) {
                     $branch[$element["parent_id"]][$element["name"]] = $element;
                 }
             }

             // echo the childs referenced by the parentId parameter
             if (isset($branch[$parentId])) {
                  echo '<tbody>';
                 echo'<tr>';
                 $total = 0;
                 foreach ($branch[$parentId] as $keyBranch => $itemBranch) {
                     echo '<td>'.$itemBranch['name'].'</td>';
                     $amount= (int)$itemBranch['amount'];
                     //echo $amount;
                     $total = $total + $amount;
                     //echo $total .'-'. $amount;
                     $parent_name = getRecord('name','test','id ='.$itemBranch['parent_id']);
                     echo '<td>'.$parent_name.'</td>';
                     echo '<td> <b>'. $itemBranch['amount'].'</b></td>';
                     //echo '<li> Amount: '. array_sum(intval($itemBranch['amount']));
                     echo'<tr>';Tablebuild($elements, $branch, $itemBranch["id"]); // iterate with the actual Id to check if this record have childs
                     echo '</tr>';
                 }

                 echo '</tr>';
                 echo '</tbody>';
             }

         }
  /*       echo'<table border=1 id="myTable">';
         echo'<th>Name</th>';
         echo'<th>Referral</th>';
         echo'<th>Amount</th>';
         Tablebuild($val, array());
         echo'</table>'; */
    //     buildTree($val, array());

       /*
         foreach($val as $i =>$row)
         {
             //$numRows = getTblNumRows('test','parent_id = "'.$i.'"');
             //echo getTblNumRows('test','parent_id = "'.$i.'"');
             if (getTblNumRows('test','parent_id = "'.$i.'"')) {
                 $index[$row['id']] = $row;
                 //echo "<pre>".print_r($index[$row['id']])."</pre>";
             }
         }


         foreach($index as $id => $indexRow)
         {
             if ($id === 1) continue;
             //echo "<pre>".print_r($index)."</pre>";

           //  echo "<pre>".print_r($id)."</pre>";

           //  echo "<pre>".print_r($indexRow)."</pre>";
             $parent = $indexRow['size'];
             $index[$parent]['children'][] = $indexRow;
             //echo "<pre>".print_r($index[$parent]['children'])."</pre>";
             //$index = array_column($index, 'name', 'parent_id');
         }

         unset($indexRow);


       */


           $json = json_encode($result,JSON_PRETTY_PRINT);
         	$filename = "testing.json";
         	if(file_put_contents($filename, $json)){
         		//echo "Json file created";
         	}
         	else{
         		//echo "An error occured in creating the file";
         	}

          ?>
          <script>

          $(document).ready( function () {


} );
            const color = d3.scaleOrdinal(d3.schemeCategory10 );


            var SI_SYMBOL = ["", "k", "M", "G", "T", "P", "E"];

    function abbreviateNumber(number){

        // what tier? (determines SI symbol)
        var tier = Math.log10(Math.abs(number)) / 3 | 0;

        // if zero, we don't need a suffix
        if(tier == 0) return number;

        // get suffix and determine scale
        var suffix = SI_SYMBOL[tier];
        var scale = Math.pow(10, tier * 3);

        // scale the number
        var scaled = number / scale;

        // format number and add suffix
        return scaled.toFixed(1) + suffix;
    }

    function updatedatachart(number){
        //alert(number);
        var quotation_id = number;

        			$.ajax({
        			 type: "GET",
        			 url: "functions/getsunburstdata.php",
        			 data: {qid : quotation_id },
        			 success: function (data) {
        				 	//alert(data);
        					 //$(".customeradd").addClass('hidden');
        					 $(".userDataTable").html(data);
                   //$(".userDataTable").html("TEST");
                   //$(".userDataTable").hide();
        					 //alert(data);


        			 }
        		 });
    }


            const myChart = Sunburst();
            fetch("test3.json").then(res => res.json()).then(data => {
              myChart()
                //.onClick((d=> updatedatachart(d.name)))
                .onNodeClick((node) => {
                  myChart.focusOnNode(node);
                  updatedatachart(node.name);
                })
                //.onClick(Sunburst.focusOnNode)
                .width(640)
                .height(480)
                .data(data)
                .label("name")
                .size("amount")
                .color((d, parent) => color(parent ? parent.data.name : null))
                .tooltipContent((d, node) => `Sale: <i>${kFormatter(node.value)}</i>`)
                (document.getElementById("chart"))
            });
            function kFormatter(num) {
            return Math.abs(num) > 999 ? Math.sign(num)*((Math.abs(num)/1000).toFixed(1)) + 'k' : Math.sign(num)*Math.abs(num)
            }
            var SI_SYMBOL = ["", "k", "M", "G", "T", "P", "E"];

            function abbreviateNumber(number){

                // what tier? (determines SI symbol)
                var tier = Math.log10(Math.abs(number)) / 3 | 0;

                // if zero, we don't need a suffix
                if(tier == 0) return number;

                // get suffix and determine scale
                var suffix = SI_SYMBOL[tier];
                var scale = Math.pow(10, tier * 3);

                // scale the number
                var scaled = number / scale;

                // format number and add suffix
                return scaled.toFixed(1) + suffix;
            }
            function testf() {
                alert("test");
            }

          </script>
				     <!-- Earnings (Monthly) Card Example -->
                          <!-- Earnings (Monthly) Card Example -->
                          <div class="row gy-5">
                              <div class="col-lg-12">
                                <div class="card border-left-info shadow h-100 py-2">
                                  <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                      <div class="col mr-2">
                                        <div class="text-sm font-weight-bold text-info text-uppercase mb-4">Agent Form</div>
                                        <div class="row  align-items-center">
                                          <div class="col-12 customerdata" id="quotationdata">
                                            <div class="form-group row" >
                                                 <div class="form-group col-4" >
                                                  <?php         // buildTree($val, array());
                                                  echo'<table class="table table-bordered userDataTable" id="userDataTable" width="100%" cellspacing="0">';
                                                  echo'<thead>';
                                                  echo'<th>Name</th>';
                                                  echo'<th>Referred by</th>';
                                                  echo'<th>Amount</th>';
                                                  echo'</thead>';
                                                  Tablebuild($val, array());
                                                  echo'</table>';
                                                  ?>
                                                  </div>
                                                   <div class="form-group col-4" >
    											                                 <div id="chart"></div>
                                                  </div>
                        											</div>
                                        </div>
                                      </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                  </div>



	<!--						<div class="alert alert-warning" role="alert">
							<div class="col-sm-4">
								<i class="fas fa-exclamation-triangle fa-2x text-gray-300"></i>



							</div>
							</div> -->
                    <!-- Page Heading -->




                    <!-- Content Row -->
                    <div class="row col-lg-8">
					<div class="row gy-5"> <div id="chart"></div></div>
					<div class="row gy-5"> </div>
					<div class="row gy-5"> </div>
					<div class="row gy-5"> </div>
					<div class="row gy-5"> </div>
					<div class="row gy-5"> </div>
					<div class="row gy-5"> </div>
					<div class="row gy-5"> </div>
					<div class="row gy-5"> </div>
					<div class="row gy-5"> </div>
					<div class="row gy-5"> </div>
					<div class="row gy-5"> </div>
					<div class="row gy-5"> </div>
					<div class="row gy-5"> </div>


                </div>
                <!-- /.container-fluid -->

            </div>
            <!-- End of Main Content -->

            <!-- Footer -->
            <footer class="sticky-footer bg-white">
                <div class="container my-auto">
                    <div class="copyright text-center my-auto">
                        <span>Copyright &copy; GBG 2020</span>
                    </div>
                </div>
            </footer>
            <!-- End of Footer -->

        </div>
        <!-- End of Content Wrapper -->

    </div>
    <!-- End of Page Wrapper -->

    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <!-- Logout Modal-->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="../gbgv2/destroy.php">Logout</a>
                </div>
            </div>
        </div>
    </div>






  </body>
</html>
