<?php

/**
 * market module
 *
 * @package market
 * @version 2.5.7
 * @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');

// Requirements
require_once cot_langfile('market', 'module');
require_once cot_incfile('forms');
require_once cot_incfile('extrafields');

// Tables and extras
cot::$db->registerTable('market');
cot::$db->registerTable('market_search');

cot_extrafields_register_table('market');

$structure['market'] = (is_array($structure['market'])) ? $structure['market'] : array();

$market_crt = 0;
$market_imgdir = 'datas/market/';
$market_imgdir_crop = 'datas/market/crop/';
$market_img_cropsize = array(372, 240);
$cfg['market']['item_profi_title'] = 'Профи';

function cot_market_val_with_crt($a = 0) {
  global $market_crt;
  if(!$a) $a = 500;

  return ($market_crt > 0 ? ($a - (($a / 100) * $market_crt)) : $a);
}

function cot_market_cost_format($main = 0, $dodji = 0, $addnbsp = false, $hiverflip = false, $split = ' / ') {
  global $cfg;

  $main_format = (floor($main) != $main) ? number_format($main, '2', '.', ' ') : number_format($main, '0', '.', ' ');
  $dodji_format = (floor($dodji) != $dodji) ? number_format($dodji, '2', '.', ' ') : number_format($dodji, '0', '.', ' ');

  $return = $main_format.($addnbsp ? '&nbsp;' : '').'<span class="rouble" title="'.$main_format.' '.$cfg['payments']['valuta'].'">Р</span>';
  if($cfg['payments']['dodjirate'] > 0 && $dodji > 0) {
    if($main > 0 && $dodji > 0) {
      if($hiverflip) {
        $return = '<span data-roublehoverflip=""><span>'.$main_format.($addnbsp ? '&nbsp;' : '').'<span class="rouble" title="'.$main_format.' '.$cfg['payments']['valuta'].'">Р</span></span><span style="display: none;">'.$dodji_format.($addnbsp ? '&nbsp;' : '').'<span class="rouble rouble-dodji" title="'.$dodji_format.' '.$cfg['payments']['valutadodji'].'">Р</span></span></span>';
      } else {
        $return = $main_format.($addnbsp ? '&nbsp;' : '').'<span class="rouble" title="'.$main_format.' '.$cfg['payments']['valuta'].'">Р</span>'.$split.$dodji_format.($addnbsp ? '&nbsp;' : '').'<span class="rouble rouble-dodji" title="'.$dodji_format.' '.$cfg['payments']['valutadodji'].'">Р</span>';
      }
    } elseif($dodji > 0) {
      $return = $dodji_format.($addnbsp ? '&nbsp;' : '').'<span class="rouble rouble-dodji" title="'.$dodji_format.' '.$cfg['payments']['valutadodji'].'">Р</span>';
    }
  }

  return $return;
}

function cot_market_img_ver($item = array()) {
  return '?ver=' . ($item['item_update_real'] > $item['item_date'] ? ($item['item_update_real'] - $item['item_date']) : 1);
}

function cot_market_js_cfg($item = array()) {
  global $db, $db_x, $market_crt, $market_imgdir, $structure, $db_market, $cfg;

  $return = array(
    'cfg' => array(
      'dodjirate' => (int)$cfg['payments']['dodjirate'],
      'valuta' => $cfg['payments']['valuta'],
      'valutadodji' => $cfg['payments']['valutadodji']
    ),
    'minDodjiPrice' => 20,
    'categories' => array(),
    'selectedCategory' => (!empty($item['item_cat']) ? $structure['market'][$item['item_cat']]['id'] : 0),
    'extras' => array(
      'cat' => array(),
      'my' => array()
     ),
     'categoryExtras' => array(),
     'categoriesWithAttributes' => array(),
     'customBundleExtras' => array(),
     'categoryPrices' => array(),
     'prdPackages' => false,
     'crt' => $market_crt,
     'selectedPackageExtras' => array(
         'standard' => array(),
         'medium' => array(),
         'premium' => array()
     ),
     'files' => array(
         'description' => array(),
         'instruction' => array()
     ),
     'photo' => array(
         'maxCount' => 6,
         'fileWrapperClass' => 'file-wrapper-block-rectangle',
         'photos' => array(),
         'fileInputName' => 'prd-photo',
         'selectorBlock' => '.prd-photos-block'
     )
  );

  if (is_array($item) && count($item) > 0) {
    if ($item['item_id'] > 0) {
        $return['saveMode'] = 'update';
        $return['prdId'] = $item['item_id'];

        $urlparams = empty($item['item_alias']) ?
            array('c' => $item['item_cat'], 'id' => $item['item_id']) :
            array('c' => $item['item_cat'], 'al' => $item['item_alias']);
        $return['prdUrl'] = cot_url('market', $urlparams, '', true);
    } else {
        $return['saveMode'] = 'continue';
    }

    $return['prdPrice'] = $item['item_cost'];
    $return['prdPriceDodji'] = (int)$item['item_cost_dodji'];

    if (!empty($item['item_file_1'])) {
        $return['photo']['photos'][] = array(
            'id' => 'photo',
            'value' => COT_ABSOLUTE_URL . $market_imgdir . $item['item_file_1'] . cot_market_img_ver($item)
        );
        $return['skip_first_photo_check'] = true;
    }
    if (!empty($item['item_file_2'])) {
        $return['photo']['photos'][] = array(
            'id' => 2,
            'value' => COT_ABSOLUTE_URL . $market_imgdir . $item['item_file_2'] . cot_market_img_ver($item)
        );
    }
    if (!empty($item['item_file_3'])) {
        $return['photo']['photos'][] = array(
            'id' => 3,
            'value' => COT_ABSOLUTE_URL . $market_imgdir . $item['item_file_3'] . cot_market_img_ver($item)
        );
    }
}


  foreach($structure['market'] as $seo => $cat) {
    if(strripos($cat['path'], '.') === false) {
      $return['categories'][$cat['id']] = array(
        'id' => $cat['id'],
        'name' => $cat['title'],
        'seo' => $seo,
        'max_days' => 10,
        'cats' => array()
      );
    }
  }

  $tmp = $return['categories'];
  foreach($tmp as $parent) {
    foreach($structure['market'] as $seo => $cat) {
      if($parent['seo'].'.'.$seo == $cat['path']) {
        $return['categories'][$parent['id']]['cats'][] = array(
          'id' => $cat['id'],
          'name' => $cat['title'],
          'seo' => $seo,
          'parent' => $parent['id'],
          'max_days' => 10,
          //'twin_category_id' => 161
        );
      }
    }
  }

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

  return json_encode($return);
}

/**
 * Update market categories counters
 *
 * @param string $cat Cat code
 * @return int
 * @global CotDB $db
 */
