<?php $this->load->view("common/header"); ?>
<!-- end: HEAD -->

<!-- start: CSS REQUIRED FOR THIS PAGE ONLY -->
s
<style type="text/css">
label {
	font-weight: 700;
}
.table> thead:first-child> tr:first-child> th, .table> thead:first-child> tr:first-child> td, .table-striped thead tr.primary:nth-child(2n+1) th {
	background-color: #428bca;
	border-color: #357ebd;
	border-top: 1px solid #357ebd;
	color: white;
	text-align: center;
}
.form-horizontal .form-group {
	margin-left: 0;
	margin-right: 0;
}
</style>

<!-- end: CSS REQUIRED FOR THIS PAGE ONLY -->
<!-- end: HEAD -->
<!-- start: BODY -->
<body>

<!-- start: HEADER -->
<div class="navbar navbar-inverse navbar-fixed-top"> 
  <!-- start: TOP NAVIGATION CONTAINER -->
  <div class="container">
    <div class="navbar-header"> 
      <!-- start: RESPONSIVE MENU TOGGLER -->
      <button data-target=".navbar-collapse" data-toggle="collapse" class="navbar-toggle" type="button"> <span class="clip-list-2"></span> </button>
      
      <!-- end: RESPONSIVE MENU TOGGLER --> 
      <!-- start: LOGO -->
      <?php $this->load->view("common/logo"); ?>
      <!-- end: LOGO --> 
    </div>
    <div class="navbar-tools"> 
      <!-- start: TOP NAVIGATION MENU -->
      <?php $this->load->view("common/notifications.php"); ?>
      <!-- end: TOP NAVIGATION MENU --> 
    </div>
  </div>
  <!-- end: TOP NAVIGATION CONTAINER --> 
</div>
<!-- end: HEADER --> 
<!-- start: MAIN CONTAINER -->
<div class="main-container">
<div class="navbar-content"> 
  <!-- start: SIDEBAR -->
  <?php $this->load->view("common/navigation"); ?>
  <!-- end: SIDEBAR --> 
</div>
<!-- start: PAGE -->
<div class="main-content">
<!-- end: SPANEL CONFIGURATION MODAL FORM -->
<div class="container">
<!-- start: PAGE HEADER -->
<div class="row">
  <div class="col-sm-12"> 
    <!-- start: PAGE TITLE & BREADCRUMB -->
    <ol class="breadcrumb">
      <li> <a href="#"> Dashboard </a> </li>
      <li> <a href="<?php echo base_url('sales?s='.rand()); ?>"> Invoice </a> </li>
      <li class="active"> Add New Invoice </li>
      <li class="search-box">
        <form class="sidebar-search">
          <div class="form-group">
            <input type="text" placeholder="Start Searching...">
            <button class="submit"> <i class="clip-search-3"></i> </button>
          </div>
        </form>
      </li>
    </ol>
    <div class="page-header">
      <h4>New Invoice</h4>
    </div>
    <p>Please fill in the information below. The field labels marked with * are required input fields.</p>
   
  </div>
</div>
<!-- end: PAGE HEADER --> 
<!-- start: PAGE CONTENT 
                    <!-- start grid -->
