<?php
	include("includes/dbconfig.php");
	$pagetitle = "New Job Entry";
	require('includes/applicationtop.php');
	require('includes/applicationmenu.php');

    
   
    
?>
			<!-- Content Wrapper. Contains page content -->
			<div class="content-wrapper">
				<!-- Content Header (Page header) -->
				<section class="content-header">
					<h1><?= $pagetitle;?></h1>
					<ol class="breadcrumb">
					</ol>
				</section>

				<!-- Main content -->
				<section class="content">
					<!-- Default card -->
					<?php
						if($_SESSION["connectedusergroup"] == 3 || $_SESSION["connectedusergroup"] == 4)
						{


                            if(isset($_POST['counter'])){
                                $start = $_POST['counter'];
                                $clientname = $_POST['clientname'];
                                $location = $_POST['location'];
                                $memo = $_POST['memo'];
                                $pickup = $_POST['pickup'];
                               

                                $storehere =array();
 
                                for($i =1; $i< ($start +1); $i++){
                                   
                        
                                    $machine   = $_POST['jobdata'.$i.''];
                                    $specifics = $_POST['specifics'.$i.''];

                                    if(!empty($machine) and !empty($specifics)){
                                         
                                        $jobtype   = $_POST['jobtype'.$i.''];
                                        $owner     = $_POST['owner'.$i.''];
                                        
                                        $jobmemo = $_POST['jobmemo'.$i.''];
                                        $job = array("machine"=>$machine, "type"=>$jobtype,  "owner" => $owner, "jobmemo" => $jobmemo,  "jobs"=> $specifics);
                                        array_push( $storehere , $job);

                                    }
                                }

                               

                                    
                                if(!empty($storehere)){


                                    
                                    $_SESSION['multiplejobs'] = array("start" =>$start, "client"=>$clientname, "location" =>$location , "memo"=>$memo, "pickup"=>$pickup , "machines" =>$storehere );

                                    ?>
                                    <script>
                                        //location.href=  "payformultiples";
                                    </script>
                                    <?php
                                
                                }

                                

                        
                                
                        
                        
                            }
					?>
					<div class="card card-info">
                                <div class="card-header">
                                    <h6 class="card-title"><?= $pagetitle ?></h6>
                                </div>
                                <div class="card-body">

                                <form name="contact"  id="contact"  action="">
                                    

                                <?php
                                $priced = DB::query("SELECT * FROM repair_jobnames");
                                $personel = DB::query("SELECT id, first_name , last_name FROM personnel_details where employee_role  ='2'   "); 
                                $locations = DB::query("SELECT * FROM repair_location");
                                $jobtypes = DB::query("SELECT * FROM repair_jobtypes");
                                
                                ?>
                            <table class='table' id='maintable'>
                                 
                                <tr id='1'> <td width='50%'>  <b>Customer Details <input type='hidden' id='cleancode'  value='<?= time();?>' /></b>  <br />  
										 
                                         <input type="text" id="search-card" placeholder="Search a customer here" required />
                                      
                                      
                                     <select class="form-control  "   style="width: 100%;"  name="clientname" id="clientname">
                                       
                                       <option value="0"   >No Name</option>
                                        
                                     </select></td>
                                     <td> <br /> 

                                     <b>Job Location</b>  <br /> 
         
                                            <select  class="form-control" name="location"   id = "location"  data-placeholder="Choose One">
                                                    
                                                    <?php
                                                        
                                                        
                                                        foreach($locations as $ow)
                                                        {
                                                    ?>
                                                    <option  value="<?php echo $ow['locid']; ?>"><?php echo $ow['loc_name']; ?></option>
                                                    <?php
                                                        }
                                                    ?>
                                                    </select>
              


                                     </td>
                                     <td> <br /> 


<b>Owner's Category</b>  <br /> 

<select  class="form-control" name="owner"   id = "ownercat"  data-placeholder="Choose One">
        
        <?php
            $owner = DB::query("SELECT * FROM repair_owner_category");
            
            foreach($owner as $ow)
            {
        ?>
        <option  value="<?php echo $ow['owid']; ?>"><?php echo $ow['owner']; ?></option>
        <?php
            }
        ?>
        </select>
                                                    </td>
                                    
                                    </tr>

                                     <tr>
                                        <td colspan='3' id='playground'>
                                            <?php 
                                            for($i =1; $i<2; $i++){
                                            ?>
                                        <div class="card card-primary">
                                            <div class="card-header">
                                                <h6 class="card-title">#<?= $i?> <button type='button' class='btn btn-mini btn-warning addnewrow' value="tableno<?= $i?>"  onclick="addjobfield(<?= $i;?>);" > <i        class="fas fa-plus right label label-info">Job particulars</i> </button></h6>
                                            </div>
                                            <div class="card-body">
                                            <table class='table table-bordered table-hover' id="tableno<?= $i?>">
                                                <tr> 
                                                    <td> 
                                                    <b>Items in Group</b>  <br /> 
										 
                                                       <input type="text" class="form-control"   id='jobdata<?= $i?>' name='jobdata<?= $i?>'  required placeholder="Details about the new job" />
                                                    </td>
													
													 <td width='15%'> 
                                                    <b>#Pairs</b><br /> 
										 
										 
										 
										 
										
										
										 <input type="number" class="form-control span1"  value='1'  OnKeyUP= "howmuch()"    name="jobmemo<?= $i ?>" id="jobmemo<?= $i ?>" required placeholder="Pairs" />
                                               

										
                                                    </td>



													<td width='15%' colspan='2'> 
                                      

                                            <b>Job type</b>  <br /> 
                                                
                                                <select  class="form-control"  id="jobtype<?= $i?>" name="jobtype<?= $i?>" data-placeholder="Choose One">
                                                
                                                        
                                                        <?php
                                                           
                                                            
                                                            foreach($jobtypes as $useemployee_role)
                                                            {
                                                        ?>
                                                        <option  value="<?php echo $useemployee_role['rptid']; ?>"><?php echo $useemployee_role['rpt_name']; ?></option>
                                                        <?php
                                                            }
                                                        ?>
                                                        </select></td>  
                                                   
                                                </tr>

                                                <tr id='tr<?= $i?>'> 
                                                    <td colspan='2'> 

                                                    <label id='tl<?= $i?>'>Task(s)</label>
                                                    
                                                        <select class="  form-control "  onchange= "specifics(this.id)"       name="specifics<?= $i?>"   id="specifics<?= $i?>" >
                                                        <option > Select</option>
                                                        <?php
                                                                   
                                                                    foreach($priced as $row)
                                                                    {
                                                                    
                                                                        ?>
                                                                        <option  value="<?php echo $row['job_id']; ?>"><?php echo $row['job_name']; ?> @<?= $row['job_amount'];?></option>
                                                                        <?php
                                                                
                                                                }
                                                                ?>
                                                        
                                                        </select>
                                                       
                                                        

                                                    </td>

                                                    <td colspan='2'> 
                                                    <label>Amount</label>
                                                    <input type='number' class="  form-control" name='charged<?= $i?>' id='charged<?= $i?>'  >
                                                    
                                                  </td>
                                                </tr>
                                            </table>

                                            <p align="right" id='p<?=$i?>'>  </p>

                         

                                        </div>
                                     </div>

                                     <?php } ?>

                                     

                                        </td>

                                     </tr>
                                     <tr> <td colspan='3'> <p align='right'> <button type='button' class='btn btn-mini btn-info' id="addRow"><i       class="fas fa-plus right label label-info">Add Item</i> </button> </p></td></tr>




                                     <tr>
                                        <td>
                                        <div class="form-group col-md-12">
                                        <label for="cashpaidin">Additional Notes </label>
										<textarea name="memo" id="memo" rows="2" placeholder="Additional Notes ..." maxlength="200" class="form-control"></textarea>

                                        <input type='hidden' value='1' id='counter' name='counter' />
										<label for="cashpaidin">Will be ready on? </label>
										<input type="date" name="pickup" id="pickup"   class="form-control"  >
									</div><!-- form-group -->
                                 </td><td colspan='2'>


                                    <div class="form-group col-md-12 bg-gradient-info" onClick="howmuch()">
                                        

                                        <div class="row"> 
                                                    <div class="col-md-6">
                                                    <label for="count">Total Items </label>
                                                                </div>
                                                    
                                                    <div class="col-md-6">
                                                    
                                                    <h4 name="count" id="count"> 0</h4>
                                                     </div>
                                                    </div>


                                                    <div class="row"> 
                                                    <div class="col-md-6">
                                                    <label for="humanbill">Charge / Total </label>
                                                                </div>
                                                    
                                                    <div class="col-md-6">
                                                    <h4 id='humanbill'> 0</h4>
                                                     </div>
                                                    </div>

                                                    <div class="row"> 
                                                    <div class="col-md-6">
                                                    <label for="humanbalance">Balance </label>
                                                                </div>
                                                    
                                                    <div class="col-md-6">
                                                    <h4 id='humanbalance'> 0</h4>
                                                     </div>
                                                    </div>

                                                    <div class="row" style="padding:10px;"> 
                                                    <div class="col-md-6">
                                                    <label for="receiptmode">Mode of payment </label>
                                                                </div>
                                                    
                                                    <div class="col-md-6">
                                                    
																<select  class="form-control" name="receiptmode" id="receiptmode"  >
																	<?php
																		$paymentmodedata = DB::query("SELECT id, payment_name FROM payment_type");
																		
																		foreach ($paymentmodedata as $paymentmode)
																		{
																	?>
																	<option value="<?php echo $paymentmode['id']; ?>"><?php echo $paymentmode['payment_name']; ?></option>
																	<?php
																		}
																	?>
																</select>
                                                     </div>
                                                    </div>

                                                    <div class="row" style="padding:10px;"> 
                                                    <div class="col-md-6">
                                                    <label for="paid">Paid </label>
                                                                </div>
                                                    
                                                    <div class="col-md-6">
                                                    <input type="number"    name="paid" id="paid"  value='0' OnKeyUP='Balance()'   class="form-control"  >
                                                     </div>
                                                    </div>
                                   
                                        
									 
										
										
                                       
                                        
										<input type="hidden"  readonly name="bill" id="bill"    class="form-control"  >

                                        
                                        
                                        
										<input type="hidden"  readonly name="balance" id="balance"    class="form-control"  >
                                        

                                       
										
                                        
									</div>
                                    
                                    <!-- form-group -->
									
									<div class="btn-list col-md-12 text-center">
										<button onclick="cancelsale()" class="btn btn-danger"><i class="fa fa-remove"></i> Cancel  </button>
										
										<button id="tableprocess" class="btn btn-success"><i class="fa fa-floppy-disk"></i> Continue</button>
									</div>
                                         </td>
                                         </tr>
                        </table>

                        </form>
							 
						</div>
					</div>
				
					 	
						 
						 
					<?php
						}
						else
						{
					?>
					<div class="alert alert-danger alert-dismissable">
						<i class="fa fa-ban-circle"></i>
						Limited Access
					</div>
					<?php
						}
					?>
				</section><!-- /.content -->
			</div><!-- /.content-wrapper -->

			 
		</div><!-- ./wrapper -->


        <div class="modal" id="largemodalr">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
						<h4 class="modal-title text-center">Response</h4>
					</div>
					<div class="modal-body">
						 
						
						 
						 
                        <div class="card-body  "  id="modelresults">
                            
                 
                        </div>
           
                       
        
						 
					</div>
					<div id="notesfooter" class="modal-footer">
                    <a href="<?= $base_url ?>multiple.php"     class="btn btn-danger"><i class="fa fa-times"></i> Close</a>
						<a href="<?= $base_url ?>multiple.php"   class="btn btn-info"><i class="fa fa-plus"></i> New Job</a>
					</div>
				</div>
			</div>
		</div>
		
		 
		
	<?php include ('includes/general_footer.php')?>
 
		
		<script src="plugins/bert/jquery.price_format.min.js" type="text/javascript"></script>
		<script src="plugins/bert/storepos.js" type="text/javascript"></script>
		<script src="plugins/bert/jobcard.js" type="text/javascript"></script> 

         

        <script>
             function deleteRow(btn) {
                var row = btn.parentNode.parentNode; 
                row.parentNode.remove();
                howmuch();
            }
 
  
            function Balance(){
                var balance = 0;
                if(parseInt($('#paid').val()) > 0){
                     balance = parseInt($('#bill').val()) - parseInt($('#paid').val());

                }
               
                 $('#balance').val(balance);
                 $('#humanbalance').html(balance.toLocaleString('en-US'));
                return false;
            }
            function howmuch(){
                
                
                
                    var k =  parseInt($('#counter').val());

                            var total= 0;
                            var quantities = 0;
                            for(var i =1; i<k+1; i++){
                                
                                var rows = $('#tableno'+i+' tr').length;  
                                var qty =parseInt($('#jobmemo'+i+'').val()); 
                                if(qty > 0){
                                
                                
                                for(var j =1; j< rows; j++){
                                    var $row2 = $('#tableno'+i).closest('table').find('tr:eq('+j+')');
                                    var item =   parseInt($('#'+$row2.find('select').attr('id')).val());
                                    if(item > 0){
                                    var newcharged =   parseInt($('#'+$row2.find('input').attr('id')).val()); 
                                    
                                     total += newcharged*qty; 
                                     
                                    }
                                    
                                } 
                                quantities += qty; 
                             }
                            }
                            

                           $('#bill').val(total);
                           $('#count').html(quantities);
                           $('#humanbill').html(total.toLocaleString('en-US'));
                          // $('#humanbill').priceFormat({ prefix: ',',  total: '' });
                           
                           Balance();
 

                 }
                $("#tableprocess").click(function(e){

                    var k =  parseInt($('#counter').val()); 

                    var location =   parseInt($('#location').val());
                    var client   =  parseInt($('#clientname').val());
                    var ownercat =  parseInt($('#ownercat').val());
                    var bill     =  parseInt($('#bill').val());
                    var paid     =  parseInt($('#paid').val());
                    var memo     =  $('#memo').val();
                    var pickup   =  $('#pickup').val();//receiptmode
                    var rmode    =  $('#receiptmode').val();

                    var cleancode    =  $('#cleancode').val();

                    if(client < 1){

                        alert('Client is missing');
                        $('#clientname').focus();

                        return false;
                    }
                    
                     
                    var process = [];
                    for(var i =1; i<k+1; i++){
                        
                        var rows = $('#tableno'+i+' tr').length; 
                         var  tasks =[];
                         var qty =parseInt($('#jobmemo'+i+'').val()); 
                         var theheader = extract_header(i);
                          
                         if(qty > 0){
                        for(var j =1; j< rows; j++){ 
                             var $row2 = $('#tableno'+i).closest('table').find('tr:eq('+j+')');
                             var newcharged =   parseInt($('#'+$row2.find('input').attr('id')).val()); 
                             var item =   parseInt($('#'+$row2.find('select').attr('id')).val());
                             if(item > 0){
                             
                              var task =  { 'task' : item , 'charged' : newcharged  }; 
                              tasks.push(task);
                             }

                             
                        }
                        if(tasks.length > 0   ){
                             process.push({'tasks': tasks ,'product': theheader} );
                        }
                    }
                }
                var final = [];  
                   if(process.length > 0){
                       
                       $.ajax({
                            type: "POST",
                            url: "jobcardformprocess.php",
                            data:{'customer_data': { 'receiptmode':rmode, 'memo': memo ,'pickup': pickup ,'client': client ,'bill': bill ,'paid': paid , 'ownercat':ownercat , 'location':location , 'cleancode':cleancode} ,'jobs': process} ,
                            beforeSend: function(){
                                
                                //$("#clientname").css("background","#FF0");
                            },
                            success: function(data){ 
                                 
                                $('#modelresults').html(data);
                                $('#largemodalr').modal('show');
 
                            }
                            });
                        

                   }else alert('Not enough data to process');
                  
                   
                   
                    return false;
        
	});

    function extract_header(id){

        var $header = $('#tableno'+id+'').closest('table').find('tr:first');

        var job = $('#jobdata'+id+'').val();
        var qty =parseInt($('#jobmemo'+id+'').val()); 
        var jtp =parseInt($('#jobtype'+id+'').val()); 
        if(job.length < 1){
            
            alert('Item name missing');
            $('#jobdata'+id+'').focus();
            return false;
        } else {

         var header =  {'job' :job, 'qty' :qty,'jtp' :jtp};
        return header;
        
        } 

        }
                    

                
      $('#addRow').on('click', function() {
         
        var k =  parseInt($('#counter').val());
        k = k+1; 
        var $row = $('#tableno1').closest('table').find('tr:first');
        var $row2 = $('#tableno1').closest('table').closest('tr').find('tr:eq(1)');
        
        var $newRow = $row.clone(); //clone it  
        $newRow.find('input:text').attr('name', "jobdata"+k);
        $newRow.find('input:text').attr('id', "jobdata"+k);
        
        $newRow.find('input:eq(1)').attr('name', "jobmemo"+k);
        $newRow.find('input:eq(1)').attr('id', "jobmemo"+k); 

        $newRow.find('select').attr('name', "jobtype"+k);
        $newRow.find('select').attr('id', "jobtype"+k);  

        
                                 //now modify their ids ad names 
        var $newRow2 = $row2.clone();  
        const d = Date.now();
        
        $newRow2.find('select').attr('name', "specifics"+d);
        $newRow2.find('select').attr('id', "specifics"+d); 

        $newRow2.find('input').attr('name', "charged"+d);
        $newRow2.find('input').attr('id', "charged"+d); 
        var f =  $('  '+job_button(k)+'   ');
        var h =  $(' <div class="card card-primary"> <div class="card-header">  #'+k+' '+job_button(k)+'   </div><div class="card-body"><table class="table table-bordered  " id="tableno'+k+'"> ');  
        
        var tr = $(  $newRow  );
        var tr2 = $(  $newRow2  );
        //id="p'+k+'
        $('#playground').append(h);
        $('#tableno'+k).append(tr);
        $('#tableno'+k).append(tr2);  
        $('#counter').val(k);
        howmuch();
        
  
        
      });
    //}); 
    function addjobfield(tid){
        
            var todelete = 'Task(s)<button type="button"  value="Delete"class="btn btn-danger btn-mini"  onclick="deleteRow(this)">Delete </button>';
            var $lastRow  = $('#tableno'+tid).closest('table').find('tr:last');
            var k          = Date.now();
            $lastRow.find('tr').attr('id', "tr"+k); 
            var $newRow   = $lastRow.clone();  
           $('#tableno'+tid).append($newRow);
           var newcharged = $newRow.find('input').attr('name');
           var newspec    = $newRow.find('select').attr('name'); 
            $newRow.find('select').attr('name', "specifics"+k);
            $newRow.find('select').attr('id', "specifics"+k); 

            $newRow.find('input').attr('name', "charged"+k);
            $newRow.find('input').attr('id', "charged"+k);
            $newRow.find('label').attr('id', "tl"+k);  
            $("#charged"+k+"").val(0); 
            $('#tl'+k).html(todelete); 
             howmuch(); 
        
              return false;
 
    }


