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

class edit extends database
{
    
    public function index($data,$id)
    {
        $where['cl_id']= $id;
        return $this->update('tb_product',$data, $where);
    }
    public function Getdata($id)
    {
        $where['cl_id']= $id;
        return $this->fetchRow('tb_product', $where);
    }

    public function getAllImages($id)
    {
        $where['cl_product_id'] = $id;
        return $this->fetchAll('tb_files', $where);
    }
	public function GetCategory()
    {
		return $this->fetchAll('tb_product_category');
	}
	public function GetBrand()
    {
		return $this->fetchAll('tb_brands');
	}

    public function getCurrentProductCategory($catID)
    {
        $where['cl_id'] = $catID;
        return $this->fetchRow('tb_product_category', $where);
    }

    public function getAllSubCategories($catID)
    {
        $where['cl_cat_id'] = $catID;
        return $this->fetchAll('tb_product_subcategory', $where);
    }

    public function getAllProductsEAN($ean)
    {
        $where['cl_ean'] = $ean;
        return $this->fetchAll('tb_product', $where);
    }

    public function getAllFiltersofSubCategory($subCategoryID)
    {
        $sql = ' SELECT f.*, pa.cl_show FROM tb_filter f INNER JOIN tb_product_subcategory_filter psf ON f.cl_id=psf.cl_filter_id LEFT JOIN tb_product_attribute pa ON f.cl_id=pa.cl_filter_id WHERE f.cl_deleted_at IS NULL AND psf.cl_sub_category_id=? ORDER BY f.cl_id ';
        $where[] = $subCategoryID;

        return $this->callQuery($sql, $where);
    }
}

$obj = new edit();

$data = $obj->Getdata($id);
if(!$data)
{
    header('Location: list.php');
    exit;
}

$productCategory = $obj->getCurrentProductCategory($data['cl_cat_id']);
$subCategories = $obj->getAllSubCategories($data['cl_cat_id']);


$images = $obj->getAllImages($id);
$productCategories=$obj->GetCategory();
$brands=$obj->GetBrand();

$filters = $obj->getAllFiltersofSubCategory($data['cl_sub_cat_id']);

$otherProducts = [];
$ean = $data['cl_ean'];
if($ean != null && trim($ean) != '')
{
    $otherProducts = $obj->getAllProductsEAN($ean);
}
$templateType = 'edit';
include '../header.php';
?>

