<?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 = $db->prep($query);

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

if($a == 'suggest') {
  if(empty($query)) {
    $search = cot_import('general-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_market_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_market_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('general-search', '', time()-63072000, $cfg['cookiepath'], $cfg['cookiedomain'], $sys['secure'], true);
}

?>
