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

list($usr['auth_read'], $usr['auth_write'], $usr['isadmin']) = cot_auth('market', 'any', 'RWA');
if(!$usr['isadmin'] && $usr['maingrp'] == 6) $usr['isadmin'] = true;

cot_block($usr['auth_read']);

$id = cot_import('id', 'G', 'INT');
$al = $db->prep(cot_import('al', 'G', 'TXT'));
$c = cot_import('c', 'G', 'TXT');

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

if ($id > 0 || !empty($al))
{
	$where = (!empty($al)) ? "item_alias='".$al."'" : 'item_id='.$id;
	$sql = $db->query("SELECT p.*, u.* FROM $db_market AS p LEFT JOIN $db_users AS u ON u.user_id=p.item_userid WHERE $where LIMIT 1");
}

if (!$id && empty($al) || !$sql || $sql->rowCount() == 0)
{
	cot_die_message(404, TRUE);
}
$item = $sql->fetch();

if($usr['id'] == 1) {
  //echo '<pre>'.print_r($item,1).'</pre>'; exit;
}

list($usr['auth_read'], $usr['auth_write'], $usr['isadmin']) = cot_auth('market', $item['item_cat'], 'RWA');
if(!$usr['isadmin'] && $usr['maingrp'] == 6) $usr['isadmin'] = true;
cot_block($usr['auth_read']);

if ($item['item_state'] != 0 && !$usr['isadmin'] && $usr['id'] != $item['item_userid'])
{
	cot_log("Attempt to directly access an un-validated", 'sec');
	cot_redirect(cot_url('message', "msg=930", '', true));
	exit;
}

if ($usr['id'] != $item['item_userid'] && (!$usr['isadmin'] || $cfg['market']['count_admin']))
{
	$item['item_count']++;
	$db->update($db_market, array('item_count' => $item['item_count']), "item_id=" . (int)$item['item_id']);
}

$title_params = array(
	'TITLE' => empty($item['item_metatitle']) ? $item['item_title'] : $item['item_metatitle'],
	'CATEGORY' => $structure['market'][$item['item_cat']]['title'],
);
$out['subtitle'] = cot_title($cfg['market']['title_market'], $title_params);

$out['desc'] = (!empty($item['item_metadesc'])) ? $item['item_metadesc'] : cot_cutstring(strip_tags(cot_parse($item['item_text'], $cfg['market']['markup'], $item['item_parser'])), 160);
$out['meta_keywords'] = (!empty($item['item_keywords'])) ? $item['item_keywords'] : $structure['market'][$item['item_cat']]['keywords'];

// Building the canonical URL
$pageurl_params = array('c' => $item['item_cat']);
empty($al) ? $pageurl_params['id'] = $id : $pageurl_params['al'] = $al;
$out['canonical_uri'] = cot_url('market', $pageurl_params);

$mskin = cot_tplfile(array('market', $structure['market'][$item['item_cat']]['tpl']));

/* === Hook === */
foreach (cot_getextplugins('market.main') as $pl)
{
	include $pl;
}
/* ===== */
$t = new XTemplate($mskin);

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

