<?php
ob_start();
error_reporting(0);
include("connect.php");
session_start(); 
$ver = $_SESSION["admin_id"];
$dis_id = $_SESSION["manager_id"];
$user_type = $_SESSION["user_type"];
$user_session = $_SESSION["user_session"];
if(!isset($_SESSION["admin_id"])){
   header('location:http://www.btcover.appexperts.net');
}
date_default_timezone_set('Asia/Calcutta');
				$cdate  = date("Y-m-d");
				$cdate11=date('Y-m-d', strtotime($cdate .'-7 days'));
				$c11  = date("m/d/Y");
				$c22=date('m/d/Y', strtotime($c11 .'-7 days'));
				$q=mysqli_query($con,"select * from tbl_manager where manager_id='$dis_id'");
$res=mysqli_fetch_assoc($q);
$imei_no=$res['imei_no'];
?>
<!DOCTYPE html>
<html dir="ltr" lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- Tell the browser to be responsive to screen width -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <!-- Favicon icon -->
    <link rel="icon" type="image/png" sizes="16x16" href="assets/images/favicon.png">
    <title>BTCOVER : Admin Dashboard</title>
    <!-- Custom CSS -->
    <link rel="stylesheet" type="text/css" href="assets/libs/select2/dist/css/select2.min.css">
    <link rel="stylesheet" type="text/css" href="assets/libs/jquery-minicolors/jquery.minicolors.css">
    <link rel="stylesheet" type="text/css" href="assets/libs/bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css">
    <link rel="stylesheet" type="text/css" href="assets/libs/quill/dist/quill.snow.css">
	<link href="assets/libs/datatables.net-bs4/css/dataTables.bootstrap4.css" rel="stylesheet">
    <link href="dist/css/style.min.css" rel="stylesheet">
	
	<script>
		function setagentid(status)
		{
			
			var com_id=document.getElementById('com_id').value;
			document.getElementById('status').value=status;
			document.getElementById('commission_id').value=com_id;
			if(status=='Approve')
			{
				document.getElementById('reason1').style.display="none";	
			 document.getElementById('txn').style.display="none";	
			 document.getElementById('type1').style.display="block";
			 document.getElementById('type2').style.display="block";
			}
			else if(status=='Reject')
			{
				document.getElementById('reason1').style.display="block";	
			 document.getElementById('txn').style.display="none";	
			 document.getElementById('type1').style.display="none";
			 document.getElementById('type2').style.display="none";
			}
			
		
		}
		</script>
		<script>
		function cash(str)
		{
			 document.getElementById('reason1').style.display="none";	
			 document.getElementById('txn').style.display="none";	
			 document.getElementById('type1').style.display="block";
			 document.getElementById('type2').style.display="block";
				document.getElementById('txn_number').value='';
		}
		</script>
		<script>
		function neft(str)
		{
			document.getElementById('reason1').style.display="none";	
			 document.getElementById('txn').style.display="block";	
			 document.getElementById('type1').style.display="block";
			 document.getElementById('type2').style.display="block";
			
		}
		</script>
			
</head>

