<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta charset="utf-8" />
<title>Sudila Printers</title>
<meta name="description" content="overview &amp; stats" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<!-- bootstrap & fontawesome -->
<link rel="stylesheet" href="assets/css/bootstrap.min.css" />
<link rel="stylesheet" href="assets/font-awesome/4.5.0/css/font-awesome.min.css" />
<!-- page specific plugin styles -->
<link rel="stylesheet" href="assets/css/chosen.min.css" />
<!-- text fonts -->
<link rel="stylesheet" href="assets/css/fonts.googleapis.com.css" />
<!-- ace styles -->
<link rel="stylesheet" href="assets/css/bootstrap-datepicker3.min.css" />
<link rel="stylesheet" href="assets/css/daterangepicker.min.css" />
<link rel="stylesheet" href="assets/css/ace.min.css" class="ace-main-stylesheet" id="main-ace-style" />
<!--[if lte IE 9]>
    <link rel="stylesheet" href="assets/css/ace-part2.min.css" class="ace-main-stylesheet" />
<![endif]-->
<link rel="stylesheet" href="assets/css/ace-skins.min.css" />
<link rel="stylesheet" href="assets/css/ace-rtl.min.css" />
<!--[if lte IE 9]>
  <link rel="stylesheet" href="assets/css/ace-ie.min.css" />
<![endif]-->
<!-- inline styles related to this page -->
<!-- ace settings handler -->
<script src="assets/js/ace-extra.min.js"></script>
<!-- HTML5shiv and Respond.js for IE8 to support HTML5 elements and media queries -->
<!--[if lte IE 8]>
    <script src="assets/js/html5shiv.min.js"></script>
    <script src="assets/js/respond.min.js"></script>