<script src="<?php echo MAIN_DOMAIN ?>/ckeditor/ckeditor.js"></script>
 <link href="<?php echo MAIN_DOMAIN ?>/dropzone/dist/dropzone.css" rel="stylesheet" />
 <script src="<?php echo MAIN_DOMAIN ?>/dropzone/dist/dropzone.js"></script>
   <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">
                                    <h2 class="title-1">Add Filter to Product - <?php echo $data['cl_name'] ?></h2>
                                    
                                </div>
                           
                            </div>
                        </div>
                        
                        <div class="row m-t-25 m-row">
                            <div class="col-lg-10">
                                <div class="card">
                                    <div class="card-body card-block">
                                        <div id="slide_container_1" style="background-color: blue;color:white;padding:15px">
                                            Filters <i class="fa fa-caret-down pull-right"></i>
                                        </div>
                                          <div class="table-responsive filter_container" style="width:100%">
                                             <div class="col-sm-12 top-margin">

                                                <div class="row input-container">

                                                    <div class="col-sm-6 ">
                                                        <input type="text" class="form-control filter_name" name="filter" placeholder="Enter Filter Name">
                                                        <div class="error-input"></div>
                                                    </div>
                                                    <div class="col-sm-6">
                                                        <button type="button" class="btn btn-success" id="btn-add">Add Filter</button>
                                                    </div>

                                                    <div class="col-sm-12 error-main">


                                                    </div>
                                                </div>
                                             </div>
                                                  <div class="filter_main_container">
                                                    <?php
                                                    $filterName = '';

                                                    if(!empty($filters))
                                                    {
                                                        foreach ($filters as $filter) {

                                                            
                                                            ?>

                                                            <div class="col-xs-12 block-container" cluster-id="<?php echo $filter['cl_id'] ?>">
                                                                <div class="col-xs-12 block-header">
                                                                    <?php echo $filter['cl_name'] ?>

                                                                </div>
                                                                <div class="col-xs-12 block-body">
                                                                    <div class="col-xs-12 block_content">
                                                                        <label><b>Show this attribute for selling?</b></label>
                                                                        <select class="form-control select_show" cluster-filter_id="<?php echo $filter['cl_id'] ?>">

                                                                            <option value="0" <?php if($filter['cl_show'] == null || $filter['cl_show'] == 0){echo 'selected';} ?>>No</option>
                                                                            <option value="1" <?php if($filter['cl_show'] == 1){echo 'selected';} ?>>Yes</option>

                                                                        </select>
                                                                        <div class="error-input"></div>
                                                                     </div>
                                                                     <div class="col-xs-12 select_value">
                                                                        <table class="table table-bordered table-striped col-xs-12">
                                                                            <thead>
                                                                                <tr>
                                                                                    <th>
                                                                                        Attribute
                                                                                    </th>
                                                                                    
                                                                                    <th>
                                                                                        Show?
                                                                                    </th>
                                                                                    <th>

                                                                                    </th>
                                                                                </tr>
                                                                            </thead>
                                                                            <tbody>


                                                                            </tbody>
                                                                        </table>
                                                                     </div>
                                                                 </div>
                                                            </div>

                                                          
                                                            <?php
                                                        }
                                                    }
                                                    ?>
                                                </div>
                                                 
                                          </div>
                                
                                        <form method="post" class="form" cluster-url="../ajax/product/edit_ajax?id=<?php echo htmlspecialchars($_GET['id']);?>" cluster-redirect="list.php" >
                                           
                                        
                                        </form>
                                    </div>
                                </div>
                            </div>
                          
                        </div>

                     


                        <script>

                            function setfiltersOnContainer(html)
                            {
                                $('.filter_main_container').html(html);
                                getEachFilterAttributes();

                            }

                            function getAllVariableProductFilters()
                            {
                                var html = '';
                                $.get('../ajax/product/getAllVariableProductFIlters?id=<?php echo $id ?>', function(res){
                                    $(res).each(function(i, value){
                                        html+= '<div class="col-xs-12 block-container top-margin" cluster-id="' + value.cl_id + '">';
                                        html+= '<div class="col-xs-12 block-header">Filter : ' + value.cl_filter + '</div>';
                                        html+= '<div class="col-xs-12 block-body">'; 

                                        html+= '<div class="col-xs-12"><label class="col-xs-12">Show?</label><select class="form-control filter_show"><option value="1"';

                                        if(value.cl_show == 1)
                                        {
                                            html+= ' selected="selected" ';
                                        }
                                        html+= ' >Yes</option><option value="0" ';
                                        if(value.cl_show == 0)
                                        {
                                            html+= ' selected="selected" ';
                                        }

                                        html+= '>No</option></select><div class="select_show_error_input"></div></div>';
                                        html+= '<div class="top-margin col-sm-12 existing_attribute"><table class="table table-bordered" style="width:100%">';
                                        html+= '<thead><tr><th colspan="3">Existing Attributes </th></tr><tr><th>Attribute</th><th>Show?</th><th></th></tr></thead>';
                                        html+= '<tbody></tbody>';
                                        html+= '</table></div>';
                                        html+= '<div class="top-margin col-sm-12 new_attribute">';
                                        html+= '<table class="table table-bordered" style="width:100%">';
                                        html+= '<thead><tr><th colspan="3">New Attributes <button type="button" class="btn btn-danger pull-right btn-attribute-add">Add +</button></th></tr><tr><th>Attribute</th><th>Show?</th><th></th></tr></thead>';
                                        html+= '<tbody><tr class="input-container"><td><input type="text" class="form-control name" name="name" /><div class="error-input"></div></td><td><select class="form-control show" name="show"><option value="1">Yes</option><option value="0">No</option></select><div class="error-input"></div></td><td><button type="button" class="btn btn-success btn-sm single_attribute_add"><i class="fa fa-plus"></i></button><div class="error-input"></div></td></tr></tbody>';
                                        html+= '</table>';
                                        
                                        html+= '</div>';
                                        html+= '</div></div>'; 

                                    });
                                    setfiltersOnContainer(html);
                                },'json');

                                
                            }

                            function getAllVAriableProductFilterAttributes(id)
                            {
                                html = '';
                                $('.block-container[cluster-id="' + id + '"]').find('.existing_attribute table tbody').html('');
                                $.get('../ajax/product/getAllFilterAttributes?id=' + id, function(res){

                                    $(res).each(function(i, value){
                                        html = '<tr class="input-container"><td><input type="text" class="form-control name" name="name" value="' + value.cl_name + '" /><div class="error-input"></div></td><td><select class="form-control show" name="show"><option value="1"';

                                        if(value.cl_show == 1)
                                        {
                                            html+= ' selected="selected" ';
                                        }

                                        html+= '>Yes</option><option value="0"';
                                        if(value.cl_show == 0)
                                        {
                                            html+= ' selected="selected" ';
                                        }
                                        html+= '>No</option></select><div class="error-input"></div></td><td><button type="button" class="btn btn-primary btn-sm single_attribute_update" cluster-id="' + id + '"><i class="fa fa-edit"></i></button><div class="error-input"></div></td></tr>';
                                        
                                        $('.block-container[cluster-id="' + id + '"]').find('.existing_attribute table tbody').append(html);
                                    })
                                    
                                },'json');
                            }

                            function getEachFilterAttributes()
                            {
                                $('.block-container').each(function(i, value){
                                    var filterID = $(this).attr('cluster-id');
                                    getAllVAriableProductFilterAttributes(filterID);
                                })
                            }

                            $(document).on('click', '#btn-add', function(){
                                var data = new Object();
                                data['filter'] = $('.filter_name').val();
                                $('.error-main').html('<div class="alert alert-warning">Adding Filter.....</div>');
                                $('#btn-add').attr('disabled', 'disabled');
                                var current = $(this);
                                $('.error-input').html('').show();

                                $.post('../ajax/product/addVariableProductFilter?id=<?php echo $id ?>', {data:data}, function(res){
                                    $('#btn-add').removeAttr('disabled');
                                    $('.filter_name').val('');
                                    $('.error-main').html('<div class="alert alert-success">' + res.message + '</div>');
                                    getAllVariableProductFilters();
                                },'json').fail(function(xhr) {

                                    $('#btn-add').removeAttr('disabled');
                                   $('.error-main').html('').show();
                                      var html = '';
                                      var res = xhr.responseJSON;
                                      if (typeof res === 'undefined') {
                                        $('.error-main').html('<div class="alert alert-danger">Something went wrong</div>').show();
                                      }
                                      if (typeof res.error_description === 'undefined') {
                                        if(typeof res.error_text === 'undefined')
                                        {
                                            $('.error-main').html('<div class="alert alert-danger">Something went wrong</div>').show();
                                           
                                            return;
                                        }
                                        else
                                        {
                                            $('.error-main').html('<div class="alert alert-danger">' + res.error_text + '</div>').show();
                                           
                                            return;
                                        }
                                      }

                                       $.each(res.error_description, function(i, value) {
                                            var parent = $(current).parents('.input-container').first();
                                            $(parent).find('.error-input').html('<div class="alert alert-danger alert-flat">' + value + '</div>');
                                          
                                      });
                                      
                                  
                                  },'json');;
                            });


                            $(document).on('click', '.btn-attribute-add', function(){
                                var parent = $(this).parents('.new_attribute').first();
                                var html = '<tr class="input-container"><td><input type="text" class="form-control name" name="name"/></td><td><select class="form-control show" name="shows"><option value="1">Yes</option><option value="0">No</option></select></td><td><button type="button" class="btn btn-success btn-sm single_attribute_add"><i class="fa fa-plus"></i></button></td></tr>';
                                $(parent).find('tbody').append(html);
                            });


                            $(document).ready(function(){
                                getAllVariableProductFilters();
                            })

                           $(document).on('click', '.single_attribute_add', function(){
                            var current = $(this);
                                var data = new Object();
                                var parent = $(this).parents('tr').first();
                                var parentTD = $(this).parents('td').first();
                                var parentBlock = $(this).parents('.block-container').first();
                                var id = $(parentBlock).attr('cluster-id');
                                data['name'] = $(parent).find('.name').val();
                                data['show'] = $(parent).find('.show').val();
                                $(current).attr('disabled', 'disabled');
                                $.post('../ajax/product/add_single_attribute?id=' + id, {data:data}, function(){
                                    $(current).removeAttr('disabled');
                                    $(parent).remove();
                                    getEachFilterAttributes();
                                },'json').fail(function(xhr) {

                                   $(current).removeAttr('disabled');
                                   $('.error-input').html('').show();
                                      var html = '';
                                      var res = xhr.responseJSON;
                                      if (typeof res === 'undefined') {
                                        $(parentTD).find('.error-input').html('<div class="alert alert-danger">Something went wrong</div>').show();
                                        return;
                                      }
                                      if (typeof res.error_description === 'undefined') {
                                        if(typeof res.error_text === 'undefined')
                                        {
                                            $(parentTD).find('.error-input').html('<div class="alert alert-danger">Something went wrong</div>').show();
                                            return;
                                        }
                                        else
                                        {
                                            $(parentTD).find('.error-input').html('<div class="alert alert-danger">' + res.error_text + '</div>').show();
                                            return;
                                        }
                                      }

                                       $.each(res.error_description, function(i, value) {
                                            var parent = $(current).find('[name="' + i + '"] .error-input').parents('.input-container').first();
                                            $(parent).find('.error-input').html('<div class="alert alert-danger alert-flat">' + value + '</div>');
                                          
                                      });
                                      
                                  
                                  },'json');;
                           });


                           $(document).on('change', '.filter_show', function(){
                            var current = $(this);
                            $(current).attr('disabled', 'disabled');
                                 var parentBlock = $(this).parents('.block-container').first();
                                 $(parentBlock).find('.select_show_error_input').html('<div class="alert alert-warning">Updating....</div>');
                                var id = $(parentBlock).attr('cluster-id');
                                var data = new Object();
                                 data['show'] = $(this).val();
                                $.post('../ajax/product/save_show_filter?id=' + id, {data:data}, function(res){
                                    $(current).removeAttr('disabled');
                                     $(parentBlock).find('.select_show_error_input').html('<div class="alert alert-success">' + res.message + '</div>');
                                },'json').fail(function(xhr) {

                                   $(current).removeAttr('disabled');
                                   $('.error-input').html('').show();
                                      var html = '';
                                      var res = xhr.responseJSON;
                                      if (typeof res === 'undefined') {
                                        $(parentBlock).find('.select_show_error_input').html('<div class="alert alert-danger">Something went wrong</div>').show();
                                        return;
                                      }
                                      if (typeof res.error_description === 'undefined') {
                                        if(typeof res.error_text === 'undefined')
                                        {
                                            $(parentBlock).find('.select_show_error_input').html('<div class="alert alert-danger">Something went wrong</div>').show();
                                            return;
                                        }
                                        else
                                        {
                                            $(parentBlock).find('.select_show_error_input').html('<div class="alert alert-danger">' + res.error_text + '</div>').show();
                                            return;
                                        }
                                      }

                                       $.each(res.error_description, function(i, value) {
                                            
                                            $(parentBlock).find('.select_show_error_input').html('<div class="alert alert-danger alert-flat">' + value + '</div>');
                                          
                                      });
                                      
                                  
                                },'json');;
                           })
                        </script>

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