<!DOCTYPE html>
<html>
<head>
	<title></title>
	<?php include("head.php");
	include "dbconfig.php";
	?>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<?php
$sql='';
$sql="SELECT bookings.pickup_date,bookings.id AS booking_id,bookings.comments, bookings.parking,bookings.driver_id, bookings.drop_address,bookings.drop_post_code,bookings.pickup_address,bookings.pickup_post_code, bookings.waiting_charges,bookings.fare,bookings.total_fare,bookings.waiting_time, bookings.hours,bookings.mins,bookings.other,
bookings.job_status,
customers.id AS customer_id, customers.name AS customer_name,customers.address1,customers.post_code,customers.city, customers.mobile, payment_type.name AS payment_type, employees.first_name AS driver,employees.id as driver_id, vehicles.make as vehicle, company_contact.name as company_contact,company_contact.email,
invoices.status as invoice_status,invoices.invoice_no
FROM bookings 
LEFT JOIN customers ON bookings.customer_id = customers.id 
LEFT JOIN payment_type ON bookings.payment_type = payment_type.id 
LEFT JOIN employees ON bookings.driver_id = employees.id 
LEFT JOIN vehicles ON bookings.vehicle_id = vehicles.id 
LEFT JOIN company_contact ON bookings.passenger_id = company_contact.id 
LEFT JOIN invoices ON bookings.invoice_no = invoices.invoice_no

";
$today= date('Y-m-d');
$from="";
$to="";
if(isset($_POST['company'])){
	$company=$_POST['company'];
$sql.="WHERE 
customers.id=$company 
AND bookings.job_status=2 

";	
}	
if (!empty($_POST['from']) && !empty($_POST['to']))
	{
	  $from=$con->real_escape_string($_POST['from']);
	  $from = str_replace("/","-",$from);
	  $from = date("Y-m-d", strtotime($from));
	  $to=$con->real_escape_string($_POST['to']);
	  $to = str_replace("/","-",$to);
	  $to = date("Y-m-d", strtotime($to));
	  $sql.=" AND bookings.pickup_date BETWEEN '$from' AND '$to'";
	}
	



$sql.=" ORDER BY bookings.id DESC
";

// $customer_id=$_GET['company_id'];
//WHERE customers.id=$customer_id GROUP BY bookings.id
$res=mysqli_query($con,$sql);
$rowcount=mysqli_num_rows($res);

//echo $sql;


?>
<body>
<form action="" method="post">
	<div class="container-fluid" style="margin-top:200x;">
						<label><h2> Select Jobs and Click Generate Invoice Button</h2></label>
			      <div class="well col-md-12" style="background-color:#e9e9e9; box-shadow: 5px 5px 5px;">
			       	 
                       <div class="form-group col-sm-5">
			       	   <select name="company" id="customer" class="form-control">
			       	   	 <option style="padding:10px; background-color:#E7D91E; color:#F9F0F1; cursor:pointer;" value="">Select a Customer </option>
                               <?php
							   
							        $customers_sql="SELECT * from customers order by name ASC";
									$t_result=mysqli_query($con,$customers_sql);
									while($customer=mysqli_fetch_assoc($t_result))
									{
									
									?>
	<option style="padding:20px; background-color:#2977C9; color:#F9F0F1; cursor:pointer;" value="<?php echo $customer['id']; ?>">
	   <?php echo $customer['name']." ,Mobile:".$customer['mobile']." ,".$customer['address1']." ".$customer['post_code']; ?>
    </option>
						<?php
						
						}
						?>
			       	   </select>
			       	   </div>
                       <div class="col-md-2">
 						<input type="text" name="from" class="from form-control" placeholder="Date From" id="from">
                     </div>
                       <div class="col-md-2">
                        <input type="text"  name="to" class="to form-control" placeholder="Date To" id="to">
             		 </div>
        
                       <div class="col-md-1">
                       	  <input type="submit" id="select_jobs" class="btn btn-warning" value="Search Jobs">
                       </div>
                       <div class="col-md-2">
                          <input type="button" name="btn" value="Generate Invoice" id="submitBtn" data-toggle="modal" data-target="#confirm-submit" class="btn btn-success btn-sm pull-right" />
                       </div>
			       	   
                       <!-- now retrieve the transactions of this customer -->
                   </div>
                 			
</div>
				  
			    
</form>
<div class="container-fluid">
  
      <div class="col-md-12" id="filter_results">
        
          <form action="" method="post" id="invoice">
            
