<?php

defined('COT_CODE') or die('Wrong URL');

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

$action = cot_import('action', 'G', 'TXT');

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

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

$ritem = array();

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

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

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

	cot_faq_validate($ritem);

  if($ritem['faq_parent'] > 0) {
    cot_check(!($db->query("SELECT COUNT(*) FROM $db_faq WHERE faq_id=".$ritem['faq_parent'].' LIMIT 1')->fetchColumn() > 0), 'Родительская категория не найдена', 'rfaqparent');
  } else {
    $ritem['faq_parent'] = 0;
  }

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

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

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

    $result['redirectUrl'] = cot_url('faq', 'article='.$id, '', 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;
}

$out['subtitle'] = 'Добавление вопрос-ответ';
$out['head'] .= $R['code_noindex'];

$mskin = cot_tplfile(array('faq', 'add'));

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

$t = new XTemplate($mskin);

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

$t->assign(array(
	"FAQADD_FORM_PARENT" => $parent,
));

// Extra fields
foreach($cot_extrafields[$db_faq] as $exfld)
{
	$uname = strtoupper($exfld['field_name']);
	$exfld_val = cot_build_extrafields('ritem'.$exfld['field_name'], $exfld, $ritem['faq_'.$exfld['field_name']]);
	$exfld_title = isset($L['faq_'.$exfld['field_name'].'_title']) ?  $L['faq_'.$exfld['field_name'].'_title'] : $exfld['field_description'];

	$t->assign(array(
		'FAQADD_FORM_'.$uname => $exfld_val,
		'FAQADD_FORM_'.$uname.'_TITLE' => $exfld_title,
		'FAQADD_FORM_EXTRAFLD' => $exfld_val,
		'FAQADD_FORM_EXTRAFLD_TITLE' => $exfld_title
	));
	$t->parse('MAIN.EXTRAFLD');
}

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

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