function job_button(k){
    return ' <button type="button" class="btn btn-mini btn-warning addnewrow" value="tableno'+k+'"  onclick="addjobfield('+k+');" >  <i        class="fas fa-plus right label label-info">Job particulars</i> </button>';

    return '<p align="right" id="p'+k+'"> <button type="button" class="btn btn-mini btn-warning addnewrow" value="tableno'+k+'"  onclick="addjobfield('+k+');" >'+k+' <i        class="fas fa-plus right label label-info">Job particulars</i> </button> </p>';

}

 
            function specifics(sk){ 
               
                var charged = $("#"+sk).find(":selected").text().split('@');
                 
                var name = $("#"+sk).prop('name').split('specifics');
                            $("#charged"+name[1]).val( charged[1]); 
                            howmuch();
                return false;
            }

      
 
  $(function () {
   

   
	$('#change_display').hide();

	$("#receiptmode").change(function()
    {
		//$('#change_display').hide();
		var id=$(this).val();
		
		var totalbill = 0.00;
				
			$("#cartitemstable").children("tbody").children("tr").each(function(i) 
			{
				$tr = $(this);
				var useindex = 0;

				$("td", $tr).each(function() 
				{
					 
					
					if(useindex == 4)
					{
						totalbill += parseFloat($(this).text().replace(/[^0-9\.]/g,""));
					}
					
					useindex +=1;
				});
			});

		 
         
         return false;
    });
 
  })
  
  // AJAX call for autocomplete 
$(document).ready(function(){
	$("#search-card").css("background","#ffe6e6");
	
	$("#search-card").keyup(function(){
		 
		$.ajax({
		type: "POST",
		url: "get_customers.php",
		data:'keyword='+$(this).val(),
		beforeSend: function(){
			 
			$("#clientname").css("background","#FF0");
		},
		success: function(data){ 
			$("#clientname").html(data); 
			 
			$("#clientname").css("background","#ffcccc");
			$("#search-card").css("background","#ffffff");
		}
		});
	});
	
	//search for items here
	
	$("#itemsearchtext").keyup(function(){
		 
		$.ajax({
		type: "POST",
		url: "searchjobs.php",
		data:'itemsearchtext='+$(this).val(),
		beforeSend: function(){
			 
			//$("#clientname").css("background","#FF0");
		},
		success: function(data){ 
			$("#searchresulthere").html(data); 
			  
		}
		});
	});
});
 
 
</script>
	</body>
</html>