function cot_market_sync($cat)
{
	global $db, $db_structure, $db_market, $cache;
	
	$parent = cot_structure_parents('market', $cat, 'first');
	$cats = cot_structure_children('market', $parent, true, true);
	foreach($cats as $c)
	{
		$subcats = cot_structure_children('market', $c, true, true);
		$count = $db->query("SELECT COUNT(*) FROM $db_market WHERE item_cat IN ('".implode("','", $subcats)."') AND item_state=0 AND item_ismoder!=0")->fetchColumn();
		$db->query("UPDATE $db_structure SET structure_count=".(int)$count." WHERE structure_area='market' AND structure_code = ?", $c);
		$summcount += $count;
		if($cat == $c) $catcount = $count;
	}
	$cache && $cache->db->remove('structure', 'system');
	
	return $catcount;
}

/**
 * Update product category code
 *
 * @param string $oldcat Old Cat code
 * @param string $newcat New Cat code
 * @return bool
 * @global CotDB $db
 */
function cot_market_updatecat($oldcat, $newcat)
{
	global $db, $db_structure, $db_market;
	return (bool)$db->update($db_market, array("item_cat" => $newcat), "item_cat='" . $db->prep($oldcat) . "'");
}


/**
 * Returns permissions for a product category.
 * @param  string $cat Category code
 * @return array       Permissions array with keys: 'auth_read', 'auth_write', 'isadmin'
 */
function cot_market_auth($cat = null)
{
  global $usr;
  return array(
    'auth_read' => true,
    'auth_write' => true,
    'isadmin' => $usr['isadmin']
  );
  /*
	if (empty($cat))
	{
		$cat = 'any';
	}
	$auth = array();
	list($auth['auth_read'], $auth['auth_write'], $auth['isadmin']) = cot_auth('market', $cat, 'RWA1');
	return $auth;
  */
}