<body>
   
    <div id="main-wrapper">
	 <?php include("header.php"); ?>
    
     <?php include("menu.php"); ?>
	
	
       
      
        <div class="page-wrapper">
		 <div class="page-breadcrumb">
                <div class="row">
                    <div class="col-12 d-flex no-block align-items-center">
                        <h4 class="page-title"> Agent Commission History</h4>
                        <div class="ml-auto text-right">
                            <nav aria-label="breadcrumb">
                                <ol class="breadcrumb">
                                    <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                   
                                    <li class="breadcrumb-item active" aria-current="page"> Agent Commission History</li>
                                </ol>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
            <!-- ============================================================== -->
            <!-- Bread crumb and right sidebar toggle -->
            <!-- ============================================================== -->
          <?php
						if(isset($_POST['searchd']))
						{
							
					$start_date1=$_POST['start_date'];
							$end_date1=$_POST['end_date'];
				 $start_date=date("Y-m-d", strtotime($start_date1) );
							$end_date=date("Y-m-d", strtotime($end_date1) );
							date_default_timezone_set('Asia/Calcutta');
			//	$cdate  = date("Y-m-d");
			//	$cdate11=date('Y-m-d', strtotime($cdate .'-7 days'));
			// $cdate1 = isset($_POST['start_date1']) ? $start_date : $cdate;
		 //	$cdate2 = isset($_POST['end_date1']) ? $end_date : $cdate;
			if($_SESSION["user_type"]=='Manager') 
				$res_product_stock = mysqli_query($con,"SELECT *,tbl_commission.status as comstatus,tbl_commission.commission_id as com_id FROM  tbl_commission,tbl_agent,tbl_manager where tbl_commission.manager_id=tbl_manager.manager_id and tbl_commission.agent_id=tbl_agent.agent_id and tbl_manager.manager_id='$dis_id' and tbl_commission.insert_date>='$start_date' and tbl_commission.insert_date<='$end_date'");
		elseif($_SESSION["user_type"]=='Admin') 
			$res_product_stock = mysqli_query($con,"SELECT *,tbl_commission.status as comstatus,tbl_commission.commission_id as com_id FROM  tbl_commission,tbl_agent,tbl_manager where tbl_commission.manager_id=tbl_manager.manager_id and tbl_commission.agent_id=tbl_agent.agent_id and tbl_manager.admin_id='$ver' and tbl_commission.insert_date>='$start_date' and tbl_commission.insert_date<='$end_date'");
						}
						
						else
						{
						if($_SESSION["user_type"]=='Manager') 
		$res_product_stock = mysqli_query($con,"SELECT *,tbl_commission.status as comstatus,tbl_commission.commission_id as com_id FROM  tbl_commission,tbl_agent,tbl_manager where tbl_commission.manager_id=tbl_manager.manager_id and tbl_commission.agent_id=tbl_agent.agent_id and tbl_manager.manager_id='$dis_id' and tbl_commission.insert_date>='$cdate11' and tbl_commission.insert_date<='$cdate'");
		elseif($_SESSION["user_type"]=='Admin') 
		$res_product_stock = mysqli_query($con,"SELECT *,tbl_commission.status as comstatus,tbl_commission.commission_id as com_id FROM  tbl_commission,tbl_agent,tbl_manager where tbl_commission.manager_id=tbl_manager.manager_id and tbl_commission.agent_id=tbl_agent.agent_id and tbl_manager.admin_id='$ver' and tbl_commission.insert_date>='$cdate11' and tbl_commission.insert_date<='$cdate'");	
						
						}	
						
						
						?>
            <div class="container-fluid"  >
                <div class="row">
                    <div class="col-12">
                        <div class="card">
						<form class="form-horizontal" method="post" name="form"  enctype="multipart/form-data">
                               <div class="card-body">
                                   <div class="form-group row">
                                  <div class="col-md-4"  >	
									<div class="form-group ">
                                        <label for="fname" class=" text-left control-label col-form-label"><b>From Date</b></label>
                                        <div class="input-group">
                                    <input type="text" class="form-control" id="datepicker-autoclose" name="start_date" placeholder="mm/dd/yyyy" value="<?php if(isset($_POST['searchd'])){ echo $_POST['start_date'];} else { echo $c22; } ?>" >
                                    <div class="input-group-append">
                                        <span class="input-group-text"><i class="fa fa-calendar"></i></span>
                                    </div>
                                </div>
                                     </div>
                                     </div>
                               
								<div class="col-md-4" style="padding:0px;">	
									<div class="form-group ">
                                        <label for="fname" class=" text-left control-label col-form-label"><b>To Date</b></label>
                                        <div class="input-group">
                                    <input type="text" class="form-control" id="datepicker-autoclose1" name="end_date" placeholder="mm/dd/yyyy" value="<?php if(isset($_POST['searchd'])){ echo $_POST['end_date'];} else { echo $c11; } ?>" >
                                    <div class="input-group-append">
                                        <span class="input-group-text"><i class="fa fa-calendar"></i></span>
                                    </div>
                                </div>
                                     </div>
                                     </div>
                             
								
								<div class="col-sm-1" style="padding-left:0px; margin-top:31px;">
										  <div class="form-group">  
                                           <button type="submit" class="form-control"  name="searchd"> <i class="fa fa-search"></i></button>
										  </div>
										</div>
								
                                </div>
                                </div>
                              
								
                                
                                
                            </form>
							
                            <div class="card-body" style="float:left; width:100%; overflow-Y: auto; height: 500px;">
                                <div class="table-responsive">
                                    <table id="zero_config" class="table table-striped table-bordered">
                                        <thead>
                                            <tr>
											  <th><b>#</b></th>
											    <th><b>Agent Name</b></th>
												 <th><b>Agent Phone No</b></th>
												 <th><b>Transaction Date</b></th>
												 <th><b>Transaction Time</b></th>
												 <th><b>Commission Amount</b></th>
												 <th><b>Adjust Amount</b></th>
												 <th><b>Status</b></th>
												 <th><b>Reason</b></th>
												<?PHP IF($_SESSION["user_type"]=='Admin') { ?>
												 <th><b>Action</b></th>
												<?php } ?>
											</tr>
                                        </thead>
                                        <tbody>
										  <?php 
									   $c=1;
									   
										if(mysqli_num_rows($res_product_stock)>0)
										{   
		
									while($fetch_product=mysqli_fetch_assoc($res_product_stock))
										{
										$a_id=$fetch_product['agent_id'];
										 $com_id=$fetch_product['commission_id'];
			$adjust_amount_val=0;
			$res = mysqli_query($con,"SELECT * FROM  tbl_agent_commission where agent_id='$a_id' and status='Pending'");
			while($fetch_detail=mysqli_fetch_assoc($res))
			{
				$adjust_amount_val=$adjust_amount_val+$fetch_detail['credit_amt']-$fetch_detail['adjust_amount'];
			}
											
										?>
										<tr>
										  <td><?php echo $c++; ?></td>
										  <td><?php echo $fetch_product['agent_name']; ?></td>
										  <td><?php echo $fetch_product['agent_phone']; ?></td>
										  <td><?php echo date("d-M-Y", strtotime($fetch_product['insert_date']) ); ?></td>
										  <td><?php echo $fetch_product['insert_time']; ?></td>
										  <td><?php echo $fetch_product['amount']; ?></td>
										  <td><?php echo $adjust_amount_val; ?></td>
										  <td><?php echo $fetch_product['comstatus']; ?></td>
										  <td><?php echo $fetch_product['rejection_reason']; ?></td>
										
										  	<?PHP if($_SESSION["user_type"]=='Admin') { ?>
										  <td style="width:20px;">
											<?php if($fetch_product['comstatus']=='Pending'){ ?>
											 <?php if($imei_no=='0' || $imei_no=='') { ?>
												<a href="javascript:void(0)" data-toggle="modal" data-target="#add-new-event" style="font-size:12px;padding:1px 5px;" onClick="setagentid('Approve')" class="btn btn-success">Approve</a>
												<a href="javascript:void(0)" data-toggle="modal" data-target="#add-new-event" style="font-size:12px;padding:1px 5px;" onClick="setagentid('Reject')" class="btn btn-danger">Reject</a>
												<?php } else { ?>
												<a href="#" data-toggle="modal" data-target="#add-new-event" style="font-size:12px;padding:1px 5px;" onClick="alert('You Are Already Login in App...First Logout Fom App then Approve Request  From Here')" class="btn btn-success">Approve</a>
												<a href="#" data-toggle="modal" data-target="#add-new-event" style="font-size:12px;padding:1px 5px;" onClick="alert('You Are Already Login in App...First Logout Fom App then Reject Request From Here')" class="btn btn-danger">Reject</a>
												<?php } ?>
											<input class="form-control form-white" placeholder="Commission Amount" id="com_id" type="hidden" name="com_id"  value="<?php echo $com_id; ?>" /> 
										 
											<?php } ?>	
										  </td>
											<?php } ?>
										</tr>
										<?php }} else { ?>
										 <tr>
										  <td colspan='10'>No Data Available</td>
										</tr>
										<?php } ?>
                                        </tbody>
                                       
                                    </table>
									
									
									
			 </div>						
			 </div>						
			 </div>	
