<?php

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

require_once cot_incfile('forms');
require_once cot_incfile('extrafields');

// Tables and extras
cot::$db->registerTable('faq');
cot::$db->registerTable('faq_search');

cot_extrafields_register_table('faq');

function cot_generate_faqtags($faq_data, $tag_prefix = '', $textlength = 0, $admin_rights = false, $faqpath_home = false, $emptytitle = '')
{
	global $db, $cot_extrafields, $cfg, $L, $Ls, $R, $db_faq, $usr, $sys, $cot_yesno;

	static $extp_first = null, $extp_main = null;
	static $pag_auth = array();

	if (is_null($extp_first))
	{
		$extp_first = cot_getextplugins('faqtags.first');
		$extp_main = cot_getextplugins('faqtags.main');
	}

	/* === Hook === */
	foreach ($extp_first as $pl)
	{
		include $pl;
	}
	/* ===== */

	if (!is_array($faq_data))
	{
		$sql = $db->query("SELECT * FROM $db_faq WHERE faq_id = '" . (int) $faq_data . "' LIMIT 1");
		$faq_data = $sql->fetch();
	}

	if ($faq_data['faq_id'] > 0 && !empty($faq_data['faq_title']))
	{
		$date_format = 'datetime_medium';

		$temp_array = array(
			'URL' => cot_url('faq', 'article='.$faq_data['faq_id']),
			'ID' => $faq_data['faq_id'],
			'TITLE' => $faq_data['faq_title'],
			'PARENT' => $faq_data['faq_parent'],
			'TEXT' => $faq_data['faq_text'],
      'TEXT_STRING' => $faq_data['faq_text_string'],
			'DATE' => cot_date($date_format, $faq_data['faq_date']),
			'UPDATED' => cot_date($date_format, $faq_data['faq_updated']),
			'DATE_STAMP' => $faq_data['faq_date'],
			'UPDATED_STAMP' => $faq_data['faq_updated'],
			'ADMIN' => $admin_rights ? 1 : 0,
		);

		// Admin tags
		if ($admin_rights)
		{
  		$edit_url = cot_url('faq', "m=edit&id={$faq_data['faq_id']}");
  		$temp_array['ADMIN_EDIT_URL'] = $edit_url;
		}

		// Extrafields
		if (isset($cot_extrafields[$db_faq]))
		{
			foreach ($cot_extrafields[$db_faq] as $exfld)
			{
				$tag = mb_strtoupper($exfld['field_name']);
				$temp_array[$tag.'_TITLE'] = isset($L['faq_'.$exfld['field_name'].'_title']) ?  $L['faq_'.$exfld['field_name'].'_title'] : $exfld['field_description'];
				$temp_array[$tag] = cot_build_extrafields_data('faq', $exfld, $faq_data['faq_'.$exfld['field_name']], $faq_data['faq_parser']);
				$temp_array[$tag.'_VALUE'] = $faq_data['faq_'.$exfld['field_name']];
			}
		}

		/* === Hook === */
		foreach ($extp_main as $pl)
		{
			include $pl;
		}
		/* ===== */

	}
	else
	{
		$temp_array = array(
			'TITLE' => (!empty($emptytitle)) ? $emptytitle : $L['Deleted'],
			'SHORTTITLE' => (!empty($emptytitle)) ? $emptytitle : $L['Deleted'],
		);
	}

	$return_array = array();
	foreach ($temp_array as $key => $val)
	{
		$return_array[$tag_prefix . $key] = $val;
	}

	return $return_array;
}