function cot_build_structure_market_tree($parent = '', $selected = '', $level = 0, $template = '')
{
	global $structure, $cfg, $db, $sys, $cot_extrafields, $db_structure;
	global $i18n_notmain, $i18n_locale, $i18n_write, $i18n_admin, $i18n_read, $db_i18n_pages;

	$urlparams = array();

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

	if (empty($parent))
	{
		$i18n_enabled = $i18n_read;
		$children = array();
		$allcat = cot_structure_children('market', '');		
		foreach ($allcat as $x)
		{
			if (mb_substr_count($structure['market'][$x]['path'], ".") == 0)
			{
				$children[] = $x;
			}
		}
	}
	else
	{
		$i18n_enabled = $i18n_read && cot_i18n_enabled($parent);
		$children = $structure['market'][$parent]['subcats'];
	}

	$t1 = new XTemplate(cot_tplfile(array('market', 'tree', $template), 'module'));

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

	if (count($children) == 0)
	{
		return false;
	}

	$t1->assign(array(
		"TITLE" => htmlspecialchars($structure['market'][$parent]['title']),
		"DESC" => $structure['market'][$parent]['desc'],
		"COUNT" => $structure['market'][$parent]['count'],
		"ICON" => $structure['market'][$parent]['icon'],
		"HREF" => cot_url("market", $urlparams + array('c' => $parent)),
		"LEVEL" => $level,
	));

	$jj = 0;

	/* === Hook - Part1 : Set === */
	$extp = cot_getextplugins('market.tree.loop');
	/* ===== */

	foreach ($children as $row)
	{
		$jj++;
		$urlparams['c'] = $row;
		$subcats = $structure['market'][$row]['subcats'];
		$t1->assign(array(
			"ROW_TITLE" => htmlspecialchars($structure['market'][$row]['title']),
			"ROW_DESC" => $structure['market'][$row]['desc'],
			"ROW_COUNT" => $structure['market'][$row]['count'],
			"ROW_ICON" => $structure['market'][$row]['icon'],
			"ROW_HREF" => cot_url("market", $urlparams),
			"ROW_SELECTED" => ((is_array($selected) && in_array($row, $selected)) || (!is_array($selected) && $row == $selected)) ? 1 : 0,
			"ROW_SUBCAT" => (is_array($subcats) && count($subcats) > 0) ? cot_build_structure_market_tree($row, $selected, $level + 1) : '',
			"ROW_LEVEL" => $level,
			"ROW_ODDEVEN" => cot_build_oddeven($jj),
			"ROW_JJ" => $jj
		));
		
		// Extra fields for structure
		foreach ($cot_extrafields[$db_structure] as $exfld)
		{
			$uname = strtoupper($exfld['field_name']);
			$t1->assign(array(
				'ROW_'.$uname.'_TITLE' => isset($L['structure_'.$exfld['field_name'].'_title']) ?  $L['structure_'.$exfld['field_name'].'_title'] : $exfld['field_description'],
				'ROW_'.$uname => cot_build_extrafields_data('structure', $exfld, $structure['market'][$row][$exfld['field_name']]),
				'ROW_'.$uname.'_VALUE' => $structure['market'][$row][$exfld['field_name']],
			));
		}

		if ($i18n_enabled && $i18n_notmain){
			$x_i18n = cot_i18n_get_cat($row, $i18n_locale);
			if ($x_i18n){
				if(!$cfg['plugin']['i18n']['omitmain'] || $i18n_locale != $cfg['defaultlang']){
					$urlparams['l'] = $i18n_locale;
				}
				$t1->assign(array(
					'ROW_URL' => cot_url('market', $urlparams),
					'ROW_TITLE' => $x_i18n['title'],
					'ROW_DESC' => $x_i18n['desc'],
				));
			}
		}

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

		$t1->parse("MAIN.CATS");
	}
	if ($jj == 0)
	{
		return false;
	}
	$t1->parse("MAIN");
	return $t1->text("MAIN");
}

function cot_mk_viewcount($c = 0) {
  $cr = $c;
  if($c >= 1000) {
    $cr = round(($c/1000), 0).'K';
  }
  return $cr;
}

/**
 * Returns all product tags for coTemplate
 *
 * @param mixed $item_data product Info Array or ID
 * @param string $tag_prefix Prefix for tags
 * @param int $textlength Text truncate
 * @param bool $admin_rights product Admin Rights
 * @param bool $pagepath_home Add home link for page path
 * @param string $emptytitle Page title text if page does not exist
 * @return array
 * @global CotDB $db
 */