<div class="row">
  <div class="col-md-12"> 
    <!-- start: DYNAMIC TABLE PANEL -->
    <div class="panel panel-default">
      <div class="panel-heading"> <i class="fa fa-plus"></i>
        <label class="form-group">Delivery No: <?php echo $cus_order_details['delivery_id']; ?> </label>
        /
        <label class="form-group" for="customer_id">Customer : <?php echo $customer_details[0]['cus_name']; ?></label>
      </div>
      <div class="panel-body">
        <div class="alert alert-danger" style="display:none;">
          <button class="close" data-dismiss="alert"> × </button>
          <i class="fa fa-times-circle"></i> <strong></strong> <span class="errortxt"></span> </div>
        <div class="alert alert-success" style="display:none;">
          <button class="close" data-dismiss="alert"> × </button>
          <i class="fa fa-check-circle"></i> <strong></strong><span class="succetxt"></span> </div>
        <form role="form" class="form-horizontal" id="create_sales_form" action="#" method="post">
          <input id="delivery_id" name="delivery_id" type="hidden" value="<?php echo $cus_order_details['delivery_id']; ?>" />
          <input id="cus_order_master_id" name="cus_order_master_id" type="hidden" value="<?php echo $cus_order_details['cus_order_master_id']; ?>" />
          <input type="hidden" id="customer_id" class="" name="customer_id" value="<?php echo $cus_order_details['customer_id']; ?>" />
          <div class="col-md-12"></div>
          <!--col-md-12-->
          <div class="col-md-12">
            <div class="col-md-2">
              <div class="form-group">
                <label>Date *</label>
                <?php $nowdate=date("Y-m-d");?>
                <input id="sale_datetime" name="sale_datetime" type='text' class="form-control date" value="" data-bv-field="date"/>
              </div>
            </div>
            <div class="col-sm-2">
              <div class="form-group">
                <label>Warehouse * </label>
                <select id="warehouse_id" class="form-control search-select" name="warehouse_id" readonly>
                  <?php 
												$ss_warehouse_id= $cus_order_details['wharehouse_id'];
                                                foreach ($warehouse_list as $row)
                                                  {
													  $sel='';
													  if($ss_warehouse_id==$row->id)
														{
															$sel=' selected="selected"';
														}?>
                  <option value="<?php echo $row->id; ?>" <?php echo $sel; ?> > <?php echo $row->name; ?> </option>
                  <?php }?>
                </select>
              </div>
            </div>
            
            
            <div class="col-sm-3">
              <div class="form-group">
                <label> Sales Representative * </label>
                
                <select id="sales_rep_id" class="form-control search-select" name="sales_rep_id">
                  <option value="">--SELECT--</option>
                  <?php
