<?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;
         $idtest = 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,totalamount as amount  FROM test";
      /*   $strSQL1 = "select
            p1.id as id,
            p1.name,
            p1.parent_id as parent_id,
            p1.amount
from test as p1
            left join   test as p2 on p2.id = p1.parent_id
            left join   test as p3 on p3.id = p2.parent_id
            left join   test as p4 on p4.id = p3.parent_id
            left join   test as p5 on p5.id = p4.parent_id
where       2 in (p1.parent_id,
                   p2.parent_id,
                   p3.parent_id,
                   p4.parent_id,
                   p5.parent_id)

order       by 1"; */
       $a = array();
/* $strSQL1 = "select  id,
        name,
        parent_id,
        amount
from    (select * from test
         order by parent_id, id) products_sorted,
        (select @pv := '".$idtest."') initialisation
where   find_in_set(parent_id, @pv)
and     length(@pv := concat(@pv, ',', id)) ";

 $strSQL1 = "select @pv:=id as id, name, parent_id,amount from test
join
(select @pv:='".$idtest."')tmp
where parent_id=@pv"; */
      //  $strSQL1 = "SELECT id,name,parent_id,amount  FROM test where  parent_id!=0 order by parent_id";

      $strSQL1 = "select  id,
             name,
             parent_id,
             amount
     from    (select * from test
              order by parent_id, id) products_sorted,
             (select @pv := '".$idtest."') initialisation
     where   find_in_set(parent_id, @pv)
     and     length(@pv := concat(@pv, ',', id))";

      //$strSQL1 = "SELECT id,name,parent_id,amount  FROM test where  parent_id!=0 order by parent_id";
         $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;
          // $a = array("id"=>$rows['id'], "name"=>$rows['name'], "parent_id"=>'0', "amount"=>$rows['amount']);
           //$val[] = array_column($rows, 'name', 'parent_id');
            //var_dump($a);
            //array_push($val,$a);
           //var_dump($val);
           //$val[] = array_column($rows, 'name', 'parent_id');
            //var_dump($val);
         }
