<?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 getAllFiltersofProduct($id)
    {
        return $this->fetchAll('tb_variable_product_filter', ['cl_product_id' => $id]);
    }
}

$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->getAllFiltersofProduct($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-12">
                                <div class="card">
                                    <div class="card-body card-block">
                                       
                                          <div class="table-responsive filter_container" style="width:100%">
                                             <div class="col-sm-12">
                                                  
                                                    <?php
                                                    $filterName = '';

                                                    if(!empty($filters))
                                                    {
                                                        foreach ($filters as $filter) {
                                                            ?>
                                                            <select class="form-control col-sm-12 pull-left select_filter" style="width:auto;margin-right: 5px" cluster-id="<?php echo $filter['cl_id'] ?>">
                                                                <option value="">---Select <?php echo $filter['cl_filter'] ?> -----</option>
                                                            </select>
                                                            <?php
                                                        }
                                                    }
                                                    ?>
                                                    <label >Default? </label> <input type="checkbox" id="input-checkbox"/>
                                                    <button class="btn btn-success" id="btn-add">Add</button>
                                                    <div class="error-main"></div>
                                                 </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 class="card">
                                    <div class="card-body card-block">
                                       
                                          <div class="table-responsive filter_container" style="width:100%">
                                             <table class="table table-bordered table-striped" id="attribute_table">
                                                <thead>
                                                    <tr>
                                                        <th>
                                                            Filter & Value
                                                        </th>
                                                        
                                                        <th>
                                                            Supplier Price
                                                        </th>
                                                        <th>
                                                            Monthly Price
                                                        </th>
                                                        <th>
                                                            Weight
                                                        </th>
                                                        <th>
                                                            Show?
                                                        </th>
                                                        <th>
                                                            Defautl?
                                                        </th>
                                                        <th>

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

                                                </tbody>
                                             </table>
                                          </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 class="col-lg-12">

                            </div>
                          
                        </div>

                      

                        <script>

                            function getAllVariableProductImages()
                            {
                                $('.table-images').each(function(i, value){
                                    var id = $(value).attr('cluster-id');
                                    console.log(id);
                                    
                                });
                            }

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

                            function getAllVariableProducts()
                            {
                                $('#attribute_table tbody').html('<tr><td colspan="4">Loading...</td></tr>');
                                var attributeTableHtml = '';
                                $.get('../ajax/product/getAllVariableProducts?id=<?php echo $id ?>', function(res){
                                    $('#attribute_table tbody').html('');
                                    $(res).each(function(i, value){
                                        var showCheckBox = '';
                                        if(value.cl_show == 1)
                                        {
                                            showCheckBox+= ' checked="checked" ';
                                        }

                                        var showDefault = '';
                                        if(value.cl_default == 1)
                                        {
                                            showDefault+= ' checked="checked" ';
                                        }

                                        var randomNumber = (Math.random() * 10000000000000000000);
                                        attributeTableHtml = '<tr style="border-top: 2px solid black"><td class="filter_value_span" >' + value.filter_value + '</td><td><input type="text" class="form-control supplier_price" value="' + value.cl_supplier_price + '"" /></td><td><input type="text" class="form-control monthly_price" value="' + value.cl_monthly_price + '"" /></td><td><input type="text" class="form-control weight" value="' + value.cl_weight + '"" /></td><td><input type="checkbox" class="show" ' + showCheckBox + '/></td><td><input type="checkbox" class="default" ' + showDefault + ' /></td><td><button type="button" cluster-id="' + value.cl_id + '" class="btn btn-success btn-update">Update</button><div class="error-input"></div></td></tr><tr><td colspan="7" > <form action="../ajax/product/variable_product_file_upload?id=' + value.cl_id + '" class="dropzone randomNumber_' + randomNumber + '"  id="flie_upload_dropzone"></form></td></tr><tr><td colspan="7"><table class="table table-bordered table-images" cluster-id="' + value.cl_id + '" style="width:100%"></table></td></tr>';
                                        $('#attribute_table tbody').append(attributeTableHtml);
                                        var myDropzone = new Dropzone(".randomNumber_" + randomNumber);

                                        var variableProductID = value.cl_id;
                                        $.get('../ajax/product/getAllVariableProductImages?id=' + variableProductID, function(res1){
                                            var html = '';
                                           
                                            $(res1).each(function(i2, value2){
                                              
                                                html = '<tr>';
                                                html+= '<td><img src="/uploads/products/' + value2.cl_name + '" style="max-width:200px"/></td><td></td>';
                                                html+= '</tr>';
                                                console.log(variableProductID);
                                                $('.table-images[cluster-id="' + variableProductID + '"]').append(html);
                                            });
                                        },'json');
                                    });
                                }, 'json');
                                getAllVariableProductImages();
                            }

                            function addVariableProduct(data)
                            {
                                $('#btn-add').attr('disabled', 'disabled');
                                $('.error-main').html('<div class="alert alert-warning">Adding...</div>').show();
                                $.post('../ajax/product/addVariableProduct?id=<?php echo $id ?>', {data:data}, function(res){
                                    $('#btn-add').removeAttr('disabled');
                                    $('.error-main').html('<div class="alert alert-success">' + res.message + '</div>').show();
                                    getAllVariableProducts();

                                },'json').fail(function(xhr) {

                                    $('#btn-add').removeAttr('disabled');
                                   
                                      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;
                                        }
                                      }
                                  
                                  },'json');;
                            }

                            $(document).on('click', '#btn-add', function(){
                                var data = new Object();
                                var count = 0;
                                var error = 1;
                                data['filters'] = new Object();
                                $('.select_filter').each(function(i, value){
                                    if($(value).val() != '')
                                    {
                                        error = 0;
                                    }

                                    console.log(value);
                                    data['filters'][count] = new Object();
                                    data['filters'][count]['filter_id'] = $(value).attr('cluster-id');
                                    data['filters'][count]['value_id'] = $(value).val();
                                    count++;
                                });

                                if($('#input-checkbox').is(':checked'))
                                {
                                    data['default'] = 1;
                                }

                                if(error == 0)
                                {
                                    addVariableProduct(data);
                                }
                                else
                                {
                                    alert('Please select atleast one filter');
                                }
                            });


                            $(document).on('click', '.btn-update', function(){
                                var current = $(this);
                                var id = $(this).attr('cluster-id');
                                var data = new Object();
                                var parent = $(this).parents('tr').first();
                                data['supplier_price'] = $(parent).find('.supplier_price').val();
                                data['monthly_price'] = $(parent).find('.monthly_price').val();
                                data['weight'] = $(parent).find('.weight').val();
                                if($(parent).find('.show').is(':checked'))
                                {
                                    data['show'] = 1;
                                }
                                else
                                {
                                    data['show'] = 0;
                                }

                                if($(parent).find('.default').is(':checked'))
                                {
                                    data['default'] = 1;
                                }
                                else
                                {
                                    data['default'] = 0;
                                }

                                $(parent).find('.error-input').html('<div class="alert alert-warning">Updating.....</div>');
                                $(current).attr('disabled', 'disabled');
                                $.post('../ajax/product/update_single_attribute?id=' + id, {data:data, product_id:<?php echo $_GET['id'] ?>}, function(res){
                                     $(current).removeAttr('disabled');
                                     $(parent).find('.error-input').html('<div class="alert alert-success">' + res.message + '</div>');
                                },'json').fail(function(xhr) {

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

                            $(document).ready(function(){
                                $('.select_filter').each(function(i, value){
                                    var html = '';
                                    var id = $(value).attr('cluster-id');
                                    var valueID = '0';


                                    $.get('../ajax/product/getVariableProductAttributes?id=' + id + '&product_id=<?php echo $id ?>', function(res){
                                        console.log(res.length);
                                        $(res).each(function(i1, value1){
                                            if(value1.cl_show == 1)
                                            {
                                                html+= '<option value="' + value1.cl_id + '">' + value1.cl_name + '</option>';
                                            }
                                        });
                                        $(value).append(html);
                                    }, 'json');
                                    
                                    
                                });
                            });


                            $(document).on('click', '.each_value', function(){
                                var current = $(this);
                                var parent = $(this).parents('tr').first();
                                var parentTD = $(this).parents('td').first();
                                if($(this).is(':checked'))
                                {
                                    value = 1;
                                }
                                else
                                {
                                    value = 0;
                                }

                                var data = new Object();
                                data['filter_id'] = $(this).attr('cluster-filter_id');
                                data['value_id'] = $(this).attr('cluster-value_id');
                                data['show'] = value;
                                var id = data['product_id'] = <?php echo $id ?>;

                                $(current).attr('disabled', 'disabled');

                                 $(parentTD).find('.error-input').html('<div class="alert alert-warning">Updating....</div>').show();
                                $.post('../ajax/product/update_attributes?id=' + id, {data:data}, function(){
                                    $(current).removeAttr('disabled');
                                    $(parentTD).find('.error-input').html('<div class="alert alert-success">Updated</div>').show();
                                },'json').fail(function(xhr) {

                                    $(current).removeAttr('disabled');
                                   
                                      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();
                                      }
                                      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();
                                            window.location.href = '#body_part';
                                            return;
                                        }
                                        else
                                        {
                                            $(parentTD).find('.error-input').html('<div class="alert alert-danger">' + res.error_text + '</div>').show();
                                            window.location.href = '#body_part';
                                            return;
                                        }
                                      }
                                  
                                  },'json');;
                            })


                            $(document).on('change', '.select_show', function(){
                                var current = $(this);
                                var parent = $(this).parents('.block_content').first();
                                
                                

                                var data = new Object();
                                data['filter_id'] = $(this).attr('cluster-filter_id');
                                data['show'] = $(this).val();
                                var id = data['product_id'] = <?php echo $id ?>;

                                $(current).attr('disabled', 'disabled');

                                 $(parent).find('.error-input').html('<div class="alert alert-warning">Updating....</div>').show();
                                $.post('../ajax/product/update_attributes_main?id=' + id, {data:data}, function(){
                                    $(current).removeAttr('disabled');
                                    $(parent).find('.error-input').html('<div class="alert alert-success">Updated</div>').show();
                                },'json').fail(function(xhr) {

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


                             $(document).on('click', '.btn-value-update', function(){
                                 var current = $(this);
                                 $(current).attr('disabled', 'disabled');
                                var parent = $(this).parents('tr').first();
                              

                                var data = new Object();
                                data['product_id'] = <?php echo $id ?>;
                                data['value_id'] = $(current).attr('cluster-value_id');
                                data['filter_id'] = $(current).attr('cluster-filter_id');
                                
                                data['supplier_price'] = $(parent).find('.supplier_price').val();
                                data['monthly_price'] = $(parent).find('.monthly_price').val();
                                data['weight'] = $(parent).find('.weight').val();

                                show = 0;
                                if($(parent).find('.each_value').is(':checked'))
                                {
                                    show = 1;
                                }
                                data['show'] = show;


                                var defaultValue = 0;
                                if($(parent).find('.default').is(':checked'))
                                {
                                    defaultValue = 1;
                                }
                                data['default'] = defaultValue;

                               $(parent).find('.error-main').html('<div class="alert alert-warning">Updating....</div>').show();
                                $.post('../ajax/product/update_attributes?id=' + data['product_id'], {data:data}, function(){
                                    $(current).removeAttr('disabled');
                                     $(parent).find('.error-main').html('<div class="alert alert-success">Updated Successfully</div>').show();
                                }).fail(function(xhr) {

                                    $(current).removeAttr('disabled');
                                   
                                      var html = '';
                                      var res = xhr.responseJSON;
                                      console.log(xhr);
                                      if (typeof res === 'undefined') {
                                        $(parent).find('.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')
                                        {
                                            $(parent).find('.error-main').html('<div class="alert alert-danger">Something went wrong</div>').show();
                                            window.location.href = '#body_part';
                                            return;
                                        }
                                        else
                                        {
                                            $(parent).find('.error-main').html('<div class="alert alert-danger">' + res.error_text + '</div>').show();
                                            window.location.href = '#body_part';
                                            return;
                                        }
                                      }
                                  
                                      
                                      
                                      window.location.href = '#body_part';
                                  },'json');;
                            });
                        </script>

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