foreach ($sales_rep_list as $row){?>
                  <option value="<?php echo $row['user_id'];?>" <?php if(isset($cus_order_details['order_rep_id'])&&$row['user_id']==$cus_order_details['order_rep_id'])echo 'selected="selected"'?>> <?php echo $row['user_first_name'];?></option>
                  <?php			}  ?>
                </select>
              </div>
            </div>
            <div class="col-md-2">
              <div class="form-group">
                <label>Invoice Type* </label>
                <select id="invoice_type" class="form-control search-select" name="invoice_type" >
                  <?php	foreach ($in_type_list as $itl){?>
                  <option value="<?php echo $itl['invoice_type_id']; ?>" <?php if(isset($cus_order_details['invoice_type'])&&$itl['invoice_type_id']==$cus_order_details['invoice_type'])echo 'selected="selected"'?> > <?php echo $itl['invoice_type_name']; ?> </option>
                  <?php }?>
                </select>
              </div>
            </div>
            <div class="col-md-2">
              <div class="form-group">
                <label>Refarance No *</label>
                <input type="text" class="form-control" id="card_ref_number" name="card_ref_number" onChange="check_recod()" value="<?php echo $cus_order_details['cus_order_ref_no']; ?>" readonly>
              </div>
            </div>
            <!--col-md-8-->             
            <!-- item add box-->
            <div id="sticker" class="col-md-12">
              <div class="well well-sm">
                <div class="form-group"> 
                  <!-- auto complete start -->
                  <div class="input-group wide-tip" style="display:none">
                    <div style="padding-left: 10px; padding-right: 10px;" class="input-group-addon"> <i class="fa fa-2x fa-barcode addIcon"></i> </div>
                    <input type="text" placeholder="Please add products to order list" id="add_item" class="form-control input-lg" value="" name="add_item" onClick="add_items()" style="border-radius: 6px;font-size: 18px;height: 46px;line-height: 1.33;padding: 10px 16px;">
                    <!--<div style="padding-left: 10px; padding-right: 10px;" class="input-group-addon">
															<i id="addIcon" class="fa fa-2x fa-plus-circle addIcon"></i></div>--> 
                  </div>
                  <!-- end auto complete end -->                   
                </div>
                <div class="clearfix"></div>
                <div class="control-group table-group">
                  <label class="table-label">Order Items</label>
                  <div class="controls table-controls">
                    <table class="table items table-striped table-bordered table-condensed table-hover" id="soTable">
                      <thead>
                        <tr>
                          <th class="col-md-7">Product Name (Product Code)</th>
                          <th class="col-md-2">Selling Price</th>
                          <th class="col-md-1">Quantity</th>
                          <th class="col-md-1 text-right">Discount </th>
                          <th class="col-md-1 text-right">Subtotal<span class="currency"></span> </th>
                          <th style="width: 30px !important; text-align: center;"><i class="fa fa-trash-o"></i> </th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr data-item-id="144680019784" class="row_144680019784" id="row_1446800197032">
                          <td></td>
                          <td class="text-right"></td>
                          <td></td>
                          <td class="text-right"></td>
                          <td class="text-right"></td>
                          <td class="text-center"></td>
                        </tr>
                      </tbody>
                      <tfoot>
                       
                        <tr class="tfoot active" id="tfoot">
                          <th colspan="4" class="text-right">Total Amount</th>
                          <th class="text-right"><span id="Subtotal">0.00</span> </th>
                        </tr>
                      
                      </tfoot>
                    </table>
                    
                    <!-- start list --> 
                    <!-- end list --> 
                  </div>
                </div>
              </div>
              <!-- end item add box-->
              <div class="col-md-2">
                <div class="form-group">
                  <label>Order Discount</label>
                  <br>
                  <input type="text" title="" data-original-title="" value="<?php echo $cus_order_details['order_discount']?>" class="form-control input-tip" id="sale_inv_discount" name="sale_inv_discount" onChange="changeMainDiscount(this.value)">
                </div>
              </div>
            </div>
          </div>
          <!-- end: col-md-12-->
          
          <div class="col-md-12">
            <div class="modal-footer" style="margin-bottom:10px;">
              <input type="submit" class="btn btn-primary" value="Add Sales" name="add_sale" id="add_sale">
              <button id="reset" class="btn btn-danger" type="button">Reset</button>
            </div>
          </div>
          <input name="sale_inv_discount_amount" type="hidden" id="sale_inv_discount_amount" value="0">
          <input name="sale_total" type="hidden" id="sale_total" value="0">
          <input name="sale_paid" type="hidden" id="sale_paid" value="0">
          <input name="sale_balance" type="hidden" id="sale_balance" value="0">
          <input name="rowCount" type="hidden" id="rowCount" value="0">
          <input name="cost_total" type="hidden" id="cost_total" value="0">
          <input name="cus_credit_limit" type="hidden" id="cus_credit_limit" value="10000">
          <input name="base_url" type="hidden" id="base_url" value="<?php echo base_url();?>">
        </form>
        
        <!-- end: DYNAMIC TABLE PANEL --> 
        
        <!-- footer amount details --> 
        <!--<div style="margin-bottom: 0px; position: fixed; bottom: 0px; width: 1082px; z-index: 50000;" class="well well-sm" id="bottom-total">
<table style="margin-bottom:0;" class="table table-bordered table-condensed totals">
<tbody><tr class="warning">
<td width="20%" class="credit_limit_td_class">Credit Limit <span id="credit_limit_txt" class="credit_limit_val pull-right">0.00</span></td>
<td class="previous_bill_td_class" style="display:none;">Previous Bill <span id="previous_bill_txt" class="pull-right">0.00</span></td>
<td width="30%">Total <span id="f_total" class="totals_val pull-right">0.00</span></td>
<td width="20%">Order Discount <span id="tds" class="totals_val pull-right">0.00</span></td>
<td>Grand Total <span id="gtotal" class="totals_val pull-right">0.00</span></td>
</tr>
</tbody></table>
</div>--> 
        <!-- end footer amount details --> 
        
      </div>
    </div>
    
    <!-- end grid --> 
    
  </div>
  <!-- end: PAGE --> 
</div>
<!-- end: MAIN CONTAINER --> 
<!-- start: FOOTER -->
<div class="footer clearfix">
  <div class="footer-inner"> 2014 &copy; clip-one by cliptheme. </div>
  <div class="footer-items"> <span class="go-top"><i class="clip-chevron-up"></i></span> </div>