function cot_generate_markettags($item_data, $tag_prefix = '', $textlength = 0, $admin_rights = null,
									 $pagepath_home = false, $emptytitle = '')
{
	global $db, $cot_extrafields, $cfg, $L, $Ls, $R, $db_market, $usr, $sys, $cot_yesno, $structure, $db_structure, $market_imgdir, $market_imgdir_crop, $market_img_cropsize;

	static $extp_first = null, $extp_main = null;

	if (is_null($extp_first))
	{
		$extp_first = cot_getextplugins('markettags.first');
		$extp_main = cot_getextplugins('markettags.main');
	}

	/* === Hook === */
	foreach ($extp_first as $pl)
	{
		include $pl;
	}
	/* ===== */
	if (!is_array($item_data))
	{
		$sql = $db->query("SELECT * FROM $db_market WHERE item_id = '" . (int)$item_data . "' LIMIT 1");
		$item_data = $sql->fetch();
	}

	if ($item_data['item_id'] > 0 && !empty($item_data['item_title']))
	{
		if (is_null($admin_rights))
		{
			$admin_rights = cot_auth('market', $item_data['item_cat'], 'A');
		}

		$item_data['item_pageurl'] = (empty($item_data['item_alias'])) ? 
			cot_url('market', 'c='.$item_data['item_cat'].'&id='.$item_data['item_id']) : cot_url('market', 'c='.$item_data['item_cat'].'&al='.$item_data['item_alias']);

		$patharray = cot_structure_buildpath('market', ((!empty($item_data['item_catattr']) && $item_data['item_cat'] != $item_data['item_catattr']) ? $item_data['item_catattr'] : $item_data['item_cat']));

		$text = cot_parse($item_data['item_text'], $cfg['market']['markup'], $item_data['item_parser']);
		$text_cut = ((int)$textlength > 0) ? cot_string_truncate($text, $textlength) : $text;
		
		$item_data['item_status'] = cot_market_status($item_data['item_state']);
		
    $item_data['item_photo_arr'] = array();
    $item_data['item_photo_firts'] = '';
    $item_data['item_photo_firts_crop'] = '';
    foreach(array(1,2,3) as $i) {
      if(!empty($item_data['item_file_'.$i]) && file_exists($market_imgdir . $item_data['item_file_'.$i])) {
        $item_data['item_photo_arr'][] = $market_imgdir . $item_data['item_file_'.$i];// . cot_market_img_ver($item_data);
      }
    }
    if(count($item_data['item_photo_arr']) > 0) {
      $item_data['item_photo_firts'] = $item_data['item_photo_arr'][0];

      $item_data['item_photo_firts_crop'] = str_replace($market_imgdir, $market_imgdir_crop, $item_data['item_photo_arr'][0]);
      if(!file_exists($item_data['item_photo_firts_crop']) || !filesize($item_data['item_photo_firts_crop'])) {
        cot_imageresize($item_data['item_photo_firts'], $item_data['item_photo_firts_crop'], $market_img_cropsize[0], $market_img_cropsize[1], '', '', 100, true);
      }
      foreach($item_data['item_photo_arr'] as $key => $val) {
        $item_data['item_photo_arr'][$key] = $val . cot_market_img_ver($item_data);
      }
      $item_data['item_photo_firts'] .= cot_market_img_ver($item_data);
      $item_data['item_photo_firts_crop'] .= cot_market_img_ver($item_data);
    }

    if($item_data['item_ismoder'] == 0 && $item_data['item_state'] == 0) $item_data['item_state'] = 2;

    $maxpatharray = 3;
    if(count($patharray) > $maxpatharray) {
      $patharray_new = array();
      foreach($patharray as $i => $cpath) {
        if($i < ($maxpatharray-1) || $i == count($patharray) - 1) $patharray_new[] = $cpath;
      }
      $patharray = $patharray_new;
    }

    $patharray_titles = array();
    foreach($patharray as $i => $cpath) {
      $patharray_titles[] = $cpath[1];
    }

		$temp_array = array(
			'ID' => $item_data['item_id'],
			'ALIAS' => $item_data['item_alias'],
			'STATE' => $item_data['item_state'],
			'STATUS' => $item_data['item_status'],
			'LOCALSTATUS' => $L['market_status_'.$item_data['item_status']],
			'URL' => $item_data['item_pageurl'],
			'TITLE' => $itempath,
			'SHORTTITLE' => $item_data['item_title'],
			'CAT' => $item_data['item_cat'],
			'CATTITLE' => htmlspecialchars($structure['market'][$item_data['item_cat']]['title']),
      'CATID' => htmlspecialchars($structure['market'][$item_data['item_cat']]['id']),
			'CATURL' => cot_url('market', 'c=' . $item_data['item_cat']),
			'CATPATH' => $patharray,
      'CATPATH_TITLES' => $patharray_titles,
      'CAT_ATTR' => (!empty($item_data['item_catattr']) ? $item_data['item_catattr'] : $item_data['item_cat']),
			'TEXT' => $text,
      'TEXT_INSTR' => $item_data['item_instruction'],
      'TEXT_PARSE' => cot_parse($item_data['item_text'], '', 'none'),
      'MODER_STATUS' => $item_data['item_ismoder'],
      'MODER_REJECTED' => $item_data['item_rejected'],
			'SHORTTEXT' => $text_cut,
			'COST' => (floor($item_data['item_cost']) != $item_data['item_cost']) ? number_format($item_data['item_cost'], '2', '.', ' ') : number_format($item_data['item_cost'], '0', '.', ' '),
			'COST_DODJI' => (floor($item_data['item_cost_dodji']) != $item_data['item_cost_dodji']) ? number_format($item_data['item_cost_dodji'], '2', '.', ' ') : number_format($item_data['item_cost_dodji'], '0', '.', ' '),
      'COST_VAL' => $item_data['item_cost'],
      'COST_DODJI_VAL' => $item_data['item_cost_dodji'],
      'DATE_STAMP' => $item_data['item_date'],
			'COUNT' => cot_mk_viewcount($item_data['item_count']),
      'COUNT_INT' => $item_data['item_count'],
			'USER_IS_ADMIN' => ($admin_rights || $usr['id'] == $item_data['item_userid']),
      'PHOTO_FIRST' => $item_data['item_photo_firts'],
      'PHOTO_FIRST_CROP' => $item_data['item_photo_firts_crop'],
      'PHOTO_ARR' => $item_data['item_photo_arr']
		);

    $temp_array['COST_FORMAT'] = cot_market_cost_format($item_data['item_cost'], $item_data['item_cost_dodji'], false, true);
    $temp_array['COST_FORMAT_FULL'] = cot_market_cost_format($item_data['item_cost'], $item_data['item_cost_dodji'], true);

		if ($admin_rights || $usr['id'] == $item_data['item_userid'])
		{
			$temp_array['ADMIN_EDIT_URL'] = cot_url('market', 'm=edit&id=' . $item_data['item_id']);
			$temp_array['HIDEPRODUCT_URL'] = cot_url('market', 'm=edit&id=' . $item_data['item_id'] .	(($item_data['item_state'] == 1) ? '&a=public' : '&a=hide'));
		}

		// Extrafields
		if (isset($cot_extrafields[$db_market]))
		{
			foreach ($cot_extrafields[$db_market] as $exfld)
			{
				$tag = mb_strtoupper($exfld['field_name']);
				$temp_array[$tag . '_TITLE'] = isset($L['market_' . $exfld['field_name'] . '_title']) ? $L['market_' . $exfld['field_name'] . '_title'] : $exfld['field_description'];
				$temp_array[$tag] = cot_build_extrafields_data('market', $exfld, $item_data['item_' . $exfld['field_name']]);
			}
		}

		// Extra fields for structure
		if (isset($cot_extrafields[$db_structure]))
		{
			foreach ($cot_extrafields[$db_structure] as $exfld)
			{
				$tag = mb_strtoupper($exfld['field_name']);
				$temp_array['CAT_' . $tag . '_TITLE'] = isset($L['structure_' . $exfld['field_name'] . '_title']) ? $L['structure_' . $exfld['field_name'] . '_title'] : $exfld['field_description'];
				$temp_array['CAT_' . $tag] = cot_build_extrafields_data('structure', $exfld,
															$structure['market'][$item_data['item_cat']][$exfld['field_name']]);
			}
		}

		/* === Hook === */
		foreach ($extp_main as $pl)
		{
			include $pl;
		}
		/* ===== */
	}
	else
	{
		$temp_array = array(
			'TITLE' => (!empty($emptytitle)) ? $emptytitle : '',
			'SHORTTITLE' => (!empty($emptytitle)) ? $emptytitle : '',
      'URL' => ''
		);
	}

	$return_array = array();
	foreach ($temp_array as $key => $val)
	{
		$return_array[$tag_prefix . $key] = $val;
	}

	return $return_array;
}

