<?php
include '../includes/connection.php';
$id=$_GET['id'];
// Create connection
$sql = mysqli_query($con,"SELECT * FROM products WHERE id='$id'");
if (mysqli_num_rows($sql) > 0) {
    // output data of each row
    
while($row = mysqli_fetch_assoc($sql)) {
        $product_name=$row['product_name'];
        $quantity=$row['quantity'];
        $price=$row['price'];
        $product_code=$row['product_code'];
        $minimum_quantity=$row['minimum_quantity'];
        $unit=$row['Units'];
        $cateid=$row['category'];
        $branc=$row['branch_id'];
        $price_whole=$row['price_whole'];
        $hasstock=$row['has_stock'];
        $vat=$row['VAT'];
        $reserve_price=$row['reserve_price'];

    }
} else {
    echo "0 results";
}

mysqli_close($con);



?>

<!DOCTYPE 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>
<html>
    
    <head>
        <?php include("../includes/header-links.php");?>
    </head>
    
    <body>
        <?php include '../includes/header.php'; ?>
        <div class="container-fluid">
            <div class="row-fluid">
                <?php include '../includes/sidebar.php'; ?>
                <!--/span-->
                <div class="span9" id="content">
                      <!-- morris stacked chart -->
                    <div class="row-fluid">
                        <!-- block -->
                        <div class="block">
                            <div class="navbar navbar-inner block-header">
                                <div class="muted pull-left">Edit Product</div>
                            </div>
                            <div class="block-content collapse in">
                                <div class="span12">
                                     <form class="form-horizontal" action="" method="POST">
                                      <fieldset>
                               
                      <div class="control-group">
                                          <label class="control-label" for="focusedInput">Category</label>
                                          <div class="controls">
                                            <select name="category" class="form-control" required style="width: 30%; height: 30px;">
                                                                     <?php 
                         $catdef=mysqli_fetch_array(mysqli_query($con,"SELECT * from product_categories where category_id='$cateid'"));
                         ?>
                          <option  value="<?php echo $catdef['category_id'];?>"><?php echo $catdef['category_name'];?></option>
                         <?php 
                         $cat=mysqli_query($con,"SELECT * from product_categories where status=1 && branch_id='$branc'");
                         while ( $rowc=mysqli_fetch_array($cat)) {
                           ?>
                           <option value="<?php echo $rowc['category_id'];?>"><?php echo $rowc['category_name'];?></option>
                           <?php
                         }
                          ?>
                         
                          
                        </select>
                                          </div>
                                        </div>
                                        <div class="control-group">
                                          <label class="control-label" for="focusedInput">Product Name</label>
                                          <div class="controls">
                                            <input class="input-xlarge focused" id="focusedInput" type="text" name="pname" value="<?php echo $product_name; ?>">
                                          </div>
                                        </div>
                                        <?php
                                        if ($gbusiness_settings['include_services']==1) {
                                          ?>
                                        <div class="control-group">
                                          <label class="control-label" for="focusedInput">Has Stock</label>
                                          <div class="controls">
                                                <select name="hasstock" class="input-xlarge focused"  required="required">
                                              <?php
                                                if ($hasstock==1) {
                                                         ?>
                                                         <option value="1">Yes</option>
                                                          <option value="0">No</option>
                                                         <?php 
                                                      }else{
                                                          ?>
                                                        <option value="0">No</option>
                                                          <option value="1">Yes</option>
                                                          <?php  
                                                      }
                                                      ?>
                                              </select>
                                            
                                           </div>
                                           </div>
                                           <?php
                       
                                              }else{
                                                ?>
                                                <input type="hidden" name="hasstock" value="<?php echo $hasstock ?>">

                                                <?php

                                              }
                                              ?>
                                              <?php
                                            if ($gbusiness_settings['vat_legibility']==1) {
                                              ?>
                                          <div class="control-group">
                                          <label class="control-label" for="focusedInput">Legible for VAT</label>
                                          <div class="controls">
                                                <select name="vat" class="input-xlarge focused"  required="required">
                                              <?php
                                                if ($vat==1) {
                                                         ?>
                                                         <option value="1">Yes</option>
                                                          <option value="0">No</option>
                                                         <?php 
                                                      }else{
                                                          ?>
                                                        <option value="0">No</option>
                                                          <option value="1">Yes</option>
                                                          <?php  
                                                      }
                                                      ?>
                                              </select>
                                            
                                           </div>
                                           </div>
                                           <?php
                       
                                              }else{
                                                ?>
                                                <input type="hidden" name="vat" value="<?php echo $vat ?>">

                                                <?php

                                              }
                                              ?>
                                        
                                        <div class="control-group">
                                          <label class="control-label" for="focusedInput">Product Code</label>
                                          <div class="controls">
                                            <input class="input-xlarge focused" id="focusedInput" type="text" name="pcode" value="<?php echo $product_code; ?>">
                                          </div>
                                        </div>
                                        <div class="control-group">
                                          <label class="control-label" for="focusedInput">Quantity</label>
                                          <div class="controls">
                                            <input readonly="readonly" class="input-xlarge focused" id="focusedInput" type="number" name="quantity" value="<?php echo $quantity; ?>" >
                                          </div>
                                        </div>
                                        <div class="control-group">
                                          <label class="control-label" for="focusedInput">Minimun Quantity</label>
                                          <div class="controls">
                                            <input  class="input-xlarge focused" id="focusedInput" type="number" name="minimum_quantity" value="<?php echo $minimum_quantity; ?>" required>
                                          </div>
                                        </div>

                                        <div class="control-group">
                                          <label class="control-label" for="focusedInput">Unit Selling Price</label>
                                          <div class="controls">
                                            <input class="input-xlarge focused" id="focusedInput" type="text" onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" name="price" value="<?php echo $price; ?>">
                                          </div>
                                          
                                        </div>
                                        <?php
                                          if ($business_type==1) {
                                            ?>
                                            <div class="control-group">
                                          <label class="control-label" for="focusedInput">Whole sale Unit Selling Price</label>
                                          <div class="controls">
                                            <input class="input-xlarge focused" id="focusedInput" type="text" onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" name="pricewhole" value="<?php echo $price_whole; ?>">
                                          </div>
                                          
                                        </div>
                                            <?php
                                          }
                                          ?>
                                          <?php
                                          if ($gbusiness_settings['inlude_reserve_prices']==1) {
                                            ?>
                                         <div class="control-group">
                                          <label class="control-label" for="focusedInput">Reserve Price</label>
                                          <div class="controls">
                                            <input class="input-xlarge focused" id="focusedInput" type="text" onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" name="reserve_price" value="<?php echo $reserve_price; ?>">
                                          </div>
                                          
                                        </div>
                                        <?php
                       
                                              }else{
                                                ?>
                                                <input type="hidden" name="reserve_price" value="<?php echo $reserve_price ?>">

                                                <?php

                                              }
                                              ?>
                                        <div class="control-group">
                                          <label class="control-label" for="focusedInput">Units</label>
                                          <div class="controls">
                                            <select name="units" class="form-control" required style="width: 30%;">
                                            <?php
                                            $defa = mysqli_fetch_array(mysqli_query($con,"SELECT * from units where UnitID='$unit'"));
                                            ?>
                          <option value="<?php echo $defa['UnitID'];?>"><?php echo$defa['Symbol'];?></option >
                          <?php
                          include("../includes/connection.php");
    
                          $query = mysqli_query($con,"select * from units where branch_id='$branc'");
                          while($row0=mysqli_fetch_array($query)){
                          ?>
                          <option value="<?php echo $row0['UnitID'];?>"><?php echo$row0['Symbol'];?></option>
                          <?php
                          
                          }
                          ?>
                          
                        </select>
                                          </div>
                                        </div>
                                       
                                        <div class="form-actions">
                                          <button type="submit" name="edit" class="btn btn-primary">Save changes</button>
                                        </div>
                                      </fieldset>
                                    </form>
                                    <?php
                                    include '../includes/connection.php';
                                    if(isset($_POST['edit'])){
                                        $product=$_POST['pname'];
                                        $pcategory=$_POST['category'];
                                        $pcode=$_POST['pcode'];
                                        $vat=$_POST['vat'];
                                        $punit=$_POST['units'];
                                        $quantityy=$_POST['quantity'];
                                        $mini_quantity=$_POST['minimum_quantity'];
                                        $bad_symbols = array(",", ".");

                                        $pricee=$_POST['price'];
                                        $reserve_price=$_POST['reserve_price'];
                                        $hasstock=$_POST['hasstock'];
                                        $pricee= str_replace($bad_symbols, "", $pricee);
                                        $reserve_price= str_replace($bad_symbols, "", $reserve_price);
                                          if ($business_type==1) {
                                            
                                        $pricewhole=$_POST['pricewhole'];
                                        $pricewhole= str_replace($bad_symbols, "", $pricewhole);
                                      }else{
                                        $pricewhole=0;
                                      }
                                // Check connection
                                if (!$con) {
                                    die("Connection failed: " . mysqli_connect_error());
                                }
                                $Checkpcode=mysqli_query($con,"SELECT * from products where product_code='$pcode' && id!='$id' && branch_id='$branc' && product_code!=''");
                                if (mysqli_num_rows($Checkpcode)>0) {
                                  echo"<script>alert('Product Code already exists')</script>";
                                }else{


                                $sql = "UPDATE products set category='$pcategory',product_name='$product',has_stock='$hasstock',minimum_quantity='$mini_quantity',product_code='$pcode', price='$pricee',price_whole='$pricewhole',Units='$punit',VAT='$vat',reserve_price='$reserve_price' WHERE id='$id'";
                                $sql1 = mysqli_query($con,"UPDATE stock set selling_price='$pricee',selling_price_whole='$pricewhole',min_quantity='$mini_quantity' where product_name='$id'");


                                if (mysqli_query($con, $sql)) {

                                      $id_user=$_SESSION['id'];
                                      $activity="Editted product ".$product_name." from (".$product_name.", ".$quantity.", ".$price.") to (".$product.", ".$quantityy.", ".$pricee.")";
                                      $log_sql=mysqli_query($con,"INSERT INTO logs(user_id, activity) VALUES 
('$id_user','$activity')");

if ($log_sql) {
 //   alert('Product updated added succesfully');
    echo "string";
    echo "<script>
    window.location='products.php';
    </script>";

} else {
    echo "Error: Failed to add log <br>" . mysqli_error($con);
}


                                   
                                } else {
                                    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
                                }

                               

                                    }
                                    // Create connection
                                
                                     }
                                    ?>

                                </div>
                            </div>
                        </div>
                        <!-- /block -->
                    </div>

              

                     <!-- wizard -->
    
                     <!-- validation -->
       


                </div>
            </div>
            <hr>
            <?php include '../includes/footer.php'; ?>
        </div>
        <!--/.fluid-container-->
        <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="../bootstrap/js/bootstrap.min.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>

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

        $(function() {
            $(".datepicker").datepicker();
            $(".uniform_on").uniform();
            $(".chzn-select").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>