<?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>
<?php
    include("../includes/header-links.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['nav_products'] != 1){
?>
<script>window.location="../main/dashboard.php"</script>
<?php
}
?>
    ?>
    <head>

		
    <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'; ?>
        <div class="container-fluid">
		
            <div class="row-fluid">
                <?php include '../includes/sidebar.php'; ?>
                <!--/span-->
                <div class="span10" id="content">
					

                     <div class="row-fluid">
                        <!-- block -->
                        <div class="block">
						
                            <div class="navbar navbar-inner block-header">
                                <div class="muted pull-left">Products in stock</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['add_product'] == 1){
                                    ?>
                                            <div class="btn-group">
                                         <a href="#myModal" data-toggle="modal" class="btn btn-success"><i class="icon-plus icon-white"></i>&nbsp;Add New</a>

                                      </div>
                                        <?php
                                   }
                                   ?>

                                   <?php
                                   // if($_SESSION['role']=="admin"|| $_SESSION['role']="Super Admin"){
                                   if( $permissions['product_stock'] == 1){
                                    ?>
                                          <div class="btn-group">
                                         <a href="stock.php" class="btn btn-primary"><i class="icon-briefcase icon-white"></i>&nbsp;Stock</a>
                                      </div>
                                      <?php
                                    }
                                      ?>
                                      <?php
                                   // if($_SESSION['role']=="admin"|| $_SESSION['role']="Super Admin"){
                                   if( $permissions['view_product_categories'] == 1){
                                    ?>
                                      <div class="btn-group">
                                       <a href="product_category_admin.php" ><button class="btn btn-warning"> <i class="icon-indent-left"></i> Product Categories</button></a>
                                     </div>
                                      <?php
                                    }
                                      ?>
                                  
                                      

                                      <!--Model begins here -->
                                      <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>Add new Product</h3>
											</div>
											<div class="modal-body">
												<form action="" method="POST" enctype="multipart/form-data"> 
                         <div align="center" class="col-lg-12">
                          <label>Branch</label>
                        
                        <select name="branch" class="form-control" required style="width: 95%; height: 30px;">
                          <option disabled selected="" value="">Select Branch</option>
                          <!-- <option value="all">All</option> -->
                         <?php 
                         $cat=mysqli_query($con,"SELECT * from branches where status=1 && business_id='$business'");
                         while ( $row1=mysqli_fetch_array($cat)) {
                           ?>
                           <option value="<?php echo $row1['branch_id'];?>"><?php echo $row1['branch_name'];?></option>
                           <?php
                         }
                          ?>
                         
                          
                        </select>
                      </div>
                      <div align="center" class="col-lg-12">
                          <label>Category</label>
                        
                        <select name="category" class="form-control" required style="width: 95%; height: 30px;">
                          <option disabled selected="" value="">Select Category</option>
                         <?php 
                         $cat=mysqli_query($con,"SELECT * from product_categories where status=1 && business_id='$business'");
                         while ( $rowc=mysqli_fetch_array($cat)) {
                           ?>
                           <option value="<?php echo $rowc['category_id'];?>"><?php echo $rowc['category_name'];?></option>
                           <?php
                         }
                          ?>
                         
                          
                        </select>
                      </div>
                      <div align="center" class="col-lg-12">
												<label>Product Name</label>
                        
												<input type="text" name="name" class="form-control" placeholder="Product Name" style="width: 95%;" required="required">
                      </div>
                       <div align="center" class="col-lg-12">
                        <label>Product Code </label>
                        
                        <input type="text" name="pcode" class="form-control" placeholder="Product Code" style="width: 95%;">
                      </div>
                      <div align="center" class="col-lg-12">
												<label>Minimum Quantity</label style="width: 95%; ">
												<input type="number" name="minquantity" class="form-control" style="width: 95%;">
											</div>
                      <div align="center" class="col-lg-12">
												<label>Units</label>
												<select name="units" class="form-control" required style="width: 95%;">
													<option value="">Select units</option >
													<?php
													include("../includes/connection.php");
		
													$query = mysqli_query($con,"select * from units,branches where units.branch_id=branches.branch_id && branches.business_id='$business'");
													while($row0=mysqli_fetch_array($query)){
													?>
													<option value="<?php echo $row0['UnitID'];?>"><?php echo$row0['Symbol'];?></option>
													<?php
													
													}
													?>
													
												</select>
                      </div>
                      <div align="center" class="col-lg-12">
												<label>Unit Selling Price</label>
												<input type="text" onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" name="unitprice" class="form-control" placeholder="Unit Price" style="width: 95%;" required="required">
                      </div>
												<div class="form-actions">
                                          <button type="submit" name="add" class="btn btn-primary">Save Product</button>
                                          <a href="Products.php" class="btn btn-danger">Cancel</a>
                                        </div>	
												</form>
											</div>
										</div>
										<!--Model Ends here -->
                                   
                                   <?php