function cot_faq_render($id = 0, $html = false) {
  global $db, $db_faq, $sys, $moderauth;

  $return = array(
    'arr' => array(),
    'cnt' => 0,
    'html' => '',
    'ids' => array()
  );

  if($id > 0) {
    $sql_faq = $db->query("SELECT *
      	FROM $db_faq
      	WHERE faq_parent=".$id."
      		ORDER BY faq_updated")->fetchAll();
  } else {
    $sql_faq = $db->query("SELECT f.*
    	FROM $db_faq as f
      LEFT JOIN (SELECT faq_parent, COUNT(*) AS cnt
         FROM $db_faq
         GROUP BY faq_parent
       ) as f2 ON (f2.faq_parent=f.faq_id)
    	WHERE f.faq_parent=".$id."
    		ORDER BY f2.cnt DESC")->fetchAll();
  }

  if($html) {
    $t1 = new XTemplate(cot_tplfile('faq.admin.row', 'module', true));

    foreach ($sql_faq as $row)
    {
      $return['ids'][] = $row['faq_id'];

    	$t1->assign(cot_generate_faqtags($row, 'ADMIN_FAQ_', 200, in_array('faq', $moderauth)));

      $render = cot_faq_render($row['faq_id'], true);

    	$t1->assign(array(
    		'ADMIN_FAQ_RENDER_CHILDRENS' => $render['html'],
        'ADMIN_FAQ_RENDER_CNT' => $render['cnt']
    	));

    	$t1->parse('MAIN.FAQ_ROW');
      $return['cnt']++;
    }

    $t1->parse('MAIN');
    $return['html'] = $t1->text('MAIN');
  } else {
    foreach ($sql_faq as $row)
    {
      $render = cot_faq_render($row['faq_id'], false);
      $row['render'] = $render;

      $return['ids'][] = $row['faq_id'];
      $return['arr'][] = $row;
      $return['cnt']++;
    }
  }

  return $return;
}

function cot_faq_article($arr = array(), $lvl = 1, $path = array(), $parent = array()) {
  $article = array(
    'id' => 0,
    'parent_id' => null,
    'parent' => null,
    'question' => '',
    'answer' => '',
    'answer_formatted' => '',
    'lang' => 'ru',
    'path' => array(),
    'has_childs' => array(),
    'order' => array(),
    'created_at' => '',
    'updated_at' => '',
    'icon' => '',
    'icon_hover' => '',
    'parent' => '',
  );

  if($arr['faq_id'] > 0) {
    $article['id'] = $arr['faq_id'];
    $article['question'] = $arr['faq_title'];
    $article['parent_id'] = ($arr['faq_parent'] > 0 ? $arr['faq_parent'] : null);

    $article['created_at'] = cot_date('Y-m-d H:i:s', $arr['faq_date']);
    $article['updated_at'] = cot_date('Y-m-d H:i:s', $arr['faq_updated']+1);

    if($arr['render']['cnt'] > 0) {
      $article['has_childs'] = array(5);
    } else {
      $article['answer'] = $arr['faq_text_string'];
      $article['answer_formatted'] = $arr['faq_text'];
    }

    if($lvl == 1) {
      $article['icon'] = $arr['faq_id'].'.png';
      $article['icon_hover'] = $arr['faq_id'].'_hover.png';

      $path = array();
    } else {
      if(count($parent) > 0) {
        unset($parent['parent']); // magic
        unset($parent['rules']); // magic
        $article['parent'] = $parent;
      }
    }
    $article['path'] = $path;
  }

  return $article;
}

function cot_faq_postrender($render = array(), $return = array(), $lvl = 1, $path = array(), $parent = array()) {

  $article = array();
  if($render['cnt'] > 0) {
    foreach($render['arr'] as $arr) {
      $article = cot_faq_article($arr, $lvl, $path, $parent);

      if($lvl == 1) {
        $path = array();
      } else {
        if(count($parent) > 0) {
          unset($parent['parent']); // magic
          unset($parent['rules']); // magic
        }
      }

      $return[] = $article;

      if($arr['render']['cnt'] > 0) {
        $path[] = $arr['faq_id'];

        $return = cot_faq_postrender($arr['render'], $return, $lvl+1, $path, $article);
      }
    }
  }

  return $return;
}

function cot_faq_article_path($parent = 0) {
  global $db, $db_faq, $sys;

  $return = array();

  while($parent > 0) {
    $parent = $db->query("SELECT faq_parent
      	FROM $db_faq
      	WHERE faq_id=".$parent." LIMIT 1")->fetchColumn();
    if($parent > 0) {
      $return[] = $parent;
    }
  }

  return array_reverse($return);
}

/**
 * Imports faq data from request parameters.
 * @param  string $source Source request method for parameters
 * @param  array  $rfaq  Existing faq data from database
 * @param  array  $auth   Permissions array
 * @return array          faq data
 */
function cot_faq_import($source = 'POST', $rfaq = array(), $auth = array())
{
	global $cfg, $db_faq, $cot_extrafields, $usr, $sys;

	if ($source == 'D' || $source == 'DIRECT')
	{
		// A trick so we don't have to affect every line below
		global $_PATCH;
		$_PATCH = $rfaq;
		$source = 'PATCH';
	}

	$rfaq['faq_parent']      = cot_import('rfaqparent', $source, 'TXT');
	$rfaq['faq_title']       = cot_import('rfaqtitle', $source, 'TXT');
	$rfaq['faq_text']        = cot_import('rfaqtext', $source, 'HTM');
  $rfaq['faq_text_string'] = cot_import('rfaqtextstring', $source, 'TXT');

	$rfaq['faq_updated']  = $sys['now'];

	// Extra fields
	foreach ($cot_extrafields[$db_faq] as $exfld)
	{
		$rfaq['faq_'.$exfld['field_name']] = cot_import_extrafields('rfaq'.$exfld['field_name'], $exfld, $source, $rfaq['faq_'.$exfld['field_name']]);
	}

	return $rfaq;
}

/**
 * Validates faq data.
 * @param  array   $rfaq Imported faq data
 * @return boolean        TRUE if validation is passed or FALSE if errors were found
 */
function cot_faq_validate($rfaq)
{
	global $cfg;
	cot_check(mb_strlen($rfaq['faq_title']) < 2, 'Укажите вопрос', 'rfaqtitle');
  //cot_check(empty($rfaq['faq_text']), 'Укажите текст ответа', 'rfaqtext');

	return !cot_error_found();
}

/**
 * Adds a new faq to the CMS.
 * @param  array   $rfaq faq data
 * @param  array   $auth  Permissions array
 * @return integer        New faq ID or FALSE on error
 */
function cot_faq_add(&$rfaq, $auth = array())
{
	global $cache, $cfg, $db, $db_x, $db_faq, $L;
	if (cot_error_found())
	{
		return false;
	}

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

	if ($db->insert($db_faq, $rfaq))
	{
		$id = $db->lastInsertId();

		cot_extrafield_movefiles();
	}
	else
	{
		$id = false;
	}

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

	cot_shield_update(30, "r faq");
	cot_log("Add faq #".$id, 'adm');

	return $id;
}

/**
 * Removes a faq from the CMS.
 * @param  int     $id    faq ID
 * @param  array   $rfaq faq data
 * @return boolean        TRUE on success, FALSE on error
 */
function cot_faq_delete($id, $rfaq = array())
{
	global $db, $db_faq, $cache, $cfg, $cot_extrafields, $L;
	if (!is_numeric($id) || $id <= 0)
	{
		return false;
	}
	$id = (int)$id;
	if (count($rfaq) == 0)
	{
		$rfaq = $db->query("SELECT * FROM $db_faq WHERE faq_id = ?", $id)->fetch();
		if (!$rfaq)
		{
			return false;
		}
	}

	foreach ($cot_extrafields[$db_faq] as $exfld)
	{
		cot_extrafield_unlinkfiles($rfaq['faq_' . $exfld['field_name']], $exfld);
	}

	$db->delete($db_faq, "faq_id = ?", $id);
	cot_log("Deleted faq #" . $id, 'adm');

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

	return true;
}

/**
 * Updates a faq in the CMS.
 * @param  integer $id    faq ID
 * @param  array   $rfaq faq data
 * @param  array   $auth  Permissions array
 * @return boolean        TRUE on success, FALSE on error
 */
function cot_faq_update($id, &$rfaq, $auth = array())
{
	global $cache, $cfg, $db, $db_faq, $L;
	if (cot_error_found())
	{
		return false;
	}

	$row_faq = $db->query("SELECT * FROM $db_faq WHERE faq_id = ?", $id)->fetch();

	if (!$db->update($db_faq, $rfaq, 'faq_id = ?', $id))
	{
		return false;
	}

	cot_extrafield_movefiles();

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

	return true;
}