$_SESSION['market_next_photo'] = array();
function cot_market_next_photo($item_data = array(), $place = 0, $fparsed = false) {
  global $market_imgdir;

  $return = '';

  if($item_data['item_id'] > 0) {
    $parsed_photos = $_SESSION['market_next_photo'][$item_data['item_id']][$place];
    if(!$parsed_photos) $parsed_photos = ($fparsed ? 1 : 0);

    $item_data['item_photo_arr'] = array();
    foreach(array(1,2,3) as $i) {
      if(!empty($item_data['item_file_'.$i]) && file_exists($market_imgdir . $item_data['item_file_'.$i])) {
        $item_data['item_photo_arr'][] = $market_imgdir . $item_data['item_file_'.$i] . cot_market_img_ver($item_data);
      }
    }
    $cnt_photos = count($item_data['item_photo_arr']);

    $parse_num = 1;
    if($parsed_photos >= $cnt_photos) {
      $parse_num = $parsed_photos % $cnt_photos;
    } else {
      $parse_num = $cnt_photos - ($cnt_photos - $parsed_photos);
    }
    if($parse_num > ($cnt_photos-1)) $parse_num = 0;
    $return = $item_data['item_photo_arr'][$parse_num];

    $parsed_photos++;
    $_SESSION['market_next_photo'][$item_data['item_id']][$place] = $parsed_photos;
  }

  return $return;
}


