<?php
chdir('../..');
require_once('api/buyers.php');
$buyers = new Buyers();
$limit = 100;

if(!$buyers->managers->access('pages'))
    return false;

$keyword = $buyers->request->get('query');

$keywords = explode(' ', $keyword);
$keyword_sql = '';
foreach($keywords as $keyword)
    $keyword_sql .= $buyers->db->placehold(" AND (name LIKE ?~ OR annotation LIKE ?~)", $keyword, $keyword);

$buyers->db->query("SELECT id, name FROM pages WHERE 1 $keyword_sql ORDER BY name LIMIT ?", $limit);
$pages = $buyers->db->results();

$suggestions = array();
foreach($pages as $page)
{
    $page->image = $buyers->images->no_image;;

    if($images = $buyers->images->get_images(array('relation'=>'pages', 'relation_id'=>$page->id)))
    {
        $image = reset($images);
        $page->image = $buyers->design->resize_modifier($image, 70, 70);
    }

    $suggestion = new stdClass();
    $suggestion->value = $page->name;
    $suggestion->data = $page;
    $suggestions[] = $suggestion;
}

$res = new stdClass;
$res->query = $keyword;
$res->suggestions = $suggestions;
header("Content-type: application/json; charset=UTF-8");
header("Cache-Control: must-revalidate");
header("Pragma: no-cache");
header("Expires: -1");
print json_encode($res);
