<?php
defined('COT_CODE') or die('Wrong URL');

$return['success'] = 1;
$return['items'] = array();

global $structure;

if(!$usr['isadmin'] && ($usr['maingrp'] == 5 || $usr['maingrp'] == 6)) $usr['isadmin'] = true;

$categoryId = cot_import('categoryId', 'G', 'INT');
$attributeIds = cot_import('attributeIds', 'G', 'ARR');

$catIds = (count($attributeIds) > 0 ? array_reverse($attributeIds) : array());
if($categoryId > 0) $catIds[] = $categoryId;

$planFind = false;
foreach($catIds as $categoryId) {
  if($planFind) break;

  if($categoryId > 0 && cot_plugin_active('catcostplans')) {
    $curCat = array('id' => 0);

    foreach($structure['market'] as $seo => $cat) {
      if($categoryId == $cat['id']) {
        $curCat = array(
          'id' => $cat['id'],
          'name' => $cat['title'],
          'seo' => $seo,
          'path' => $cat['path']
        );

        /* === Hook === */
        foreach (cot_getextplugins('api.getCatsPlans.catfind') as $pl)
        {
        	include $pl;
        }
        /* ===== */

        break;
      }
    }

    if($curCat['id'] > 0) {
      require_once cot_incfile('catcostplans', 'plug');

      $plan = $db->query("SELECT * FROM $db_catcostplans WHERE p_area='market' AND p_catid=".$curCat['id']." LIMIT 1")->fetch();
      if($plan['p_id'] > 0) {
        $options = $db->query("SELECT * FROM $db_catcostplans_attrs WHERE at_planid=".$plan['p_id']." ORDER BY at_id ASC")->fetchAll();

        if($plan['p_onlyprice'] == 1 && $structure['market'][$curCat['seo']]['parent'] != $curCat['seo']) {
          $parent = $db->query("SELECT * FROM $db_structure WHERE structure_area='market' AND structure_code='" . $structure['market'][$curCat['seo']]['parent'] . "' LIMIT 1")->fetch();
          if($parent['structure_id'] > 0 && $parent['structure_id'] != $curCat['id']) $options = get_catcostplans_parent_attrs($parent, 'market', $plan['p_bl_attrs'], $options);
        }

        foreach($options as $otp) {
          if($otp['at_type'] == '1') {
            $otp['at_int_minmax'] = (!empty($otp['at_int_minmax']) ? json_decode($otp['at_int_minmax'],1) : array(0, 0));
            $return['items'][$otp['at_id']] = array(
              'id' => $otp['at_id'],
              'name' => $otp['at_title'],
              'hint' => $otp['at_hint'],
              'type' => 'integer',
              'min' => $otp['at_int_minmax'][0],
              'max' => $otp['at_int_minmax'][1],
              'can_lower' => ($otp['can_lower'] == 1 ? '1' : '0')
            );
          } else {
            $return['items'][$otp['at_id']] = array(
              'id' => $otp['at_id'],
              'name' => $otp['at_title'],
              'hint' => $otp['at_hint'],
              'type' => 'bool'
            );
          }
        }

        /* === Hook === */
        foreach (cot_getextplugins('api.getCatsPlans.extra') as $pl)
        {
        	include $pl;
        }
        /* ===== */

        $planFind = true;
      }
    }
  }
}

?>
