<?php

/**
 * projects module
 *
 * @package projects
 * @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('projects', 'any', 'RWA');
if(!$usr['isadmin'] && $usr['maingrp'] == 6) $usr['isadmin'] = true;

$id = cot_import('id', 'G', 'INT');
$action = cot_import('action', 'G', 'TXT');
/* === Hook === */
foreach (cot_getextplugins('projects.edit.first') as $pl)
{
	include $pl;
}
/* ===== */

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

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

$sql = $db->query("SELECT * FROM $db_projects 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']);

if ($a == 'update')
{
	/* === Hook === */
	foreach (cot_getextplugins('projects.edit.update.first') as $pl)
	{
		include $pl;
	}
	/* ===== */

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

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

    $r_url = ($usr['isadmin'] ? cot_url('moderation', 'm=projects&state='.$item['item_state'], '', true) : cot_url('projects', 'm=myprojects', '', true));
    if(COT_AJAX) {
      $result = array(
        'result' => 'success',
        'redirectUrl' => $r_url,
        'errors' => array()
      );

      echo json_encode($result);
      exit;
    } else {
      cot_redirect($r_url);
    }
	}

  if($usr['isadmin']) {
    $ritem['item_state'] = 0;
    $ritem['item_ismoder'] = $usr['id'];
    $ritem['item_rejected'] = '';

    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'];
    }
  } else {
    $ritem['item_ismoder'] = 0;
    if($usr['ban']['banned'] && $usr['ban']['block']['projects_buyer']) {
      $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_update_real'] = $sys['now'];
	
	/* === Hook === */
	foreach (cot_getextplugins('projects.edit.update.import') as $pl)
	{
		include $pl;
	}
	/* ===== */

	cot_projects_validate($ritem);

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

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

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

		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']);
				$r_url = cot_url('projects', $urlparams, '', true);
				
				if (!$usr['isadmin'])
				{
					$rbody = cot_rc($L['project_added_mail_body'], array(
						'user_name' => $usr['profile']['user_name'],
						'prj_name' => $item['item_title'],
						'sitename' => $cfg['maintitle'],
						'link' => COT_ABSOLUTE_URL . $r_url
					));
					cot_mail($usr['profile']['user_email'], $L['project_added_mail_subj'], $rbody);
				}
				break;
			case 1:
				$r_url = cot_url('projects', 'm=preview&id=' . $id, '', 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('projects', $urlparams, '', true);
				
				if (!$usr['isadmin'])
				{
					$rbody = cot_rc($L['project_senttovalidation_mail_body'], array( 
						'user_name' => $usr['profile']['user_name'],
						'prj_name' => $item['item_title'],
						'sitename' => $cfg['maintitle'],
						'link' => COT_ABSOLUTE_URL . $r_url
					));
					cot_mail($usr['profile']['user_email'], $L['project_senttovalidation_mail_subj'], $rbody);
				}
				break;
		}

    $result['redirectUrl'] = ($usr['isadmin'] ? cot_url('moderation', 'm=projects&state=2', '', true) : cot_url('projects', 'm=myprojects', '', true));
  }
  else
	{
    $result['errors'] = array();
  	$errors = cot_get_messages('', 'error');
  	if (count($errors) > 0)
  	{
  		foreach ($errors as $msg)
  		{
  			$result['errors'][$msg['src']] = isset($L[$msg['text']]) ? $L[$msg['text']] : $msg['text'];
  		}
  	}
  	cot_clear_messages();
	}

  echo json_encode($result);
  exit;
}

if ($action == 'public')
{
  if($usr['ban']['banned'] && $usr['ban']['block']['market_seller']) {
    cot_error('Вы не можете активировать запросы на услуги, из за временной блокировки.');
    cot_redirect(cot_url('projects', 'm=myprojects', '', true));
    exit;
  } else {
  	$ritem = array();
  	$ritem['item_state'] = ($item['item_ismoder'] != 0 ? 0 : 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('projects', $urlparams, '', true);

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

  	cot_projects_sync($item['item_cat']);

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

  	cot_redirect(cot_url('projects', 'm=myprojects', '', true));
  	exit;
  }
}

if ($action == 'stop')
{
	$ritem = array();
	$ritem['item_state'] = 1;
	$db->update($db_projects, $ritem, 'item_id = ?', $id);
	
	cot_projects_sync($item['item_cat']);
	
	$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('projects', $urlparams, '', true);
	
	/* === Hook === */
	foreach (cot_getextplugins('projects.edit.hide') as $pl)
	{
		include $pl;
	}
	/* ===== */
	
	cot_redirect(cot_url('projects', 'm=myprojects', '', true));
	exit;
}

if ($action == 'delete')
{
	cot_projects_delete($id);

	$r_url = cot_url('projects', 'm=myprojects', '', true);
	
	/* === Hook === */
	foreach (cot_getextplugins('projects.edit.delete') as $pl)
	{
		include $pl;
	}
	/* ===== */
	
	cot_redirect(cot_url('projects', 'm=myprojects', '', true));
	exit;
}

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

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

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

$t = new XTemplate($mskin);

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

$t->assign(array(
	"PRJEDIT_FORM_ID" => $item['item_id'],
	"PRJEDIT_FORM_DELETE" => cot_radiobox(0, 'rdelete', array(1,0), array($L['Yes'], $L['No']))
)); 

$t->assign(cot_generate_projecttags($item, 'PRJ_EDIT_', 0, $usr['isadmin'], $cfg['homebreadcrumb']));

// Extra fields
foreach($cot_extrafields[$db_projects] 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['projects_'.$exfld['field_name'].'_title']) ?  $L['projects_'.$exfld['field_name'].'_title'] : $exfld['field_description'];

	$t->assign(array(
		'PRJEDIT_FORM_'.$uname => $exfld_val,
		'PRJEDIT_FORM_'.$uname.'_TITLE' => $exfld_title,
		'PRJEDIT_FORM_EXTRAFLD' => $exfld_val,
		'PRJEDIT_FORM_EXTRAFLD_TITLE' => $exfld_title
	));
	$t->parse('MAIN.EXTRAFLD');
}

$jjcat=0;
foreach($structure['market'] as $code => $cat) {
  if (mb_substr_count($cat['path'], ".") == 0) {
    $cat['subcatselected'] = 0;
    $cat['subcnt'] = 0;
    foreach($structure['market'] as $subcode => $subcat) {
      if($subcat['parent'] == $code && $subcat['parent'] != $subcode) {
        $cat['subcnt']++;
        if($item['item_cat'] == $subcode) $cat['subcatselected'] = 1;
        $t->assign(array(
          'SUBCAT_ROW_ID' => $subcat['id'],
          'SUBCAT_ROW_TITLE' => $subcat['title'],
          'SUBCAT_ROW_CODE' => $subcode,
          'SUBCAT_ROW_SELECTED' => ($item['item_cat'] == $subcode ? ' selected="selected"' : '')
        ));
        $t->parse('MAIN.CATSUBCATS_ROW.SUBCATS_ROW');
      }
    }

    $t->assign(array(
      'CAT_ROW_ID' => $cat['id'],
      'CAT_ROW_TITLE' => $cat['title'],
      'CAT_ROW_CODE' => $code,
      'CAT_ROW_SELECTED' => (($cat['subcatselected'] || $item['item_cat'] == $code)? ' selected="selected"' : '')
    ));

    $t->parse('MAIN.CATS_ROW');
    if($cat['subcnt'] > 0) $t->parse('MAIN.CATSUBCATS_ROW');
  }
}

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

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