<div class="modal fade none-border" id="add-new-event">
									<div class="modal-dialog">
									<div class="modal-content">
								<div class="modal-header">
                             
                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                            </div>
                            <div class="modal-body">
                                <form  method="post" name="form2"  enctype="multipart/form-data">
                                    
										<div class="row" id="reason1">
										<div class="col-md-12">
										<div class="form-group ">
                                            <label class="control-label">Reason</label>
                                             <input class="form-control form-white" placeholder="Reason" id="reason" type="text" name="reason"  />
                                        </div>
                                        </div>
                                        </div>
											<div class="form-group row" >
										 <div class="col-md-6" id="type2">
                                        <div class="custom-control custom-radio">
                                            <input type="radio" class="custom-control-input" checked id="customControlValidation1" name="type" value="Cash" onclick="cash(this.value);"   required>
                                            <label class="custom-control-label" for="customControlValidation1"><b>Cash</b></label>
										</div>
										</div>
										<div class="col-md-6" id="type1">
										 <div class="custom-control custom-radio">
											<input type="radio" class="custom-control-input" id="customControlValidation2" name="type" value="NEFT/RTGS" onclick="neft(this.value)"  >
                                            <label class="custom-control-label" for="customControlValidation2"><b>NEFT/RTGS</b></label>
											
                                        </div>
                                        </div>
                                    </div>
									<div class="row">
										<div class="col-md-12" id="txn">
										<div class="form-group ">
                                            <label class="control-label">Transaction Number</label>
                                             <input class="form-control form-white" placeholder="Transaction Number" id="txn_number" type="text" name="txn_number"  />
                                        </div>
                                        </div>
                                        </div>
										
										<br>
										 <input class="form-control form-white" placeholder="Commission Amount" id="status" type="hidden"   name="status" /> 
										  <input class="form-control form-white" placeholder="Commission Amount" id="commission_id" type="hidden"   name="commission_id" /> 
										
										 
										 
										
                                <button type="submit" class="btn btn-success" name="sub" >Save</button>
                                <button type="button" class="btn btn-secondary waves-effect" data-dismiss="modal">Close</button>
                            </div>
                                </form>
								<?php 
								if(isset($_POST['sub']))
								{
	$ver = $_SESSION['manager_id'];
	$admin_id=$_SESSION['admin_id'];
	$txn_id=$_POST['commission_id'];
	$type=$_POST['type'];
	$transaction_number=$_POST['txn_number'];
	$reason=$_POST['reason'];
	 $status=$_POST['status'];
	date_default_timezone_set('Asia/Calcutta');
	$cdate  = date("Y-m-d");
	$ctime=date('h:i:s');
	$success_flag=false;
	if($status=='Approve')
	{
		$res_product_stock = mysqli_query($con,"SELECT * FROM  tbl_commission where commission_id='$txn_id' and status='Pending'");
		if(mysqli_num_rows($res_product_stock)>0)
		{	
			while($fetch_detail=mysqli_fetch_assoc($res_product_stock))
			{
				$actual_adjust_amt_final=$fetch_detail['amount'];
				$actual_adjust_amt=$actual_adjust_amt_final;
				$agent_id=$fetch_detail['agent_id'];
				$res_purchase_adjust = mysqli_query($con,"SELECT * FROM tbl_agent_commission where agent_id='$agent_id' and status='Pending'");
				while($fetch_pending_data=mysqli_fetch_assoc($res_purchase_adjust))
				{
					$update_txn_id=$fetch_pending_data['credit_list_id'];
					$sale_credit_amt=round($fetch_pending_data['credit_amt']-$fetch_pending_data['adjust_amount']);
					if($sale_credit_amt==0)
						$uq1=mysqli_query($con,"UPDATE tbl_agent_commission SET status='Complete' where credit_list_id='$update_txn_id' and agent_id='$agent_id'");
					if($actual_adjust_amt<=0)
						break;
					if($actual_adjust_amt>$sale_credit_amt)
					{
						if($sale_credit_amt>0)
						{
							$actual_adjust_amt11=round($sale_credit_amt+$fetch_pending_data['adjust_amount']);
							$uq1=mysqli_query($con,"UPDATE tbl_agent_commission SET settlement_date='$cdate',adjust_amount='$actual_adjust_amt11',status='Complete' where agent_id='$agent_id' and credit_list_id='$update_txn_id'");
							$actual_adjust_amt=$actual_adjust_amt-$sale_credit_amt;
						}
					}
					else if($sale_credit_amt>0)
					{
						$actual_adjust_amt11=round($actual_adjust_amt+$fetch_pending_data['adjust_amount']);
						$uq1=mysqli_query($con,"UPDATE tbl_agent_commission SET adjust_amount='$actual_adjust_amt11' where agent_id='$agent_id' and credit_list_id='$update_txn_id'");
						$actual_adjust_amt=0;
						break;
					}
				}
				$actual_adjust_amt_credit=$actual_adjust_amt_final-$actual_adjust_amt;
				if($actual_adjust_amt_credit==0)
				{
					$uq2=mysqli_query($con,"update tbl_commission set status='Complete',pay_type='$type',transaction_number='$transaction_number', complete_date='$cdate',complete_time='$ctime' where commission_id='$txn_id'"); 
				}
				else if($actual_adjust_amt_credit>0)
				{
					$uq2=mysqli_query($con,"update tbl_commission set status='Complete',pay_type='$type',transaction_number='$transaction_number',complete_date='$cdate',complete_time='$ctime',paid_amt='$actual_adjust_amt_credit' where commission_id='$txn_id'"); 
				}	
			}
				
			$success_flag=true;
		}
		else
		{
			
			$success_flag=false;
		}
	}
	else
	{
		$uq2=mysqli_query($con,"update tbl_commission set status='Reject',rejection_reason='$reason',complete_date='$cdate',complete_time='$ctime' where commission_id='$txn_id'"); 
		
		$success_flag=true;
	}

	if($success_flag==true){
		$res_agent = mysqli_query($con,"SELECT *,agent_name,manager_name FROM `tbl_commission`,`tbl_agent`,`tbl_manager` where tbl_commission.agent_id = tbl_agent.agent_id and tbl_commission.commission_id='$txn_id'and admin_id='$admin_id' and manage_type='Admin'");
		if(mysqli_num_rows($res_agent)>0)
		{	
			$fetch_detail=mysqli_fetch_assoc($res_agent);
			$agent_name=$fetch_detail['agent_name'];
			$admin_name=$fetch_detail['manager_name'];
			$amount=$fetch_detail['amount'];
			$agent_id=$fetch_detail['agent_id'];
		}	

		$title = "Commission Request Response";
		$message="$admin_name has $status your request for Commission of Agent $agent_name of amount Rs. $amount";

		$res_device_id = mysqli_query($con,"SELECT * FROM `tbl_commission`,`tbl_manager` where tbl_commission.manager_id=tbl_manager.manager_id and tbl_commission.commission_id='$txn_id'");
		if(mysqli_num_rows($res_device_id)>0)
		{	
			while( $fetch_detail=mysqli_fetch_assoc($res_device_id))
			{
				$key=$fetch_detail['device_id'];
				$manager_id=$fetch_detail['manager_id'];
				include("api/send_notification.php");
				$query = mysqli_query($con,"INSERT INTO `tbl_notification_history`(`manager_id`, `agent_id`, `title`, `message`, `date`, `time`) VALUES ('$manager_id','$agent_id','$title','$message','$cdate','$ctime')");
			}
		}
	}
	header('location:agent-commission-history.php');
}
								?>
                            </div>
                           
                        </div>
                    </div>			 
         
            <footer class="footer text-center">
                  2019 &copy; All Rights Reserved by BTCOVER. Designed and Developed by <a href="http://www.belltechnology.in/">Bell Technology</a>.
            </footer>
          
        </div>
      
    </div>
    </div>
  
   <script src="assets/libs/jquery/dist/jquery.min.js"></script>
    <!-- Bootstrap tether Core JavaScript -->
    <script src="assets/libs/popper.js/dist/umd/popper.min.js"></script>
    <script src="assets/libs/bootstrap/dist/js/bootstrap.min.js"></script>
    <!-- slimscrollbar scrollbar JavaScript -->
    <script src="assets/libs/perfect-scrollbar/dist/perfect-scrollbar.jquery.min.js"></script>
    <script src="assets/extra-libs/sparkline/sparkline.js"></script>
    <!--Wave Effects -->
    <script src="dist/js/waves.js"></script>
    <!--Menu sidebar -->
    <script src="dist/js/sidebarmenu.js"></script>
    <!--Custom JavaScript -->
    <script src="dist/js/custom.min.js"></script>
    <!-- This Page JS -->
    <script src="assets/libs/inputmask/dist/min/jquery.inputmask.bundle.min.js"></script>
    <script src="dist/js/pages/mask/mask.init.js"></script>
    <script src="assets/libs/select2/dist/js/select2.full.min.js"></script>
    <script src="assets/libs/select2/dist/js/select2.min.js"></script>
    <script src="assets/libs/jquery-asColor/dist/jquery-asColor.min.js"></script>
    <script src="assets/libs/jquery-asGradient/dist/jquery-asGradient.js"></script>
    <script src="assets/libs/jquery-asColorPicker/dist/jquery-asColorPicker.min.js"></script>
    <script src="assets/libs/jquery-minicolors/jquery.minicolors.min.js"></script>
    <script src="assets/libs/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js"></script>
    <script src="assets/libs/quill/dist/quill.min.js"></script>
	 <script src="assets/extra-libs/multicheck/datatable-checkbox-init.js"></script>
    <script src="assets/extra-libs/multicheck/jquery.multicheck.js"></script>
    <script src="assets/extra-libs/DataTables/datatables.min.js"></script>
    <script>
        /****************************************
         *       Basic Table                   *
         ****************************************/
        $('#zero_config').DataTable();
    </script>

    <script>
        //***********************************//
        // For select 2
        //***********************************//
        $(".select2").select2();

        /*colorpicker*/
        $('.demo').each(function() {
        //
        // Dear reader, it's actually very easy to initialize MiniColors. For example:
        //
        //  $(selector).minicolors();
        //
        // The way I've done it below is just for the demo, so don't get confused
        // by it. Also, data- attributes aren't supported at this time...they're
        // only used for this demo.
        //
        $(this).minicolors({
                control: $(this).attr('data-control') || 'hue',
                position: $(this).attr('data-position') || 'bottom left',

                change: function(value, opacity) {
                    if (!value) return;
                    if (opacity) value += ', ' + opacity;
                    if (typeof console === 'object') {
                        console.log(value);
                    }
                },
                theme: 'bootstrap'
            });

        });
        /*datwpicker*/
        jQuery('.mydatepicker').datepicker();
        jQuery('#datepicker-autoclose').datepicker({
            autoclose: true,
            todayHighlight: true
        });
        var quill = new Quill('#editor', {
            theme: 'snow'
        });
		jQuery('.mydatepicker').datepicker();
        jQuery('#datepicker-autoclose1').datepicker({
            autoclose: true,
            todayHighlight: true
        });
        var quill = new Quill('#editor', {
            theme: 'snow'
        });

    </script>
</body>

</html>