<?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_cost'] = 0;
$ritem['item_cost_dodji'] = 0;

$bundles = array(
  'bundle_type' => cot_import('bundle_type', 'P', 'TXT'),
  'bundles' => array(
    'category' => array(),
    'custom' => array()
  ),
  'epackages' => array()
);

if($bundles['bundle_type'] == 'package') {
  $bundles['bundles'] = array(
    'standard' => array(
      'category' => array(),
      'custom_val' => array(),
      'duration' => 0,
      'price' => 0
    ),
    'medium' => array(
      'category' => array(),
      'custom_val' => array(),
      'duration' => 0,
      'price' => 0
    ),
    'premium' => array(
      'category' => array(),
      'custom_val' => array(),
      'duration' => 0,
      'price' => 0
    )
  );
} else {
  $bundles['bundle_type'] = 'single';
}

//array('standard', 'medium', 'premium')

$checkcat = (!empty($ritem['item_catattr']) ? $ritem['item_catattr'] : $ritem['item_cat']);

if(!empty($checkcat)) {
  if($bundles['bundle_type'] == 'package') {
    $catsql = $db->query("SELECT * FROM $db_structure WHERE structure_area='market' AND structure_code='".$checkcat."' LIMIT 1")->fetch();

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

      $plan = $db->query("SELECT * FROM $db_catcostplans WHERE p_area='market' AND p_catid=".$catsql['structure_id']." LIMIT 1")->fetch();
      $jj=0;
      while($jj < 5 && !$plan['p_id'] && $structure['market'][$catsql['structure_code']]['parent'] != $catsql['structure_code']) {
        $catsql = $db->query("SELECT * FROM $db_structure WHERE structure_area='market' AND structure_code='".$structure['market'][$catsql['structure_code']]['parent']."' LIMIT 1")->fetch();
        if($catsql['structure_id'] > 0) {
          $plan = $db->query("SELECT * FROM $db_catcostplans WHERE p_area='market' AND p_catid=".$catsql['structure_id']." LIMIT 1")->fetch();
        }
        $jj++;
      }

      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'][$catsql['structure_code']]['parent'] != $catsql['structure_code']) {
          $parent = $db->query("SELECT * FROM $db_structure WHERE structure_area='market' AND structure_code='" . $structure['market'][$catsql['structure_code']]['parent'] . "' LIMIT 1")->fetch();
          if($parent['structure_id'] > 0 && $parent['structure_id'] != $catsql['structure_id']) $options = get_catcostplans_parent_attrs($parent, 'market', $plan['p_bl_attrs'], $options);
        }

        $bundle_extra_value = array(
          'standard' => cot_import('bundle_extra_standard_value', 'P', 'ARR'),
          'medium' => cot_import('bundle_extra_medium_value', 'P', 'ARR'),
          'premium' => cot_import('bundle_extra_premium_value', 'P', 'ARR')
        );

        foreach($options as $otp) {
          foreach(array('standard', 'medium', 'premium') as $type) {
            $value = $bundle_extra_value[$type]['category'][$otp['at_id']];

            if($otp['at_type'] == '1') {
              $otp['at_int_minmax'] = ((!empty($otp['at_int_minmax']) && !is_array($otp['at_int_minmax'])) ? json_decode($otp['at_int_minmax'],1) : array(0, 0));

              if($value > $otp['at_int_minmax'][0]) {
                $bundles['bundles'][$type]['category'][] = array(
                  'id' => $otp['at_id'],
                  'val' => ($value < $otp['at_int_minmax'][1] ? $otp['at_int_minmax'][1] : $value)
                );
              }
            } elseif($value == 1) {
              $bundles['bundles'][$type]['category'][] = array(
                'id' => $otp['at_id'],
                'val' => $value
              );
            }
          }
        }

        $custom_types = array(
          'names' => cot_import('bundle_custom_extra_name', 'P', 'ARR'),
          'types' => cot_import('bundle_custom_extra_type', 'P', 'ARR'),
          'hints' => cot_import('bundle_custom_extra_hint', 'P', 'ARR')
        );

        if(count($custom_types['names']) > 0) foreach($custom_types['names'] as $key => $val) {
          $bundles['epackages'][] = array(
            'id' => $key,
            'name' => $val,
            'hint' => $custom_types['hints'][$key],
            'type' => $custom_types['types'][$key],
          );
        }

        foreach(array('standard', 'medium', 'premium') as $type) {
          if(is_array($bundle_extra_value[$type]['custom'])) {
            foreach($bundle_extra_value[$type]['custom'] as $key => $bundcust) {
              $bundles['bundles'][$type]['custom_val'][$key] = $bundcust;
            }
          }
          $bundles['bundles'][$type]['duration'] = cot_import('bundle_'.$type.'_duration', 'P', 'INT');
        }

        $prices = cot_import('bundle_free_price_value', 'P', 'ARR');
        $prices_pluscrt = cot_import('bundle_free_price_value_apply_crt', 'P', 'ARR');
        foreach($prices_pluscrt as $key => $plus_crt) {
          if($plus_crt == 1 && $market_crt > 0 && $prices[$key] > 0) {
             $prices[$key] = (int)$prices[$key] + (($prices[$key] / (100 - $market_crt)) * $market_crt);
          }
        }

        $bundles['bundles']['standard']['price'] = (int)$prices['priceStandard'];
        $bundles['bundles']['medium']['price'] = (int)$prices['priceMedium'];
        $bundles['bundles']['premium']['price'] = (int)$prices['pricePremium'];

        $prices_dodji = array(
          'priceStandard' => 0,
          'priceMedium' => 0,
          'pricePremium' => 0,
        );
        if($cfg['payments']['dodjirate']) {
          $prices_dodji = cot_import('bundle_free_price_dodji_value', 'P', 'ARR');
          //foreach($prices_pluscrt as $key => $plus_crt) {
          //  if($plus_crt == 1 && $market_crt > 0 && $prices_dodji[$key] > 0) {
          //     $prices_dodji[$key] = (int)$prices_dodji[$key] + (($prices_dodji[$key] / (100 - $market_crt)) * $market_crt);
          //  }
          //}
          $bundles['bundles']['standard']['price_dodji'] = (int)$prices_dodji['priceStandard'];
          $bundles['bundles']['medium']['price_dodji'] = (int)$prices_dodji['priceMedium'];
          $bundles['bundles']['premium']['price_dodji'] = (int)$prices_dodji['pricePremium'];
        }

        $prices_cnt = array(
          'main' => 0,
          'dodji' => 0
        );

        foreach($prices as $k => $cost) {
          //if((!$cfg['payments']['dodjirate'] || !($prices_dodji[$k] > 0)) && !($cost > 0)) {
          //  cot_check(true, 'Укажите корректную цену пакетов', '');
          //  break;
          //}
          if($cost > 0) $prices_cnt['main']++;
          if($cfg['payments']['dodjirate'] && $prices_dodji[$k] > 0) $prices_cnt['dodji']++;

          if($cfg['payments']['dodjirate'] && ($ritem['item_cost_dodji'] == 0 || ($prices_dodji[$k] > 0 && $prices_dodji[$k] < $ritem['item_cost_dodji']))) $ritem['item_cost_dodji'] = $prices_dodji[$k];
          if($ritem['item_cost'] == 0 || ($cost > 500 && $cost < $ritem['item_cost'])) $ritem['item_cost'] = $cost;
        }

        if($prices_cnt['main'] != 3) {
          cot_check(true, 'Укажите корректную цену пакетов', '');
        } elseif($cfg['payments']['dodjirate'] && $prices_cnt['dodji'] > 0 && $prices_cnt['dodji'] != 3) {
          cot_check(true, 'Укажите корректную цену пакетов', '');
        }

      }
    }
  } else {

    $bundles['bundles'] = array(
      'category' => array(
        'title' => cot_import('service_size', 'P', 'TXT'),
        'time' => cot_import('work_time', 'P', 'INT'),
        'price' => cot_import('typicalPriceSelect', 'P', 'INT'),
        'price_dodji' => cot_import('typicalPriceDodjiValue', 'P', 'INT'),
      ),
      'custom' => array()
    );

    if($cfg['payments']['dodjirate']) {
      $ritem['item_cost_dodji'] = $bundles['bundles']['category']['price_dodji'];
    }
    if((!$cfg['payments']['dodjirate'] || !$ritem['item_cost_dodji']) && !($bundles['bundles']['category']['price'] > 0)) $bundles['bundles']['category']['price'] = 500;
    $ritem['item_cost'] = $bundles['bundles']['category']['price'];

    $bund_custom = array(
      'names' => cot_import('my_extras_name', 'P', 'ARR'),
      'prices' => cot_import('my_extras_price', 'P', 'ARR'),
      'prices_dodji' => cot_import('my_extras_price_dodji', 'P', 'ARR'),
      'durations' => cot_import('my_extras_duration', 'P', 'ARR'),
    );

    global $costplans_prices;

    if(count($bund_custom['names']) > 0) foreach($bund_custom['names'] as $key => $name) {
      if(!empty($name)) {
        $priceId = $bund_custom['prices'][$key] - 0;
        $bundles['bundles']['custom'][] = array(
          'id' => $key,
          'name' => $name,
          'price' => (int)$priceId,
          'price_dodji' => ((int)$bund_custom['prices_dodji'][$key] > 0 ? (int)$bund_custom['prices_dodji'][$key] : 0),
          'duration' => (int)$bund_custom['durations'][$key],
        );
      }
    }
  }
}

if((!$cfg['payments']['dodjirate'] || !$ritem['item_cost_dodji']) && (!$ritem['item_cost'] || $ritem['item_cost'] < 500)) $ritem['item_cost'] = 500;
$ritem['item_catcostplans'] = json_encode($bundles);