<?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;

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

/* === Hook === */
foreach (cot_getextplugins('faq.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_faq WHERE faq_id='$id' LIMIT 1");
cot_die($sql->rowCount() == 0);
$item = $sql->fetch();

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

$haschilds = $db->query("SELECT COUNT(*) FROM $db_faq WHERE faq_parent=".$item['faq_id'])->fetchColumn();

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

	$ritem = cot_faq_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)
	{
    if($db->query("SELECT COUNT(*) FROM $db_faq WHERE faq_parent=".$id.' LIMIT 1')->fetchColumn() > 0) {
      if(COT_AJAX) {
        $result = array(
          'result' => 'error',
          'redirectUrl' => '',
          'errors' => array(
            'rfaqparent' =>  'Данный вопрос является категорий, удалить можно при отсутствии дочерних вопросов'
          )
        );

        echo json_encode($result);
        exit;
      } else {
        cot_check(true, 'Данный вопрос является категорий, удалить можно при отсутствии дочерних вопросов', 'rfaqparent');
        cot_redirect(cot_url('faq', 'm=edit&id='.$id, '', true));
      }
    } else {
  		cot_faq_delete($id, $item);

      if(COT_AJAX) {
        $result = array(
          'result' => 'success',
          'redirectUrl' => cot_url('admin', 'm=faq'),
          'errors' => array()
        );

        echo json_encode($result);
        exit;
      } else {
        cot_redirect(cot_url('admin', 'm=faq', '', true));
      }
    }
	}

	/* === Hook === */
	foreach (cot_getextplugins('faq.edit.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');
  }

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

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

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

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

$t = new XTemplate($mskin);

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

$t->assign(array(
	"FAQEDIT_FORM_ID" => $item['faq_id'],
	"FAQEDIT_FORM_DELETE" => cot_radiobox(0, 'rdelete', array(1,0), array($L['Yes'], $L['No'])),
  "FAQEDIT_FORM_HASCHILDS" => ($haschilds > 0 ? $haschilds : 0),
));

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

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

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

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