<?php
	chdir('../..');
	require_once('api/Simpla.php');
	$simpla = new Simpla();
	$limit = 100;
	
	$keyword = $simpla->request->get('query', 'string');
	
	$simpla->db->query('SELECT id, name, marka_id FROM __model
	                    WHERE name LIKE "%'.mysql_real_escape_string($keyword).'%" ORDER BY name LIMIT ?', $limit);
	$products = $simpla->db->results();

	foreach($products as $product)
	{
		$marka = $simpla->model->getMarka($product->marka_id);
		$product->name = $marka ? $marka->name . ' - ' . $product->name : $product->name;
	    //$products_names[] = $product->name;	
				
		$products_data[] = $product;
	}

	usort($products_data, 'sortNamesUsort');
	
	$products_names = array();
	foreach($products_data as $row) $products_names[] = $row->name;
	

	$res->query = $keyword;
	$res->suggestions = $products_names;
	$res->data = $products_data;
	header("Content-type: application/json; charset=UTF-8");
	header("Cache-Control: must-revalidate");
	header("Pragma: no-cache");
	header("Expires: -1");
	echo json_encode($res);
	
	
function sortNamesUsort($a, $b){
	if($a->name < $b->name) return -1;
	return $a->name > $b->name ? 1 : 0;
}