<!DOCTYPE html>
<html>
<script type="text/javascript">
    function FormatCurrency(ctrl) {
                  //Check if arrow keys are pressed - we want to allow navigation around textbox using arrow keys
                  if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
                      return;
                  }

                  var val = ctrl.value;

                  val = val.replace(/,/g, "")
                  ctrl.value = "";
                  val += '';
                  x = val.split('.');
                  x1 = x[0];
                  x2 = x.length > 1 ? '.' + x[1] : '';

                  var rgx = /(\d+)(\d{3})/;

                  while (rgx.test(x1)) {
                      x1 = x1.replace(rgx, '$1' + ',' + '$2');
                  }

                  ctrl.value = x1 + x2;
              }

              function CheckNumeric() {
                  return event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 46;
              }
</script>
    
    <head>
       <?php   include("../includes/header-links.php");?>
        <!-- Bootstrap -->
        <link href="../bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
        <link href="../bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
        <link href="../assets/styles.css" rel="stylesheet" media="screen">
        <link href="../assets/DT_bootstrap.css" rel="stylesheet" media="screen">
        <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="vendors/flot/excanvas.min.js"></script><![endif]-->
        <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
        <!--[if lt IE 9]>
            <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
        <script src="../vendors/modernizr-2.6.2-respond-1.1.0.min.js"></script>
    </head>
    
    <body>
        <?php include '../includes/header.php';
         $total=0; ?>
        <div class="container-fluid">
            <div class="row-fluid">
                <?php include '../includes/sidebar.php'; ?>
                <!--/span-->
           <div class="span7" id="content">

                        <div class="row-fluid">
                        <!-- block -->
                        <div class="block">
                            <div class="navbar navbar-inner block-header">
                                <div class="muted pull-left">Purchases</div>
                                
                                <div class="muted pull-right" >&nbsp &nbsp &nbsp</div>
                                <div class="muted pull-right"><a href="../stock/stock.php"><button class="bt btn-primary">Stock</button> </a></div>
                                
                            </div>
                            <div class="block-content collapse in">
                                <div class="span12">
                                    <?php
                                    include '../includes/connection.php';
                                    $sql = mysqli_query($con,"SELECT id, (select product_name from products where id=getstock.product_id)as product_name, quantity, unitprice,expiry_date,batch_no from getstock where branch_id='$branch' && user_id='$id_user' order by id");
                                    if (mysqli_num_rows($sql) > 0) {
                                       ?>
  									<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="example">
										<thead>
											<tr>
												<th>Id</th>
												<th>Product Name</th>
												<th>Quantity</th>
												<th>Unit Price</th>
                        <th>Total Price</th>
                        <?php
                         if ($gbusiness_settings['add_batchnumber_onpurchase']==1) {
                        ?>
                        <th>BatchNo</th>
                        <?php
                         }
                        ?>
                        <?php
                         if ($gbusiness_settings['add_expirydate_onpurchase']==1) {
                        ?>
                        <th>Expiry Date</th>
                        <?php
                         }
                        ?>
                          <th>Action</th>
											</tr>
										</thead>
										<tbody>
                                        <?php
                                        
                                         // output data of each row
                                        $nnnn=0;
                while($row = mysqli_fetch_assoc($sql)) {
                        $total=$total+$row['unitprice']*$row['quantity'];
                        $nnnn++;
                    ?>
                    <tr class="odd gradeX">

        
                                                <td><?php echo $nnnn; ?></td>
                                                <td><?php echo $row['product_name']; ?></td>
                                                <td><?php echo $row['quantity']; ?></td>
                                                <td class="center"> <?php echo $row['unitprice']; ?></td>
                                                <td class="center"><?php echo number_format($row['unitprice']*$row['quantity']); ?></td>
                                                <?php
                                                   if ($gbusiness_settings['add_batchnumber_onpurchase']==1) {
                                                  ?>
                                                <td class="center"><?php echo $row['batch_no']; ?></td>
                                                  <?php
                                                   }
                                                  ?>
                                                  <?php
                                                   if ($gbusiness_settings['add_expirydate_onpurchase']==1) {
                                                  ?>
                                                <td class="center"><?php echo $row['expiry_date']; ?></td>
                                                  <?php
                                                   }
                                                  ?>
                                                <td class="center">
                                                    <a href="edit_purchase.php?id=<?php echo $row['id']; ?>"><button class="btn btn-primary"><i class="icon-edit icon-white"></i></button></a>
                                                    <a href="deletepurchase.php?id=<?php echo $row['id']; ?>"><button class="btn btn-danger"><i class="icon-trash icon-white"></i></button></a>
                                                </td>
                                            </tr>
                                            <?php
    }?>
    </tbody>
                                    </table>

                                    <h3><center>TOTAL: Ushs. <?php echo number_format($total); ?> </center></h3>
                                    <?php
                                    $sqlsup=mysqli_fetch_array(mysqli_query($con,"SELECT distinct supplier from getstock where branch_id='$branch'"));
                                    $supplierName=$sqlsup['supplier'];
                                    $fromsup=mysqli_fetch_array(mysqli_query($con,"SELECT name, credit_limit from suppliers where supplier_id='$supplierName'"));
                                    $ssname=$fromsup['name'];
                                    $climit=$fromsup['credit_limit'];
                                    ?>
                                    <?php
                                         if ($gbusiness_settings['indicate_supplier_onpurchase']==1) {
                                        ?>
                                    <h4><center>Supplier:  <?php echo $ssname; ?>&nbsp; <a href="#myModal" data-toggle='modal'><i class="icon-pencil icon-large"></i></a><br>Credit Limit <?php echo number_format($climit);?>/=</center></h4>
                                    <?php
                                      }
                                    ?>
                                    
            <form action="process_purchase.php?total=<?php echo $total; ?>" method="POST">
    <div class="muted pull-left">
        
        Amount Paid: <input type="number"  name="amount_paid" class="form-control" value="<?php echo $total; ?>" min="<?php echo $total-$climit; ?>" max="<?php echo $total;?>" required>
        <?php
        if ($gbusiness_settings['record_invoice_number']==1) {
          ?>
        Invoice Number: <input type="text"  name="invoice_number" class="form-control"><br>
        <?php
          }else{
            ?>
            <input type="hidden"  name="invoice_number" class="form-control">
            <?php
          }
        ?>
        <?php 
        if ($gbusiness_settings['back_date_purchases']==1) {
          ?>
          Purchase date: <input type="date"  name="purchase_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" max="<?php echo date('Y-m-d'); ?>" max="<?php echo $total;?>">
    
          <?php
        }
        ?>
    
    </div>
    <div class="muted pull-right">
    

                                <button type="submit" name="process_order" class="btn btn-primary"> Save purchase</button></div>
    
                                </form>
                               
                                    <?php 
} else {
    echo " No Purchase Have been Added Yet!";
}

