<?php

/**
 * market module
 *
 * @package market
 * @version 2.5.2
 * @author CMSWorks Team
 * @copyright Copyright (c) CMSWorks.ru, littledev.ru
 * @license BSD
 */
defined('COT_CODE') or die('Wrong URL');

$sdisplay = cot_import('sdisplay', 'G', 'TXT');
if(!$sdisplay) {
  $sdisplay = cot_import('sdisplay', 'C', 'TXT');
  if(!$sdisplay) $sdisplay = 'table';
} elseif(!empty($sdisplay)) {
  cot_setcookie('sdisplay', $sdisplay, time()+(86400*7), $cfg['cookiepath'], $cfg['cookiedomain'], $sys['secure'], true);
}
$s = cot_import('s', 'G', 'ALP');
$c = cot_import('c', 'G', 'ALP');
$subid = cot_import('subid', 'G', 'INT');
$is_attr = cot_import('is_attr', 'G', 'INT');
$id_sub_attr = cot_import('id_sub_attr', 'G', 'INT');
$price_lim = cot_import('price_lim', 'G', 'NUM');
$price_ot = cot_import('price_ot', 'G', 'NUM');
$price_do = cot_import('price_do', 'G', 'NUM');
$sq = cot_import('sq', 'G', 'TXT');
$sq = $db->prep($sq);

$show_search_onlvl1 = 'mobile';