</div>
<!-- end: FOOTER --> 
<!-- start: RIGHT SIDEBAR --> 
<!-- end: RIGHT SIDEBAR -->
<div id="event-management" class="modal fade" tabindex="-1" data-width="760" style="display: none;">
  <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>
        <h4 class="modal-title">Event Management</h4>
      </div>
      <div class="modal-body"></div>
      <div class="modal-footer">
        <button type="button" data-dismiss="modal" class="btn btn-light-grey"> Close </button>
        <button type="button" class="btn btn-danger remove-event no-display"> <i class='fa fa-trash-o'></i> Delete Event </button>
        <button type='submit' class='btn btn-success save-event'> <i class='fa fa-check'></i> Save </button>
      </div>
    </div>
  </div>
</div>
<input name="tmpVal" type="hidden" id="tmpVal" value="0">
<input name="" id="type_sale" type="hidden" value="22">
<!-- start ajax model -->
<div id="ajax-modal" class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1" style="display: none;"></div>
<!-- end ajax model --> 

<!-- start: MAIN JAVASCRIPTS -->
<?php $this->load->view("common/footer"); ?>
<!-- end: MAIN JAVASCRIPTS --> 
<!-- start: JAVASCRIPTS REQUIRED FOR THIS PAGE ONLY VALIDATION--> 
<script src="<?php echo asset_url(); ?>js/form-validation-create_sales.js"></script> 
<script src="<?php echo asset_url(); ?>js/sales.js"></script> 
<!-- end: JAVASCRIPTS REQUIRED FOR THIS PAGE ONLY  VALIDATION--> 

<script>		

	function addextraprice() {
		calculateTotal();
	}

				/*$(document).ready(function() {
				  $(window).keydown(function(event){
				    if(event.keyCode == 13) {
				      event.preventDefault();
				      return false;
				    }
				  });
				});*/
//--------------------------------------------------------------------
				$( '#add_item' ).keypress( function ( e ) {
					if ( e.which == 13 ) return false;
					//or...
					if ( e.which == 13 ) e.preventDefault();
				} );
//--------------------------------------------------------------------
				function changeQtyByProductID( qty, nxtCount ) {
					if ( isNaN( qty ) ) {
						displayNotice( 'page', 'Invalid Quantity' );
						var quantity_fld = '#quantity_' + nxtCount;
						var product_id_fld = '#product_id' + nxtCount;
						var oldVal = $( '#tmpVal' ).val();
						$( quantity_fld ).val( oldVal ); //set last val
					} else {
						//getavalable product count
						var product_id_fld = '#product_id' + nxtCount;
						var product_id = $( product_id_fld ).val();
						var availble_qty_fld = '#qtyforcheck_' + nxtCount;
						var availble_qty = parseFloat( $( availble_qty_fld ).val() );
						if ( qty <= availble_qty && qty > 0 ) {
							var warehouse_id = $( '#warehouse_id' ).val();
							$.get( "<?php echo base_url();?>sales/get_avalable_product_qty", {
									product_id: product_id,
									warehouse_id: warehouse_id
								} )
								.done( function ( data ) {
									var obj = jQuery.parseJSON( data );
								} );
							//end getavalable product count
							calculateTotal();
							//displayNotice('page','Product quantity successfully updated!');		
						} else {
							if ( qty > availble_qty ) {
								bootbox.alert( 'Out of stock.', function () {
									$( '#quantity_' + nxtCount ).focus();
								} );
							}
							if ( qty <= 0 ) {

								bootbox.alert( 'System cannot accept your quntity requirement.', function () {
									$( '#quantity_' + nxtCount ).focus();
								} );
							}
							$( '#quantity_' + nxtCount ).val( 1 );
							calculateTotal();
						}
					}
				}