//mysqli_close($conn);
?>
					 <div id="myModal" class="modal hide">
        <div class="modal-header" style="background-color: #08c; color: white;">
            <button data-dismiss="modal" class="close" type="button">&times;</button>
            <h3>Edit Supplier</h3>
            
        </div>
        <div class="modal-body">
            <div>
                <form action="" method="POST">
                    <select name="updatevalue" id=""  required="required" class="span12">
       <option value="<?php echo $supplierName; ?>" ><?php echo $ssname; ?></option>
       <?php 
       include '../includes/connection.php';
       $supl=mysqli_query($con,"SELECT * from suppliers where status=1 && suspend=1 && branch_id='$branch'");
       while ($results=mysqli_fetch_array($supl)) {

    $supid=$results['supplier_id'];
    $sname=$results['name'];
    ?>
    <option value="<?php echo $supid; ?>"><?php echo $sname; ?></option>
    <?php
       }
        ?>
  </select>
    <button type="submit" class="btn btn-large btn-block btn-primary" name="save_changes">Save Changes</button>
                </form>
                <?php
if(isset($_POST['save_changes'])){
    $newsup=mysqli_real_escape_string($con,ucwords($_POST['updatevalue']));
    $sql1 = "UPDATE getstock SET supplier='$newsup' where supplier='$supplierName'";

if (mysqli_query($conn, $sql1)) {
     ?><meta http-equiv="refresh" content="0;URL='new_purchase.php'" /><?php
} else {
    echo "Error updating record: " . mysqli_error($conn);
}

}
                ?>
            </div>
        </div>
    </div>						
											
								
                                </div>
                            </div>
                        </div>
                        <!-- /block -->
                    </div>

         
                </div>
                <div class="span3">
                                     <form  action="" method="POST"> 
                                      <fieldset>
                                        <legend style="text-align: center;">Add product</legend>
                                        <div class="control-group" >
                                          <label class="control-label" for="selectError" style="font-size: 20px;">Product</label>
                                          <div class="controls">
                                          <?php
                                          if ($store=="1") {
                                            ?>
                                            <select id="select01" class="chzn-select" name="product" required="required" title="Please select product" onchange="setminmax(this.value); getAvereagePrice(this.value);" style="width: 100%; font-size: 18px; height: 35px;">
                                            <option disabled selected value="" style="font-size: 18px;"> Product</option>
                                              <?php include 'listproducts.php'; ?>
                                            
                                            </select>
                                            <?php
                                           
                                          }else{
                                            ?>
                                            <select id="select01" class="chzn-select" name="product" onchange="getAvereagePrice(this.value);" required="required" style="width: 80%; font-size: 18px; height: 35px;" >
                                            <option disabled selected value="" >Select Product</option>
                                              <?php include 'listproducts.php'; ?>
                                            
                                            </select>
                                            <?php
                                          }
                                          ?>
                                            
                                          </div>
                                          

                                          <script type="text/javascript">

    function setminmax(idd){
          var xhttp = new XMLHttpRequest();
          
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var response=this.responseText;
      document.getElementById("quantitya").max =
      response;
      document.getElementById("quantitya").placeholder ="Store Quantity: "+
      response;
      document.getElementById("txtt").innerHTML ="Store Quantity: "+
      response;
      

      

      if(response==0){
        document.getElementById("txtt").innerHTML ="! Item is Not in Store !";
       document.getElementById("txtt").style.color="red" 
       document.getElementById("approved").style.display="none";
       //document.getElementById("approved").style.disabled=true;
        document.getElementById("txttprice").innerHTML="";


      }
      else{
        document.getElementById("txtt").style.color="green";
        // document.getElementById("txttprice").innerHTML="Unit price "+response;
      document.getElementById("approved").style.display="block";
      }
      
    }
  };
  xhttp.open("GET", "getstorequantity.php?id="+idd, true);
  xhttp.send();

    }

