<?php
/* ====================
  [BEGIN_COT_EXT]
  Hooks=market.list.query
  [END_COT_EXT]
  ==================== */

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

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

$ads_positions_cfg = $ads_positions[$ads_positions_special['market_top']];
$ad_catvariant = 0;

if($ads_positions_cfg['limit'] > 0) {
  $adswhere = array();

  $adswhere['item_position'] = "item_position=".$ads_positions_special['market_top'];
  $adswhere['item_published'] = "item_paused=0";
  $adswhere['item_expire'] = "item_expire >='".(int)$sys['now']."'";

  if($marketsearchpage) {
    $totalcats = $db->query("SELECT item_cat, COUNT(*) as cnt FROM $db_market AS m $join_condition
    	LEFT JOIN $db_users AS u ON u.user_id=m.item_userid
    	" . (is_array($where) ? (count($where) > 0 ? 'WHERE ' . implode(' AND ', $where) : '') : $where) . " GROUP BY item_cat")->fetchAll(PDO::FETCH_KEY_PAIR);

    $adscatswhere = array();
    foreach($totalcats as $key => $val) {
      $val = substr_count($structure['market'][$key]['rpath'], ".")+1;
      $ad_catvariant = $val;
      if ($val == 1) {
        $adscatswhere[] = "(item_catvariant=1 AND item_cat='".$key."')";
      } elseif ($val == 2) {
        $c_parent_lvl1 = $structure['market'][$key]['parent'];
        $adscatswhere[] = "((item_catvariant=1 AND item_cat='".$c_parent_lvl1."') OR (item_catvariant=2 AND item_cat='".$key."'))";
      } elseif ($val == 3) {
        $c_parent_lvl2 = $structure['market'][$key]['parent'];
        $c_parent_lvl1 = $structure['market'][$c_parent_lvl2]['parent'];
        $adscatswhere[] = "((item_catvariant=1 AND item_cat='".$c_parent_lvl1."') OR (item_catvariant=2 AND item_cat='".$c_parent_lvl2."') OR (item_catvariant=3 AND item_cat='".$key."'))";
      }
    }

    if(count($adscatswhere) > 0) {
      $adswhere['item_cats'] = '('.implode(' OR ', $adscatswhere).')';
    }
  } else {
    $ad_catvariant = $catlvl;
    if ($catlvl == 1) {
      $adswhere['item_cats'] = "(item_catvariant=1 AND item_cat='".$c_work."')";
    } elseif ($catlvl == 2) {
      $c_parent_lvl1 = $structure['market'][$c_work]['parent'];
      $adswhere['item_cats'] = "((item_catvariant=1 AND item_cat='".$c_parent_lvl1."') OR (item_catvariant=2 AND item_cat='".$c_work."'))";
    } elseif ($catlvl == 3) {
      $c_parent_lvl2 = $structure['market'][$c_work]['parent'];
      $c_parent_lvl1 = $structure['market'][$c_parent_lvl2]['parent'];
      $adswhere['item_cats'] = "((item_catvariant=1 AND item_cat='".$c_parent_lvl1."') OR (item_catvariant=2 AND item_cat='".$c_parent_lvl2."') OR (item_catvariant=3 AND item_cat='".$c_work."'))";
    }
  }

  $adswhere = (!empty($adswhere)) ? ' WHERE '.implode(' AND ', $adswhere) : '';

  $ads = $db->query("SELECT * FROM $db_ads
      $adswhere ORDER BY item_lastshow ASC LIMIT ".$ads_positions_cfg['limit'])->fetchAll();

  $parsedmrktids = array();

  /* === Hook === */
  $extp = cot_getextplugins('market.list.loop');
  /* ===== */

  $tmpwhere = array();
  if(count($catsub) > 0) $tmpwhere[] = "item_cat IN ('" . implode("','", $catsub) . "')";
  if(count($catsub_attr) > 0) $tmpwhere[] = "item_catattr IN ('" . implode("','", $catsub_attr) . "')";
  $tmpwhere = (count($tmpwhere) > 0 ? ' AND '.implode(' AND ', $tmpwhere) : '');

  foreach ($ads as $ad)
  {
    if($ad['item_marketid'] > 0 && !in_array($ad['item_marketid'], $parsedmrktids)) {
      $item = $db->query("SELECT * FROM $db_market WHERE item_id=".$ad['item_marketid']." AND item_userid=".$ad['item_userid'].' AND item_state=0 AND item_ismoder!=0 '.$tmpwhere.' LIMIT 1')->fetch();
      if($item['item_id'] > 0) {
        $totalcats_extra[$item['item_cat']]++;

       	$t->assign(cot_generate_usertags($item['item_userid'], 'PRD_ROW_OWNER_'));
       	$t->assign(cot_generate_markettags($item, 'PRD_ROW_', $cfg['market']['shorttextlen'], $usr['isadmin'], $cfg['homebreadcrumb']));

       	/* === Hook - Part2 : Include === */
       	foreach ($extp as $pl)
       	{
       		include $pl;
       	}
       	/* ===== */

        if($usr['id'] != $item['item_userid']) {
          $t->assign('PRD_ROW_URL', cot_url('plug', 'e=ads&a=click&id='.$ad['item_id'].'&c='.$c));
          ads_tracks($ad['item_id'], 'show');  // записываем показ
        }

        $t->parse("MAIN.PRD_ROWS".($sdisplay == 'table' ? '_TABLE' : ''));

        $parsedmrktids[] = $ad['item_marketid'];

        $maxrowsperpage_work--;
        $totalitems++;
      } else {
        if($ad['item_expire'] < $sys['now']) $db->update($db_ads,  array('item_expire' => 0, 'item_paused' => ($ad['item_expire'] - $sys['now'])), "item_id=".(int)$ad['item_id']);
      }
    }
  }

  if(count($parsedmrktids) > 0) {
    $where['ads'] = '(item_id!='.implode(' AND item_id!=', $parsedmrktids).')';
  }
}

$adswhere_boldANDup = '';
if ($catlvl == 1) {
  $adswhere_boldANDup = "(item_catvariant=1 AND item_cat='".$c_work."')";
} elseif ($catlvl == 2) {
  $c_parent_lvl1 = $structure['market'][$c_work]['parent'];
  $adswhere_boldANDup = "((item_catvariant=1 AND item_cat='".$c_parent_lvl1."') OR (item_catvariant=2 AND item_cat='".$c_work."'))";
} elseif ($catlvl == 3) {
  $c_parent_lvl2 = $structure['market'][$c_work]['parent'];
  $c_parent_lvl1 = $structure['market'][$c_parent_lvl2]['parent'];
  $adswhere_boldANDup = "((item_catvariant=1 AND item_cat='".$c_parent_lvl1."') OR (item_catvariant=2 AND item_cat='".$c_parent_lvl2."') OR (item_catvariant=3 AND item_cat='".$c_work."'))";
}