//--------------------------------------------------------------------
				function insertSalesData() {
					var type = 'A';
					var sale_reference_no = $( '#sale_reference_no' ).val();
					var fields = $( "#create_sales_form" ).serialize();
					var rowCount = $( '#rowCount' ).val();
					if ( rowCount != 0 ) {
						$( "#add_sale" ).prop( "disabled", true );
						$( "#add_sale" ).val( 'Please wait...' );
						// create_sales_form.add_sale.disabled = true;
						// create_sales_form.add_sale.value = "Please wait...";
						//	return true;
						//type:type, sale_reference_no:sale_reference_no
						$.post( "<?php echo base_url();?>sales/save_cus_order", fields )
							.done( function ( data ) {
								var obj = jQuery.parseJSON( data );
								if ( obj.error == 1 ) {
									$( '.alert-success' ).hide();
									$( '.alert-danger' ).show();
									$( ".errortxt" ).text( obj.disMsg );
									window.scrollTo( 500, 0 );
									//empty item table				
								}
								if ( obj.error == 0 ) {
									window.scrollTo( 500, 0 );
									$( "#soTable > tbody" ).empty();
									displayNotice( 'page', 'Sale successfully added!' );
									clearForm();
									//empty footer details				
									sendUrl= $('#base_url').val()+"marketing_delivery_process/pending_delivery_details/"+<?php echo $cus_order_details['delivery_id']; ?>;
									window.location.href = sendUrl;									
								}
							} );
						return false;
					} else {
						bootbox.alert( 'Please add products.', function () {
							$( '#add_item' ).focus();
						} );
					}
				}
//--------------------------------------------------------------------
				$( window ).scroll( function () {
					if ( $( window ).scrollTop() + $( window ).height() == $( document ).height() ) {
						//alert("bottom!");
						$( '#bottom-total' ).css( {
							position: 'static',
							width: '100%'
						} );
					} else {
						$( '#bottom-total' ).css( {
							position: 'fixed',
							width: '1082px'
						} );
					}
				} );
//--------------------------------------------------------------------
				//function to initiate bootstrap-datepicker
				$( function () {
					//showKeys();
					var currentDate = new Date();
					$( '#sale_datetime' ).datetimepicker( {
						defaultDate: new Date()
					} );
					$( ".search-select" ).select2();
				} );	
//--------------------------------------------------------------------
				$( document ).ready( function () {
					$( '#in_type' ).focus();
					calculateTotal();
					clearForm();
					$('#warehouse_id option:not(:selected)').prop('disabled', true);
					$('#invoice_type option:not(:selected)').prop('disabled', true);
					$('#sales_rep_id option:not(:selected)').prop('disabled', true);
					
					$( ".noEnterSubmit" ).on( 'keyup', function ( e ) {
						// if (e.keyCode == 13) {
						// Do something
						// }
					} );
//----------------------------------------------------------------------
					$( '#add_sale' ).keypress( function ( event ) {
						//alert();
						//  if(event.keyCode == 13) {
						//   event.preventDefault();
						//   return false;
						// }
					} );
//----------------------------------------------------------------------
					$( window ).keydown( function ( event ) {
						$( ":focus" ).each( function () {
							//alert("Focused Elem_id = "+ this.id );
							focus_id = this.id;
							//	alert(focus_id);
							//	alert(event.keyCode);
							var rowCount = $( '#rowCount' ).val();
							var fld = 'quantity_' + rowCount;
							if ( focus_id == fld ) {
								if ( event.keyCode == 16 ) {
									$( '#add_item' ).focus();
								}
							}
							if ( event.keyCode == 18 ) {
								calculateTotal();

								setTimeout( function () {
									//alert();
									$( "#create_sales_form" ).submit()
										//do something special
								}, 1000 );
							}
							if ( event.keyCode == 13 ) {
								event.preventDefault();
								return false;
							}
						} );

					} );
				} );
//----------------------------------------------------------------------
				function check_recod() {
					$.post( "<?php echo  base_url(); ?>sales/check_recod?CRN=" + $( "#card_ref_number" ).val(), function ( data ) {
						//window.alert(fields);
						var obj = jQuery.parseJSON( data );
						//window.alert(data);
						if ( obj == 0 ) {} else {
							bootbox.alert( 'This card number already issued. Please try differant card Number', function () {
								$( '#card_ref_number' ).focus();
								document.getElementById( "card_ref_number" ).value = "";
							} );
						}
					} );
				}
//----------------------------------------------------------------------				
<?php
foreach($products as $pds){
	echo "addProductsToListByID(\"".$pds['product_id']."\",\"".$pds['product_name']."\",\"".$pds['product_code']."\",\"".$pds['product_price']."\",\"\",\"\",\" ".$pds['product_cost']." \", \"\",\"".$pds['issue_qty']."\",\"".$pds['issue_qty']."\",\"".$pds['discount']."\");";
	} ?>			