include '../includes/connection.php';
                   //if($_SESSION['role']=="Super Admin"){
//if($permissions['business_id'] != 0 && $permissions['branch_id']==0){
if( $permissions['products_admin_branch'] == 1){
        $sql = mysqli_query($con,"SELECT *,(select branch_name from branches where branch_id=products.branch_id) as bchname FROM products where status=1 && business_id='$business'");
       
       }else{
         $sql = mysqli_query($con,"SELECT * FROM products where status=1 && branch_id='$branch'");
       }                
      // Create connection

//$result = mysqli_query($con, $sql);

if (mysqli_num_rows($sql) > 0) {
    // output data of each row
    


                                   ?>
        </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>ID</th>

                         <?php
                        if( $permissions['products_admin_branch'] == 1){
                          //if ($business!=0) {
                            ?>
                                                <th>Branch</th>
                                                <?php
                         }
                         ?>
                                                <th>Category</th>
                                                <th>Product Name</th>
                                                <th>Product Code</th>
                                                <th>Quantity</th>
                                                <th>Price</th>
                                                
                                                <th>Action</th>
                                                

                                            </tr>
                                        </thead>
                                        <tbody>
                                        
                                        <?php
                                        $no=0;
while($row = mysqli_fetch_assoc($sql)) {
	 $no++;

        ?>
<tr class="gradeU">
                                                <td><?php echo $no; ?></td>
                                                 <?php
                        if( $permissions['products_admin_branch'] == 1){
                          //if ($business!=0) {
                            ?>
                                                <td><?php echo $row['bchname']; ?>
                                                </td>
                                                <?php
                         }
                         ?>
                                                <?php
                                                 $categ=$row['category']; 
                                                $sqlc=mysqli_fetch_array(mysqli_query($con,"SELECT * FROM product_categories where category_id='$categ'"));
                                                 ?>
                                                <td><?php echo $sqlc['category_name']; ?></td>
                                                <td><?php echo $row['product_name']; ?></td>
                                                <td><?php echo $row['product_code']; ?></td>
                                               <!-- <td><img src="<?php// echo $row['ProductImage'];?>" alt="no image" width="100px" height="100px"/></td>-->
                                                <td><?php echo $row['quantity']; ?></td>
                                                <td class="center"><?php echo number_format($row['price']); ?>/=</td>
                                                
                                                <td class="center">
                                                <?php $newid=$row['id'];
                                                    $prodname=$row['product_name'];?>

                                                               <?php
                                   // if($_SESSION['role']=="admin"|| $_SESSION['role']="Super Admin"){
                                   if( $permissions['edit_product'] == 1){
                                    ?>
                                                
                                                	<a href="editproduct.php?id=<?php echo $row['id']; ?>"><button class="btn btn-primary"><i class="icon-edit icon-white"></i></button></a>
                                                                 <?php
                                    }
                                      ?>

                                                  <?php
                                   // if($_SESSION['role']=="admin"|| $_SESSION['role']="Super Admin"){
                                   if( $permissions['delete_product'] == 1){
                                    ?>

                                                	<a href="deleteconfirm.php?id=<?php echo base64_encode($row['id']); ?>&prodname=<?php echo base64_encode($prodname); ?>"><button class="btn btn-danger"><i class="icon-trash icon-white"></i></button></a>
                                                  <?php
                                    }
                                      ?>
                                                	
									<div id="myAlert" class="modal hide">
											<div class="modal-header">
												<button data-dismiss="modal" class="close" type="button">&times;</button>
												<h3>Warning !</h3>
											</div>
											<div class="modal-body">
												<p>Are you sure you want to delete this product?</p>
											</div>
											<div class="modal-footer">
												<a href="deleteproduct.php?id=<?php echo $newid; ?>"><button class="btn btn-primary"> Yes</button></a>
												<a data-dismiss="modal" class="btn" href="#">No</a>
											</div>
										</div>
                                            
                                                </td>
                                              
                                            </tr>
                                            
                                            <?php


    }
} else {
    echo "No products added yet!";
}

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======-->
       
 