/* другие услуги пользователя */
$olimit = 15;
if($db->query("SELECT COUNT(*) FROM $db_market WHERE item_userid=".$item['item_userid'].' AND item_state=0')->fetchColumn() > 0) {
  $parseditems = array($item['item_id']);

  /* first step (catattr check) */
  $owhere = "item_userid=".$item['item_userid'].(count($parseditems) > 0 ? ' AND (item_id!='.implode(' AND item_id!=', $parseditems).')' : '').' AND item_state=0';
  if($olimit > 0) {
    $otheritems = $db->query("SELECT * FROM $db_market WHERE ".$owhere." AND ".(!empty($item['item_catattr']) ? "item_catattr='".$item['item_catattr']."'" : "item_cat='".$item['item_cat']."'")." ORDER BY item_date LIMIT ".$olimit)->fetchAll();
    if(count($otheritems) > 0) {
      foreach($otheritems as $oitem) {
        $parseditems[] = $oitem['item_id'];
        $t->assign(cot_generate_usertags($oitem['item_userid'], 'OPRD_OWNER_'));
        $t->assign(cot_generate_markettags($oitem, 'OPRD_', $cfg['market']['shorttextlen'], $usr['isadmin'], $cfg['homebreadcrumb']));
        $t->parse('MAIN.OTHER_ITEMS.OITEMS_ROW');
        $olimit--;
      }
    }
  }

  /* second step (cat check) */
  $owhere = "item_userid=".$item['item_userid'].(count($parseditems) > 0 ? ' AND (item_id!='.implode(' AND item_id!=', $parseditems).')' : '').' AND item_state=0';
  if($olimit > 0 && !empty($item['item_catattr']) && $item['item_catattr'] != $item['item_cat']) {
    $otheritems = $db->query("SELECT * FROM $db_market WHERE ".$owhere." AND item_cat='".$item['item_cat']."' ORDER BY item_date LIMIT ".$olimit)->fetchAll();
    if(count($otheritems) > 0) {
      foreach($otheritems as $oitem) {
        $parseditems[] = $oitem['item_id'];
        $t->assign(cot_generate_usertags($oitem['item_userid'], 'OPRD_OWNER_'));
        $t->assign(cot_generate_markettags($oitem, 'OPRD_', $cfg['market']['shorttextlen'], $usr['isadmin'], $cfg['homebreadcrumb']));
        $t->parse('MAIN.OTHER_ITEMS.OITEMS_ROW');
        $olimit--;
      }
    }
  }

  /* last step */
  $owhere = "item_userid=".$item['item_userid'].(count($parseditems) > 0 ? ' AND (item_id!='.implode(' AND item_id!=', $parseditems).')' : '').' AND item_state=0';
  if($olimit > 0) {
    $otheritems = $db->query("SELECT * FROM $db_market WHERE ".$owhere." ORDER BY item_date LIMIT ".$olimit)->fetchAll();
    if(count($otheritems) > 0) {
      foreach($otheritems as $oitem) {
        $parseditems[] = $oitem['item_id'];
        $t->assign(cot_generate_usertags($oitem['item_userid'], 'OPRD_OWNER_'));
        $t->assign(cot_generate_markettags($oitem, 'OPRD_', $cfg['market']['shorttextlen'], $usr['isadmin'], $cfg['homebreadcrumb']));
        $t->parse('MAIN.OTHER_ITEMS.OITEMS_ROW');
        $olimit--;
      }
    }
  }

  if($olimit != 15) {
    $t->parse('MAIN.OTHER_ITEMS');
  }
}