</script>
<script type="text/javascript">
   function getAvereagePrice(idd){
          var xhttp = new XMLHttpRequest();
          
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var response=this.responseText;
      document.getElementById("AVP").innerHTML ="Average Buying Price: "+response;
    
      
    }
  };
  xhttp.open("GET", "getaveragePrice.php?id="+idd, true);
  xhttp.send();

    }

</script>
                      
                                        </div>
                                        <div class="text-center" style="color: green;"><b>
                                            <h3 id="AVP" align="center"></h3>
                                            <h3 id="txtt" align="center"></h3>
                                        </div>
                                        <div id="approved"> 
                                        <div class="control-group">
                                          <label class="control-label"  for="focusedInput" style=" font-size: 20px;">Quantity</label>
                                          <div class="controls">
                                            <input class="input-xlarge focused" name="quantity" id="quantitya" type="number" value="Enter Quantity" required="required" style=" font-size: 20px;">
                                          </div>
                                        </div>
                                        <div class="control-group">
                                          <label class="control-label"  for="focusedInput" style=" font-size: 20px;">Unit buying price</label>
                                          <div class="controls">
                                            <input class="input-xlarge focused" name="unitprice" id="focusedInput" type="text" onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" required="required" style=" font-size: 20px;">
                                          </div>
                                        </div>
                                        <?php
                                         if ($gbusiness_settings['add_batchnumber_onpurchase']==1) {
                                        ?>
                                        <div class="control-group">
                                        <?php
                                           }else{
                                            ?>
                                           <div class="control-group" style="display: none;">

                                            <?php
                                           }
                                           ?>
                                          <label class="control-label"  for="focusedInput" style=" font-size: 20px;">Batch Number</label>
                                          <div class="controls">
                                            <input class="input-xlarge focused" name="batch_no" id="focusedInput" type="text" style=" font-size: 20px;">
                                          </div>
                                        </div>
                                        <?php
                                         if ($gbusiness_settings['add_expirydate_onpurchase']==1) {
                                        ?>
                                        <div class="control-group">
                                        <?php
                                          }else{
                                            ?>
                                        <div class="control-group" style="display: none;">

                                            <?php
                                          }
                                        ?>
                                          <label class="control-label"  for="focusedInput" style=" font-size: 20px;">Expiry Date</label>
                                          <div class="controls">
                                            <input class="input-xlarge focused" name="expiry_date" id="focusedInput" type="date"  style=" font-size: 20px;">
                                          </div>
                                        </div>
                                        <?php
                                         if ($gbusiness_settings['indicate_supplier_onpurchase']==1) {
                                        ?>
                                        <div class="control-group">
                                        <?php
                                          }else{
                                            ?>
                                        <div class="control-group" style="display: none;">

                                            <?php
                                          }
                                        ?>
                                          <label class="control-label"  for="focusedInput" style=" font-size: 20px;">supplier</label>
                                          <div class="controls">
    <?php