//echo $strSQL1;

          //$strSQL1 = "SELECT id,name,parent_id,amount  FROM test where  id=".$idtest."  ";
            //$strSQL1 = "SELECT id,name,parent_id,amount  FROM test where  parent_id=1 order by parent_id";
            $strSQL1 = "SELECT id,name,parent_id,amount  FROM test where id=".$idtest." ";
          $sqlQuery2 = mysqli_query($con2,$strSQL1);
          //$numRows = mysqli_num_rows($sqlQuery);
          while($rows = mysqli_fetch_array($sqlQuery2,MYSQLI_ASSOC)) {
            //$val = array($rows['id'] => $rows['parent_id']);


            $a = array("id"=>$rows['id'], "name"=>$rows['name'], "parent_id"=>'0', "amount"=>$rows['amount']);
            //$val[] = array_column($rows, 'name', 'parent_id');
             //var_dump($a);
             array_push($val,$a);
            // print_r($val);
          //   var_dump($val);
             // code...

          }
          //$a = array("id"=>"2", "name"=>"Robert", "parent_id"=>"0", "amount"=>"50");

          mysqli_close($con2);


       //JSON Creation
       $result = 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']];
       }
       if(empty($tree))
       {
         $result = "";
       }
       else {

         $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 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) {


                    $parent_name = getRecord('name','test','id ='.$itemBranch['parent_id']);
                    $agentID = getRecordbyID('id','test','name ="'.$itemBranch['name'].'"');
                    $getlevel = getRecord('commisionsoldby','sales','soldby ='.$agentID);
                    $amount= (int)$itemBranch['amount'];
                    //echo $amount;
                    $total = $total + $amount;
                    $datecreated = getRecord('datecreated','sales','soldby ='.$agentID);
                     echo'<tr>';
                     //echo '<td> <b data-toggle="modal" class="trhistory" data-target="#historymodal">'.$datecreated.'</b></td>';
                     echo '<td visible="hidden"><b data-toggle="modal" class="trhistory" data-target="#historymodal">'.$datecreated.'</b></td>';
                     echo '<td><b data-toggle="modal" class="trhistory" data-target="#historymodal">'.$itemBranch['name'].'</b></td>';
                     //$agent_id =  1;
                     //$agentnamelevel1 = GetAgentLevelFromParent($agent_id,"lev1");
                     //if($agentnamelevel1!="" && $agentnamelevel1=$itemBranch['name'])
                     //{
                      // echo $agentname;
                      //echo $agentID;
                        $comission = 0;
                        //$agentID = getRecord('id','test','name ='.$itemBranch['name']);
                        //echo $getlevel;
                        if($getlevel == "Level 1")
                        {
                      /*    $comission = GetDataUsingSQL("select
            										 sum(level1) as level1
            						 from    (select * from sales
            						          order by soldby) products_sorted,
            						         (select @pv := '".$agentID."') initialisation
            						 where   find_in_set(soldby, @pv)
            						 and     length(@pv := concat(@pv, ',', boughtby))","level1");
                          //$comission = 50; */

                        /*  $comission = GetDataUsingSQL("select @pv:=boughtby as boughtby, level1, soldby from sales
                                  join
                                  (select @pv:='".$agentID."')tmp
                                  where soldby=@pv","level1");
*/

                          $comission = GetDataUsingSQL("select  boughtby,
                                  soldby,
                                  level1
                          from    (select * from sales where status=1
                                   order by soldby, id) products_sorted,
                                  (select @pv := '".$agentID."') initialisation
                          where   find_in_set(soldby, @pv)
                          and     length(@pv := concat(@pv, ',', boughtby))","level1");




                    /*              $con = mysqli_connect(get_dbserver(),get_dbuser(),get_dbpassword(),get_dbname());
                                  $strSQL = "select @pv:=boughtby as boughtby, level1, soldby from sales
                                          join
                                          (select @pv:='".$agentID."')tmp
                                          where soldby=@pv";
                                  $sqlQuery = mysqli_query($con,$strSQL) or die(mysqli_error($con));
                                  $numRows = mysqli_num_rows($sqlQuery);
                                  $val  = array();
                                  while($rows = mysqli_fetch_array($sqlQuery,MYSQLI_ASSOC)) {
                                    //$val = array($rows['id'] => $rows['parent_id']);
                                    $val[] = $rows;
                                    $list[] = array($rows['level1']);

                                  }
                                  $final = 0;
                                  $ctr = count($comission);
                                  //echo $ctr;
                                  for ($c=0;$c<$ctr;$c++)
                                  {
                                    //echo $list[$c][0];
                                    $final = $final + $comission[$c][0];

                                  }*/
                                  //mysqli_close($con);

                                  //echo $comission;


                          //$comission = 50;
                        }
                        elseif($getlevel == "Level 2")
                        {
                          $comission = GetDataUsingSQL("select  boughtby,
                                  soldby,
                                  level2
                          from    (select * from sales where status=1
                                   order by soldby, id) products_sorted,
                                  (select @pv := '".$agentID."') initialisation
                          where   find_in_set(soldby, @pv)
                          and     length(@pv := concat(@pv, ',', boughtby))","level2");
                          //$comission = 20;
                        }
                        elseif($getlevel == "Level 3")
                        {
                          $comission = GetDataUsingSQL("select  boughtby,
                                  soldby,
                                  level3
                          from    (select * from sales where status=1
                                   order by soldby, id) products_sorted,
                                  (select @pv := '".$agentID."') initialisation
                          where   find_in_set(soldby, @pv)
                          and     length(@pv := concat(@pv, ',', boughtby))","level3");
                          //$comission = 15;
                        }
                        elseif($getlevel == "Level 4")
                        {
                          $comission = GetDataUsingSQL("select  boughtby,
                                  soldby,
                                  level4
                          from    (select * from sales where status=1
                                   order by soldby, id) products_sorted,
                                  (select @pv := '".$agentID."') initialisation
                          where   find_in_set(soldby, @pv)
                          and     length(@pv := concat(@pv, ',', boughtby))","level4");
                          //$comission = 10;
                        }
                        elseif($getlevel == "Level 5")
                        {
                          $comission = GetDataUsingSQL("select  boughtby,
                                  soldby,
                                  level5
                          from    (select * from sales where status=1
                                   order by soldby, id) products_sorted,
                                  (select @pv := '".$agentID."') initialisation
                          where   find_in_set(soldby, @pv)
                          and     length(@pv := concat(@pv, ',', boughtby))","level5");
                          //$comission = 5;
                        }

                        //$qty = getRecord('sum(quantity)','sales','soldby ='.$parentId);
                        $productID = getRecord('productID','sales','soldby ='.$parentId);
                        $productname = getRecordbyID('name','products','id ="'.$productID.'"');
                        echo '<td> <b data-toggle="modal" class="trhistory" data-target="#historymodal">'. $parent_name.'</b></td>';
                        //echo '<td> <b>'. $qty.'</b></td>';
                        //echo '<td> <b>'. $comission.'</b></td>';
                        $total = (int)$comission;
                        //$total = (int)$comission;
                        echo '<td> <b data-toggle="modal" class="trhistory" data-target="#historymodal">'. $total. ' PHP</b> </td>';
                        //echo '<td> <b>Product: '. $productname.' Quantity: '. $qty.' Comission: '. $comission.'</b></td>';
                     //}
                       //echo '<td> <b>'. $itemBranch['amount'].'</b></td>';
                     //echo '<td> <b>'. $itemBranch['amount'].'</b></td>';
                     //echo '<li> Amount: '. array_sum(intval($itemBranch['amount']));
                       // iterate with the actual Id to check if this record have childs
                       Tablebuild($elements, $branch, $itemBranch["id"]);
                       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);


       */
      class vector implements JsonSerializable {
        public function __construct(array $arr) {
            $this->array = $arr;
        }

        public function jsonSerialize() {
            return $this->array;
        }
    }
    function file_get_contents_curl($url) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

        $data = curl_exec($ch);
        curl_close($ch);

        return $data;
    }
//    echo ("<pre>");
    //print_r($result);
  //  echo ("</pre>");
    //foreach($result as $key => $item){
        // unset them
     //   unset($result[$key]["id"]);
     //   unset($result[$key]["parent_id"]);

     //   }
     function deep_delete_keys($arr, $keys) {
        if (!is_array($keys)) $keys = array($keys);
        if(!empty($arr))
        {
        $filteredArr = array_diff_key( $arr, array_flip( $keys ) );
        }
        else {
          $filteredArr = array();
        }
        foreach ($filteredArr as &$val) {
            if (is_array($val)) {
                $val = deep_delete_keys($val, $keys);
            }
        }
        return $filteredArr;
    }
    $result = deep_delete_keys($result,"id");
  $result = deep_delete_keys($result,"parent_id");
        if (in_array("parent_id", $result)) {
          //  echo "Got Irix";
        }
        else
        {
    //      echo "no irix";
        }
        //echo ("<pre>");
      //  print_r($result);
    //    echo ("</pre>");
           //$json = json_encode($result,JSON_PRETTY_PRINT);

           $json = json_encode(new vector($result),JSON_PRETTY_PRINT);
           //$array = substr($json,1,-1);
           //echo($array);

           $array = json_decode($json, true);

           // loop through array

           //foreach($array as &$item){

            // unset specific key
           // unset($item["id"]);

            //}
            //unset($item);

            $result = deep_delete_keys($result,"id");
            $result = deep_delete_keys($result,"parent_id");
            $result = deep_delete_keys($result,"totalamount");

           $json = json_encode(new vector($result),JSON_PRETTY_PRINT);
           $json = substr($json,1,-1);
         	$filename = "testing3.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) {

        					 //$(".customeradd").addClass('hidden');
        					 $(".userDataTable").html(data);
                   //$(".userDataTable").html("TEST");
                   //$(".userDataTable").hide();
        					 //alert(data);


        			 }
        		 });
    }
            const myChart = Sunburst();
            fetch("testing3.json",{
              headers : {
                'Content-Type': 'application/json',
                'Accept': 'application/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>

          <script>
      $(document).ready(function () {

        $('.trhistory').click(function () {
            var id = $(this).closest("tr").find('td:eq(0)').text();
            //alert(id);
            $('.historyuser').val(id);
            $(".userowner").text(id);
            //alert(id);
            //alert($('.historyuser').val());
            $.ajax({
             type: "GET",
             url: "functions/gethistoryuser.php",
             data: {historyname : id },
             success: function (data) {
                 $(".historyUserData").html(data);
             }
           });
        });












      $('.min').datepicker({
        		  autoHide: true,
                  format: "yyyy-mm-dd"

              });
      $('.max').datepicker({
              		  autoHide: true,
                        format: "yyyy-mm-dd"

                    });


          //var test = $('.min').val();
          //$('.min').datepicker({ onSelect: function () { table.draw(); }, changeMonth: true, changeYear: true });
          //$('.max').datepicker({ onSelect: function () { table.draw(); }, changeMonth: true, changeYear: true });
          var table =  $('#userDataTable').DataTable( {
                    dom: 'Brtip',
                    buttons: [
                        'copy', 'csv', 'excel', 'pdf', 'print'
                    ],
                    columnDefs: [{

                      targets: [0], visible: false
                    }]



                } );


                $('.testing').on( 'keyup', function () {
    table
        .columns( 1 )
        .search( this.value )
        .draw();
} );
          //table.column(0).visible(false);
          //table.row( ':eq(0)' ).delete();

          $( ".min" ).keyup(function() {
            //alert( "Handler for .keyup() called." );
            table.draw();
          });
          $( ".max" ).keyup(function() {
            //alert( "Handler for .keyup() called." );
            table.draw();
          });


          $('#userDataTable thead tr:eq(1) th').each( function () {
           // if($(this).index() == 0)
            //{
              var title = $('#userDataTable thead tr:eq(1) th').eq( $(this).index() ).text();
              $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
           // }
          } );



          table.columns().every(function (index) {
            $('.dataTable thead tr:eq(1) th:eq(' + index + ') input').on('keyup change', function () {
                //table.column($(this).parent().index() + ':visible')
                table.column($(this).parent().index() + ':visible')
                    .search(this.value)
                    .draw();
            });
        });




             // DataTable



          $.fn.dataTable.ext.search.push(
              function (settings, data, dataIndex) {
                  var min = $('.min').val();
                  var max = $('.max').val();
                  //alert(min);
                  //alert(max);
                  //var startDate = new Date(data[0]);
                  if ( settings.nTable.id !== 'userDataTable' ) {
                    return true;
                  }
                  var startDate = data[0];
                  //alert(startDate);
                  if (min == "" && max == "") {  return true; }
                  if (min == "" && startDate <= max) {   return true;}
                  if(max == "" && startDate >= min) {  return true;}
                  if (startDate <= max && startDate >= min) { return true; }
                  return false;



    /*              if ( ( isNaN( min ) && isNaN( max ) ) ||
                      ( isNaN( min ) && startDate <= max ) ||
                      ( min <= startDate   && isNaN( max ) ) ||
                      ( min <= startDate   && startDate <= max ) )
                 {
                     return true;
                 }
                 return false; */

              }
          );



          $('.deletedateagent').click(function () {


            $('.min').val("");
            $('.max').val("");
            var randomdata = 1;
          //  $('#userDataTable').trigger('sortReset');
          // table.fnFilterClear();
          //  return false;

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

                     //$(".userDataTable").html("TEST");
                     //$(".userDataTable").hide();
                     //alert(data);


                 }
               }); */

          });





          // Event listener to the two range filtering inputs to redraw on input
          $('.min, .max').change(function () {
                table.draw();

          });






      });


          </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 row col-5" id="txtResult1">

                                              <table border="0" cellspacing="2" cellpadding="2">
                                                      <tbody>
                                                        <tr>
                                                          <td>Minimum date:</td>
                                                          <td><input type="text" id="min" class="min" name="min"></td>

                                                          <td>Maximum date:</td>
                                                          <td><input type="text" id="max" class="max" name="max"></td>
                                                          
                                                      <!--    <td><a href="#"  class="btn btn-sm btn-primary shadow-sm deletedateagent" ><i class="far fa-trash-alt"></i></a></td> -->
                                                      </tr>
                                                  </tbody></table>

                                              <table class="table table-bordered userDataTable" id="userDataTable" width="100%" cellspacing="0">
                                                    <thead>
                                                        <tr>
                                                          <th class="filterhead">Date</th>
                                                          <th class="testsearch">Agent Name</th>
                                                          <th class="filterhead">Referred b</th>
                                                          <th class="filterhead">Comission</th>
                                                        </tr>

                                                        <tr>
                                                          <th class="filterhead">Date</th>
                                                          <th class="testsearch">Agent Name</th>
                                                          <th class="filterhead">Referred b</th>
                                                          <th class="filterhead">Comission</th>
                                                        </tr>


                                                    </thead>
                                                  <tbody>

                                                      <?php   Tablebuild($val, array()); ?>
                                                  </tbody>



                                                </table>

                                            </div>





                                                   <div class="form-group col-4" >
    											                                 <div id="chart"></div>
                                                           <div id="chart2" ></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="historymodal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
        aria-hidden="true">
        <div class="modal-dialog  modal-xl modal-dialog-centered modal-dialog-scrollable" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel"><span class="userowner"></span> Commission Transaction History</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">

                  <span class="userowner"></span> Commission Transaction History



                  <input type="hidden"  class="historyuser" name="historyuser" id ="historyuser" value="">
                  <table class="table table-bordered historyUserData" id="userDataTable" width="100%" cellspacing="0">


                    </table>


                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Close</button>
                  <!--  <a class="btn btn-primary" href="../gbgv2/destroy.php">Logout</a> -->
                </div>
            </div>
        </div>
    </div>






  </body>
</html>
