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

$id = cot_import('id', 'G', 'INT');
$a = cot_import('a', 'G', 'TXT');
$group = cot_import('group', 'G', 'TXT');

cot_block($usr['id'] > 0);

$out['subtitle'] = 'Мои '.cot_sitename('padeg', '_i');

if($usr['ban']['banned'] && $usr['ban']['block']['market_seller']) {
  $sqlmrkt = $db->query("SELECT * FROM $db_market WHERE item_state=0 AND item_userid=".$usr['id'])->fetchAll();
  foreach($sqlmrkt as $item) {
    $ritem = array();
    $ritem['item_state'] = 1;
    $db->update($db_market, $ritem, 'item_id = ?', $item['item_id']);

    cot_market_sync($item['item_cat']);
  }
  $db->update($db_users, array('user_workstatus' => $sys['now']), 'user_id='.$usr['id']);
}

if (in_array($a, array('activate', 'suspend', 'delete')) && $id > 0)
{
  cot_check_xg();

  $item = $db->query("SELECT * FROM $db_market WHERE item_id=".$id.' AND item_userid='.$usr['id'].' LIMIT 1')->fetch();
  if($item['item_id'] > 0) {
    if($a == 'activate')
    {
      if($usr['ban']['banned'] && $usr['ban']['block']['market_seller']) {
        cot_error('Вы не можете активировать '.cot_sitename('padeg', 'v').', из за временной блокировки.');
        $redirect = cot_import('redirect', 'G', 'TXT');
        cot_redirect(empty($redirect) ? cot_url('market', 'm=myitems&group=feated') : base64_decode($redirect));
      	exit;
      }
      elseif($item['item_ismoder'] == 0 && !empty($item['item_rejected']))
      {
        cot_error('Вы не можете активировать '.cot_sitename('padeg', 'v').', отклоненный модератором. Вам нужно его отредактировать и исправить ошибки.');
        $redirect = cot_import('redirect', 'G', 'TXT');
        cot_redirect(empty($redirect) ? cot_url('market', 'm=myitems&group=rejected') : base64_decode($redirect));
      	exit;
      }
      else
      {
      	$ritem = array();
        $ritem['item_update_real'] = $sys['now'];
      	$ritem['item_state'] = ($item['item_ismoder'] != 0) ? 0 : (!empty($item['item_rejected']) ? 3 : 2);

      	$urlparams = empty($item['item_alias']) ?
      		array('c' => $item['item_cat'], 'id' => $id) :
      		array('c' => $item['item_cat'], 'al' => $item['item_alias']);
      	$r_url = cot_url('market', $urlparams, '', true);

      	if(!$usr['isadmin'])
      	{
      		if($ritem['item_state'] == 2)
      		{
      			$rbody = cot_rc($L['market_senttovalidation_mail_body'], array(
      				'user_name' => $usr['profile']['user_name'],
      				'prd_name' => $item['item_title'],
      				'sitename' => $cfg['maintitle'],
      				'link' => COT_ABSOLUTE_URL . $r_url
      			));
      			cot_mail($usr['profile']['user_email'], $L['market_senttovalidation_mail_subj'], $rbody);
      		}
      		else
      		{
      			$rbody = cot_rc($L['market_added_mail_body'], array(
      				'user_name' => $usr['profile']['user_name'],
      				'prd_name' => $item['item_title'],
      				'sitename' => $cfg['maintitle'],
      				'link' => COT_ABSOLUTE_URL . $r_url
      			));
      			cot_mail($usr['profile']['user_email'], $L['market_added_mail_subj'], $rbody);
      		}
      	}

      	$db->update($db_market, $ritem, 'item_id = ?', $id);

      	cot_market_sync($item['item_cat']);

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

        cot_message(cot_sitename('padeg', 'i', 'fcharup').' '.cot_sitename('words', 'activated'));

        $redirect = cot_import('redirect', 'G', 'TXT');
        cot_redirect(empty($redirect) ? cot_url('market', 'm=myitems&group='.(($ritem['item_state'] == 0) ? 'active' : ($ritem['item_state'] == 3 ? 'rejected' : 'suspend'))) : base64_decode($redirect));
      	exit;
      }
    }
    elseif ($a == 'delete')
    {
    	$ritem = array();
    	$ritem['item_state'] = -1;
    	$db->update($db_market, $ritem, 'item_id = ?', $id);

    	cot_market_sync($item['item_cat']);

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

      cot_message(cot_sitename('padeg', 'i', 'fcharup').' '.cot_sitename('words', 'deleted'));
      $redirect = cot_import('redirect', 'G', 'TXT');
      cot_redirect(empty($redirect) ? cot_url('market', 'm=myitems') : base64_decode($redirect));
    	exit;
    }
    elseif ($a == 'suspend')
    {
    	$ritem = array();
      $ritem['item_update_real'] = $sys['now'];
    	$ritem['item_state'] = 1;
    	$db->update($db_market, $ritem, 'item_id = ?', $id);

    	cot_market_sync($item['item_cat']);

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

      cot_message(cot_sitename('padeg', 'i', 'fcharup').' '.cot_sitename('words', 'paused'));
      $redirect = cot_import('redirect', 'G', 'TXT');
      cot_redirect(empty($redirect) ? cot_url('market', 'm=myitems&group=feated') : base64_decode($redirect));
    	exit;
    }
  }
  cot_redirect(cot_url('market', 'm=myitems'));
  exit;
}

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