<![endif]-->
</head>
<body class="no-skin">
<?php include 'common/navbar.php'; ?>
<div class="main-container ace-save-state" id="main-container">
  <?php include 'common/sidebar.php'; ?>
  <div class="main-content">
    <div class="main-content-inner">
      <div class="breadcrumbs ace-save-state" id="breadcrumbs">
        <ul class="breadcrumb">
          <li> <i class="ace-icon fa fa-home home-icon"></i> <a href="home">Home</a> </li>
          <li>  <a href="add_GRN">Select Supplier</a> </li>
          <li class="active">Add GRN Items </li>
        </ul>
        <!-- /.breadcrumb --> 
      </div>
      <div class="page-content">
        <div class="page-header">
          <h1> Add GRN Items </h1>
        </div>
		
		<?php
		$s_name = $order_no = '';
		$inv = $sup = 0;
		if(isset($_GET['inv']) && isset($_GET['sup'])) {
			$inv = htmlspecialchars(strip_tags(trim($_GET['inv'])), ENT_QUOTES, 'UTF-8');
			$sup = htmlspecialchars(strip_tags(trim($_GET['sup'])), ENT_QUOTES, 'UTF-8');
			
			$sql_b = mysqli_query($conn, "SELECT name FROM supplier where id='$sup'");
			if(mysqli_num_rows($sql_b) == 0) {
				$redirectUrl = "add_GRN";
				echo "<script type=\"text/javascript\">";
				echo "window.location.href = '$redirectUrl'";    
				echo "</script>";
				
			} else {
				$row_b = mysqli_fetch_assoc($sql_b);
				$s_name = $row_b['name'];
				
				$sql_grn = mysqli_query($conn, "SELECT order_no FROM grn_tkn_order WHERE inv_no='$inv' AND sup_id='$sup'");
				if(mysqli_num_rows($sql_grn) == 0) {
					$redirectUrl = "add_GRN";
					echo "<script type=\"text/javascript\">";
					echo "window.location.href = '$redirectUrl'";    
					echo "</script>";
					
				} else {
					$sql_gr = mysqli_fetch_assoc($sql_grn);
					$order_no = $sql_gr['order_no'];
				}
			}
		
		} else {
			$redirectUrl = "add_GRN";
			echo "<script type=\"text/javascript\">";
			echo "window.location.href = '$redirectUrl'";    
			echo "</script>";
		}
		?>
		
        <!-- /.page-header -->
        <div class="row">
          <div class="col-xs-12"> 
            <!-- PAGE CONTENT BEGINS -->
            <div class="widget-box">
              <div class="widget-body">
                <div class="widget-main">
				<h5>Supplier Name: <span class="text-primary"><?php echo $s_name; ?></span></h5>
				<h5>Order No: <span class="text-primary"><?php echo $order_no; ?></span></h5>
				<hr>
                  <!-- Content -->
				  <form id="form_submit" method="post">
					  <div class="form-group">
						<label>Select Item:<sup class="red">*</sup></label>
						<select class="chosen-select form-control txt_nav" data-placeholder="Select Item..." name="item_id" required>
							<?php
							echo "<option></option>";
							$sql = "SELECT * FROM bookdetails ORDER BY name";
							$result = mysqli_query($conn, $sql);
							while ($row = mysqli_fetch_array($result)){
								echo "<option value='".$row['id']."'>".$row['name']."</option>"; 
							}
							?>
						</select>
						<span class="help-block"></span>
					  </div>
					  <div class="form-group">
						<label>Retail Price:<sup class="red">*</sup></label>
						  <input type="text"  class="form-control txt_nav" name="r_price" id="r_price" required autocomplete="off"/>
						<span class="help-block"></span>
					  </div>
					  <div class="form-group">
						<label>Discount (%):<sup class="red">*</sup></label>
						  <input type="text"  class="form-control txt_nav" name="discount" id="dis_val" required autocomplete="off"/>
						<span class="help-block"></span>
					  </div>
					  <div class="form-group">
						<label>Cost:<sup class="red">*</sup></label>
						  <input type="text"  class="form-control" name="cost" id="cost" required readonly autocomplete="off"/>
						<span class="help-block"></span>
					  </div>
					  <div class="form-group">
						<label>Quantity:<sup class="red">*</sup></label>
						  <input type="text"  class="form-control txt_nav" name="qty" required autocomplete="off"/>
						<span class="help-block"></span>
					  </div>
					  <input type="hidden" name="gsup_id" value="<?php echo $sup ?>">
					  <input type="hidden" name="ginv_no" value="<?php echo $inv ?>">
					  <br>
					  <div class="form-group">
						<button class="btn btn-primary btn-sm" id="submit_btn"> SUBMIT</button>
					  </div>
				  </form>
                  <!-- End Content --> 
                </div>
              </div>
            </div>
            <!-- /End .widget-box --> 
          </div>
        </div>
        <div class="space-10"></div>
        <div class="row">
          <div class="col-xs-12">
            <div class="widget-box">
              <div class="widget-body">
                <div class="widget-main">
                  <div class="table-header"> GRN Items </div>
                  <!-- div.table-responsive --> 
                  <!-- div.dataTables_borderWrap -->
                  <div class="table-responsive">
                    <table id="dynamic-table" class="table table-striped table-bordered table-hover">
                      <thead>
                        <tr>
                          <th>ID</th>
						<th>Item Name</th>
						<th>Retail Price (Rs)</th>
						<th>Discount (%)</th>
						<th>Cost (Rs)</th>
						<th>Quantity</th>
						<th>Total (Rs)</th>
						<th>Remove</th>
                        </tr>
                      </thead>
                      <tbody>
                        <?php
						$sql = mysqli_query($conn, "SELECT
grn_tkn_stock.cost,
grn_tkn_stock.qty,
grn_tkn_stock.r_price,
grn_tkn_stock.discount,
bookdetails.name,
grn_tkn_stock.id
FROM
grn_tkn_stock
Inner Join bookdetails ON bookdetails.id = grn_tkn_stock.item
WHERE
grn_tkn_stock.inv_no = '$inv' AND
grn_tkn_stock.sup_id = '$sup'");
						$x = $tcost = 0;
						while ($row = mysqli_fetch_array($sql)) {
							$x++;
						?>
                        <tr>
                          <td><?php echo $x; ?>.</td>
                          <td><?php echo $row['name']; ?></td>
                          <td align="right"><?php echo $row['r_price']; ?></td>
                          <td align="right"><?php echo $row['discount']; ?></td>
                          <td align="right"><?php echo $row['cost']; ?></td>
                          <td align="right"><?php echo $row['qty']; ?></td>
                          <td align="right"><?php $tot = ($row['cost']*$row['qty']); echo number_format($tot, 2); ?></td>
                          <td align="center"><div class="action-buttons">
						  <button title="Remove" class="btn btn-info btn-sm btn_remove" value="<?php echo $row['id']; ?>"> <i class="ace-icon fa fa-trash-o"> </i> </button> </div>
						  </td>
                        </tr>
                        <?php $tcost+=$tot; } ?>
                      </tbody>
                    </table>
                  </div><hr>
				  <h5><b>Total Cost: Rs. <?php echo number_format($tcost, 2); ?></b></h5>
				  <?php if(mysqli_num_rows($sql) > 0) { ?>
				  <hr>
				  <button title="Finalize GRN" class="btn btn-danger btn_final btn-sm"> FINALIZE </button> </div>
				  <?php } ?>
                </div>
              </div>
            </div>
            <!-- PAGE CONTENT ENDS --> 
          </div>
          <!-- /.col --> 
        </div>
        <!-- /.row --> 
      </div>
      <!-- /.page-content --> 
    </div>
  </div>
  <!-- /.main-content -->
  <?php include 'common/footer.php'; ?>
</div>
<!-- /.main-container -->

<!-- basic scripts --> 
<!--[if !IE]> -->
<script src="assets/js/jquery-2.1.4.min.js"></script>
<!-- <![endif]--> 
<!--[if IE]>
<script src="assets/js/jquery-1.11.3.min.js"></script>
<![endif]--> 
<script type="text/javascript">
	if('ontouchstart' in document.documentElement) document.write("<script src='assets/js/jquery.mobile.custom.min.js'>"+"<"+"/script>");
</script> 
<script src="assets/js/bootstrap.min.js"></script> 
<!-- page specific plugin scripts --> 
<!--[if lte IE 8]>
  <script src="assets/js/excanvas.min.js"></script>
<![endif]-->
<script src="assets/js/jquery.dataTables.min.js"></script>
<script src="assets/js/jquery.dataTables.bootstrap.min.js"></script>
<!-- ace scripts -->
<script src="assets/js/chosen.jquery.min.js"></script>
<script src="assets/js/ace-elements.min.js"></script>
<script src="assets/js/ace.min.js"></script>
<script src="assets/jquery.validate.min.js"></script>
<link rel="stylesheet" href="bootstrap-sweetalert/lib/sweet-alert.css" />
<script src="bootstrap-sweetalert/lib/sweet-alert.min.js"></script>
<script src="assets/js/bootstrap-datepicker.min.js"></script>
<!-- inline scripts related to this page --> 
<script type="text/javascript">
jQuery(function ($) {
	//initiate dataTables plugin
	var myTable =
	$('#dynamic-table')
	//.wrap("<div class='dataTables_borderWrap' />")   //if you are applying horizontal scrolling (sScrollX)
	.DataTable({
		bAutoWidth: false,
		"aaSorting": [],
	});
	
	if(!ace.vars['touch']) {
		$('.chosen-select').chosen({allow_single_deselect:true}); 
		//resize the chosen on window resize

		$(window)
		.off('resize.chosen')
		.on('resize.chosen', function() {
			$('.chosen-select').each(function() {
				 var $this = $(this);
				 $this.next().css({'width': $this.parent().width()});
			})
		}).trigger('resize.chosen');
		//resize chosen on sidebar collapse/expand
		$(document).on('settings.ace.chosen', function(e, event_name, event_val) {
			if(event_name != 'sidebar_collapsed') return;
			$('.chosen-select').each(function() {
				 var $this = $(this);
				 $this.next().css({'width': $this.parent().width()});
			})
		});
	}
	//datepicker plugin
	//link
	$('.date-picker').datepicker({
		autoclose: true,
		todayHighlight: true
	})
	//show datepicker when clicking on the icon
	.next().on(ace.click_event, function(){
		$(this).prev().focus();
	});
});

$(function() {
    $(':input[required=""],:input[required]').bind('focusout', function() {
        if ($(this).val() == ""){
          $(this).css("border-color", "red");
        } else {
          $(this).css("border-color", "#ccc");
        }
    });

    //$('.txt_nav:first').focus();
    var $inp = $('.txt_nav');
    $inp.bind('keydown', function(e) {
        var n = $inp.length;
        var key = e.which;
        if (key == 13) {
            e.preventDefault();
            var nxtIdx = $inp.index(this) + 1;
            if(nxtIdx < n) {
                $('.txt_nav')[nxtIdx].focus();
              }
             else
             {
               $('.txt_nav')[nxtIdx-1].blur();
               $('#submit_btn').focus();
             }
        }
    });

    $( "#submit_btn" ).keypress(function( event ) {
      if ( event.which == 13 ) {
        req_input_check();     
      }
    });         

});

function req_input_check() {
  $(':input[required=""],:input[required]').bind('keypress', function(event){
      if ( event.which == 13 ) {
      if ($(this).val() == ""){
        $(this).css("border-color", "red");
      } else {
        $(this).css("border-color", "#ccc");
		$('#form_submit').validate();
      }
    }
  });
}

$("#form_submit").on('submit',(function(e) {
    e.preventDefault();
})).validate({
	ignore: [],
	rules: {
		cost: {
			number: true,
			min: 1,
		},
		qty: {
			number: true,
			min: 1,
		},
		discount: {
			number: true,
			min: 0,
		},
		r_price: {
			number: true,
			min: 1,
		},
	}, messages:
	{
		cost: {
			number: "Invalid Value",
			min: "Invalid Value",
		},
		qty: {
			number: "Invalid Quantity",
			min: "Invalid Quantity",
		},
		discount: {
			number: "Invalid Discount Value",
			min: "Invalid Discount Value",
		},
		r_price: {
			number: "Invalid Retail Price",
			min: "Invalid Retail Price",
		},
	},
	 errorPlacement : function(error, element) {
		$(element).closest('.form-group').find('.help-block').html(error.html());
	 },
	 highlight : function(element) {
		$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
	 },
	 unhighlight: function(element, errorClass, validClass) {
		$(element).closest('.form-group').removeClass('has-error');
		$(element).closest('.form-group').find('.help-block').html('');
	 },
	
    submitHandler: function(e) {
		$.ajax({
		url: 'connection/grn_conn',
		type: "POST",
		data:  new FormData(e),
		dataType: 'json',
		contentType: false,
			cache: false,
		processData:false,
		success: function(data){
		  if(data === '') {
			swal("", "Something went wrong! Please Try Again!", "warning");
		  
		  } else {
			  if ( data.msgType === 1 ) {
				  location.reload();
			  
			  } else if ( data.msgType === 3 ) {
				  swal("", "Selected Item Already Exist. Please Try Again!", "warning");
			  
			  } else {
				  swal("", "Something went wrong! Please Try Again!", "warning");
			  }
		  }      
		  },
		  error: function(e) 
		  {
			swal("", "Something went wrong! Please Try Again!", "warning");
		  }
	   });
		//submit via ajax
		return false;  //This doesn't prevent the form from submitting.
    }
});

/******************* Remove **********************/

$(".btn_remove").click(function(){
  var row_id = $(this).val();
	swal({
	  title: "",
	  text: "Are you sure you want to delete this?",
	  type: "warning",
	  showCancelButton: true,
	  confirmButtonClass: "btn-danger",
	  confirmButtonText: "Yes, delete it!",
	  cancelButtonText: "No, cancel!",
	  closeOnConfirm: false,
	  closeOnCancel: true
	},
	function(isConfirm) {
	  if (isConfirm) {
		$.post( "connection/grn_conn", {remove_data: "data", id : row_id}, function( data ) {
			if (data.msgType === 1) {
			  swal({
				title: "",
				text: "Successfully Deleted!",
				type: "success",
				confirmButtonText: "OK"
				  },
				  function (isConfirm) {
				if (isConfirm) {
					location.reload();
				}
			  });
			} else{
			  swal("", "Something went wrong! Please Try Again!", "warning");
			}
		}, "json");
	  }
	});
});

/******************* Finalize **********************/

$(".btn_final").click(function(){
	swal({
	  title: "",
	  text: "Are you sure you want to finalize this?",
	  type: "warning",
	  showCancelButton: true,
	  confirmButtonClass: "btn-danger",
	  confirmButtonText: "Yes!",
	  cancelButtonText: "No, cancel!",
	  closeOnConfirm: false,
	  closeOnCancel: true
	},
	function(isConfirm) {
	  if (isConfirm) {
		$.post( "connection/grn_conn", {finalize_grn: "data", fsup_id : <?php echo $sup ?>, finv_no : <?php echo $inv ?>}, function( data ) {
			if (data.msgType === 1) {
			  swal({
				title: "",
				text: "Successfully Finalized!",
				type: "success",
				confirmButtonText: "OK"
				  },
				  function (isConfirm) {
				if (isConfirm) {
					window.location.href = "add_GRN";
				}
			  });
			
			} else if (data.msgType === 5) {
			  swal({
				title: "",
				text: "Already Finalized!",
				type: "success",
				confirmButtonText: "OK"
				  },
				  function (isConfirm) {
				if (isConfirm) {
					window.location.href = "add_GRN";
				}
			  });
			
			} else{
			  swal("", "Something went wrong! Please Try Again!", "warning");
			}
		}, "json");
	  }
	});
});

$("#r_price").keyup(function () {
	cost_cal();
});

$("#dis_val").keyup(function () {
	cost_cal();
});

function cost_cal() {
	$('#cost').val('');
	var r_price = parseFloat($("#r_price").val());
	var dis_val = parseFloat($("#dis_val").val());
	
	if($.isNumeric(r_price) && $.isNumeric(dis_val)) {
		var tot_dis = (r_price * dis_val) / 100;
		var cost = parseFloat(r_price - tot_dis);
		$("#cost").val(cost.toFixed(2));
	
	} else {
		$('#cost').val('');
	}
}

</script>
</body>
</html>