//----------------------------------------------------------------------
function addProductsToListByID(product_id, product_name, product_code, product_price, product_part_no, product_oem_part_number, item_cost, item_qty,qty,disco,ds) {
    
    var customer_id = $('#customer_id').val();
    error = false;
    if (customer_id == '') {
        error = true;
    }
    if (error) {
        bootbox.alert('Please select Customer before adding any product', function() {
            $('#add_item').focus();
        });
    } else {
        var rowCount = $('#rowCount').val();
        var nxtCount = parseInt(rowCount) + 1;
        $('#rowCount').val(nxtCount);
        //alert(product_price);
        var product_price = product_price;
        var product_price_dis = convertToAmount(product_price);
        var sub_total_item = convertToAmount(product_price * 1); //when add qty=1
        var discount_val = 0;
        var discount_val_tot = 0;
        var product_part_no_txt = '';
        var curqty = qty;
        var product_oem_part_number_txt = '';
        if (product_part_no) product_part_no_txt = ', SAP Code.:' + product_part_no;
        //if(product_oem_part_number) product_oem_part_number_txt=', OEM Part No.:'+product_oem_part_number;
        //alert(rowCount);
		
		$('#soTable tbody').prepend('<tr class="child" id="row_' + nxtCount + '">' +
		  '<td>' + product_name + ' (' + product_code + ')' + product_part_no_txt + product_oem_part_number_txt + '<input type="hidden" class="form-control text-center rquantity" name="row[' + nxtCount + '][product_id][]" value="' + product_id + '" id="product_id_' + nxtCount + '"></td>' 
		+ '<td class="text-right"><input type="hidden" name="row[' + nxtCount + '][unit_price][]" id="product_price_' + nxtCount + '" value="' + product_price + '"><input type="hidden" name="row[' + nxtCount + '][item_cost][]" id="item_cost_' + nxtCount + '" value="' + item_cost + '"><input type="text" style="width:50px;" name="row[' + nxtCount + '][item_price_p][]" id="item_price_p_' + nxtCount + '" value="' + 0 + '"  onchange="addextraprice();"> + ' + product_price_dis + '</td>' 
		+ '<td><input type="text" class="form-control text-center rquantity" name="row[' + nxtCount + '][qty][]" value="'+qty+'" id="quantity_' + nxtCount + '" onclick="this.select(); setTmpVal(this.value);" onchange="changeQtyByProductID(this.value,' + nxtCount + ');"><input type="hidden" id="qtyforcheck_' + nxtCount + '" value="' + curqty + '"></td>' 
		+ '<td class="text-right"><span class="text-right sdiscount text-danger" id="sdiscount_1446800197032"><input type="text" name="row[' + nxtCount + '][discount][]" value="'+ds+'" id="discount_' + nxtCount + '" onclick="this.select(); setTmpVal(this.value);" onchange="changeDiscountByProductID(this.value,' + nxtCount + ');" style="width:50px;"> </span><input type="hidden" name="row[' + nxtCount + '][discount_val][]" value="' + discount_val + '" id="discount_val_' + nxtCount + '"><input type="hidden" name="row[' + nxtCount + '][discount_val_tot][]" value="' + discount_val_tot + '" id="discount_val_tot_' + nxtCount + '"></td>' 
		+ '<td class="text-right"><span class="text-right ssubtotal" id="subtotal_' + nxtCount + '">' + sub_total_item + '</span><input type="hidden" name="row[' + nxtCount + '][gross_total][]" value="0" id="gross_total_' + nxtCount + '">&nbsp;</td>' 
		+ '<td ><a onclick="deleteSalesItem(' + nxtCount + ')"><i class="fa fa-times tip podel" id="1446800197032" title="Remove" style="cursor:pointer;"></i></a><input type="hidden"  id="stock_qty' + nxtCount + '" value="' + item_qty + '" ></td>'
		+'</tr>');
        //$.post( "<?php //echo base_url();?>sales/add_sales_item_to_list", product_id:product_id)
        //	  var obj = jQuery.parseJSON(data);
        //  });		
        calculateTotal();
    } //end error check
}
				/**/
				
			</script>
</body>
<!-- end: BODY -->

</html>