$maxrowsperpage = ($cfg['market']['cat_' . $c]['maxrowsperpage']) ? $cfg['market']['cat_' . $c]['maxrowsperpage'] : $cfg['market']['cat___default']['maxrowsperpage'];
list($pn, $page, $d_url) = cot_import_pagenav('page', $maxrowsperpage);

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

if(empty($group)) {
  if($db->query("SELECT COUNT(*) FROM $db_market WHERE item_userid=".$usr['id'].' AND item_state=0')->fetchColumn()) $group = 'active';
}

$where['item_userid'] =  'item_userid='.$usr['id'];
//$where['item_userid'] =  "item_cat='website-repair'";

if(!empty($group)) {
  switch($group)
  {
  	case 'active':
  		$where['group'] = 'item_state=0';
  		break;

  	case 'feated':
  		$where['group'] = 'item_state=1';
  		break;

  	case 'suspend':
  		$where['group'] = 'item_state=2';
  		break;

  	case 'rejected':
  		$where['group'] = 'item_state=3';
  		break;

  	default:
  		$where['group'] = 'item_state!=-1';
  		break;
  }
}

if(!empty($where['group']) && !empty($group) && $db->query("SELECT COUNT(*) FROM $db_market WHERE item_userid=".$usr['id'].' AND '.$where['group'])->fetchColumn() == 0) cot_redirect(cot_url('market', 'm=myitems'));

$order['date'] = 'item_date DESC';

$list_url_path = array('m' => 'myitems', 'group' => $group);

// Building the canonical URL
$out['canonical_uri'] = cot_url('market', $list_url_path);

$mskin = cot_tplfile(array('market', 'myitems'));

$t = new XTemplate($mskin);

$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);

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

$t->assign(array(
	"PAGENAV_PAGES" => $pagenav['main'],
	"PAGENAV_PREV" => $pagenav['prev'],
	"PAGENAV_NEXT" => $pagenav['next'],
	"PAGENAV_COUNT" => $totalitems,
  "PRDCOUNT_ALL" => $db->query("SELECT COUNT(*) FROM $db_market WHERE item_userid=".$usr['id'].' AND item_state!=-1')->fetchColumn(),
  "PRDCOUNT_ACTIVE" => $db->query("SELECT COUNT(*) FROM $db_market WHERE item_userid=".$usr['id'].' AND item_state=0')->fetchColumn(),
  "PRDCOUNT_FEATED" => $db->query("SELECT COUNT(*) FROM $db_market WHERE item_userid=".$usr['id'].' AND item_state=1')->fetchColumn(),
  "PRDCOUNT_SUSPEND" => $db->query("SELECT COUNT(*) FROM $db_market WHERE item_userid=".$usr['id'].' AND item_state=2')->fetchColumn(),
  "PRDCOUNT_REJECTED" => $db->query("SELECT COUNT(*) FROM $db_market WHERE item_userid=".$usr['id'].' AND item_state=3')->fetchColumn(),
));

$sqllist_rowset = $sqllist->fetchAll();

$redirect = base64_encode(cot_url('market', $list_url_path, '', true));

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

foreach ($sqllist_rowset as $item)
{
	$jj++;
	$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),
    'PRD_ROW_ACTURL_DELETE' => cot_url('market', 'm=myitems&a=delete&id='.$item['item_id'].'&x='.$sys['xk'].'&redirect='.$redirect),
    'PRD_ROW_ACTURL_ACTIVATE' => cot_url('market', 'm=myitems&a=activate&id='.$item['item_id'].'&x='.$sys['xk']),
    'PRD_ROW_ACTURL_SUSPEND' => cot_url('market', 'm=myitems&a=suspend&id='.$item['item_id'].'&x='.$sys['xk']),
	));

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

  $t->parse("MAIN.PRD_ROWS");
}

// Error handling
cot_display_messages($t);

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