<?php
defined('COT_CODE') or die('Wrong URL');

$return['success'] = true;

$a = cot_import('a', 'G', 'TXT');
$query = json_decode(trim(file_get_contents('php://input')),1);
$query = ((is_array($query) && !empty($query['query'])) ? $query['query'] : '');
$query_origin = $query;
$query = $db->prep($query);

$return['data'] = array(
  'suggestions' => array()
);

require_once cot_incfile('faq', 'module');

if($a == 'suggest') {
  if(empty($query)) {
    $search = cot_import('faq-search', 'C', 'TXT');
    $search = (!empty($search) ? json_decode($search, 1) : array());

    foreach($search as $stag) {
      if(!empty($stag)) $return['data']['suggestions'][] = array(
        'suggestion' => $stag,
        'excerpt' => preg_replace("/($query)/iu",'<b>$1</b>', $stag)
      );
    }
  } else {
    if(strlen($query) > 1) {
      $return['data']['suggestions'][] = array(
        'suggestion' => $query,
        'excerpt' => '<b>'.$query.'</b>'
      );

      $limit = 9;

      $showed = array($query);

      $searchrequest = $db->query("SELECT s_query FROM $db_faq_search WHERE s_query!='".implode("' AND s_query!='", $showed)."' AND LOWER(s_query) LIKE '".strtolower($query)."%' ORDER BY s_found DESC, s_request DESC LIMIT ".$limit)->fetchAll(PDO::FETCH_COLUMN);
      foreach($searchrequest as $qry) {
        $return['data']['suggestions'][] = array(
          'suggestion' => $qry,
          'excerpt' => preg_replace("/($query)/iu",'<b>$1</b>', $qry)
        );
        $showed[] = $qry;
        $limit--;
      }

      if($limit > 0) {
        $searchrequest = $db->query("SELECT s_query FROM $db_faq_search WHERE s_query!='".implode("' AND s_query!='", $showed)."' AND LOWER(s_query) LIKE '%".strtolower($query)."%' ORDER BY s_found DESC, s_request DESC LIMIT ".$limit)->fetchAll(PDO::FETCH_COLUMN);
        foreach($searchrequest as $qry) {
          $return['data']['suggestions'][] = array(
            'suggestion' => $qry,
            'excerpt' => preg_replace("/($query)/iu",'<b>$1</b>', $qry)
          );
          $showed[] = $qry;
          $limit--;
        }
      }

    }
  }
} elseif($a == 'clear-history') {
  cot_setcookie('faq-search', '', time()-63072000, $cfg['cookiepath'], $cfg['cookiedomain'], $sys['secure'], true);
} elseif($a == 'search') {
  $return = array(
    'success' => true,
    'data' => array(
      'articles' => array(),
      'total' => 0
    )
  );

  if(!empty($query)) {
    $totalitems = $db->query("SELECT COUNT(*) FROM $db_faq
      WHERE (faq_title LIKE '%".$query."%' OR faq_text LIKE '%".$query."%' OR faq_text_string LIKE '%".$query."%') AND faq_text!=''")->fetchColumn();

    if($totalitems > 0) {
      $maxrowperpage = 10;
      $offset = json_decode(trim(file_get_contents('php://input')),1);
      $offset = ((is_array($offset) && !empty($offset['offset'])) ? $offset['offset'] : '');
      $offset = ($offset > 0 ? $offset : 0);

      $faqs = $db->query("SELECT * FROM $db_faq
        WHERE (faq_title LIKE '%".$query."%' OR faq_text LIKE '%".$query."%' OR faq_text_string LIKE '%".$query."%') AND faq_text!='' ORDER BY faq_updated DESC LIMIT $offset, $maxrowperpage")->fetchAll();

      $return['data']['total'] = $totalitems;

      $article_default = array(
        'answerExcerpt' => '',
        'answerExcerptMobile' => '',
        'questionExcerpt' => '',
        'article' => null,
        'rootArticle' => null,
      );

      foreach($faqs as $faq) {
        $render = cot_faq_render($faq['faq_id'], false);
        $faq['render'] = $render;
        $faq['path'] = cot_faq_article_path($faq['faq_id']);

        $article = $article_default;

        $article['questionExcerpt'] = $faq['faq_title'];

        $article['answerExcerpt'] = cot_string_truncate_seach($faq['faq_text_string'], $query_origin, 100, true, '');

        $article['answerExcerptMobile'] = cot_string_truncate($faq['faq_text_string'], 62);

        $article['article'] = cot_faq_article($faq, count($faq['path'])+1, $faq['path']);
        if($faq['path'][0] > 0) {
          $faq_parent = $db->query("SELECT *
          	FROM $db_faq
          	WHERE faq_id=".$faq['path'][0]." LIMIT 1")->fetch();
          if($faq_parent['faq_id'] > 0) {
            $article['rootArticle'] = cot_faq_article($faq_parent, 1);
          }
        }

        $article['test_path'] = $faq['path'];

        $return['data']['articles'][] = $article;
      }

      $faqsearch = cot_import('faq-search', 'C', 'TXT');
      $faqsearch = (!empty($faqsearch) ? json_decode($faqsearch, 1) : array());
      $faqsearch[] = $query_origin;
      $faqsearch = array_unique($faqsearch);
      cot_setcookie('faq-search', json_encode($faqsearch), time()+63072000, $cfg['cookiepath'], $cfg['cookiedomain'], $sys['secure'], true);

      $lastsearchrequest = $db->query("SELECT s_request FROM $db_faq_search WHERE s_query='".$query."' LIMIT 1")->fetchColumn();
      if($lastsearchrequest > 0) {
        $db->update($db_faq_search, array('s_found' => $totalitems, 's_request' => $lastsearchrequest+1), "s_query='".$query."'");
      } else {
        $db->insert($db_faq_search, array(
          's_query' => $query,
          's_found' => $totalitems,
          's_request' => 1
        ));
      }
    }
  }
}

?>