<?php defined('COT_CODE') or die('Wrong URL.');
/**
 * [BEGIN_COT_EXT]
 * Hooks=tools
 * [END_COT_EXT]
 */
defined('COT_CODE') or die('Wrong URL.');

require_once cot_incfile('catcostplans', 'plug');

$a = cot_import('a', 'G', 'TXT');
$area = cot_import('area', 'G', 'TXT');
if(!$area) $area = 'market';

if($a == 'add')
{
 $p_data = array(
  'p_catid' => cot_import('p_catid', 'P', 'INT'),
  'p_area' => cot_import('p_area', 'P', 'TXT'),
  'p_type' => cot_import('p_type', 'P', 'INT'),
  'p_priceStandard' => cot_import('p_priceStandard', 'P', 'TXT'),
  'p_priceMedium' => cot_import('p_priceMedium', 'P', 'TXT'),
  'p_pricePremium' => cot_import('p_pricePremium', 'P', 'TXT'),
  'p_priceMin' => cot_import('p_priceMin', 'P', 'NUM'),
  'p_priceMax' => cot_import('p_priceMax', 'P', 'NUM'),
  'p_onlyprice' => cot_import('p_onlyprice', 'P', 'INT'),
  'p_bl_attrs' => cot_import('p_bl_attrs', 'P', 'TXT'),
 );

 if($p_data['p_type'] == 0) {
  $p_data['p_priceStandard'] = cot_import('p_priceMain', 'P', 'TXT');
  $p_data['p_priceMedium'] = '';
  $p_data['p_pricePremium'] = '';
 }

 cot_check(empty($p_data['p_catid']), 'Укажите категорию не ниже 2-го уровня');
 cot_check(empty($p_data['p_area']), 'Не указан модуль для выборки категорий');
 if($p_data['p_catid'] > 0) {
    $yetadd = $db->query("SELECT p_id FROM $db_catcostplans WHERE p_area='" . $db->prep($area) . "' AND p_catid=".$p_data['p_catid']." LIMIT 1")->fetchColumn();
 }

 if(!cot_error_found())
 {
   if($yetadd > 0) {
     $db->update($db_catcostplans, $p_data, 'p_id='.$yetadd);
     cot_message('План успешно обновлен');
   } else {
     $db->insert($db_catcostplans, $p_data);
     cot_message('План успешно создан');
   }
 }
 cot_redirect(cot_url('admin', 'm=other&p=catcostplans', '', true));
}
elseif($a == 'attradd')
{
 $p_data = array(
  'at_planid' => cot_import('at_planid', 'P', 'INT'),
  'at_area' => cot_import('at_area', 'P', 'TXT'),
  'at_title' => cot_import('at_title', 'P', 'TXT'),
  'at_hint' => cot_import('at_hint', 'P', 'TXT'),
  'at_type' => cot_import('at_type', 'P', 'INT'),
  'at_canlower' => cot_import('at_canlower', 'P', 'BOL')
 );

 cot_check(empty($p_data['at_planid']), 'Укажите план для добавления опции');
 cot_check(empty($p_data['at_area']), 'Не указан модуль для выборки категорий');
 cot_check(empty($p_data['at_title']), 'Укажите название опции');

 if(!cot_error_found())
 {
   $p_data['at_int_minmax'] = array(
     0 => cot_import('at_int_min', 'P', 'NUM'),
     1 => cot_import('at_int_max', 'P', 'NUM')
   );
   if(!is_numeric($p_data['at_int_minmax'][0])) $p_data['at_int_minmax'][0] = 0;
   if(!is_numeric($p_data['at_int_minmax'][1])) $p_data['at_int_minmax'][1] = 0;
   $p_data['at_int_minmax'] = json_encode($p_data['at_int_minmax']);

   cot_message('Опция успешно создана');
   $db->insert($db_catcostplans_attrs, $p_data);
 }
 cot_redirect(cot_url('admin', 'm=other&p=catcostplans', '', true));
}
elseif($a == 'del')
{
 $id = cot_import('id', 'G', 'INT');
 if($id > 0) {
    $db->delete($db_catcostplans, 'p_id='.$id);
    $db->delete($db_catcostplans_attrs, 'at_planid='.$id);
 }
 cot_redirect(cot_url('admin', 'm=other&p=catcostplans', '', true));
}
elseif($a == 'delattr')
{
 $id = cot_import('id', 'G', 'INT');
 if($id > 0) $db->delete($db_catcostplans_attrs, 'at_id='.$id);
 cot_redirect(cot_url('admin', 'm=other&p=catcostplans', '', true));
}

$t = new XTemplate(cot_tplfile('catcostplans.admin', 'plug', true));

$epArr = array();
$sql = $db->query("SELECT * FROM $db_catcostplans WHERE p_area='" . $db->prep($area) . "' ORDER BY p_catid ASC")->fetchAll();
foreach($sql as $val) {
  $epArr[$val['p_catid']] = $val;
}

//$db->update($db_catcostplans, array('p_onlyprice' => 1), 'p_id=25 OR p_id=26 OR p_id=29 OR p_id=30 OR p_id=7 OR p_id=9 OR p_id=11 OR p_id=15 OR p_id=17');