/* похожие услуги */
$slimit = 5;
if(1 == 1) {
  /* first step (catattr check AND relev) */
  foreach(array(5,3,1) as $relev) {
    $owhere = "item_state=0".(count($parseditems) > 0 ? ' AND (item_id!='.implode(' AND item_id!=', $parseditems).')' : '');
    if($slimit > 0) {
      $otheritems = $db->query("SELECT * FROM $db_market WHERE ".$owhere." AND ".(!empty($item['item_catattr']) ? "item_catattr='".$item['item_catattr']."'" : "item_cat='".$item['item_cat']."'")." AND MATCH (`item_title`) AGAINST ('*".$db->prep($item['item_title'])."*' IN BOOLEAN MODE)>".$relev." AND item_date>".($sys['now']-86400*30)." ORDER BY item_date LIMIT ".$slimit)->fetchAll();
      if(count($otheritems) > 0) {
        foreach($otheritems as $oitem) {
          $parseditems[] = $oitem['item_id'];
          $t->assign(cot_generate_usertags($oitem['item_userid'], 'SPRD_OWNER_'));
          $t->assign(cot_generate_markettags($oitem, 'SPRD_', $cfg['market']['shorttextlen'], $usr['isadmin'], $cfg['homebreadcrumb']));
          $t->parse('MAIN.SIMULAR_ITEMS.SITEMS_ROW');
          $slimit--;
        }
      }
    }
  }

  /* step (cat check AND relev) */
  if($slimit > 0 && !empty($item['item_catattr']) && $item['item_catattr'] != $item['item_cat']) {
    foreach(array(5,3,1) as $relev) {
      $owhere = "item_state=0".(count($parseditems) > 0 ? ' AND (item_id!='.implode(' AND item_id!=', $parseditems).')' : '');
      if($slimit > 0) {
        $otheritems = $db->query("SELECT * FROM $db_market WHERE ".$owhere." AND item_cat='".$item['item_cat']."' AND MATCH (`item_title`) AGAINST ('*".$db->prep($item['item_title'])."*' IN BOOLEAN MODE)>".$relev." AND item_date>".($sys['now']-86400*30)." ORDER BY item_date LIMIT ".$slimit)->fetchAll();
        if(count($otheritems) > 0) {
          foreach($otheritems as $oitem) {
            $parseditems[] = $oitem['item_id'];
            $t->assign(cot_generate_usertags($oitem['item_userid'], 'SPRD_OWNER_'));
            $t->assign(cot_generate_markettags($oitem, 'SPRD_', $cfg['market']['shorttextlen'], $usr['isadmin'], $cfg['homebreadcrumb']));
            $t->parse('MAIN.SIMULAR_ITEMS.SITEMS_ROW');
            $slimit--;
          }
        }
      }
    }
  }

  /* step (catattr check AND relev) */
  $owhere = "item_state=0".(count($parseditems) > 0 ? ' AND (item_id!='.implode(' AND item_id!=', $parseditems).')' : '');
  if($slimit > 0) {
    $otheritems = $db->query("SELECT * FROM $db_market WHERE ".$owhere." AND ".(!empty($item['item_catattr']) ? "item_catattr='".$item['item_catattr']."'" : "item_cat='".$item['item_cat']."'")." ORDER BY item_date LIMIT ".$slimit)->fetchAll();
    if(count($otheritems) > 0) {
      foreach($otheritems as $oitem) {
        $parseditems[] = $oitem['item_id'];
        $t->assign(cot_generate_usertags($oitem['item_userid'], 'SPRD_OWNER_'));
        $t->assign(cot_generate_markettags($oitem, 'SPRD_', $cfg['market']['shorttextlen'], $usr['isadmin'], $cfg['homebreadcrumb']));
        $t->parse('MAIN.SIMULAR_ITEMS.SITEMS_ROW');
        $slimit--;
      }
    }
  }

  /* step (cat check) */
  $owhere = "item_state=0".(count($parseditems) > 0 ? ' AND (item_id!='.implode(' AND item_id!=', $parseditems).')' : '');
  if($slimit > 0 && !empty($item['item_catattr']) && $item['item_catattr'] != $item['item_cat']) {
    $otheritems = $db->query("SELECT * FROM $db_market WHERE ".$owhere." AND item_cat='".$item['item_cat']."' ORDER BY item_date LIMIT ".$slimit)->fetchAll();
    if(count($otheritems) > 0) {
      foreach($otheritems as $oitem) {
        $parseditems[] = $oitem['item_id'];
        $t->assign(cot_generate_usertags($oitem['item_userid'], 'SPRD_OWNER_'));
        $t->assign(cot_generate_markettags($oitem, 'SPRD_', $cfg['market']['shorttextlen'], $usr['isadmin'], $cfg['homebreadcrumb']));
        $t->parse('MAIN.SIMULAR_ITEMS.SITEMS_ROW');
        $slimit--;
      }
    }
  }

  /* last step (cat not check AND relev) */
  if($slimit > 0) {
    foreach(array(5,3,1) as $relev) {
      $owhere = "item_state=0".(count($parseditems) > 0 ? ' AND (item_id!='.implode(' AND item_id!=', $parseditems).')' : '');
      if($slimit > 0) {
        $otheritems = $db->query("SELECT * FROM $db_market WHERE ".$owhere." AND MATCH (`item_title`) AGAINST ('*".$db->prep($item['item_title'])."*' IN BOOLEAN MODE)>".$relev." AND item_date>".($sys['now']-86400*30)." ORDER BY item_date LIMIT ".$slimit)->fetchAll();
        if(count($otheritems) > 0) {
          foreach($otheritems as $oitem) {
            $parseditems[] = $oitem['item_id'];
            $t->assign(cot_generate_usertags($oitem['item_userid'], 'SPRD_OWNER_'));
            $t->assign(cot_generate_markettags($oitem, 'SPRD_', $cfg['market']['shorttextlen'], $usr['isadmin'], $cfg['homebreadcrumb']));
            $t->parse('MAIN.SIMULAR_ITEMS.SITEMS_ROW');
            $slimit--;
          }
        }
      }
    }
  }

  if($slimit != 5) {
    $t->parse('MAIN.SIMULAR_ITEMS');
  }
}

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

// Error handling
cot_display_messages($t);

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