<?php

/**
 * [BEGIN_COT_EXT]
 * Hooks=market.add.add.error,market.edit.update.error
 * [END_COT_EXT]
 */

defined('COT_CODE') or die('Wrong URL.');

$ritem['item_catextratypes'] = array();
$ritem['item_catextratypes_other'] = array();

$catattribute = cot_import('attribute', 'P', 'ARR');

if(count($catattribute) > 0) {
  $catattribute_implode = array();
  foreach($catattribute as $key => $val) {
    if($val > 0 && $db->query("SELECT COUNT(*) FROM $db_structure WHERE structure_area='market' AND structure_id=".$val)->fetchColumn() > 0) {
      $catattribute_implode[] = $val;
    }
  }

  if(count($catattribute_implode) > 0) {
    require_once cot_incfile('catextratypes', 'plug');
    $epArr = $db->query("SELECT e_id FROM $db_catextratypes WHERE e_area='market' AND (e_catid=".implode(' OR e_catid=', $catattribute_implode).") ORDER BY e_title ASC")->fetchAll(PDO::FETCH_COLUMN);

    $attribute_ep = cot_import('attribute_ep', 'P', 'ARR');
    $attribute_ep_custom = cot_import('new_custom_attribute_title', 'P', 'ARR');

    if(count($attribute_ep_custom) > 0) {
      $ritem['item_catextratypes_other'] = $attribute_ep_custom;
    }

    if(count($epArr) > 0) {
      foreach($attribute_ep as $sep) {
        if($sep > 0 && in_array($sep, $epArr)) $ritem['item_catextratypes'][] = $sep;
      }

      $epcfg = get_catextratypes_cfg($curCat['id']);

      if($epcfg['cetextra'] > 0) {
        if($epcfg['cetlimit'] > 0 && count($ritem['item_catextratypes_other']) > $epcfg['cetlimit']) {
          $tmp_custom = array();
          $jj = 0;
          while($epcfg['cetlimit'] > $jj && $jj < 25) {
            $tmp_custom[] = $ritem['item_catextratypes_other'][$jj];
            $jj++;
          }
        }
      } else {
        $ritem['item_catextratypes_other'] = array();
      }

      if(count($ritem['item_catextratypes']) == 0 && count($ritem['item_catextratypes_other']) == 0) {
        cot_check(true, 'Укажите '.(!empty($epcfg['cetlabel']['label']) ? $epcfg['cetlabel']['label'] : 'Тип').', от 1'.($epcfg['cetlimit'] > 0 ? ' до '.cot_declension($epcfg['cetlimit'], 'варианта,вариантов,вариантов'): ''), '');
      }
    }
  }
}

$ritem['item_catextratypes'] = implode(',', $ritem['item_catextratypes']);
$ritem['item_catextratypes_other'] = json_encode($ritem['item_catextratypes_other']);