<?php

class SearchController {
	static public function api_title_search() {
		$out = new Collection;

		$q = DB::getInstance()->query("
			select 
				id, internal_id, title, subtitle, subsubtitle,
				match (internal_id, title, subtitle, subsubtitle, overview)
				against (:search in boolean mode)
				as rel
			from 
				document
			where 
				match (internal_id, title, subtitle, subsubtitle, overview) 
				against (:search in boolean mode)
			order by
				rel desc
			limit
				10
		", ["search" => $_POST['search']]);
		while ($r = DB::getInstance()->nextRecord($q)) {
			$o = new Document($r->id);
			$out->push($o);
		}
		return $out;
	}

	static public function search($page = 0) {
		if (array_key_exists("search", $_POST)) {
			$q = DB::getInstance()->query("
				select
					revision.id as id,
					match(ocr.body) against (:search) as relevance
				from
					revision,ocr
				where
					match(ocr.body) against (:search) and
					ocr.revision = revision.id and
					not revision.document is null
				order by
					relevance desc
	
				", ["search" => $_POST['search']]);
	
			$slog = [];
	
			while ($r = DB::getInstance()->nextRecord($q)) {
				$slog[] = $r->id;
			}

			Session::set("search", json_encode($slog));
		}

		$rpp = 8;

		$offset = $page * $rpp;

		$out = [];

		$slog = json_decode(Session::get("search"));

		for ($i = 0; $i < $rpp; $i++) {
			if ($offset + $i < count($slog)) {
				$rev = new Revision($slog[$offset + $i]);
				if ($rev) {
					$out[] = $rev;
				}
			}
		}

		return blade("search", ["page" => $page, "count" => count($slog), "results" => $out, "pages" => ceil(count($slog) / $rpp)]);
	}
}

