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

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

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

cot_block($usr['auth_read']);

if (!$id || $id < 0)
{
	cot_die_message(404);
}

$sql = $db->query("SELECT * FROM $db_market WHERE item_id='$id' LIMIT 1");
cot_die($sql->rowCount() == 0);
$item = $sql->fetch();

cot_block($usr['isadmin'] || $usr['auth_write'] && $usr['id'] == $item['item_userid']);

$sys['parser'] = $item['item_parser'];
$parser_list = cot_get_parsers();

require_once cot_incfile('mavatars', 'plug');

if ($a == 'update')
{
	/* === Hook === */
	foreach (cot_getextplugins('market.edit.update.first') as $pl)
	{
		include $pl;
	}
	/* ===== */
	
	cot_block($usr['isadmin'] || $usr['auth_write'] && $usr['id'] == $item['item_userid']);

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

  $sendisnotmodermail = false;
  if($usr['isadmin']) {
    $ritem['item_state'] = 0;
    $ritem['item_ismoder'] = $usr['id'];
    $ritem['item_rejected'] = '';
    //$ritem['item_showonindex'] = (cot_import('ritemshowonindex', 'P', 'BOL') ? 1 : 0);

    if(cot_import('notismoder', 'P', 'BOL')) {
      $sendisnotmodermail = true;
      $ritem['item_state'] = 3;
      $ritem['item_ismoder'] = 0;
      $ritem['item_rejected'] = cot_import('ritemrejected', 'P', 'HTM');
    } else {
      if($item['item_update'] == 0) $ritem['item_update'] = (int)$sys['now'];
      if(!$item['item_firstmoderdate']) {
        $ritem['item_firstmoderdate'] = $sys['now'];
      }
    }
  } else {
    $ritem['item_ismoder'] = 0;
    if($usr['ban']['banned'] && $usr['ban']['block']['market_seller']) {
      $ritem['item_state'] = 1;
    } else {
      if($item['item_state'] == 3) $ritem['item_state'] = 2;
      if($item['item_state'] == 0) $ritem['item_state'] = 2;
    }
  }

  $ritem['item_ismoder_last'] = $usr['id'] . ',' . $sys['now'];

  $ritem['item_update_real'] = (int)$sys['now'];
  //$db->query("ALTER TABLE $db_market ADD COLUMN `item_update_real` int(11) DEFAULT '0'");

	if ($_SERVER['REQUEST_METHOD'] == 'POST')
	{
		$rdelete = cot_import('rdelete', 'P', 'BOL');
	}
	else
	{
		$rdelete = cot_import('delete', 'G', 'BOL');
		cot_check_xg();
	}

	if ($rdelete)
	{
		cot_market_delete($id, $item);

    $r_url = ($usr['isadmin'] ? cot_url('moderation', 'm=market&state=-1', '', true) : cot_url('market', 'm=myitems', '', true));
    if(COT_AJAX) {
      $result = array(
        'result' => 'success',
        'redirectUrl' => $r_url,
        'errors' => array()
      );

      echo json_encode($result);
      exit;
    } else {
      cot_redirect($r_url);
    }
	}
	
	/* === Hook === */
	foreach (cot_getextplugins('market.edit.update.import') as $pl)
	{
		include $pl;
	}
	/* ===== */

	cot_market_validate($ritem);

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

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

	if (!cot_error_found())
	{
    $result['result'] = 'success';
		cot_market_update($id, $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);
  	}

    if($ritem['item_state'] == 0) {
				$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'] = $r_url;
				
				if (!$usr['isadmin'])
				{
					$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);
        }

        if ($usr['isadmin'] && $usr['id'] != $item['item_userid'])
        {
          $result['redirectUrl'] = cot_url('moderation', 'm=market&state='.$item['item_state']);
        }
    }
    elseif($ritem['item_state'] == 1)
    {
				$result['redirectUrl'] = cot_url('market', 'm=myitems&group=feated', '', true);
        if ($usr['isadmin'] && $usr['id'] != $item['item_userid'])
        {
          $result['redirectUrl'] = cot_url('moderation', 'm=market&state='.$item['item_state']);
        }
    }
    elseif($ritem['item_state'] == 2 && $item['item_state'] != 3)
    {
				$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' => $item['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' => $item['item_title'],
						'sitename' => $cfg['maintitle'],
						'link' => COT_ABSOLUTE_URL . $r_url
					));
					cot_mail($cfg['adminemail'], $L['market_notif_admin_moderate_mail_subj'], $nbody);
				}

        if ($usr['isadmin'] && $usr['id'] != $item['item_userid'])
				{
          $result['redirectUrl'] = cot_url('moderation', 'm=market&state='.$item['item_state']);
        }
    } elseif($ritem['item_state'] == 3 || $item['item_state'] == 3) {
				$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);

        if($sendisnotmodermail) {
          $owner = $db->query("SELECT * FROM $db_users WHERE user_id=".$item['item_userid'].' LIMIT 1')->fetch();
          if(!empty($owner['user_email'])) {
  					$rbody = cot_rc($L['market_sentfiledmoderation_mail_body'], array(
  						'user_name' => $owner['user_name'],
  						'prd_name' => $item['item_title'],
              'rejected' => $ritem['item_rejected'],
  						'sitename' => $cfg['maintitle'],
  						'link' => COT_ABSOLUTE_URL . $r_url
  					));
  					cot_mail($owner['user_email'], $L['market_sentfiledmoderation_mail_subj'], $rbody);
          }
        }
        elseif (!$usr['isadmin'] && $cfg['market']['notifmarket_admin_moderate'])
				{
					$nbody = cot_rc($L['market_notif_admin_remoderate_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($cfg['adminemail'], $L['market_notif_admin_remoderate_mail_subj'], $nbody);
				}
        $ritem['item_state'] = 3;
        $ritem['item_ismoder'] = 0;
        $ritem['item_rejected'] = cot_import('ritemrejected', 'P', 'HTM');

        if($ritem['item_state'] == 2) {
          $result['redirectUrl'] = cot_url('market', 'm=myitems&group=suspend', '', true);
        } else {
				  $result['redirectUrl'] = cot_url('market', 'm=myitems&group=rejected', '', true);
        }

				if ($usr['isadmin'] && $usr['id'] != $item['item_userid'])
				{
          $result['redirectUrl'] = cot_url('moderation', 'm=market&state=2');
        }
    }
	}
	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();
	}

  //echo json_encode($ritem);
  echo json_encode($result);
  exit;
}