/**
 * Determines products status
 *
 * @param int $item_state
 * @return string 'hidden', 'moderated', 'published'
 */
function cot_market_status($item_state)
{
	global $sys;

	if ($item_state == 0)
	{
		return 'published';
	}
	elseif ($item_state == 2)
	{
		return 'moderated';
	}
	return 'hidden';
}


/**
 * Returns possible values for category sorting order
 */
function cot_market_config_order()
{
	global $cot_extrafields, $L, $db_market;

	$options_sort = array(
		'id' => $L['Id'],
		'title' => $L['Title'],
		'text' => $L['Body'],
		'userid' => $L['Owner'],
		'date' => $L['Date']
	);

	foreach($cot_extrafields[$db_market] as $exfld)
	{
		$options_sort[$exfld['field_name']] = isset($L['market_'.$exfld['field_name'].'_title']) ? $L['market_'.$exfld['field_name'].'_title'] : $exfld['field_description'];
	}

	$L['cfg_order_params'] = array_values($options_sort);
	return array_keys($options_sort);
}




/**
 * Imports product data from request parameters.
 * @param  string $source Source request method for parameters
 * @param  array  $ritem  Existing product data from database
 * @param  array  $auth   Permissions array
 * @return array          Product data
 */
function cot_market_import($source = 'POST', $ritem = array(), $auth = array())
{
	global $cfg, $db_market, $market_crt, $cot_extrafields, $structure, $usr, $sys, $db, $db_structure;

	if (count($auth) == 0)
	{
    $auth =  array(
      'auth_read' => true,
      'auth_write' => true,
      'isadmin' => $usr['isadmin']
    );
	}

	if ($source == 'D' || $source == 'DIRECT')
	{
		// A trick so we don't have to affect every line below
		global $_PATCH;
		$_PATCH = $ritem;
		$source = 'PATCH';
	}

  $ritem['item_cat'] = '';
  $ritem['item_catattr'] = '';

	$cat_id = cot_import('category_id', $source, 'INT');
  if($cat_id > 0) {
    $catsql = $db->query("SELECT * FROM $db_structure WHERE structure_area='market' AND structure_id=".$cat_id." LIMIT 1")->fetch();
    if($catsql['structure_id'] > 0) {
      $ritem['item_cat'] = $catsql['structure_code'];
    }
  }

  $catattribute = cot_import('attribute', $source, 'ARR');
  foreach($catattribute as $key => $val) {
    if($val > 0 && !$catattribute[$val]) {
        $catsql = $db->query("SELECT * FROM $db_structure WHERE structure_area='market' AND structure_id=".$val." LIMIT 1")->fetch();
        if($catsql['structure_id'] > 0) {
          $ritem['item_catattr'] = $catsql['structure_code'];
        }
      break;
    }
  }

  if(empty($ritem['item_catattr'])) $ritem['item_catattr'] = $ritem['item_cat'];

  $ritem['item_alias'] = '';
	$ritem['item_title'] = cot_import('title', $source, 'TXT');
	$ritem['item_text'] = cot_import('description', $source, 'HTM');

  $ritem['item_instruction'] = cot_import('instruction', $source, 'HTM');
  $ritem['item_youtubelink'] = cot_import('youtube_link', $source, 'TXT');

  $ritem['item_links_auditory'] = cot_import('auditory', $source, 'TXT');
  $ritem['item_links_sites'] = cot_import('links_sites', $source, 'HTM');

	if(!$ritem['item_date'] || empty($ritem['item_date']))
	{
		$ritem['item_date'] = (int)$sys['now'];
	}
	else
	{
		//$ritem['item_update'] = (int)$sys['now'];
	}
	
	if ($auth['isadmin'] && isset($ritem['item_userid']))
	{
		$ritem['item_userid'] = $ritem['item_userid'];
	}
	else
	{
		$ritem['item_userid'] = $usr['id'];
	}
	
	// Extra fields
	foreach ($cot_extrafields[$db_market] as $exfld)
	{
		$ritem['item_'.$exfld['field_name']] = cot_import_extrafields('ritem'.$exfld['field_name'], $exfld, $source, $ritem['item_'.$exfld['field_name']]);
	}
	
	return $ritem;
}