$catsArr = array();

$sql = $db->query("SELECT * FROM $db_structure WHERE structure_area='" . $db->prep($area) . "' ORDER BY structure_path ASC, structure_code ASC");
$totalitems = $db->query("SELECT COUNT(*) FROM $db_structure WHERE structure_area='" . $db->prep($area) . "'")->fetchColumn();

require_once cot_incfile('forms');
$values = array();
$plans = array();
foreach ($sql->fetchAll() as $row) {
    $count = mb_substr_count($row['structure_path'], '.');
    $sosub = '';
    for ($i = 0; $i < $count - 1; $i++) {
        $sosub .= "° ";
    }
    if ($count > 0) {
        $sosub .="° ";
    }

    $values[($count > 0 ? $row['structure_id'] : 0)] = $sosub . $row['structure_title'];

    if(is_array($epArr[$row['structure_id']])) {
      $cp = $epArr[$row['structure_id']];

      $plans[$cp['p_id']] = $sosub . $row['structure_title'];

      $options = $db->query("SELECT * FROM $db_catcostplans_attrs WHERE at_planid=".$cp['p_id']." ORDER BY at_id ASC")->fetchAll();

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

      foreach($options as $opt) {
        $opt['options'] = array();
        if($opt['at_type'] == '1') {
          $opt['at_int_minmax'] = (!empty($opt['at_int_minmax']) ? json_decode($opt['at_int_minmax'],1) : array(0, 0));
          if(is_numeric($opt['at_int_minmax'][0]) && is_numeric($opt['at_int_minmax'][1]) && $opt['at_int_minmax'][0] != $opt['at_int_minmax'][1]) {
            $jj = $opt['at_int_minmax'][0];
            while($jj <= $opt['at_int_minmax'][1]) {
              $opt['options'][$jj] = (($opt['at_canlower'] && $jj != 1) ? 'до ' : '').$jj;
              $jj++;
            }
          }
        }
        $t->assign(array(
        	'ATTR_LIST_ID' => $opt['at_id'],
          'ATTR_LIST_HINT' => $opt['at_hint'],
          'ATTR_LIST_TYPE' => $opt['at_type'],
          'ATTR_LIST_SHOW' => ($opt['at_type'] == '0' ? '<input type="checkbox"/>' : cot_selectbox('', '', $opt['options'], $opt['options'], false, '')),
          'ATTR_LIST_TITLE' => $opt['at_title'],
          'ATTR_LIST_RIGHT_DEL' => ($opt['notdelete'] == 1 ? 0 : 1)
        ));
        $t->parse('MAIN.CP_ROW.ATTR_LIST');
      }

      $t->assign(array(
        'CP_ROW_CAT_ID' => $row['structure_id'],
      	'CP_ROW_CAT' => $row['structure_title'],
        'CP_ROW_CNT' => count($options),
        'CP_ROW_ID' => $cp['p_id'],
        'CP_ROW_TYPE' => $cp['p_type'],
        'CP_ROW_PRICE_1' => (!empty($cp['p_priceStandard']) ? (stripos($cp['p_priceStandard'], ',') === false ? 'Фикс. '.$cp['p_priceStandard'] : cot_selectbox('', '', explode(',', $cp['p_priceStandard']), explode(',',$cp['p_priceStandard']), false, '')) : '<input type="text" class="form-control" placeholder="Свободная цена" />'),
        'CP_ROW_PRICE_2' => (!empty($cp['p_priceMedium']) ? (stripos($cp['p_priceMedium'], ',') === false ? 'Фикс. '.$cp['p_priceMedium'] : cot_selectbox('', '', explode(',', $cp['p_priceMedium']), explode(',',$cp['p_priceMedium']), false, '')) : '<input type="text" class="form-control" placeholder="Свободная цена" />'),
        'CP_ROW_PRICE_3' => (!empty($cp['p_pricePremium']) ? (stripos($cp['p_pricePremium'], ',') === false ? 'Фикс. '.$cp['p_pricePremium'] : cot_selectbox('', '', explode(',', $cp['p_pricePremium']), explode(',',$cp['p_pricePremium']), false, '')) : '<input type="text" class="form-control" placeholder="Свободная цена" />'),
        'CP_ROW_PRICE_MIN' => ($cp['p_priceMin'] > 0 ? $cp['p_priceMin'] : 0),
        'CP_ROW_PRICE_MAX' => ($cp['p_priceMax'] > 0 ? $cp['p_priceMax'] : 0)
      ));

      $t->parse('MAIN.CP_ROW');
    }
}

$t->assign(array(
	'ADMIN_STRUCTURE_PARENT' => cot_selectbox('', 'p_catid', array_keys($values), array_values($values), false, ''),
  'ADMIN_STRUCTURE_PLANS' => cot_selectbox('', 'at_planid', array_keys($plans), array_values($plans), false, ''),
));

cot_display_messages($t);

$t->parse('MAIN');
$adminmain = $t->text('MAIN');