<modification>
  <name>Similar products free version</name>
  <version>1.0</version>
  <link>https://opencartforum.com/profile/689478-pimur/?tab=node_downloads_Files</link>
  <author>Pimur</author>
  <code>similar_products_free_version</code>

  <file path="admin/view/template/catalog/product_form.tpl">
    <operation error="skip">
      <search><![CDATA[<?php echo $footer; ?>]]></search>
      <add position="before"><![CDATA[
<!--similar_products_free_version-->
<style>
  .list_popover {
    margin: 0;
  }
  .list_popover .list-group-item:first-child {
    padding-top: 0;
    border-top: 0;
  }
  .list_popover .list-group-item {
    padding-left: 0;
    padding-right: 0;
    border-left: 0;
    border-radius: 0;
    border-right: 0;
    border-bottom: 0;
  }
</style>

<script type="html/tpl" id="js_pimurtemplate">
<div class="row">
<div class="col-sm-10 col-sm-push-2">

<div class="form-inline alert alert-info">
<div class="pull-right">
<button type="button" class="btn btn-default btn-sm" id="js_pimur_help" data-toggle="popover" title="Принцип работы" data-content="
              <ul class='list-group list_popover'>
<li class='list-group-item small'>
                    id - это главный товар к которому происходит привязка всех остальных товаров у которых проставлен этот <b>id</b>
</li>
<li class='list-group-item small'>
                      hex - это цвета в hex формате <a href='https://ru.wikipedia.org/wiki/%D0%A6%D0%B2%D0%B5%D1%82%D0%B0_HTML' target='_blank'>читать подробнее</a>, <ins>опционально</ins>
</li>
<li class='list-group-item small'>
                      Name - альтернативное название на карточке товара в выводе группы. <ins>опционально</ins>
</li>
<li class='list-group-item small'>
                      Выберите 1 товар, и впишите его id во все товары и в него самого, что бы объединить их в группу. У не главных - на странице будет проставлет тег rel='canonical' на главный товар. Если поля <b>hex</b> или <b>name</b> не заполненны, будет только привязка тегом rel='canonical' без вывода на карточке доп товаров
                  </li>
</ul>
              "><i class="fa fa-question-circle" aria-hidden="true"></i></button>
</div>
<div class="input-group input-group-sm">
<label class="input-group-addon" for="js_jan">Id</label>
<input type="number" name="jan" value="{{jan}}" placeholder="Значение" id="js_jan" class="form-control js_pimur_element" style="width: 80px;" />
</div>

<div class="input-group input-group-sm">
<label class="input-group-addon" for="js_isbn">Hex #</label>
<input type="text" name="isbn" value="{{isbn}}" placeholder="Значение" id="js_isbn" class="form-control js_pimur_element" style="width: 90px;" />
</div>

<div class="input-group input-group-sm">
<label class="input-group-addon" for="js_mpn">Name</label>
<input type="text" name="mpn" value="{{mpn}}" placeholder="Значение" id="js_mpn" class="form-control js_pimur_element" style="width: 152px;" />
</div>

</div>
</div>

<div class="col-sm-2 col-sm-pull-10">
<div class="alert alert-warning"><button type="button" class="btn btn-default btn-block btn-sm" id="js_prev_btn" {{prev_id}}>{{button_text}}</button></div>
</div>

<div class="clearfix"><br><br><br></div>
</div>
</script>
<script>
    var elementsValue = {};

    $('#input-jan, #input-isbn, #input-mpn').each(function () {
      elementsValue[$(this).prop('name')] = $(this).prop('disabled', true).val();
    });

    if (localStorage.getItem('prev_id')) {
      elementsValue.prev_id = 'data="' + localStorage.getItem('prev_id') + '"';
      elementsValue.button_text = 'Сохраненный id ' + localStorage.getItem('prev_id');
    } else {
      elementsValue.prev_id = 'disabled';
      elementsValue.button_text = 'Пока пусто';
    }

    $('#tab-general').prepend(renderPimurTemplate('js_pimurtemplate', elementsValue));

    function renderPimurTemplate(name, data) {
      var template = document.getElementById(name).innerHTML;

      for (var property in data) {
        if (data.hasOwnProperty(property)) {
          var search = new RegExp('{{' + property + '}}', 'g');
          template = template.replace(search, data[property]);
        }
      }
      return template;
    }

    if (elementsValue.prev_id !== 'disabled') {

      elementsValue.prev_id = elementsValue.prev_id.replace(/\D/g, '');

      $('#js_prev_btn').on('click', function () {
        $('#js_jan').val(elementsValue.prev_id);
        localStorage.setItem('prev_id', elementsValue.prev_id);
      });
    }

    $('#js_jan').on('input', function () {
      localStorage.setItem('prev_id', $(this).val());
    });

    var helpPopover = {
      html: true,
      placement: 'left'
    }

    $('#js_pimur_help').popover(helpPopover)
      .on('hide.bs.popover', function () {
        localStorage.setItem('togglepopover', 1);
      })
      .on('show.bs.popover', function () {
        if (localStorage.getItem('togglepopover')) localStorage.removeItem('togglepopover');
      });

    if (!localStorage.getItem('togglepopover')) {
      $('#js_pimur_help').popover('show');
    }
</script>
<!--/similar_products_free_version-->]]></add>
    </operation>
  </file>
  <file path="catalog/model/catalog/product.php">
    <operation error="abort">
      <search ><![CDATA[public function getProfiles($product_id) {]]></search>
      <add position="before"><![CDATA[
      //similar_products_free_version-->
      public function getProductsToProducts($product_id, $jan) {
		$query = $this->db->query("SELECT p.product_id, p.jan, p.isbn, p.mpn, p.image FROM " . DB_PREFIX . "product p WHERE p.jan = '" . (int)$jan . "' AND p.quantity > '0' AND p.status = '1' ORDER BY p.product_id = '" . (int)$product_id . "' DESC");
		return $query->rows;
	    }
        //similar_products_free_version<--]]></add>
    </operation>
  </file>
  <file path="catalog/controller/product/product.php">
    <operation error="abort">
      <search ><![CDATA[$this->document->addLink($this->url->link('product/product', 'product_id=' . $this->request->get['product_id']), 'canonical');]]></search>
      <add position="replace"><![CDATA[
        //similar_products_free_version-->
        //$this->document->addLink($this->url->link('product/product', 'product_id=' . $this->request->get['product_id']), 'canonical');
        //similar_products_free_version<--]]></add>
    </operation>
    <operation error="abort">
      <search><![CDATA[$data['text_select'] = $this->language->get('text_select');]]></search>
      <add position="before"><![CDATA[
      //similar_products_free_version -->
      $data['products_to_products'] = array();
			if((int)$product_info['jan']) {

				if((int)$this->request->get['product_id'] !== (int)$product_info['jan']) {
					$this->document->addLink($this->url->link('product/product', 'product_id=' . (int)$product_info['jan']), 'canonical');
				}
				if($product_info['isbn'] || $product_info['mpn']) {
					$this->load->model('tool/image');

					$results = $this->model_catalog_product->getProductsToProducts($this->request->get['product_id'], $product_info['jan']);
					
					foreach ($results as $key => $result) {

						if($result['isbn']) {
							$background = 'background-color: #' . $result['isbn'] . ';';
						} else {
							if($result['image']) {
								$background = 'background: url(' . $this->model_tool_image->resize($result['image'], 120, 120) . ') center / contain no-repeat;';
							} else {
								$background = 'background: url(' . $this->model_tool_image->resize('placeholder.png', 120, 120) . ') center / contain no-repeat;';
							}
						}

						$active = '';

						if($result['product_id'] === $this->request->get['product_id']) {
							$background .= ' ';
							$active .= ' active';
						}
						$data['products_to_products'][$key] = array( 
                        'product_id' => $result['product_id'], 
                        'name' => $result['mpn'] ? 'title="' . $result['mpn'] . '"' : '',
						'background' => $background, 
                        'active' => $active,
                        'href' => $active ? '' : 'href="' . $this->url->link('product/product', 'product_id=' . $result['product_id']) . '"'
						);
					}
				unset($results);
				}
				//$this->log->write($data['products_to_products']);
        //similar_products_free_version <--
			}]]></add>
    </operation>
  </file>
  <file path="catalog/view/theme/*/template/product/product.tpl">
    <operation error="abort">
      <search ><![CDATA[<?php echo $header; ?>]]></search>
      <add position="after"><![CDATA[
      <!--similar_products_free_version-->
      <style>
        .detail_option__heading {
            font-size: 21px;
            margin-bottom: 15px;
            color: #444;
        }
        .detail_option__link {
            background-size: contain;
            position: relative;
            display: inline-block;
            width: 60px;
            height: 60px;
            -webkit-border-radius: 50%;
            -moz-border-radius: 50%;
            border-radius: 50%;
            -webkit-box-shadow: inset 0 0 0 5px #fff, 0 0 0 1px #ced4da;
            -moz-box-shadow: inset 0 0 0 5px #fff,0 0 0 1px #ced4da;
            box-shadow: inset 0 0 0 5px #fff, 0 0 0 1px #ced4da;
            background-position: 50%;
            -webkit-background-size: cover;
            -moz-background-size: cover;
            background-size: cover;
            cursor: pointer;
            -webkit-transition: border-color .1s;
            -o-transition: border-color .1s;
            -moz-transition: border-color .1s;
            transition: border-color .1s;
        }
        .detail_option__li.active .detail_option__link {
            -webkit-box-shadow: inset 0 0 0 5px #fff, 0 0 0 1px #464647;
            -moz-box-shadow: inset 0 0 0 5px #fff,0 0 0 1px #464647;
            box-shadow: inset 0 0 0 5px #fff, 0 0 0 1px #464647;
        }
      </style>
        <!--/similar_products_free_version-->]]></add>
    </operation>
    <operation error="abort">
      <search ><![CDATA[<?php if ($options) { ?>]]></search>
      <add position="before"><![CDATA[
      <!--similar_products_free_version-->
      <?php if($products_to_products) { ?>
        <div class="detail_option">
          <div class="detail_option__heading">Варианты</div>
          <ul class="list-inline detail_option__list">
            <?php foreach ($products_to_products as $key => $to_products) { ?>

            <li class="list-inline-item detail_option__li<?php echo $to_products['active']; ?>">
              <a <?php echo $to_products['href']; ?> style="<?php echo $to_products['background']; ?>" class="detail_option__link" <?php echo $to_products['name']; ?>></a>
            </li>

            <?php } ?>
          </ul>
        </div>
      <?php } ?>
        <!--/similar_products_free_version-->]]></add>
    </operation>
  </file>
</modification>
