<?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');
$r = cot_import('r', 'G', 'ALP');

$c = cot_import('c', 'G', 'TXT');
if (!empty($c) && !isset($structure['market'][$c]))
{
	$c = '';
}

list($usr['auth_read'], $usr['auth_write'], $usr['isadmin']) = cot_auth('market', 'any', 'RWA');
cot_block($usr['auth_write']);

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

$sys['parser'] = $cfg['market']['parser'];
$parser_list = cot_get_parsers();

$a = 'add';

if (COT_AJAX && $a == 'add')
{
	cot_shield_protect();

	$ritem = array();

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

	$ritem = cot_market_import('POST', array(), $usr);

	list($usr['auth_read'], $usr['auth_write'], $usr['isadmin']) = cot_auth('market', $ritem['item_cat']);
	cot_block($usr['auth_write']);

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

	cot_market_validate($ritem);

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

  $result = array(
    'result' => 'error',
    'redirectUrl' => '',
    'errors' => array()
  );

	if (!cot_error_found())
	{
    $result['result'] = 'success';
		$id = cot_market_add($ritem, $usr);

  	$files = 0;
  	if ($_FILES)
  	{
      $ritem_files = array();
      require_once cot_incfile('uploads');

  		@clearstatcache();
  		foreach(array(1,2,3) as $code)
  		{
        $file = false;
        $extradata = array();

        if($code == 1) {
          $file = $_FILES['first-prd-photo'];
          $extradata = cot_import('first-prd-photo-size', 'P', 'TXT');
          $extradata = (!empty($extradata) ? json_decode($extradata,1) : array());
        } else {
          $delphoto = $_POST['delete-photo'][($code-2)];
          if(!$delphoto[($code-1)]) {
            $file = array(
              'error' => $_FILES['prd-photo']['error'][($code-2)],
              'name' => $_FILES['prd-photo']['name'][($code-2)],
              'size' => $_FILES['prd-photo']['size'][($code-2)],
              'tmp_name' => $_FILES['prd-photo']['tmp_name'][($code-2)],
              'type' => $_FILES['prd-photo']['type'][($code-2)]
            );
            $extradata = cot_import('prd-photo-size', 'P', 'ARR');
            $extradata = (!empty($extradata[($code-2)]) ? json_decode($extradata[($code-2)],1) : array());
          }
        }

  			if(!$file) continue;
  			if (!empty($file['tmp_name']) && $file['size'] > 0 && is_uploaded_file($file['tmp_name']))
  			{
  				$gd_supported = array('jpg', 'jpeg', 'png', 'gif');
  				$var = explode(".", $file['name']);
  				$file_ext = strtolower(array_pop($var));
  				$fcheck = cot_file_check($file['tmp_name'], $file['name'], $file_ext);
  				if (in_array($file_ext, $gd_supported) && $fcheck == 1)
  				{
  					$file['name'] = cot_safename($file['name'], true);

  					$filename_full = $id . '_' . $code . '.' . $file_ext;
  					$filepath = $market_imgdir . '/' . $filename_full;

  					if (!empty($item['item_file_'.$code]) && file_exists($market_imgdir. $item['item_file_'.$code]) && $item['item_file_'.$code] != $filename_full)
            {
  						unlink($market_imgdir. $item['item_file_'.$code]);
  					}
            elseif (file_exists($filepath))
  					{
  						unlink($filepath);
  					}

  					move_uploaded_file($file['tmp_name'], $filepath);

  					cot_imageresize($filepath, $filepath, 650, 433, '', '', 100, true, $extradata);
  					@chmod($filepath, $cfg['file_perms']);

            $ritem_files['item_file_'.$code] = $filename_full;
  					$files++;
  				}
  			}
  		}
      if($files > 0 && count($ritem_files) > 0) $db->update($db_market, $ritem_files, 'item_id='.$id);
  	}

		switch ($ritem['item_state'])
		{
			case 0:
				$urlparams = empty($ritem['item_alias']) ?
					array('c' => $ritem['item_cat'], 'id' => $id) :
					array('c' => $ritem['item_cat'], 'al' => $ritem['item_alias']);
				$result['redirectUrl'] = cot_url('market', $urlparams, '', true);
				break;
			case 1:
				$result['redirectUrl'] = cot_url('market', 'm=myitems&group=feated', '', true);
				break;
			case 2:
				$urlparams = empty($ritem['item_alias']) ?
					array('c' => $ritem['item_cat'], 'id' => $id) :
					array('c' => $ritem['item_cat'], 'al' => $ritem['item_alias']);
        $r_url = cot_url('market', $urlparams, '', true);

				$result['redirectUrl'] = cot_url('market', 'm=myitems&group=suspend', '', true);

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

				if ($cfg['market']['notifmarket_admin_moderate'])
				{
					$nbody = cot_rc($L['market_notif_admin_moderate_mail_body'], array(
						'user_name' => $usr['profile']['user_name'],
						'prd_name' => $ritem['item_title'],
						'sitename' => $cfg['maintitle'],
						'link' => COT_ABSOLUTE_URL . $r_url
					));
					cot_mail($cfg['adminemail'], $L['market_notif_admin_moderate_mail_subj'], $nbody);
				}
				break;
		}

		$_SESSION['market_add'] = '';
	}
	else
	{
    $result['errors'] = array();

  	$errors = cot_get_messages('', 'error');
  	if (count($errors) > 0)
  	{
  		foreach ($errors as $msg)
  		{
  			$result['errors'][] = isset($L[$msg['text']]) ? $L[$msg['text']] : $msg['text'];
  		}
  	}
  	cot_clear_messages();

    $_SESSION['market_add'] = $ritem;
	}

  echo json_encode($result);
  exit;
}

if(is_array($_SESSION['market_add'])) $ritem = $_SESSION['market_add'];

if (empty($ritem['item_cat']) && !empty($c))
{
	$ritem['item_cat'] = $c;
	$usr['isadmin'] = cot_auth('market', $ritem['item_cat'], 'A');
}

if (empty($ritem['item_type']) && !empty($type))
{
	$ritem['item_type'] = $type;
}

$out['subtitle'] = $L['market_add_product_title'];
$out['head'] .= $R['code_noindex'];
$sys['sublocation'] = $structure['market'][$c]['title'];

if(is_array($_SESSION['market_add']) && count($_SESSION['market_add']) > 0) {
  $mskin = cot_tplfile(array('market', 'add', 'continue', $structure['market'][$ritem['item_cat']]['tpl']));
} else {
  $mskin = cot_tplfile(array('market', 'add', $structure['market'][$ritem['item_cat']]['tpl']));
}

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

$t = new XTemplate($mskin);

// Error and message handling
cot_display_messages($t);

// Extra fields
foreach($cot_extrafields[$db_market] as $exfld)
{
	$uname = strtoupper($exfld['field_name']);
	$exfld_val = cot_build_extrafields('ritem'.$exfld['field_name'], $exfld, $ritem['item_'.$exfld['field_name']]);
	$exfld_title = isset($L['market_'.$exfld['field_name'].'_title']) ?  $L['market_'.$exfld['field_name'].'_title'] : $exfld['field_description'];
	$t->assign(array(
		'PRDADD_FORM_'.$uname => $exfld_val,
		'PRDADD_FORM_'.$uname.'_TITLE' => $exfld_title,
		'PRDADD_FORM_EXTRAFLD' => $exfld_val,
		'PRDADD_FORM_EXTRAFLD_TITLE' => $exfld_title
		));
	$t->parse('MAIN.EXTRAFLD');
}

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

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