<?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">Pending Payment List</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 PaymentDataTable" id="PaymentDataTable"  >
																		<thead>
                                          <tr>
                                          <th>Sales ID</th>
    																			<th>Sale Date</th>
    																			<th>Agent</th>
                                          <th>Buyer</th>
    																			<th>Product</th>
    																			<th>Quantity</th>
    																			<th>Comission</th>
    																			<th><input type="checkbox" name="checkall" class="select-checkall" id="checkall" value=""> Mark as Paid</th>
                                        </tr>

                                        <tr>
                                        <th>Sales ID</th>
                                        <th>Sale Date</th>
                                        <th>Agent</th>
                                        <th>Buyer</th>
                                        <th>Product</th>
                                        <th>Quantity</th>
                                        <th>Comission</th>
                                        <th></th>
                                      </tr>


																		</thead>
																	<tbody>
																	<?php
																	//$salesinquiryrow =  getTblNumRows('tbl_sales_inquiry',"salesinquiry_status = 'Added'");

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

																	$resultlist = getpaymentlist();
																	//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'].'');


                                        $soldby = $row['soldby'];
                                        $getlevelroot = getRecord('commisionsoldby','sales','soldby ='.$soldby);
                                        //$comission = 20;
																				echo '<tr>';
                                        echo '<td>'. $row['id'] . '</td>';
																				echo '<td>'. $row['datecreated'] . '</td>';
																				echo '<td>'.$usernamessoldby.'('. $fnamesoldby . ' '. $lnamesoldby . ')</td>';
                                        echo '<td>'.$usernameboughtby.'('. $fnameboughtby . ' '. $lnameboughtby . ')</td>';
                                        echo '<td>'. $productname . '</td>';
                                        echo '<td>'. $row['quantity'] . '</td>';
                                        $datecreated = $row['datecreated'];
                                        if($getlevelroot == "Level 1")
                                    		{
                                        $comission = GetDataUsingSQL("select  boughtby,
                                                soldby,
                                                level1
                                        from    (select * from sales where datecreated='".$datecreated."' and paymentstatus = 'Pending' and status=1
                                                 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>'. $comission . '</td>';
                                        }
                                        else if($getlevelroot == "Level 2")
                                  			{
                                          $comission = GetDataUsingSQL("select  boughtby,
                                                  soldby,
                                                  level2
                                          from    (select * from sales where datecreated='".$datecreated."' and paymentstatus = 'Pending' and status=1
                                                   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>'. $comission . '</td>';
                                        }
                                        else if($getlevelroot == "Level 3")
                                  			{
                                          $comission = GetDataUsingSQL("select  boughtby,
                                                  soldby,
                                                  level3
                                          from    (select * from sales where datecreated='".$datecreated."' and paymentstatus = 'Pending' and status=1
                                                   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>'. $comission . '</td>';
                                        }
                                        else if($getlevelroot == "Level 4")
                                  			{
                                          $comission = GetDataUsingSQL("select  boughtby,
                                                  soldby,
                                                  level4
                                          from    (select * from sales where datecreated='".$datecreated."' and paymentstatus = 'Pending' and status=1
                                                   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>'. $comission . '</td>';
                                        }
                                        else if($getlevelroot == "Level 5")
                                  			{
                                          $comission = GetDataUsingSQL("select  boughtby,
                                                  soldby,
                                                  level5
                                          from    (select * from sales where datecreated='".$datecreated."' and paymentstatus = 'Pending' and status=1
                                                   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>'. $comission . '</td>';
                                        }


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

																				echo '</tr>';
																	}
																	?>




																	</tbody>
                                            <tfoot>
                                              <tr>
                                                  <th colspan="7" style="text-align:right"></th>
                                                  <th><button type="button" class="btn btn-success btn-sm  submitpaymentdata">Submit</button></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="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>




    <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 =  $('#PaymentDataTable').DataTable( {
               dom: 'Brtip',
               buttons: [
                   'copy', 'csv', 'excel', 'pdf', 'print'
               ],
               columnDefs: [{
                 //targets: [0], visible: false
                }],
                'order': [1, 'asc']

           });


           $('#PaymentDataTable thead tr:eq(1) th').each( function () {
            // if($(this).index() == 0)
             //{
             if($(this).index() == 7)
             {}
             else {


               var title = $('#PaymentDataTable 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();
             });
         });

           $('#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 !== 'PaymentDataTable' ) {
                           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;

                     }
                 );

   $('.submitpaymentdata').on('click', function(){
     var arr = [];
     var commission = [];
     var agent = [];
     var saledate = [];
     var favorite1 = [];
     var favorite2 = [];
     var favorite3 = [];
     var favorite4 = [];
     i = 0;

        $.each($("input[name='id[]']:checked"), function(){
          favorite1.push($(this).closest("tr").find('td:eq(0)').text());
          favorite2.push($(this).closest("tr").find('td:eq(2)').text());
          favorite3.push($(this).closest("tr").find('td:eq(1)').text());
          favorite4.push($(this).closest("tr").find('td:eq(6)').text());
          arr =  favorite1.join(",");
          agent =  favorite2.join(",");
          saledate =  favorite3.join(",");
          commission =  favorite4.join(",");
        });


var datastring = "";
datastring = datastring + "checklistdata="+arr;
datastring = datastring + "&commission="+commission;
datastring = datastring + "&agent="+agent;
datastring = datastring + "&saledate="+saledate;
//alert(datastring);

if (arr.length === 0) { alert("Please check an item"); } else{


      $.ajax({
       type: "GET",
       url: "functions/updatepaymentstatus.php",
       data: datastring,
       success: function (data) {
           alert("Payment Status Updated");
           window.location = "paymentlist.php";
           alert(data);
       }
     });
   }

});





   // Handle click on checkbox to set state of "Select all" control
   $('#checkall tbody').on('change', 'input[type="checkbox"]', function(){
      // If checkbox is not checked
      if(!this.checked){
         var el = $('#checkall').get(0);
         // If "Select all" control is checked and has 'indeterminate' property
         if(el && el.checked && ('indeterminate' in el)){
            // Set visual state of "Select all" control
            // as 'indeterminate'
            el.indeterminate = true;
         }
      }
   });
});
</script>


  </body>
</html>
