<?php
session_start();
include_once "../config.php";
require_once '../database1.php';
require_once "../check_admin.php";

class category extends database
{
   public function getAllProducts($page, $name, $categoryID, $inStock, $supplier)
    {
        $whereStr = '';
        $whereStr1 = '';
        $where = [];
        if(trim($name) != '')
        {
            
            $whereStr.= ' AND (p.cl_name LIKE ? OR p.cl_id LIKE ? OR p.cl_product_id=? OR p.cl_ean=?)  ';
            $whereStr1.= ' AND (p.cl_name LIKE ? OR p.cl_id LIKE ? OR p.cl_product_id=? OR p.cl_ean=? OR vp.cl_ean=?)  ';

            $where[] = '%' . $name . '%';
            $where[] = '%' . $name . '%';
            $where[] = $name;
            $where[] = $name;

            $where[] = '%' . $name . '%';
            $where[] = '%' . $name . '%';
            $where[] = $name;
            $where[] = $name;
            $where[] = $name;
        }

        if(trim($categoryID) != '')
        {
            $whereStr.= ' AND p.cl_cat_id=? ';
            $where[] = $categoryID;
        }
        
        if(trim($inStock) != '')
        {
            $whereStr.= ' AND p.cl_stock=? ';
            if($inStock == 2)
            {
                $inStock = 0;
            }
            $where[] = $inStock;
        }
        
        if(trim($supplier) != '')
        {
            $whereStr.= ' AND p.cl_supplier=? ';
            $where[] = $supplier;
        }
        
        
		$start = $page - 1;
        $sql = " SELECT t.* FROM (SELECT p.*, c.cl_name AS category, '' AS all_ean FROM tb_product p INNER JOIN tb_product_category c ON p.cl_cat_id=c.cl_id WHERE p.cl_deleted_at IS NULL AND p.cl_type='General' " . $whereStr . " GROUP BY p.cl_id  
        UNION All
            SELECT p.*, c.cl_name AS category, GROUP_CONCAT(vp.cl_ean) AS all_ean FROM tb_product p INNER JOIN tb_product_category c ON p.cl_cat_id=c.cl_id INNER JOIN tb_variable_product vp ON p.cl_id=vp.cl_product_id WHERE p.cl_deleted_at IS NULL AND p.cl_type='Variable' " . $whereStr1 . " ) AS t ORDER BY FIELD(t.cl_stock,1,0), t.cl_created_at DESC LIMIT " . $start * 50 . "," . 50;

      //  $sql = " SELECT p.*, c.cl_name AS category, '' AS all_ean FROM tb_product p INNER JOIN tb_product_category c ON p.cl_cat_id=c.cl_id WHERE p.cl_deleted_at IS NULL " . $whereStr . " GROUP BY p.cl_id ORDER BY p.cl_created_at DESC LIMIT " . $start * 50 . "," . 50;
        return $this->callQuery($sql, $where);
		//return $this->callQuery('tb_product', null, 'cl_created_at', 'DESC', ($start * 50), 50);
	}

    public function getAllCategories()
    {
        return $this->fetchAll('tb_product_category');
    }
}
$msg='';
if(isset($_GET['message']))
{
	$msg=$_GET['message'];
}
$page = 1;
if(isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 1)
{
    $page = htmlspecialchars($_GET['page']);
}