$out['subtitle'] = $L['market_edit_product_title'];
$out['head'] .= $R['code_noindex'];
$sys['sublocation'] = $structure['market'][$item['item_cat']]['title'];

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

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

$t = new XTemplate($mskin);

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

$t->assign(array(
	"PRDEDIT_FORM_SEND" => cot_url('market', "m=edit&a=update&id=" . $item['item_id'] . "&r=" . $r),
	"PRDEDIT_FORM_ID" => $item['item_id'],
	"PRDEDIT_FORM_CAT" => cot_selectbox_structure('market', $item['item_cat'], 'rcat'),
	"PRDEDIT_FORM_CATTITLE" => $structure['market'][$item['item_cat']]['title'],
	"PRDEDIT_FORM_TITLE" => cot_inputbox('text', 'rtitle', $item['item_title'], 'size="56"'),
	"PRDEDIT_FORM_ALIAS" => cot_inputbox('text', 'ralias', $item['item_alias'], array('size' => '32', 'maxlength' => '255')),
	"PRDEDIT_FORM_TEXT" => cot_textarea('rtext', $item['item_text'], 10, 60, 'id="formtext"', ($prdeditor && $prdeditor != 'disable') ? 'input_textarea_'.$prdeditor : ''),
	"PRDEDIT_FORM_COST" => cot_inputbox('text', 'rcost', $item['item_cost'], 'size="10"'),
	"PRDEDIT_FORM_STATE" => $item['item_state'],
	"PRDEDIT_FORM_PARSER" => cot_selectbox($item['item_parser'], 'rparser', cot_get_parsers(), cot_get_parsers(), false),
	"PRDEDIT_FORM_DELETE" => cot_radiobox(0, 'rdelete', array(1,0), array($L['Yes'], $L['No']))
)); 

$ismoder_last = explode(',', $item['item_ismoder_last']);

$t->assign(array(
  "PRDEDIT_ISMODER_LAST_USER_ID" => ($ismoder_last[0] > 0 ? $ismoder_last[0] : 0),
	"PRDEDIT_ISMODER_LAST_USER_NAME" => ($ismoder_last[0] > 0 ? $db->query("SELECT user_name FROM $db_users WHERE user_id=".$ismoder_last[0].' LIMIT 1')->fetchColumn() : ''),
  "PRDEDIT_ISMODER_LAST_DATE" => ($ismoder_last[1] > 0 ? cot_date('d.m.Y в H:i', $ismoder_last[1]) : ''),
));

// Extra fields
foreach($cot_extrafields[$db_market] as $exfld)
{
	$uname = strtoupper($exfld['field_name']);
	$exfld_val = cot_build_extrafields('ritem'.$exfld['field_name'], $exfld, $item['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(
		'PRDEDIT_FORM_'.$uname => $exfld_val,
		'PRDEDIT_FORM_'.$uname.'_TITLE' => $exfld_title,
		'PRDEDIT_FORM_EXTRAFLD' => $exfld_val,
		'PRDEDIT_FORM_EXTRAFLD_TITLE' => $exfld_title
	));
	$t->parse('MAIN.EXTRAFLD');
}

/* === Hook === */
foreach (cot_getextplugins('market.edit.tags') as $pl)
{
	include $pl;
}
/* ===== */
$t->parse('MAIN');
$module_body = $t->text('MAIN');