<?php
session_start();
error_reporting(0);
@ini_set('display_errors', 0);
$id_user=$_SESSION['id'];
$branch=$_SESSION['branch_id'];
$business=$_SESSION['business_id'];
?>

<!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");
$permissions = mysqli_fetch_array(mysqli_query($con,"SELECT * FROM  
  permissions,users WHERE  permissions.role_id = users.role 
  AND users.id='$id_user' AND users.business_id ='$business' AND users.branch_id ='$branch'"));

if($permissions['view_stock'] != 1){
?>
<script>window.location="../main/dashboard.php"</script>
<?php
}
?>
		<?php
		include("../includes/header-links.php");
		?>
    <link rel="stylesheet" href="../data-table-css/bootstrap-table.css">
    <link rel="stylesheet" href="../data-table-css/bootstrap-editable.css">
    </head>
    
    <body>
    
        <?php include '../includes/header.php'; ?>
        <?php
                                                $checkarrangement=mysqli_fetch_array(mysqli_query($conn,"SELECT * from receipt_settings where branch_id='$branch'"));
                                                $arrange_products=$checkarrangement['arrange_products'];

                                                   ?>
        <div class="container-fluid">
		
            <div class="row-fluid">
                <?php include '../includes/sidebar.php'; ?>
                <!--/span-->
                <div class="span9" id="content">
					

                     <div class="row-fluid">
                        <!-- block -->
                        <div class="block">
						
                            <div class="navbar navbar-inner block-header">
                                 
                                <div class="muted pull-left" > &nbsp&nbsp&nbsp<br> <h4>Available stock</h4></div>
                            </div>

                            <div class="block-content collapse in">
							
                                <div class="span12">
<div class="row">
	<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">

	</div>
	<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
	</div>		 
</div>
                                   <div class="table-toolbar">
                                   <?php
                                    // if($_SESSION['role']=="admin" || $_SESSION['role']=="Super Admin"){
                                   if( $permissions['view_products'] == 1){
                                    ?>

                                    <div class="btn-group">
                                   <a <?php 
                                   // if($_SESSION['role']=="Super Admin")
                                   if( $_SESSION['branch_id'] == 0)
                                   {?>href="product_admin.php"<?php }else{?>href="products.php"<?php }?>><button class="btn btn-success">Products</button> </a>
                                      </div>
                                            <div class="btn-group">
                                         <a <?php 

                                         //if($_SESSION['role']=="Super Admin")
                                         //if( $permissions['add_stock'] == 1)
                                         if($branch==0 && $business !=0)

                                          {?>href="../purchases/new_purchase_admin.php"<?php }else{?>href="../purchases/new_purchase.php"<?php }?>  class="btn btn-primary"><i class="icon-plus icon-white"></i>&nbsp;Add Stock</a>
                                      </div>
                                      
                                   <?php }
                                   //if($_SESSION['role']=="admin")
                                   if( $permissions['spoilt_stock'] == 1)
                                   {
                                    ?>
                                      <div class="btn-group">
                                         <a href="spoilt_stock.php"  class="btn btn-warning"><i class="icon-eye-open icon-white"></i>&nbsp;Spoilt Stock</a>
                                       </div>
                                       <div class="btn-group">
                                       <a href="reconcile.php" class="btn btn-info"><i class="icon-certificate icon-white"></i>&nbsp;Reconcile stock</a>
                                      </div>
                                        <p>&nbsp <bd> &nbsp</p>
                                       
                                    <?php
                                   }
                                   ?>
                

                                      <!--Model begins here -->
                        
										<!--Model Ends here -->
                  
                                   <?php
include '../includes/connection.php';
                                   // Create connection
//if($_SESSION['role']=="Super Admin"){
 if( $_SESSION['branch_id'] == 0){
   if ($arrange_products=="Aphabetical Order") {
   $sql = mysqli_query($con,"SELECT id, (SELECT product_name from products where id=stock.product_name && branch_id=stock.branch_id)as product_name, quantity, buying_price, selling_price,selling_price_whole, (select symbol from units where UnitID=(select Units from products where id=stock.product_name) && branch_id='$branch')as unitf, min_quantity from stock where status=1 && business_id='$business' order by (SELECT product_name from products where id=stock.product_name)");

  }else if ($arrange_products=="By Category") {
    
 $sql = mysqli_query($con,"SELECT id, (SELECT product_name from products where id=stock.product_name && branch_id=stock.branch_id)as product_name, quantity, buying_price, selling_price,selling_price_whole, (select symbol from units where UnitID=(select Units from products where id=stock.product_name) && branch_id='$branch')as unitf, min_quantity from stock where status=1 && business_id='$business' order by (SELECT category from products where id=stock.product_name)");

  }else if ($arrange_products=="By Quantity") {
     $sql = mysqli_query($con,"SELECT id, (SELECT product_name from products where id=stock.product_name && branch_id=stock.branch_id)as product_name, quantity, buying_price, selling_price,selling_price_whole, (select symbol from units where UnitID=(select Units from products where id=stock.product_name) && branch_id='$branch')as unitf, min_quantity from stock where status=1 && business_id='$business' order by quantity DESC");
  }else{
    $sql = mysqli_query($con,"SELECT id, (SELECT product_name from products where id=stock.product_name && branch_id=stock.branch_id)as product_name, quantity, buying_price, selling_price,selling_price_whole, (select symbol from units where UnitID=(select Units from products where id=stock.product_name) && branch_id='$branch')as unitf, min_quantity from stock where status=1 && business_id='$business' order by (SELECT category from products where id=stock.product_name)");

  }
 

}
else{
   if ($arrange_products=="Aphabetical Order") {
   $sql = mysqli_query($con,"SELECT id, (SELECT product_name from products where id=stock.product_name && branch_id='$branch')as product_name, quantity, buying_price, selling_price,selling_price_whole, (select symbol from units where UnitID=(select Units from products where id=stock.product_name) && branch_id='$branch')as unitf, min_quantity from stock where status=1 && branch_id='$branch' order by (SELECT product_name from products where id=stock.product_name)");

  }else if ($arrange_products=="By Category") {
    $sql = mysqli_query($con,"SELECT id, (SELECT product_name from products where id=stock.product_name && branch_id='$branch')as product_name, quantity, buying_price, selling_price,selling_price_whole, (select symbol from units where UnitID=(select Units from products where id=stock.product_name) && branch_id='$branch')as unitf, min_quantity from stock where status=1 && branch_id='$branch' order by (SELECT category from products where id=stock.product_name)");

  }else if ($arrange_products=="By Quantity") {
  $sql = mysqli_query($con,"SELECT id, (SELECT product_name from products where id=stock.product_name && branch_id='$branch')as product_name, quantity, buying_price, selling_price,selling_price_whole, (select symbol from units where UnitID=(select Units from products where id=stock.product_name) && branch_id='$branch')as unitf, min_quantity from stock where status=1 && branch_id='$branch' order by quantity DESC");

  }else{
    $sql = mysqli_query($con,"SELECT id, (SELECT product_name from products where id=stock.product_name && branch_id='$branch')as product_name, quantity, buying_price, selling_price,selling_price_whole, (select symbol from units where UnitID=(select Units from products where id=stock.product_name) && branch_id='$branch')as unitf, min_quantity from stock where status=1 && branch_id='$branch' order by (SELECT category from products where id=stock.product_name)");

  }
  
  
  
}
if (mysqli_num_rows($sql) > 0) {
  
  
                                   ?>

        </div>
                                <div class="datatable-dashv1-list custom-datatable-overright">
                                    <div id="toolbar">
                                        <select class="form-control">
                                                <option value="">Export Basic</option>
                                                <option value="all">Export All</option>
                                                <option value="selected">Export Selected</option>
                                            </select>
                                    </div>
                                    <table  id="table" data-toggle="table" data-pagination="true" data-search="true" data-show-columns="true" data-show-pagination-switch="true" data-show-refresh="true" data-key-events="true" data-show-toggle="true" data-resizable="true" data-cookie="true"
                                        data-cookie-id-table="saveId" data-show-export="true" data-click-to-select="true" data-toolbar="#toolbar" data-export-options='{"fileName": "Testing_filename"}'>
                                        <thead>
                                            <tr>
                                                <th>S/NO</th>
                                                <th>Product Name</th>
                                               
                                                <th>Quantity</th>
                                                 <?php if( $permissions['view_buyingprice'] == 1)
                                                  { ?>
                                                 <th>Buying Price</th>
                                                <?php } ?>
                                               
                                                 <th>Selling Price</th>
                                                 <?php if($business_type==1){ ?>
                                                <th>Wholesale Unit price</th>
                                                <?php } ?>
                                                  <th>Status</th>
                                                <?php 
                                                //if($_SESSION['role']=="admin")
                                                if( $permissions['edit_stock'] == 1)
                                                  { ?>
                                                <th>Action</th>
                                                <?php } ?>

                                            </tr>
                                        </thead>
                                        <tbody>
                                        
                                        <?php
                                        $n=0;
while($row = mysqli_fetch_assoc($sql)) {
	$pid=$row['id'];
  $n++;
 ?>
<tr class="gradeU">
  


                                                <td><?php echo $n; ?></td>
                                                <td><?php echo $row['product_name']; ?></td>
                                                <td><?php echo $row['quantity'];?></td>
                                                <?php if( $permissions['view_buyingprice'] == 1)
                                                  { ?>
                                                  <td><?php echo ($row['buying_price']); ?></td>
                                                <?php } ?>
                                               
                                                <td><?php echo number_format($row['selling_price']); ?></td>
                                                <?php if($business_type==1){ ?>
                                                <td><?php echo number_format($row['selling_price_whole']); ?></td>
                                                <?php } ?>
                                                <td>
                                                  <?php
                                                  if($row['quantity']<=$row['min_quantity'] && $row['quantity']>0){
    ?>
<span class="label label-warning"> Product is Reducing</span>
    <?php
  }else if($row['quantity']==0){
    ?>
<span class="label label-danger"> Product out of stock</span>
    <?php
  }
    else{
    ?>
<span class="label label-info"> Product Still in stock</span>
    <?php
  }     ?>
                                                </td>
                                                
                                                <?php
                                                // if($_SESSION['role']=="admin")
                                                if( $permissions['edit_stock'] == 1)
                                                
                                                { ?>
                                                <td><a href="#edit<?php echo $pid; ?>" data-toggle="modal"><button class="btn btn-primary"><i class="icon-edit icon-white"></i></button></a></td>
                                                <?php
                                                } ?>
                         <div id="edit<?php echo $pid; ?>" class="modal hide">
                      <div class="modal-header">
                        <button data-dismiss="modal" class="close" type="button">&times;</button>
                        <h3>Edit porduct selling price</h3>
                      </div>
                      <div class="modal-body">
                        <?php
                        $sqledit=mysqli_fetch_array(mysqli_query($con,"select * from stock where id='$pid'"));
                          $id=$sqledit['id'];
                          $prod=$sqledit['product_name'];
                          $pri=$sqledit['buying_price'];
                          $sp=$sqledit['selling_price'];
                              $sqleditp=mysqli_fetch_array(mysqli_query($con,"select * from products where id='$prod'"));
                             $podct=$sqleditp['product_name'];
                        ?>
                        <form action="" method="POST" enctype="multipart/form-data">
                        <input type="hidden" value="<?php echo $id; ?>" name="id" style="width: 95%; height: 30px;">
                        <label>Product </label>
                        <div class="controls">
                          <input type="text" value="<?php echo  $podct; ?>" name="sproduct" class="input-xlarge focused" readonly="readonly" style="width: 95%; height: 30px;">
                                          </div>
                        <label>Buying Price</label>
                        <div class="controls">
                          <input type="number" value="<?php echo (int)$pri; ?>" name="bprice" class="input-xlarge focused" required="required" style="width: 95%; height: 30px;">
                                          </div>
                        
                        <label>Selling Price</label>
                         <div class="controls">
                        <input type="text" onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" value="<?php echo $sp; ?>" name="sprice" class="input-xlarge focused" placeholder="Selling price" style="width: 95%; height: 30px;">
                      </div>
                        <div class="form-actions">
                                          <button type="submit" name="next" class="btn btn-primary">Save </button>
                                          
                                        </div>  
                        </form>
                      </div>
                    </div>
                                            </tr>
                                            
                                            <?php


    }

} else {
    echo "0 results";
}

mysqli_close($con);


                                        ?>
                                        <?php
                                        if(isset($_POST['next'])){
  include '../includes/connection.php';
  $bad_symbols = array(",", ".");
    $bprice=mysqli_real_escape_string($con,$_POST['bprice']);
    $sprice=mysqli_real_escape_string($con,$_POST['sprice']);
    $sprice= str_replace($bad_symbols, "", $sprice);


$bprice=mysqli_real_escape_string($con,$_POST['bprice']);
$id=$_POST['id'];
 $up=mysqli_fetch_array(mysqli_query($con,"select * from stock where id='$id'"));
 $pname=$up['product_name'];

if ($sprice<=$bprice) {
 echo"<script>alert('Failed: The selling price should be greater than the buying price'),history.go(-1);</script>";
}else{
$sqlsp = mysqli_query($con,"update stock set selling_price='$sprice',buying_price='$bprice' where id='$id' ");
$sqlps = mysqli_query($con,"update products set price='$sprice' where id='$pname' ");

if ($sqlsp) {
  $id_user=$_SESSION['id'];
  $activity="Edited selling price for ". $podct;
 $log_sqlp=mysqli_query($con,"INSERT INTO logs(user_id, activity) VALUES 
('$id_user','$activity')");

if ($log_sqlp) {
 //alert('Updated a selling price for  $podct succesfully');
    echo "<script>
    
    window.location='stock.php';
    </script>";
} else {
    echo "Error: Failed to add log <br>" . mysqli_error($con);
}
  ?>


    <meta http-equiv="refresh" />  
    <?php
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($con);
}

mysqli_close($con);
}
}
?>
                                            
                                        </tbody>
                                    </table>
                                  </div>
                                    
                                </div>
                            </div>
                        </div>
                        <!-- /block -->
                    </div>
                </div>
            </div>
            <hr>
            <?php include '../includes/footer.php'; ?>
        </div>
        <!--/.fluid-container-->

        <!--==========Footer js======-->
		<?php require_once("../includes/footerjs.php");?>
        <!--==========Footer js======-->
       
   


<script src="../data-table-js/bootstrap-table.js"></script>
    <script src="../data-table-js/tableExport.js"></script>
    <script src="../data-table-js/data-table-active.js"></script>
    <script src="../data-table-js/bootstrap-table-editable.js"></script>
    <script src="../data-table-js/bootstrap-editable.js"></script>
    <script src="../data-table-js/bootstrap-table-resizable.js"></script>
    <script src="../data-table-js/colResizable-1.5.source.js"></script>
    <script src="../data-table-js/bootstrap-table-export.js"></script>
  </body>
</html>
