<?php

/*

CREATE TABLE artists (
        id SERIAL PRIMARY KEY,
	url TEXT UNIQUE,
	name TEXT,
	website TEXT
);
CREATE INDEX artists_url_index ON artists (url);

CREATE TABLE songs (
        id SERIAL PRIMARY KEY,
	url TEXT UNIQUE,
	name TEXT,
	artist INT REFERENCES artists
);
CREATE INDEX songs_url_index ON songs (url);

CREATE TABLE albums (
        id SERIAL PRIMARY KEY,
	url TEXT UNIQUE,
	name TEXT
);
CREATE INDEX albums_url_index ON albums (url);

CREATE TABLE base_urls (
        url TEXT PRIMARY KEY,
	last_update TIMESTAMP DEFAULT '-infinity',
	last_attempt TIMESTAMP DEFAULT '-infinity'
);
CREATE INDEX last_update_index ON base_urls (last_update);
CREATE INDEX last_attempt_index ON base_urls (last_attempt);

CREATE TABLE recommend_counter (
	count INT
);

*/

$search_db = pg_pconnect('localhost', '', '', '', 'gnomoradio-search');

$stipulations = '';
if ($q) {
	$terms = split('[^A-Za-z0-9]', $q);
	for ($i = 0; $i < count($terms) && $i < 5; $i++) {
		if ($stipulations) {
			$stipulations .= ' UNION ';
		}
		$terms[$i] = strtolower($terms[$i]);
		$stipulations .= "(select songs.name, songs.url, artists.name from songs, artists where artists.id = songs.artist and (songs.name ilike '%$terms[$i]%' or artists.name ilike '%$terms[$i]%'))";
	}
}

echo "<results>\n";

if ($stipulations) {
	$result = pg_exec($search_db, $stipulations);
	
	for ($i = 0; $i < pg_numrows($result); ++$i) {
		echo '<song url="', pg_result($result, $i, 1), '">', "\n";
		echo '<title>', pg_result($result, $i, 0), "</title>\n";
		echo '<artist>', pg_result($result, $i, 2), "</artist>\n";
		echo "</song>\n";
	}
	pg_freeresult($result);
}

echo "</results>\n";

?>