$name = '';
$categoryID = '';
$inStock = '';
$supplier = '';
if(isset($_POST['data']))
{
    $data = $_POST['data'];
    $name = $data['name'];
    $categoryID = $data['category_id'];
    $inStock = $data['in_stock'];
    $supplier = $data['supplier'];
}
$obj = new category();	
$products = $obj->getAllProducts($page, $name, $categoryID, $inStock, $supplier);
$categories = $obj->getAllCategories();
include '../header.php';
?>
					 
            <!-- MAIN CONTENT-->
            <div class="main-content">
                <div class="section__content section__content--p30">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="overview-wrap">
                                    <div class="row">
                                    <div class="col-12">
                                        <h2 class="title-1">All Products - Page <?php echo $page ?></h2>
                                    </div>
                                    <div class="col-12">
                                    <a class="btn btn-success " href="add_bulk.php">Add Product as Bulk</a>
                                    <a class="btn btn-success " href="update_bulk.php">Update Product as Bulk</a>
                                     <a class="btn btn-success " href="update_stock.php">Update Stock & Price</a>
                                      <a class="btn btn-success " href="update_ean.php">Update EAN</a>
                                      <a class="btn btn-success " href="update_weight.php">Update Weight</a>
                                    <a class="btn btn-success " href="add.php">Add Product</a>
                                    </div>
                                    </div>
                                </div>
								<?php if($msg !=''){echo '<span class="col-md-6 alert alert-danger pull-left">'.$msg.'</span>';}?>
                            </div>
                        </div>
                        
                        <div class="row m-t-25 m-row">
							<form class="col-sm-12" method="POST">
                                <div class="well-white col-xs-12 col-sm-12" method="POST">
                                    <div class="row">
                                        <div class="col-md-4 col-xs-12">
                                            <input type="text" name="data[name]" class="form-control" placeholder="Search by name or product id or ean"  value="<?php if(isset($data['name'])){echo $data['name'];} ?>"/>
                                        </div>
                                        <div class="col-md-4 col-xs-12">
                                            <select class="form-control" name="data[category_id]">
                                                <option value="">---Search by Category---</option>
                                            <?php
                                            if(!empty($categories))
                                            {
                                                foreach($categories AS $category)
                                                {
                                                    ?>
                                                    <option value="<?php echo htmlspecialchars($category['cl_id']) ?>" <?php if(isset($data['category_id']) && $data['category_id'] == $category['cl_id']){echo 'selected';} ?>><?php echo htmlspecialchars($category['cl_name']) ?></option>
                                                    <?php
                                                }
                                            }
                                            ?>
                                        </select>
                                           
                                        </div>
                                        <div class="col-md-4 col-xs-12">
                                            <select class="form-control" name="data[in_stock]">
                                                <option value="">---All Stocks--</option>
                                                <option value="1" <?php if($data['in_stock'] == 1){echo ' selected="selected" ';} ?>>Only In Stock</option>
                                                <option value="2" <?php if($data['in_stock'] == 2){echo ' selected="selected" ';} ?>>Only Out Of Stock</option>
                                        </select>
                                           
                                        </div>
                                        <div class="col-md-4 col-xs-12">
                                            <select class="form-control" name="data[supplier]">
                                                <option value="">---Search by Supplier---</option>
                                                <option value="abpl" <?php if($data['supplier'] == 'abpl'){echo ' selected="selected" ';} ?>>abpl</option>
                                                <option value="action" <?php if($data['supplier'] == 'action'){echo ' selected="selected" ';} ?>>action</option>
                                                <option value="difox" <?php if($data['supplier'] == 'difox'){echo ' selected="selected" ';} ?>>difox</option>
                                                <option value="innpro" <?php if($data['supplier'] == 'innpro'){echo ' selected="selected" ';} ?>>innpro</option>
                                                <option value="makant" <?php if($data['supplier'] == 'makant'){echo ' selected="selected" ';} ?>>makant</option>
                                                <option value="wave" <?php if($data['supplier'] == 'wave'){echo ' selected="selected" ';} ?>>wave</option>
                                        </select>
                                           
                                        </div>
                                        <div class="col-md-4 col-xs-12 ">
                                            <button type="submit" class="btn btn-success">Search</button>
                                        </div>
                                    </div>
                                </div>
                                <div class="table-responsive table--no-card m-b-30 col-sm-12">
                                    <table class="table table-borderless table-data3 ACP_table" id="myTable" style="width:100%">
                                        <thead>
                                            <tr>
                                                <th>

                                                </th>
                                                <th>
                                                    Product ID
                                                </th>
                                                <th>Name</th>
                                                <th>
                                                    Warantty Active?
                                                </th>
                                                <th>
                                                    Category
                                                </th>
											<?php  if($groupArray['short'] != 'PRM'){ ?>
                                                <th>Supplier Price</th>
                                                <th>Shipping Price</th>
                                            <?php } ?>
                                                <th>EAN</th>
                                                
												<th data-priority="1">Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                         <?php
                                         $count = 1;
											foreach($products as $product)
											{
											?>
											<tr class="action-container">
                                                <td>
                                                    <?php echo $count++ ?>
                                                </td>
                                                <td>
                                                    Efix ID : <?php echo htmlspecialchars($product['cl_id']);?><br/>
                                                    Supplier : <?php echo htmlspecialchars($product['cl_supplier']);?><br/>
                                                    Product ID : <?php echo htmlspecialchars($product['cl_product_id']);?>
                                                </td>
												<td><?php echo htmlspecialchars($product['cl_name']);?></td>
                                                <td>
                                                    <select class="form-control warranty_active" cluster-product_id="<?php echo htmlspecialchars($product['cl_id']);?>">
                                                        <option value="1" <?php if($product['cl_warranty_active'] == 1){echo 'selected';} ?>>Yes</option>
                                                        <option value="0" <?php if($product['cl_warranty_active'] == 0){echo 'selected';} ?>>No</option>
                                                    </select>
                                                    <div class="warranty_error"></div>
                                                </td>
                                                <td>
                                                    <?php echo htmlspecialchars($product['category']) ?>
                                                </td>
												
                                                <?php  if($groupArray['short'] != 'PRM'){ ?>
                                                <td><?php echo htmlspecialchars($product['cl_supplier_price']);?></td>
                                                <td><?php echo htmlspecialchars($product['cl_shipping_price']);?></td>
                                            <?php } ?>
                                                <td>
                                                    <?php echo htmlspecialchars($product['cl_ean']);?><br/>
                                                    <?php echo htmlspecialchars($product['all_ean']) ?>

                                                </td>
                                               
												<td>
                                                <!--    <a href="filter.php?id=<?php echo htmlspecialchars($product['cl_id']) ?>" class="btn btn-primary btn-sm col-sm-12">Add Filters & Values</a> 
                                                    <a href="attributes.php?id=<?php echo htmlspecialchars($product['cl_id']) ?>" class="btn btn-info btn-sm col-sm-12" style="margin-top:5px">Add Product Atributes</a> 
                                                    <a href="attributes_details.php?id=<?php echo htmlspecialchars($product['cl_id']) ?>" class="btn btn-primary btn-sm col-sm-12" style="margin-top:5px;margin-bottom: 5px">Add Attribute Details</a>  -->
                                                    <a href="edit.php?id=<?php echo htmlspecialchars($product['cl_id']) ?>" class="btn btn-success btn-sm">Edit</a>   
                                                    <button type="button" cluster-href="../ajax/product/delete_ajax?id=<?php  echo htmlspecialchars($product['cl_id']); ?>" class="remove btn btn-danger btn-delete btn-sm"><i class="fa fa-trash"></i></button>      
                                                    <div class="error-input"></div>                              
                                                </td>
											</tr>
											<?php
											}
											?>
                                           
                                        </tbody>
                                        <tfoot>
                                            <tr>
                                                <td colspan="<?php  if($groupArray['short'] == 'PRM'){ echo 7;}else{echo 9;} ?>">
                                             <?php
                                        if($page > 1)
                                        {
                                        ?>
                                        <button type="submit" formaction="list?page=<?php echo htmlspecialchars($page) - 1 ?>" class="track-btn">Previous</button>
                                           
                                        <?php
                                        }
                                        if(count($products) == 50)
                                        {
                                        ?>
                                        <button type="submit" formaction="list?page=<?php echo htmlspecialchars($page) + 1 ?>" class="track-btn">Next</button>
                                        <?php
                                        }
                                        ?>
                                    </td>
                                </tr>
                                        </tfoot>
                                    </table>
									<div class="pull-right col-xs-12 top-margin">
										
									</div>
                                </div>
                            </form>
                            
                          
                        </div>
                       
						
						
                       <script>
						$(document).ready(function(){
							$('.active').removeClass('active');
							$('#cat-menu').addClass('active');
						}); 

                        jQuery('.warranty_active').change(function(){
                            var productID = jQuery(this).attr('cluster-product_id');
                            var value = jQuery(this).val();
                            var parent = jQuery(this).parents('td').first();
                            jQuery(parent).find('.warranty_error').html('<div class="alert alert-warning">Changing Warranty Status</div>');
                            $.post('../ajax/product/update_warranty_status?id=' + productID, {value:value}, function(res){
                                    jQuery(parent).find('.warranty_error').html('<div class="alert alert-success">' + res.message + '</div>');
                             },'json')
                              .fail(function(xhr) {

                               
                                  var html = '';
                                  var res = xhr.responseJSON;
                                  console.log(xhr);
                                  if (typeof res === 'undefined') {
                                    jQuery(parent).find('.warranty_error').html('<div class="alert alert-danger">Something went wrong</div>').show();
                                  }
                                 
                                    if(typeof res.error_text === 'undefined')
                                    {
                                        jQuery(parent).find('.warranty_error').html('<div class="alert alert-danger">Something went wrong</div>').show();
                                        window.location.href = '#body_part';
                                        return;
                                    }
                                    else
                                    {
                                        jQuery(parent).find('.warranty_error').html('<div class="alert alert-danger">' + res.error_text + '</div>').show();
                                        window.location.href = '#body_part';
                                        return;
                                    }
                                  
                                  
                              },'json');;
                        });
						</script>              

  <?php
  include '../footer.php';
  ?>