<?php

/**
 * [BEGIN_COT_EXT]
 * Hooks=market.tags
 * Order=1
 * [END_COT_EXT]
 */

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

$costplan = (!empty($item['item_catcostplans']) ? json_decode($item['item_catcostplans'],1) : array());
if(count($costplan) == 0) {
  $costplan = array(
    'bundle_type' => 'single',
    'bundles' => array(
      'category' => array(),
      'custom' => array()
    ),
    'epackages' => array()
  );
}

$t->assign(array(
  'PRD_COSTPLAN' => $costplan
));

global $costplans_prices;
require_once cot_incfile('catcostplans', 'plug');

if($costplan['bundle_type'] == 'package') {

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

  $cpinfo = array(
    'days' => 1,
    'price' => 0,
    'price_dodji' => 0,
  );
  if(!empty($checkcat)) {
    $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);
        }

        foreach($options as $otp) {
          $t->assign(array(
            'OP_DATA' => array(
              'id' => $otp['at_id'],
              'name' => $otp['at_title'],
              'hint' => $otp['at_hint'],
              'type' => ($otp['at_type'] ? 'text' : 'bool'),
            ),
          ));

          $otp['inplans_arr'] = array();

          foreach(array('standard', 'medium', 'premium') as $type) {
            $popval = false;
            if(count($costplan['bundles'][$type]['category']) > 0) {
              foreach($costplan['bundles'][$type]['category'] as $popt) {
                if($popt['id'] == $otp['at_id']) {
                  $otp['inplans_arr'][] = $type;
                  $popval = $popt['val'];
                  $t->parse('MAIN.CP_PACKAGE_RB.OP_'.strtoupper($type).'_ROW');
                  break;
                }
              }
            }
            $t->assign(array(
              'POPT_VAL' => $popval,
            ));
            $t->parse('MAIN.CP_PACKAGE_MB.OP_'.strtoupper($type).'_ROW');
          }

          $t->assign(array(
            'OP_INPLANS_ARR' => $otp['inplans_arr'],
          ));

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

        if(count($costplan['epackages']) > 0) foreach($costplan['epackages'] as $otp) {
          $t->assign(array(
            'OP_DATA' => $otp,
          ));

          $otp['inplans_arr'] = array();

          foreach(array('standard', 'medium', 'premium') as $type) {
            $popval = $costplan['bundles'][$type]['custom_val'][$otp['id']];
            if(!empty($popval)) {
              $otp['inplans_arr'][] = $type;
              $t->parse('MAIN.CP_PACKAGE_RB.OP_'.strtoupper($type).'_ROW');
            } else {
              $popval = false;
            }

            $t->assign(array(
              'POPT_VAL' => $popval,
            ));
            $t->parse('MAIN.CP_PACKAGE_MB.OP_'.strtoupper($type).'_ROW');
          }

          $t->assign(array(
            'OP_INPLANS_ARR' => $otp['inplans_arr'],
          ));

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

        $cpinfo = array(
          'days' => 0,
          'price' => 0,
          'price_dodji' => 0
        );

        $costplansinfo = array();
        foreach(array('standard', 'medium', 'premium') as $type) {
          $tmparr = array(
            'duration' => $costplan['bundles'][$type]['duration'],
            'price' => $costplan['bundles'][$type]['price'],
            'price_dodji' => $costplan['bundles'][$type]['price_dodji']
          );

          $costplansinfo[$type] = $tmparr;
          $costplansinfo[$type]['price_format'] = number_format($costplansinfo[$type]['price'], 0, '', ' ');
          $costplansinfo[$type]['price_dodji_format'] = number_format($costplansinfo[$type]['price_dodji'], 0, '', ' ');
          $costplansinfo[$type]['duration_format'] = cot_declension($costplansinfo[$type]['duration'], 'день,дня,дней');

          if($cpinfo['price'] == 0 || $cpinfo['price'] > $tmparr['price']) $cpinfo['price'] = $tmparr['price'];
          if($cpinfo['price_dodji'] == 0 || $cpinfo['price_dodji'] > $tmparr['price_dodji']) $cpinfo['price_dodji'] = $tmparr['price_dodji'];

          if($cpinfo['days'] == 0 || $cpinfo['days'] > $tmparr['duration']) $cpinfo['days'] = $tmparr['duration'];
        }

        $t->assign(array(
          'PRD_COSTPLANS_INFO' => $costplansinfo
        ));

      }
    }
  }

  $t->assign(array(
    'PRD_CPINFO_DAYS' => ($cpinfo['days'] > 0 ? $cpinfo['days'] : 1),
    'PRD_CPINFO_TITLE' => '',
    'PRD_CPINFO_PRICE' => ($cpinfo['price'] > 0 ? $cpinfo['price'] : 0),
    'PRD_CPINFO_PRICE_DODJI' => ($cpinfo['price_dodji'] > 0 ? $cpinfo['price_dodji'] : 0),
  ));

  if($item['item_info_costplan_days'] != $cpinfo['days']) {
    $db->update($db_market, array('item_info_costplan_days' => $cpinfo['days']), 'item_id='.$item['item_id']);
  }
  $item['item_info_costplan_days'] = $cpinfo['days'];

  $t->parse('MAIN.CP_PACKAGE_RB');
  $t->parse('MAIN.CP_PACKAGE_MB');

} elseif($costplan['bundle_type'] == 'single') {
  $popular_cust = array();

  /* === Hook === */
  foreach (cot_getextplugins('catcostpalns.market.tags.single.first') as $pl)
  {
  	include $pl;
  }
  /* ===== */

  if(count($costplan['bundles']['custom']) > 0) {
    foreach($costplan['bundles']['custom'] as $cust) {

      $priceId = 0;
      $cost = $cust['price'];
      if($cost > 0 && $cost < 100) {
        $priceId = $cost;
        $cost = $costplans_prices[$priceId];
      }

      $priceselect = '';
      for($i=1;$i<=10;$i++) {
        $priceselect .= '<option value="'.$i.'">'.$i.' ('.($item['item_cost'] > 0 ? number_format(round($cost * $i), 0, '', ' ').' Р ' : '').($cust['price_dodji'] > 0 ? ($item['item_cost'] > 0 ? ' / ' : '').number_format(round($cust['price_dodji'] * $i), 0, '', ' ').' d' : '').' )</option>';
      }
      $t->assign(array(
        'CP_ID' => $cust['id'],
        'CP_NAME' => $cust['name'],
        'CP_PRICE' => $cost,
        'CP_PRICE_FORMAT' => number_format($cost, 0, '', ' '),
        'CP_PRICE_DODJI' => $cust['price_dodji'],
        'CP_PRICE_DODJI_FORMAT' => ($cust['price_dodji'] > 0 ? number_format($cust['price_dodji'], 0, '', ' ') : 0),
        'CP_PRICE_SELECT' => $priceselect,
        'CP_DURATION' => $cust['duration'],
        'CP_POPULAR' => (in_array($cust['id'], $popular_cust) ? 1 : 0)
      ));
      $t->parse('MAIN.CP_SINGLE_RB.CP_ROW');
      $t->parse('MAIN.CP_SINGLE_MB.CP_ROW');
    }
  }

  $t->assign(array(
    'PRD_CPINFO_DAYS' => $costplan['bundles']['category']['time'],
    'PRD_CPINFO_TITLE' => $costplan['bundles']['category']['title'],
    'PRD_CPINFO_PRICE' => $costplan['bundles']['category']['price'],
    'PRD_CPINFO_PRICE_DODJI' => $costplan['bundles']['category']['price_dodji'],
  ));

  if($item['item_info_costplan_days'] != $cpinfo['days']) {
    $db->update($db_market, array('item_info_costplan_days' => $cpinfo['days']), 'item_id='.$item['item_id']);
  }
  $item['item_info_costplan_days'] = $costplan['bundles']['category']['time'];

  $t->parse('MAIN.CP_SINGLE_RB');
  if(count($costplan['bundles']['custom']) > 0) $t->parse('MAIN.CP_SINGLE_MB');
}