/**
 * Validates product data.
 * @param  array   $ritem Imported product data
 * @return boolean        TRUE if validation is passed or FALSE if errors were found
 */
function cot_market_validate($ritem)
{
	global $cfg, $structure;
	cot_check((empty($ritem['item_cat']) || empty($ritem['item_catattr'])), 'market_select_cat', 'rcat');

	cot_check(mb_strlen($ritem['item_title']) < 2, 'market_empty_title', 'rtitle');

	cot_check(empty($ritem['item_text']), 'market_empty_text', 'rtext');
  cot_check(empty($ritem['item_text']), 'market_empty_instruction', 'rtext');

	return !cot_error_found();
}



/**
 * Adds a new product to the CMS.
 * @param  array   $ritem product data
 * @param  array   $auth  Permissions array
 * @return integer        New product ID or FALSE on error
 */
function cot_market_add(&$ritem, $auth = array())
{
	global $usr, $cache, $cfg, $db, $db_market, $db_structure, $structure, $L;
	if (cot_error_found())
	{
		return false;
	}

	if (count($auth) == 0)
	{
		$auth = cot_market_auth($ritem['item_cat']);
	}
	
	if(!$cfg['market']['preview']){
		$ritem['item_state'] = (!$cfg['market']['prevalidate']) ? 0 : 2;
    $ritem['item_ismoder'] = (!$cfg['market']['prevalidate']) ? $usr['id'] : 0;
	}
	else
	{
		$ritem['item_state'] = 1;
    $ritem['item_ismoder'] = 0;
	}

  if($usr['ban']['banned'] && $usr['ban']['block']['market_seller']) {
		$ritem['item_state'] = 1;
    $ritem['item_ismoder'] = 0;
  }

	if (!empty($ritem['item_alias']))
	{
		$prd_count = $db->query("SELECT COUNT(*) FROM $db_market WHERE item_alias = ?", $ritem['item_alias'])->fetchColumn();
		if ($prd_count > 0)
		{
			$ritem['item_alias'] = $ritem['item_alias'].rand(1000, 9999);
		}
	}
	/* === Hook === */
	foreach (cot_getextplugins('market.add.add.query') as $pl)
	{
		include $pl;
	}
	/* ===== */

	if ($db->insert($db_market, $ritem))
	{
		$id = $db->lastInsertId();

		cot_extrafield_movefiles();
	}
	else
	{
		$id = false;
	}
	
	cot_market_sync($ritem['item_cat']);
	
	/* === Hook === */
	foreach (cot_getextplugins('market.add.add.done') as $pl)
	{
		include $pl;
	}
	/* ===== */

	cot_shield_update(30, "r product");
	cot_log("Add product #".$id, 'adm');

	return $id;
}




/**
 * Removes a product from the CMS.
 * @param  int     $id    Product ID
 * @param  array   $rpage Product data
 * @return boolean        TRUE on success, FALSE on error
 */
function cot_market_delete($id, $ritem = array())
{
	global $db, $db_market, $db_structure, $cache, $cfg, $cot_extrafields, $structure, $L, $market_imgdir, $market_imgdir_crop;
	if (!is_numeric($id) || $id <= 0)
	{
		return false;
	}
	$id = (int)$id;
	if (count($ritem) == 0)
	{
		$ritem = $db->query("SELECT * FROM $db_market WHERE item_id = ?", $id)->fetch();
		if (!$ritem)
		{
			return false;
		}
	}

  foreach(array(1,2,3) as $i) {
    if(!empty($ritem['item_file_'.$i])) {
      if(file_exists($market_imgdir . $ritem['item_file_'.$i])) unlink($market_imgdir . $ritem['item_file_'.$i]);
      if(file_exists($market_imgdir_crop . $ritem['item_file_'.$i])) unlink($market_imgdir_crop . $ritem['item_file_'.$i]);
    }
  }

	foreach ($cot_extrafields[$db_market] as $exfld)
	{
		cot_extrafield_unlinkfiles($ritem['item_' . $exfld['field_name']], $exfld);
	}

	$db->delete($db_market, "item_id = ?", $id);
	cot_log("Deleted product #" . $id, 'adm');

	cot_market_sync($ritem['item_cat']);
	
	/* === Hook === */
	foreach (cot_getextplugins('market.edit.delete.done') as $pl)
	{
		include $pl;
	}
	/* ===== */

	return true;
}