<?php


if(isset($_POST['add'])){
	include '../includes/connection.php';
echo$pbranch=mysqli_real_escape_string($con,ucwords($_POST['branch']));
$category=mysqli_real_escape_string($con,ucwords($_POST['category']));
$product_name=mysqli_real_escape_string($con,ucwords($_POST['name']));
$pcode=mysqli_real_escape_string($con,$_POST['pcode']);
$minquantity=mysqli_real_escape_string($con,$_POST['minquantity']);
if($pbranch=="all"){
    $sql1 = mysqli_query($con,"SELECT * from branches where business_id='$business' and status=1");
    while($row2=mysqli_fetch_array($sql1)){
        $branchd = $row2['branch_id'];
        $sql0 = mysqli_query($con,"select * from products where product_name='$product_name' && branch_id='$branchd'");
    if(mysqli_num_rows($sql0)>0){
        echo"<script>alert('product already exists')</script>";
    }
    else{	
                
    $id_user=$_SESSION['id'];
    
    $unit=$_POST['units'];
    $bad_symbols = array(",", ".");

    $unitprice= mysqli_real_escape_string($con,$_POST['unitprice']);
    $unitprice= str_replace($bad_symbols, "", $unitprice);
    $sql = mysqli_query($con,"INSERT INTO products (category,product_name,product_code,minimum_quantity,Units, price,branch_id,business_id,AddedBy)
    VALUES ('$category','$product_name','$pcode','$minquantity', '$unit','$unitprice','$branchd','$business','$id_user')");

    }
}}
else{
    $branchd = $pbranch;
    $sql0 = mysqli_query($con,"select * from products where product_name='$product_name' && branch_id='$branchd'");
    if(mysqli_num_rows($sql0)>0){
        echo"<script>alert('product already exists')</script>";
    }
    else{	
                
    $id_user=$_SESSION['id'];
    
    $unit=$_POST['units'];
    $bad_symbols = array(",", ".");

    $unitprice= mysqli_real_escape_string($con,$_POST['unitprice']);
    $unitprice= str_replace($bad_symbols, "", $unitprice);
    $sql = mysqli_query($con,"INSERT INTO products (category,product_name,product_code,minimum_quantity,Units, price,branch_id,business_id,AddedBy)
    VALUES ('$category','$product_name','$pcode','$minquantity', '$unit','$unitprice','$branchd','$business','$id_user')");

    }
}

if ($sql) {


    $id_user=$_SESSION['id'];
  $activity="Added a new product ".$product_name;
     

 $log_sql=mysqli_query($con,"INSERT INTO logs(user_id, activity,branch_id,business_id) VALUES 
('$id_user','$activity','$branchd','$business')");

if ($log_sql) {

  ?>
    <meta http-equiv="refresh" content="0;URL='defaultdata2.php'" />  
    <?php


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

mysqli_close($con);
}

?>
<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>