<table  style="font-family:Montserrat; font-size:13px;" id="list_jobs" class="table table-responsive list_jobs table-hover table-bordered table-striped table-info" cellspacing="0" border="1">

        <thead>
       
            <tr class="btn-primary" style="padding:10px;">
                           <th>Job ID</th>
                           <th>Pickup Date</th>
                           
                           <th>Company/Passenger</th>
                          
                           <th>Pickup From</th>
                           
                           <th>Drop To</th>
                            <th>Driver</th>
                           <th>Waiting Time</th>
                           <th style="text-align:right;">Waiting Charges</th>
                           <th style="text-align:right;">Parking</th>
                           <th style="text-align:right;">Fare</th>
                           <th style="text-align:right;">other</th>
                           <th style="text-align:right;">Total Fare</th>
                           <th><input type="checkbox" id="select_all" /> Select all</th>
                          
            </tr>

        </thead>

        <tfoot>

            <tr class="btn-primary">
                          <th>Job ID</th>
                           <th>Pickup Date</th>
                          
                           <th>Company/Passenger</th>
                          
                           <th>Pickup From</th>
                           
                           <th>Drop To</th>
                            <th>Driver</th>
                            <th>Waiting Time</th>
                            <th style="text-align:right;">Waiting Charges</th>
                           <th style="text-align:right;">Parking</th>
                           <th style="text-align:right;">Fare</th>
                           <th style="text-align:right;">other</th>
                           <th style="text-align:right;">Total Fare</th>
                           <th><input type="checkbox" id="select_all" /> Select all</th>

        </tfoot>

        <tbody>
        

        <?php

                while($job=mysqli_fetch_assoc($res))

                  {
					  //echo $job['payment_type'];
					  //exit;
					 
					 ?>
                     <?php if($job['invoice_status']<3 AND $job['invoice_status']>0){?>
					 <tr style="background-color:#07E427;">
					<?php }?>
                      <input name="hours[]" type="hidden" value="<?php echo $job['hours'];?>">
                              <input name="mins[]" type="hidden" value="<?php echo $job['mins'];?>">
                              <?php $pickup_time= $job['hours'].":".$job['mins'];?>
                           <td><input name="booking_id[]" type="hidden" value="<?php echo $job['booking_id'];?>"><label><?php echo $job['booking_id'];?></label></td>
                           <td><input name="booking_date[]" type="hidden" value="<?php echo date("d/m/y", strtotime($job['pickup_date']));?>"><label><?php echo date("d/m/y", strtotime($job['pickup_date']))." at ".$pickup_time;?></label></td>
                           
                          <input name="customer_name[]" type="hidden" value="<?php echo $job['customer_name'];?>">
                           <input type="hidden" name="customer_id" value="<?php echo $job['customer_id'];?>"/>
                           <td><input name="company_contact[]" type="hidden" value="<?php echo $job['company_contact'];?>"><label><?php echo $job['customer_name']."/".$job['company_contact'];?></label></td>
                            <!-- Pickup Address -->
                           <td>
                             <input name="address1[]" type="hidden" value="<?php echo $job['address1'];?>">
                              <input name="city[]" type="hidden" value="<?php echo $job['city'];?>">
                               <input name="post_code[]" type="hidden" value="<?php echo $job['post_code'];?>">
                               
                              <label><?php echo $job['address1'].",".$job['city'].",".$job['post_code'];?></label>
                           </td>
                            <!-- Drop Address --> 
                           <td>
                             <input name="drop_address[]" type="hidden" value="<?php echo $job['drop_address'];?>">
                               <input name="drop_post_code[]" type="hidden" value="<?php echo $job['drop_post_code'];?>">
                               
                              <label><?php echo $job['drop_address'].",".$job['drop_post_code'];?></label>
                           </td>
                           <?php $booking_id=$job['booking_id'];?>
                           <td><input name="driver[]" type="hidden" value="<?php echo $job['driver'];?>"><label><?php echo $job['driver'];?></label></td>
                        
                          <td><input name="waiting_time[]" type="hidden" value="<?php echo $job['waiting_time'];?>"><label><?php echo $job['waiting_time'];?></label></td>
                          
                          <td style="text-align:right;"><input name="waiting_charges[]" type="hidden" value="<?php echo $job['waiting_charges'];?>"><label><?php echo "£".$job['waiting_charges'];?></label></td>
                          <td style="text-align:right;"><input name="parking[]" type="hidden" value="<?php echo $job['parking'];?>"><label><?php echo "£".$job['parking'];?></label></td>
                          <td style="text-align:right;"><input name="fare[]" type="hidden" value="<?php echo $job['fare'];?>"><label><?php echo "£".$job['fare'];?></label></td>
                          <td style="text-align:right;"><input name="other[]" type="hidden" value="<?php echo $job['other'];?>"><label><?php echo "£".$job['other'];?></label></td>
                          <td style="text-align:right;"><input name="total_fare[<?php echo $booking_id;?>]" type="hidden" value="<?php echo $job['total_fare'];?>"><label><?php echo "£".$job['total_fare'];?></label></td>
                           <td style="text-align:right;"><input name="selected_booking[]" type="checkbox" class="checkbox selected_booking" value=<?php echo $job['booking_id'];?>></td>
                        
                                    <input type="hidden" id="selected_booking">
										</td>
       
                          
                 
              </tr>
   <?php } ?>
   		 </tbody>
			   </table>
 
 </form>

        
		    </div>
	    </div>