/**
 * Updates a product in the CMS.
 * @param  integer $id    Product ID
 * @param  array   $ritem Product data
 * @param  array   $auth  Permissions array
 * @return boolean        TRUE on success, FALSE on error
 */
function cot_market_update($id, &$ritem, $auth = array())
{
	global $usr, $cache, $cfg, $db, $db_users, $db_market, $db_structure, $structure, $L;
	if (cot_error_found())
	{
		return false;
	}

	if (count($auth) == 0)
	{
		$auth = cot_market_auth($ritem['item_cat']);
	}

	if (!empty($ritem['item_alias']))
	{
		$prd_count = $db->query("SELECT COUNT(*) FROM $db_market WHERE item_alias = ? AND item_id != ?", array($ritem['item_alias'], $id))->fetchColumn();
		if ($prd_count > 0)
		{
			$ritem['item_alias'] = $ritem['item_alias'].rand(1000, 9999);
		}
	}

	$item = $db->query("SELECT * FROM $db_market WHERE item_id = ?", $id)->fetch();	
	
	if (!$db->update($db_market, $ritem, 'item_id = ?', $id))
	{
		return false;
	}

	cot_market_sync($item['item_cat']);
	cot_market_sync($ritem['item_cat']);
	
	cot_extrafield_movefiles();

  $user_market_cntmoderprd_uid = $item['item_userid'];
  $user_market_cntmoderprd = 0;
  if($user_market_cntmoderprd_uid > 0 && !$item['item_firstmoderdate'] && $ritem['item_firstmoderdate'] > 0) {
    $urr = $db->query("SELECT * FROM $db_users WHERE user_id=".$user_market_cntmoderprd_uid.' LIMIT 1')->fetch();
    if($urr['user_id'] > 0) {
      $user_market_cntmoderprd = $urr['user_market_cntmoderprd'];
      $user_market_cntmoderprd++;

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

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

	return true;
}

function cot_getmarketlist($template = 'index', $count = 5, $sqlsearch = '', $order = "item_date DESC")
{
	global $db, $db_market, $cfg, $db_users;
	
	list($usr['auth_read'], $usr['auth_write'], $usr['isadmin']) = cot_auth('market', 'any', 'RWA');
	
	$t = new XTemplate(cot_tplfile(array('market', $template), 'module'));
	
	$sqlsearch = !empty($sqlsearch) ? " AND " . $sqlsearch : '';
	
	$sqllist = $db->query("SELECT * FROM $db_market AS p LEFT JOIN $db_users AS u ON u.user_id=p.item_userid
	WHERE item_state=0 $sqlsearch ORDER BY $order LIMIT " . (int)$count);
	
	$sqllist_rowset = $sqllist->fetchAll();
	$sqllist_idset = array();
	foreach($sqllist_rowset as $item)
	{
		$sqllist_idset[$item['item_id']] = $item['item_alias'];
	}
	
	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),
		));
		$t->parse("MARKET.PRD_ROWS");
	}

	$t->parse("MARKET");

	return $t->text("MARKET");
}



/**
 * Select market cat for search from
 * 
 * @global array $structure
 * @param type $check
 * @param type $name
 * @param type $subcat
 * @param type $hideprivate
 * @param type $is_module
 * @return type
 */
function cot_market_selectcat($check, $name, $subcat = '', $hideprivate = true)
{
	global $structure;

	$structure['market'] = (is_array($structure['market'])) ? $structure['market'] : array();

	$result_array = array();
	foreach ($structure['market'] as $i => $x)
	{
		$display = ($hideprivate) ? cot_auth('market', $i, 'R') : true;
		if (!empty($subcat) && isset($structure['market'][$subcat]))
		{
			$mtch = $structure['market'][$subcat]['path'].".";
			$mtchlen = mb_strlen($mtch);
			$display = (mb_substr($x['path'], 0, $mtchlen) == $mtch || $i === $subcat);
		}

		if ((!$is_module || cot_auth('market', $i, 'R')) && $i!='all' && $display)
		{
			$result_array[$i] = $x['tpath'];
		}
	}
	$result = cot_selectbox($check, $name, array_keys($result_array), array_values($result_array), true);

	return($result);
}

if ($cfg['market']['markup'] == 1){
  $prdeditor = $cfg['market']['prdeditor'];
}