<?php session_start();

require_once __DIR__."/includes/headerincludes.php";
require_once __DIR__."/includes/dbconfig.php";
require_once __DIR__."/functions/allfunctions.php";



if(empty($_SESSION["itemarrayinventory"]))
{
    $itemarray = array();
}
else
{
  $itemarray = $_SESSION["itemarrayinventory"];
}

if(empty($_SESSION["MEMBER_ID"]) && empty($_SESSION["TYPE"]) && empty($_SESSION["DEPT"]) && empty($_SESSION["FIRST_NAME"]) && empty($_SESSION["ACCESS_TYPE"]))
{
  $itemarray = array();
  $memberid = "";
  $type = "";
  $firstname = "";
  $dept = "";
  $accesstype = "";
}
else
{
  $memberid = $_SESSION['MEMBER_ID'];
  $type = $_SESSION['TYPE'];
  $firstname = $_SESSION['FIRST_NAME'];
  $dept = $_SESSION['DEPT'];
  $accesstype = $_SESSION['ACCESS_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();

if($type != "Admin")
{
?>
<script type="text/javascript">
  window.location = "index.php";
</script>

<?php
}
?>
<!DOCTYPE html>
<head>
    <title>GBG Enterprise - Dashboard</title>

</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>



            <!-- Nav Item - Pages Collapse Menu -->
            <?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">


                    <!-- Content Row -->
                    <div class="row gy-5">



				<!--Image Content Row -->

						<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">Sales Transaction History</div>
												<div class="row  align-items-center">
													<div class="card-body">

                            <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>
                                <div class="row gy-5"></div>

														<div class="form-group row txtResult1" id="txtResult1">



																															<table class="table table-bordered ReportDataTable" id="ReportDataTable" width="100%" cellspacing="0">
																		<thead>
                                      <tr>
                                      <th>Sales ID</th>
                                      <th>Sales Date</th>
																			<th>Agent</th>
																			<th>Quantity Sold</th>
                                      <th>Total Sales</th>
																			<th>Total Comission</th>
                                    </tr>
                                    <tr>
                                      <th>Sales ID</th>
                                      <th>Sales Date</th>
																			<th>Agent</th>
																			<th>Quantity Sold</th>
                                      <th>Total Sales</th>
																			<th>Total Comission</th>
                                    </tr>
																		</thead>
																	<tbody>
																	<?php
																	//$salesinquiryrow =  getTblNumRows('tbl_sales_inquiry',"salesinquiry_status = 'Added'");

																	//$salesinquirydata =  getRecord('product_id','tbl_sales_inquiry',"salesinquiry_status = 'Added'");

																	$resultlist = getpaymentlistreport();
																	//echo $memberid;
																	while($row=mysqli_fetch_array($resultlist,MYSQLI_ASSOC)) {



  																		//$salesinquirycustomer = getRecord('customer_id','tbl_sales_inquiry','sales_inquiry_id ='.$row['salesinquiryID'].'');


																	//	$salesinquirydatacustomer = getRecord('customer_company_name','tbl_customer','customer_id ='.$salesinquirycustomer.'');
																	//	$salesinquirydataproduct = getRecord('product_name','tbl_product','product_id ='.$row['productID'].'');
																	//	$status = $row['status'];
																	//	$quotation_id = $row['quotationID'];
																		//$firstapprover = $row['approver'];
																		//$secondapprover = $row['secondapprover'];

                                        $productname = getRecord('name','products','id ='.$row['productID']);
                                        $fnamesoldby = getRecord('FIRST_NAME','users','id ='.$row['soldby'].'');
                                        $lnamesoldby = getRecord('LAST_NAME','users','id ='.$row['soldby'].'');
                                        $usernamessoldby = getRecord('USERNAME','users','id ='.$row['soldby'].'');


                                        //$fnameboughtby = getRecord('FIRST_NAME','users','id ='.$row['boughtby'].'');
                                        //$lnameboughtby = getRecord('LAST_NAME','users','id ='.$row['boughtby'].'');
                                        //$usernameboughtby = getRecord('USERNAME','users','id ='.$row['boughtby'].'');
                                        //$usernamessoldby = getRecord('USERNAME','users','id ='.$row['soldby'].'');

                                        $soldby = $row['soldby'];
                                        $getlevelroot = getRecord('commisionsoldby','sales','soldby ='.$soldby);
                                        //$qty = $row['quantity'];

                                        //$comission = 20;

																				echo '<tr data-toggle="modal"  data-target="#historymodal" class="trhistoryreport">';
                                        echo '<td data-toggle="modal"  data-target="#historymodal" class="trhistoryreport">'. $row['id'] . '</td>';
																				echo '<td data-toggle="modal"  data-target="#historymodal" class="trhistoryreport">'. $row['datecreated'] . '</td>';
																				echo '<td data-toggle="modal"  data-target="#historymodal" class="trhistoryreport" >'.$usernamessoldby.'('. $fnamesoldby . ' '. $lnamesoldby . ')</td>';
                                        //echo '<td>'.$usernameboughtby.'('. $fnameboughtby . ' '. $lnameboughtby . ')</td>';

                                        echo '<td data-toggle="modal"  data-target="#historymodal" class="trhistoryreport">'. $row['quantity'] . '<b class="hidden datasales">'. $row['soldby'] . '</b></td>';
                                        echo '<td data-toggle="modal"  data-target="#historymodal" class="trhistoryreport">'. $row['total_sales'] . '</td>';


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

                                        echo '<td data-toggle="modal"  data-target="#historymodal" class="trhistoryreport">'. $comission . '</td>';
                                        }
                                        else if($getlevelroot == "Level 2")
                                  			{
                                          $comission = GetDataUsingSQL("select  boughtby,
                                                  soldby,
                                                  level2
                                          from    (select * from sales
                                                   order by soldby, id) products_sorted,
                                                  (select @pv := '".$soldby."') initialisation
                                          where   find_in_set(soldby, @pv)
                                          and     length(@pv := concat(@pv, ',', boughtby))","level2");
                                          echo '<td data-toggle="modal"  data-target="#historymodal" class="trhistoryreport">'. $comission . '</td>';
                                        }
                                        else if($getlevelroot == "Level 3")
                                  			{
                                          $comission = GetDataUsingSQL("select  boughtby,
                                                  soldby,
                                                  level3
                                          from    (select * from sales
                                                   order by soldby, id) products_sorted,
                                                  (select @pv := '".$soldby."') initialisation
                                          where   find_in_set(soldby, @pv)
                                          and     length(@pv := concat(@pv, ',', boughtby))","level3");
                                          echo '<td data-toggle="modal"  data-target="#historymodal" class="trhistoryreport">'. $comission . '</td>';
                                        }
                                        else if($getlevelroot == "Level 4")
                                  			{
                                          $comission = GetDataUsingSQL("select  boughtby,
                                                  soldby,
                                                  level4
                                          from    (select * from sales
                                                   order by soldby, id) products_sorted,
                                                  (select @pv := '".$soldby."') initialisation
                                          where   find_in_set(soldby, @pv)
                                          and     length(@pv := concat(@pv, ',', boughtby))","level4");
                                          echo '<td data-toggle="modal"  data-target="#historymodal" class="trhistoryreport">'. $comission . '</td>';
                                        }
                                        else if($getlevelroot == "Level 5")
                                  			{
                                          $comission = GetDataUsingSQL("select  boughtby,
                                                  soldby,
                                                  level5
                                          from    (select * from sales
                                                   order by soldby, id) products_sorted,
                                                  (select @pv := '".$soldby."') initialisation
                                          where   find_in_set(soldby, @pv)
                                          and     length(@pv := concat(@pv, ',', boughtby))","level5");
                                          echo '<td data-toggle="modal"  data-target="#historymodal" class="trhistoryreport">'. $comission . '</td>';
                                        }


																			   //echo '<td><input type="checkbox" name="id[]" value=""/></td>';

																				echo '</tr>';
																	}
																	?>




																	</tbody>
                                        <!--    <tfoot>
                                              <tr>
                                                  <th colspan="6" style="text-align:right"></th>
                                                  <th></th>

                                              </tr>
                                          </tfoot> -->


																</table>

														</div>



													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
							</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>Sales Report 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>Sales Report Transaction History



                 <input type="hidden"  class="historyuser" name="historyuser" id ="historyuser" value="">
                 <table class="table table-bordered historyreportUserData" id="historyreportUserData" 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>




    <div class="modal fade" id="DisableAccModal" 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">Reject</h5>
                     <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                         <span aria-hidden="true">×</span>
                     </button>
                 </div>
                 <div class="modal-body">Are you sure you want to deactivate this account?</div>
                 <div class="modal-footer">
 			<!-- 	<form class="user rejectdata" name="rejectdata"  id="rejectdata"> -->
 			<!--			<textarea class="form-control reason" id="reason" rows="3"></textarea> -->
 					<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
 					 <input class="useridval" type="hidden" id="useridval" name="useridval" value="<?php echo $qid; ?>">
                     <button type="button" class="btn btn-primary deactivateuseracc" href="#" >Deactivate</button>

                 </div>
             </div>
         </div>
     </div>




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


     var table =  $('#ReportDataTable').DataTable( {
               dom: 'Brtip',
               buttons: [
                   'copy', 'csv', 'excel', 'pdf', 'print'
               ],
               columnDefs: [{
                 targets: [0,1], visible: false
                }],
                'order': [1, 'asc']

           });


           $('#ReportDataTable thead tr:eq(1) th').each( function () {
            // if($(this).index() == 0)
             //{
               var title = $('#ReportDataTable thead tr:eq(0) 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();
             });
         });

           $('#checkall').on('click', function(){
      // Check/uncheck all checkboxes in the table
      var rows = table.rows({ 'search': 'applied' }).nodes();
      $('input[type="checkbox"]', rows).prop('checked', this.checked);
   });



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

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

                 });

          $('.min, .max').change(function () {
                  table.draw();

                 });

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

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


                 $.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 !== 'ReportDataTable' ) {
                           return true;
                         }
                         var startDate = data[1];
                         //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;

                     }
                 );

                 $('.trhistoryreport').click(function () {
                     var id = $(this).closest("tr").find('td:eq(0)').text();
                     var id2 = $(this).closest("tr").find('.datasales').text();
                     var label = $(this).closest('tr').find('td:eq(1)').children('.datasales').text();
                     $('.historyuser').val(label);
                     $(".userowner").text(id);
                     //alert(id);
                     //alert(label);
                     //alert($('.historyuser').val());
                     $.ajax({
                      type: "GET",
                      url: "functions/gethistoryreportsales.php",
                      data: {historyname : label },
                      success: function (data) {
                          $(".historyreportUserData").html(data);
                      }
                    });
                 });






});
</script>


  </body>
</html>