if(isset($ssname)){
?>
<select class="input-xlarge focused" name="supplier" id="focusedInput"   required="required"  readonly style=" font-size: 20px;">
  <option value="<?php echo $supplierName; ?>"><?php echo $ssname ?></option>
</select>
<?php
}else{
  ?>
  <select class="input-xlarge focused" name="supplier" id="focusedInput" style=" font-size: 20px;">
       <option  selected value="">Select supplier</option>
       <?php 
       include '../includes/connection.php';
       $supl=mysqli_query($con,"SELECT * from suppliers where status=1 && suspend=1 && branch_id='$branch'");
       while ($results=mysqli_fetch_array($supl)) {

    $supid=$results['supplier_id'];
    $sname=$results['name'];
    ?>
    <option value="<?php echo $supid; ?>"><?php echo $sname; ?></option>
    <?php
       }
        ?>
  </select>
  <?php   
}
    ?>
                                           
                                          </div>
</div>
                                        
                                       
                                        
                                        <div class="form-actions">
                                          <button type="submit" class="btn btn-primary" name="add"><i class="icon-plus "></i>Add</button>
                                       
                                        </div>
                                        </div>
                                        </div>
                                      </fieldset>
                                    </form>
                                    <?php
                                        include '../includes/connection.php';

                                        if(isset($_POST['add'])){
                                            $product=$_POST['product'];
                                            $quantity=$_POST['quantity'];
                                            $batch_no=$_POST['batch_no'];
                                            $expiry_date=$_POST['expiry_date'];
                                            
                                              $bad_symbols = array(",");                                         $unitprice=$_POST['unitprice'];
                                         $unitprice= str_replace($bad_symbols, "", $unitprice);

                                            $supplier=mysqli_real_escape_string($con,ucwords($_POST['supplier']));
                                            if(isset($expiry_date)){
                                              $expiry_date=$_POST['expiry_date'];
                                              $sql2 = mysqli_query($con,"INSERT INTO getstock(product_id, quantity,unitprice,supplier,branch_id,business_id,batch_no,expiry_date,user_id)
                                        VALUES ('$product', '$quantity','$unitprice','$supplier','$branch','$business','$batch_no','$expiry_date','$id_user')");
                                            }else{
                                              
                                              $sql2 = mysqli_query($con,"INSERT INTO getstock(product_id, quantity,unitprice,supplier,branch_id,business_id,batch_no,expiry_date,user_id)
                                        VALUES ('$product', '$quantity','$unitprice','$supplier','$branch','$business','$batch_no',null,'$id_user')");
                                            }
                                        

                                        if ($sql2) {
                                           ?><meta http-equiv="refresh" content="0;URL='new_purchase.php'" /><?php
                                        } else {
                                            echo "Error: " . $sql2 . mysqli_error($con);
                                        }

                                        mysqli_close($con);
                                        }
                                        
                                        ?>

                                </div>
            </div>



<div class="row-fluid">
    
</div>

            <hr>
            <?php include '../includes/footer.php'; ?>
        </div>
        <!--/.fluid-container-->

       <script src="../vendors/jquery-1.9.1.js"></script>
        <script src="../bootstrap/js/bootstrap.min.js"></script>
        <script src="../vendors/datatables/js/jquery.dataTables.min.js"></script>


        <script src="../assets/scripts.js"></script>
        <script src="../assets/DT_bootstrap.js"></script>


        <link href="../vendors/datepicker.css" rel="stylesheet" media="screen">
        <link href="../vendors/uniform.default.css" rel="stylesheet" media="screen">
        <link href="../vendors/chosen.min.css" rel="stylesheet" media="screen">

        <link href="../vendors/wysiwyg/bootstrap-wysihtml5.css" rel="stylesheet" media="screen">

        <script src="../vendors/jquery-1.9.1.js"></script>
        <script src="../vendors/jquery.uniform.min.js"></script>
        <script src="../vendors/chosen.jquery.min.js"></script>
        <script src="../vendors/bootstrap-datepicker.js"></script>

        <script src="../vendors/wysiwyg/wysihtml5-0.3.0.js"></script>
        <script src="../vendors/wysiwyg/bootstrap-wysihtml5.js"></script>

        <script src="../vendors/wizard/jquery.bootstrap.wizard.min.js"></script>
        <script type="text/javascript" src="../vendors/jquery-validation/dist/jquery.validate.min.js"></script>
    <script src="../assets/form-validation.js"></script>
        
    <script src="../assets/scripts.js"></script>
        <script>
        $(function() {
            
        });
        </script>
        <script>

    jQuery(document).ready(function() {   
       FormValidation.init();
    });
    

        $(function() {
            $(".datepicker").datepicker();
            $(".uniform_on").uniform();
            $(".chzn-select").chosen();
            $(".chzn-select1").chosen();
            $('.textarea').wysihtml5();

            $('#rootwizard').bootstrapWizard({onTabShow: function(tab, navigation, index) {
                var $total = navigation.find('li').length;
                var $current = index+1;
                var $percent = ($current/$total) * 100;
                $('#rootwizard').find('.bar').css({width:$percent+'%'});
                // If it's the last tab then hide the last button and show the finish instead
                if($current >= $total) {
                    $('#rootwizard').find('.pager .next').hide();
                    $('#rootwizard').find('.pager .finish').show();
                    $('#rootwizard').find('.pager .finish').removeClass('disabled');
                } else {
                    $('#rootwizard').find('.pager .next').show();
                    $('#rootwizard').find('.pager .finish').hide();
                }
            }});
            $('#rootwizard .finish').click(function() {
                alert('Finished!, Starting over!');
                $('#rootwizard').find("a[href*='tab1']").trigger('click');
            });
        });
        </script>

    </body>

</html>