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

require_once cot_incfile('market', 'module');

global $db_market;


$out['market_lastprd'] = $db->query("SELECT item_date FROM $db_market ORDER BY item_date DESC LIMIT 1")->fetchColumn();
$out['market_lastprd'] = cot_build_timeago($out['market_lastprd']);

$out['market_myitems_active_cnt'] = 0;
$out['market_myitems_cnt'] = 0;
if($usr['id'] > 0) {
  $out['market_myitems_active_cnt'] = $db->query("SELECT COUNT(*) FROM $db_market WHERE item_userid=".$usr['id'].' AND item_state=0 AND item_ismoder!=0')->fetchColumn();
  $out['market_myitems_cnt'] = $db->query("SELECT COUNT(*) FROM $db_market WHERE item_userid=".$usr['id'].' AND (item_state=0 OR item_state=1) AND item_ismoder!=0')->fetchColumn();
}

if(!is_array($marketfirstcats) && is_array($structure)) {
  $marketfirstcats = array();
  foreach($structure['market'] as $code => $cat) {
    if(mb_substr_count($cat['rpath'], ".") == 0) {
      $marketfirstcats[$code] = $cat;
    }
  }
}

$jjcat=0;
$fstcuktcats = (!empty($cfg['market']['headersortcats']) ? explode("\n", $cfg['market']['headersortcats']) : array());
$fstcuktcats_cnt = count($fstcuktcats);
foreach($fstcuktcats as $code) {
  $code = trim($code);
  if(!empty($code) && is_array($marketfirstcats[$code])) {
    $cat = $marketfirstcats[$code];

    $jj=0;
    $parsejj=0;

    $jjcat++;
    $cat['subcnt'] = 0;
    foreach($structure['market'] as $subcode => $subcat) {
      if($subcat['parent'] == $code && $subcat['parent'] != $subcode) {
        $jj++;

        $cat['subcnt']++;
        $t->assign(array(
          'SUBCAT_ROW_ID' => $subcat['id'],
          'SUBCAT_ROW_TITLE' => $subcat['title'],
          'SUBCAT_ROW_CODE' => $subcode,
          'SUBCAT_ROW_URL' => cot_url('market', 'c='.$subcode)
        ));
        $t->parse('HEADER.STRUCT_MARKET.SUBCATS_BLOCK.SB_COL');

        if(($jj % 2) == 0) {
          $parsejj += 2;
          $t->parse('HEADER.STRUCT_MARKET.SUBCATS_BLOCK');
        }
      }
    }
    if($jj > $parsejj) {
      $t->parse('HEADER.STRUCT_MARKET.SUBCATS_BLOCK.SB_TD');
      $t->parse('HEADER.STRUCT_MARKET.SUBCATS_BLOCK');
    }

    $t->assign(array(
      'CAT_ROW_ID' => $cat['id'],
      'CAT_ROW_TITLE' => $cat['title'],
      'CAT_ROW_CODE' => $code,
      'CAT_ROW_URL' => cot_url('market', 'c='.$code),
      'CAT_ROW_SUBCNT' => $cat['subcnt'],
      'CAT_ROW_LAST' => (($fstcuktcats_cnt - $jjcat) < 3 ? 1 : 0),
    ));

    $t->parse('HEADER.STRUCT_MARKET');
  }
}