<?php
include 'rb-include.php';
rb_header();

if ($artist) {
	pg_exec($db, "update songs set artist='$artist' where id='$id' and owner='$uid'");
}
if ($title) {
	pg_exec($db, "update songs set title='$title', last_manual_update=current_timestamp where id='$id' and owner='$uid'");
}
if ($lyrics) {
	pg_exec($db, "update songs set lyrics='$lyrics', last_manual_update=current_timestamp where id='$id' and owner='$uid'");
}
if ($license) {
	pg_exec($db, "update songs set license='$license', last_manual_update=current_timestamp where id='$id' and owner='$uid'");
}

if ($artist || $title || $lyrics || $license) {
	echo '<p>Your submission has been saved.  Please return to the <a href="rb-main.php">main menu</a>.</p>', "\n";
	rb_footer();
	exit(0);
}

$songs_res = pg_exec($db, "select artist, title, lyrics, license from songs where id='$id' and owner='$uid'"); // join to also determine artist name
if (pg_numrows($songs_res) == 0) {
	echo '<p>Error: song does not exist</p>', "\n";
} else {
	echo '<p><b>Edit song information:</b></p>', "\n";
	echo '<table>', "\n";
	echo '<form method="post" action="rb-song.php">', "\n";
	echo '<input type="hidden" name="id" value="', $id, '"/>', "\n";
	echo '<tr valign="top"><td align="right"><b>Artist: </b></td><td>';
	echo '<select name="artist">';
	$artists_res = pg_exec($db, "select id, name from artists where owner='$uid'");
	for ($i = 0; $i < pg_numrows($artists_res); $i++) {
		echo '<option';
		if (pg_result($artists_res, $i, 0) == pg_result($songs_res, 0, 0)) {
			echo ' selected';
		}
		echo ' value="', pg_result($artists_res, $i, 0), '">', pg_result($artists_res, $i, 1), '</option>';
	}
	// fixme: option for new artist
	echo '</select>';
	echo '</td></tr>', "\n";
	echo '<tr valign="top"><td align="right"><b>Title: </b></td><td><input size="40" name="title" value="', pg_result($songs_res, 0, 1), '"/></td></tr>', "\n";
	echo '<tr valign="top"><td align="right"><b>Lyrics: </b></td><td><textarea name="lyrics">', pg_result($songs_res, 0, 2), '</textarea></td></tr>', "\n";
	echo '<tr valign="top"><td align="right"><b>License: </b></td><td>', license_summary(pg_result($songs_res, 0, 3)), ' <i>(edit from main page)</i></td></tr>', "\n";
	echo '<tr><td></td><td><input type="submit" value="Save"/></td></tr>', "\n";
	echo '</form>', "\n";
	echo '</table>', "\n";
}
pg_freeresult($songs_res);

rb_footer();
?>