if (!empty($c) && is_array($structure['market'][$c]) || COT_AJAX) {
  if(!$sdisplay) $sdisplay = 'table';
  $catdata = $structure['market'][$c];
  if(mb_substr_count($catdata['rpath'], ".") == 0 && !COT_AJAX && !$isajax) {
    require_once cot_incfile('market', 'module', 'list_lvl1');
  } else {
    $show_search_onlvl1 = 'notlvl1';
  }
  if($show_search_onlvl1 != 'none') {
    $c_work = $c;
   /* 
    if($subid > 0) {
      foreach($structure['market'] as $key => $val) {
        if($val['id'] == $subid) {
          $c_work = $key;
          break;
        }
      }
    }
    
     */

    $catlvl = substr_count($structure['market'][$c_work]['rpath'], ".")+1;

    while($catlvl >= 3) { //if($catlvl == 3) {
      $is_attr = 1;
      $subid = $structure['market'][$c_work]['id'];
      $c = $c_work = $structure['market'][$c_work]['parent'];
      $catlvl--;
    }

    $isajax = COT_AJAX;

    $list_url_path = array('c' => $c, 's' => $s, 'sq' => $sq, 'sdisplay' => $sdisplay, 'subid' => $subid, 'id_sub_attr' => $id_sub_attr);

    $list_url_path['price_lim'] = $price_lim;
    $list_url_path['price_ot'] = $price_ot;
    $list_url_path['price_do'] = $price_do;

    $sellerlvl = cot_import('sellerlvl', 'G', 'INT');
    $sminreview = cot_import('sminreview', 'G', 'INT');
    $sdeliverytime = cot_import('sdeliverytime', 'G', 'INT');
    $sordersqueue = cot_import('sordersqueue', 'G', 'INT');
    $strack = cot_import('strack', 'G', 'INT');

    $list_url_path['sellerlvl'] = $sellerlvl;
    $list_url_path['sminreview'] = $sminreview;
    $list_url_path['sdeliverytime'] = $sdeliverytime;
    $list_url_path['sordersqueue'] = $sordersqueue;
    $list_url_path['strack'] = $strack;

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

    $out['subtitle'] = (!empty($cfg['market']['cat_' . $c_work]['metatitle'])) ? $cfg['market']['cat_' . $c_work]['metatitle'] : $cfg['market']['cat___default']['metatitle'];
    $out['subtitle'] = (!empty($out['subtitle'])) ? $out['subtitle'] : $L['market'];
    $out['desc'] = (!empty($cfg['market']['cat_' . $c_work]['metadesc'])) ? $cfg['market']['cat_' . $c_work]['metadesc'] : $cfg['market']['cat___default']['metadesc'];
    $out['keywords'] = (!empty($cfg['market']['cat_' . $c_work]['keywords'])) ? $cfg['market']['cat_' . $c_work]['keywords'] : $cfg['market']['cat___default']['keywords'];

    $where = array();
    $order = array();

    $where['state'] = "item_state=0";

    $catsub = array();
    $catsub_attr = array();

    $catsub = cot_structure_children('market', $c);
    if(count($catsub) > 0) $where['cat'] = "item_cat IN ('" . implode("','", $catsub) . "')";

    if(!empty($c_work)) {
      $catsub = cot_structure_children('market', $c_work);
      if(count($catsub) > 0) $where['cat'] = "item_cat IN ('" . implode("','", $catsub) . "')";
    }

    $c_work_attr = '';
    if($is_attr && $id_sub_attr > 0) {
      foreach($structure['market'] as $key => $val) {
        if($val['id'] == $id_sub_attr) {
          $c_work_attr = $key;
          break;
        }
      }
    } elseif($subid) {
      foreach($structure['market'] as $key => $val) {
        if($val['id'] == $subid) {
          $c_work_attr = $key;
          break;
        }
      }
    }
    if(!empty($c_work_attr)) {
      $catsub_attr = cot_structure_children('market', $c_work_attr);
      if(count($catsub_attr) > 0) $where['cat_attr'] = "item_catattr IN ('" . implode("','", $catsub_attr) . "')";
    }

    if (!empty($sq))
    {
    	$words = explode(' ', preg_replace("'\s+'", " ", $sq));
    	$sqlsearch = '%'.implode('%', $words).'%';

    	$where['search'] = "(item_title LIKE '".$db->prep($sqlsearch)."' OR item_text LIKE '".$db->prep($sqlsearch)."')";
    }

    if($price_ot > 0) $where['price_ot'] = 'item_cost>='.$price_ot;
    if($price_do > 0) $where['price_do'] = 'item_cost<='.$price_do;
    if($price_lim > 0) $where['price_do'] = 'item_cost<='.$price_lim;

    if(isset($_GET['price_lim']) && $price_lim == 0) $where['price_do'] = 'item_cost=0';

    if($sellerlvl > 0) {
      $sellerlvlarr = array(
        'found' => false
      );
      foreach($cfg['lvl_gradation'][4] as $lvlgrad) {
        if($lvlgrad['mainlvl'] > 0 && $lvlgrad['mainlvl'] == $sellerlvl) {
          $sellerlvlarr = $lvlgrad;
          $sellerlvlarr['found'] = true;

          break;
        }
      }
      if($sellerlvlarr['found']) {
        $where['sellerlvl'] = '(user_mk_done_cnt>='.$sellerlvlarr['cnt'].' AND user_mk_rating>='.$sellerlvlarr['prc'].')';
      }
    }
    if($sminreview > 0) {
      require_once cot_incfile('reviews', 'plug');
      $where['sminreview'] = "(SELECT COUNT(*) FROM $db_reviews as reviews WHERE reviews.item_type='review' AND reviews.item_touserid=user_id AND reviews.item_score=1) > ".$sminreview;
    }
    if($sdeliverytime > 0) {
      $where['sdeliverytime'] = 'item_info_costplan_days<='.$sdeliverytime;
    }
    if($sordersqueue > 0) {
       $where['sordersqueue'] = "(SELECT COUNT(*) FROM $db_market_orders as sordersqueue WHERE sordersqueue.order_seller=user_id AND sordersqueue.order_accept>0 AND sordersqueue.order_status!='cancel' AND sordersqueue.order_status!='new' AND sordersqueue.order_status!='paid' AND sordersqueue.order_status!='done' AND sordersqueue.order_accept<".$sys['now'].") < ".$sordersqueue;
    }
    if($strack == 2) { /* заказанные */
      $where['strack'] = "(SELECT COUNT(*) FROM $db_market_orders as strack WHERE strack.order_pid=item_id AND strack.order_userid=".$usr['id'].") > 0";
    } elseif($strack == 3) {
      $where['strack'] = "(SELECT COUNT(*) FROM $db_market_orders as strack WHERE strack.order_pid=item_id AND strack.order_userid=".$usr['id'].") = 0";
    }

    switch($s)
    {
    	case 'popular':
    		$order['s'] = 'item_count ASC';
    		break;

    	case 'groups':
    		$order['s'] = 'item_count DESC';
    		break;

    	case 'new':
    		$order['s'] = 'item_date DESC';
    		break;

    	default:
    		$order['s'] = 'item_date DESC';
    		break;
    }

    $out['canonical_uri'] = cot_url('market', $list_url_path);

    $t = new XTemplate(cot_tplfile(array('market', 'list')));

    $maxrowsperpage = 24;
    $maxrowsperpage_work = $maxrowsperpage;
    $totalitems = 0;

    /* === Hook === */
    foreach (cot_getextplugins('market.list.query') as $pl)
    {
    	include $pl;
    }
    /* ===== */

    list($pn, $page, $d_url) = cot_import_pagenav('page', $maxrowsperpage);

    $where = ($where) ? 'WHERE ' . implode(' AND ', $where) : '';
    $order = ($order) ? 'ORDER BY ' . implode(', ', $order) : '';

    $totalitems += $db->query("SELECT COUNT(*) FROM $db_market AS m $join_condition
    	LEFT JOIN $db_users AS u ON u.user_id=m.item_userid
    	" . $where . "")->fetchColumn();

    $sqllist = $db->query("SELECT m.*, u.* $join_columns
    	FROM $db_market AS m $join_condition
    	LEFT JOIN $db_users AS u ON u.user_id=m.item_userid
    	" . $where . "
    	" . $order . "
    	LIMIT $page, " . $maxrowsperpage_work);

    $pagenav = cot_pagenav('market', $list_url_path, $page, $totalitems, $maxrowsperpage);

   if(!$isajax) {
    if(mb_substr_count($catdata['rpath'], ".") != 0) {
      $parents = cot_structure_parents('market', $c);
      $parcnt = count($parents);
      $isattr = 0;
      $pathmaincat = 2;
      $jj=0;
    } else {
      $parents = cot_structure_parents('market', $c);
      $parcnt = 2;
      $isattr = 0;
      $pathmaincat = 1;
      $jj=1;
    }

    /* === Hook === */
    $extp = cot_getextplugins('market.list.catsparse');
    $extp1 = cot_getextplugins('market.list.catsparse.childrens');
    $extp2 = cot_getextplugins('market.list.catsparse.childrens_2');
    $extp3 = cot_getextplugins('market.list.catsparse.childrens_js');
    /* ===== */

    foreach($parents as $parent) {
      $jj++;
      $tmpurl = $list_url_path;
      $tmpurl['c'] = $parent;
      $tmpurl['subid'] = '';
      //if($jj == 2) $tmpurl['id_sub_attr'] = '';
      $ctmp = $structure['market'][$parent];
      $t->assign(array(
        "CATS_ROW_ID" => $ctmp['id'],
      	"CATS_ROW_TITLE" => $ctmp['title'],
        "CATS_ROW_CODE" => $parent,
      	"CATS_ROW_URL" => cot_url('market', $tmpurl),
        "CATS_ROW_LAST" => ($jj == $parcnt ? 1 : 0),
        "CATS_ROW_JJ" => $jj,
        "CATS_ROW_ATTR_LVL" => ($jj > 2 ? ($jj-2) : 0),
      ));

      /* === Hook === */
      foreach ($extp as $pl)
      {
      	include $pl;
      }
      /* ===== */

      $t->assign(array(
        "CATS_BC_ROW_ID" => $ctmp['id'],
      	"CATS_BC_ROW_TITLE" => $ctmp['title'],
        "CATS_BC_ROW_CODE" => $parent,
      	"CATS_BC_ROW_URL" => cot_url('market', $tmpurl),
        "CATS_BC_ROW_LAST" => ((!$subid && $jj == $parcnt) ? 1 : 0),
        "CATS_BC_ROW_ISATTR" => 0,
        "CATS_BC_ROW_JJ" => $jj,
      ));
      $t->parse("MAIN.CATS_BREADCRUMBS");

      $childrens = array();
      if($jj == $parcnt) {
        $childrens = cot_structure_children('market', $parent, false, false);
        foreach($childrens as $children) {
          $ctmpchilds = cot_structure_children('market', $children, false, false);
          $ctmp = $structure['market'][$children];
          $hassubs = (count($ctmpchilds) > 0 ? 1 : 0);

          $t->assign(array(
            "ATTR_ROW_ID" => $ctmp['id'],
          	"ATTR_ROW_TITLE" => $ctmp['title'],
            "ATTR_ROW_CODE" => $children,
            "ATTR_ROW_HINT" => '',
            "ATTR_ROW_ATTR_LVL" => 1,
            "ATTR_ROW_ACTIVE" => ($subid == $ctmp['id'] ? 1 : 0),
            "ATTR_ROW_HIDE" => (!$subid || $subid == $ctmp['id'] ? 0 : 1),
            "ATTR_ROW_ARROWHIDE" => (($subid == $ctmp['id'] && $id_sub_attr > 0) ? 0 : 1),
            "ATTR_ROW_HASSUBS" => $hassubs,
          ));

          if($subid > 0 && $subid == $ctmp['id']) {
            $tmpurl = $list_url_path;
            $tmpurl['id_sub_attr'] = '';
            $tmpurl['is_attr'] = 1;
            $t->assign(array(
              "CATS_BC_ROW_ID" => $ctmp['id'],
            	"CATS_BC_ROW_TITLE" => $ctmp['title'],
              "CATS_BC_ROW_CODE" => $children,
            	"CATS_BC_ROW_URL" => cot_url('market', $tmpurl),
              "CATS_BC_ROW_LAST" => ($id_sub_attr ? 0 : 1),
              "CATS_BC_ROW_ISATTR" => 1,
              "CATS_BC_ROW_JJ" => 1,
            ));
            $t->parse("MAIN.CATS_BREADCRUMBS");
          }

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

          foreach($ctmpchilds as $child) {
            $ctmpcld = $structure['market'][$child];
            $t->assign(array(
              "ATTR_2_ROW_ID" => $ctmpcld['id'],
            	"ATTR_2_ROW_TITLE" => $ctmpcld['title'],
              "ATTR_2_ROW_CODE" => $child,
              "ATTR_2_ROW_ATTR_LVL" => 2,
              "ATTR_2_ROW_ACTIVE" => ($id_sub_attr == $ctmpcld['id'] ? 1 : 0)
            ));

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

            if($id_sub_attr > 0 && $id_sub_attr == $ctmpcld['id']) {
              $tmpurl = $list_url_path;
              $tmpurl['id_sub_attr'] = $ctmpcld['id'];
              $t->assign(array(
                "CATS_BC_ROW_ID" => $ctmpcld['id'],
              	"CATS_BC_ROW_TITLE" => $ctmpcld['title'],
                "CATS_BC_ROW_CODE" => $child,
              	"CATS_BC_ROW_URL" => cot_url('market', $tmpurl),
                "CATS_BC_ROW_LAST" => 1,
                "CATS_BC_ROW_ISATTR" => 1,
                "CATS_BC_ROW_JJ" => 2,
              ));
              $t->parse("MAIN.CATS_BREADCRUMBS");
            }

            $t->parse("MAIN.CATS_CATALOG.CC_CHILDRENS_1.CC_CHILDRENS_2");
          }

          $t->parse("MAIN.CATS_CATALOG.CC_CHILDRENS_1");

          $parsejs = true;

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

          if($parsejs) $t->parse("MAIN.CATS_CATALOG.CC_CHILDRENS_JS");
        }
      }

      $t->parse("MAIN.CATS_CATALOG");
      if($jj >= 2) $isattr = 1;
    }

    $sortlinks = array();
    $tmpurl = $list_url_path;
    foreach(array('popular', 'new', 'groups') as $val) {
      $tmpurl['s'] = $val;
      $sortlinks[$val] = cot_url('market', $tmpurl);
    }

    $displaylinks = array();
    $tmpurl = $list_url_path;
    $tmpurl['page'] = ($page > 0 ? $page : 1);
    foreach(array('table', 'list') as $val) {
      $tmpurl['sdisplay'] = $val;
      $displaylinks[$val] = cot_url('market', $tmpurl);
    }

    $catfiltermodule = array();
    $tmpurl['page'] = ($page > 0 ? $page : 1);
    foreach($list_url_path as $key => $val) {
      if($key != 'c') $catfiltermodule[] = '"'.$key.'": "'.str_replace('"', '\"', $val).'"';
    }
    $catfiltermodule[] = '"page": "'.($page > 0 ? $page : 1).'"';

    $t->assign(array(
    	"SEARCH_URL" => cot_url('market', $list_url_path),
      "SEARCH_SORTLINKS_URL" => $sortlinks,
      "SEARCH_DISPLINKS_URL" => $displaylinks,
      "SEARCH_CAT_FILTER_MODULE" => implode(', ', $catfiltermodule),
      "CAT_DATA" => $catdata,
    ));
   }

    /* === Hook === */
    foreach (cot_getextplugins('market.list.search.tags') as $pl)
    {
    	include $pl;
    }
    /* ===== */

    $sqllist_rowset = $sqllist->fetchAll();

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

    foreach ($sqllist_rowset as $item)
    {
    	$jj++;
    	$t->assign(cot_generate_usertags($item, 'PRD_ROW_OWNER_'));

    	$t->assign(cot_generate_markettags($item, 'PRD_ROW_', $cfg['market']['shorttextlen'], $usr['isadmin'], $cfg['homebreadcrumb']));
    	$t->assign(array(
    		"PRD_ROW_ODDEVEN" => cot_build_oddeven($jj),
    	));

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

    	$t->parse("MAIN.PRD_ROWS".($sdisplay == 'table' ? '_TABLE' : ''));
    }
    /* === Hook === */
    foreach (cot_getextplugins('market.list.tags') as $pl)
    {
    	include $pl;
    }
    /* ===== */

    if(!$page) $page = 1;

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

    if($isajax) {
      $module_body = array(
        'html' => trim(str_replace("\r\n", '', $module_body)),
        'paging' => array(
          'items_per_page' => $maxrowsperpage,
          'page' => $page,
          'total' => $totalitems
        ),
        'priceFiltersHtml' => '',
        'renderPriceFilters' => true,
        'volumePriceFiltersHtml' => ''
      );

      $module_body = json_encode($module_body);
    }
  }
} else {
  require_once cot_incfile('market', 'module', 'list_lvl0');
}