<?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');

$marketsearchpage = true; //хуки одинаковы с list, что бы различать

$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');
$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('query', 'G', 'TXT');

if(COT_AJAX) $sq = urldecode($sq);
$sq = trim($sq);
$sq_urlencode = urlencode($sq);
$sq_origin = $sq;
$sq = $db->prep($sq);

$show_search_onlvl1 = 'mobile';

if (strlen($sq) > 1 || COT_AJAX) {
  if(true) {
    $c_work = $c;
    $catlvl = substr_count($structure['market'][$c_work]['rpath'], ".")+1;

    $isajax = COT_AJAX;

    $list_url_path = array('m' => 'search', 'c' => $c, 's' => $s, 'query' => $sq, 'sdisplay' => $sdisplay);

    $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'] = $sq.' Результат поиска '.(!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();
    if(!empty($c_work)) {
      $catsub = cot_structure_children('market', $c_work);
      if(count($catsub) > 0) $where['cat'] = "item_catattr IN ('" . implode("','", $catsub) . "')";
    }

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

    	$where['search'] = "(LOWER(item_title) LIKE '".$db->prep($sqlsearch)."' OR LOWER(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);

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

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

    $totalcats_extra = array();

    /* === 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();

    $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
    	" . $where . " GROUP BY item_cat")->fetchAll(PDO::FETCH_KEY_PAIR);

    foreach($totalcats_extra as $key => $val) {
      $totalcats[$key] += $val;
    }
    arsort($totalcats);

    $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($totalitems > 0) {
      $generalsearch = cot_import('general-search', 'C', 'TXT');
      $generalsearch = (!empty($generalsearch) ? json_decode($generalsearch, 1) : array());
      $generalsearch[] = $sq_origin;
      $generalsearch = array_unique($generalsearch);
      cot_setcookie('general-search', json_encode($generalsearch), time()+63072000, $cfg['cookiepath'], $cfg['cookiedomain'], $sys['secure'], true);

      $lastsearchrequest = $db->query("SELECT s_request FROM $db_market_search WHERE s_query='".$sq."' LIMIT 1")->fetchColumn();
      if($lastsearchrequest > 0) {
        $db->update($db_market_search, array('s_found' => $totalitems, 's_request' => $lastsearchrequest+1), "s_query='".$sq."'");
      } else {
        $db->insert($db_market_search, array(
          's_query' => $sq,
          's_found' => $totalitems,
          's_request' => 1
        ));
      }
    }

   if(!$isajax) {

    if(count($totalcats) > 0) {
      $tmpurl = $list_url_path;
      $tmpurl['c'] = '';

      $t->assign(array(
      	"CAT_TOTAL_CNT" => $totalitems,
        "CAT_TOTAL_URL" => cot_url('market', $tmpurl),
        "CAT_TOTAL_BOLD" => (empty($c_work) ? 1 : 0),
      ));

      $catjj=0;
      foreach($totalcats as $foundincat => $foundcnt) {
        $catjj++;

        $tmpurl['c'] = $foundincat;

        $t->assign(array(
        	"CAT_ROW_TITLE" => $structure['market'][$foundincat]['title'],
          "CAT_ROW_CNT" => $foundcnt,
          "CAT_ROW_URL" => cot_url('market', $tmpurl),
          "CAT_ROW_BOLD" => ($foundincat == $c_work ? 1 : 0),
        ));

        if($catjj < 3) {
          $t->parse("MAIN.CAT_ROW");
        } else {
          $t->parse("MAIN.CATSMORE.CATM_ROW");
        }
      }

      if($catjj > 2) {
        $t->parse("MAIN.CATSMORE");
      }
    }

    $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 {
  $t = new XTemplate(cot_tplfile(array('market', 'search', 'empty')));

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