</div>
<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                Confirm Submit
            </div>
            <div class="modal-body">
                Are you sure you want to create invoice of these bookings. Once created, invoice can not be deleted. Are You Sure?
               
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal">Check Again</button>
                <a href="#" id="submit" class="btn btn-success success">Generate Invoice</a>
            </div>
        </div>
    </div>
</div>


 <?php
 if(isset($_POST['selected_booking']))
			{
				
			$booking_id=$_POST['selected_booking'];
			//print_r($booking_id);
		/*	
			echo "<pre>";
  				 print_r($_POST);
			echo "</pre>";
		    exit;
		*/
		$bookingIds = $_POST;
		
		$sql="select customer_id from bookings WHERE id=".$booking_id[0];
		
		$result=$con->query($sql);
		$customer_data=mysqli_fetch_assoc($result);
		$customer_id=$customer_data['customer_id'];
		$today= date('Y-m-d');
		$create_invoice_sql="INSERT INTO invoices 
		(status,date,customer_id) VALUES('2','$today','$customer_id');";
		
		
		if (!mysqli_query($con,$create_invoice_sql)) {
			  echo $create_invoice_sql;
			  die('INSERT 3 INTO Bookings -Error: ' . mysqli_error($con));
			  exit;
		  }
		   $invoice_no=mysqli_insert_id($con);
		  
		  // exit;
			$count=count($_POST['selected_booking']);
			//echo $count;
			$total_fare='';
			$sum='';
			for ($i=0;$i<$count;$i++){
			$counter=1+$i;
			$index = array_search($_POST['selected_booking'][$i] ,$bookingIds['booking_id']);
			//echo "index=".$index;
		$booking_id=$con->real_escape_string($_POST['selected_booking'][$i]);
		//echo $booking_id;
        $total_fare=$con->real_escape_string($_POST['total_fare'][$booking_id]);
	//echo $total_fare;
	//exit;
	$sum +=  $total_fare;
	
	// Now update the bookings with invoice number
					  $update_booking="UPDATE bookings SET
					  invoice_no=$invoice_no,
					  invoice_status=2
					  WHERE id=$booking_id";
					  //echo $update_booking;
					  //exit;
						if (!mysqli_query($con,$update_booking)) {
							echo $update_booking;
							die('INSERT 3 INTO Bookings -Error: ' . mysqli_error($con));
							exit;
						 }
  }

		// Now we got total of all selected values so now update update invoice
	
		
		
//The VAT rate / percentage.
$vat_p = 20;
 
 
//Calculate how much VAT needs to be paid.
$vat = ($sum / 100) * $vat_p;
 
//The total price, including VAT.
$gross = $sum + $vat;
 
//Print out the final price, with VAT added.
//Format it to two decimal places with number_format.
$nett= $sum;
$vat= $vat;
$gross= $gross;

		$update_invoice_sql="UPDATE invoices 
		SET
		nett='$nett',
		vat='$vat',
		gross='$gross'		
		WHERE invoice_no=$invoice_no
		";
		//echo $update_invoice_sql;
		//exit;
		if (!mysqli_query($con,$update_invoice_sql)) {
			  echo $update_invoice_sql;
			  die('INSERT 3 INTO Bookings -Error: ' . mysqli_error($con));
			  exit;
		  }
		   echo '<script>alert("Invoice Created Succesfully");window.location.replace("new_invoice.php");</script>';
		}
			?>
            
<script type="text/javascript">

$(document).ready(function(){
    $('#select_all').on('click',function(){
        if(this.checked){
            $('.checkbox').each(function(){
                this.checked = true;
            });
        }else{
             $('.checkbox').each(function(){
                this.checked = false;
            });
        }
    });
    
    $('.checkbox').on('click',function(){
        if($('.checkbox:checked').length == $('.checkbox').length){
            $('#select_all').prop('checked',true);
        }else{
            $('#select_all').prop('checked',false);
        }
    });
});
</script>

<script>
$('#submit').click(function(){
   // alert('submitting');
	
    $('#invoice').submit();
	
});

</script>
<script>
//When user click on Start_date execute the filter
  $('.to').datepicker({
	
    	onSelect: function() {
			
			$( ".to" ).datepicker( "option", "dateFormat","dd/mm/yy");
		var to=$('#to').val();
                $( ".from" ).datepicker( "option", "dateFormat","dd/mm/yy");
		
    }
  
  });

	$('#name').keyup(function(){
	
});	
$('.from').datepicker({
	
    	onSelect: function() {
			
                $( ".from" ).datepicker( "option", "dateFormat","dd/mm/yy");
		
        }
        });
</script>
</body>
</html>