<?php

require_once('include/admin.inc.php');

auth_redirect(); // Require logged in user to access this page.


if( isset($_REQUEST['action']) && 'edit_twitter' == $_REQUEST['action']) {
	check_nonce('edit-twitter');
	foreach(array_keys($_REQUEST) as $k) {
		if(0 !== strpos($k, 'id_'))
			continue;

		$id = (int) $_REQUEST[$k];
		$position = (int) $_REQUEST["position_$id"];
		$msg = $_REQUEST["message_$id"];

		if(0 == $id && !empty($msg)) {
			// Add a new preset
			$dbConnection->executeUpdate('INSERT INTO twitter_status (position, message) VALUES (?, ?)', array($position, $msg));
			adminlog("Added new preset: $msg", MTS_TWITTER, MTA_ADD);
		} elseif(empty($msg)) {
			// Delete an existing preset
			$dbConnection->executeUpdate('DELETE FROM twitter_status WHERE id = ?', array($id));
			adminlog("Removed preset: $id", MTS_TWITTER, MTA_ADD);
		} else {
			// Modify an existing preset
			$dbConnection->executeUpdate('UPDATE twitter_status SET position = ?, message = ? WHERE id = ?', array($position, $msg, $id));
		}
	}
}

$statuses = $dbConnection->fetchAll('SELECT id, position, message FROM twitter_status ORDER BY position, id');

adminhead('Manage Twitter Presets');
adminmenu();

?>

<h2>Manage Twitter Presets</h2>
<p>To add a new preset, enter it into the empty box below.</p>
<p>To delete a preset, remove all text from its message box.</p>

<p><a href="post-twitter.php">&lt;- Done</a></p>

<form method="post" action="manage-twitter-presets.php">
<?php nonce_field('edit-twitter'); ?>
<input type="hidden" name="action" value="edit_twitter" />

<table class="widefat">
	<thead>
		<tr>
		<th scope="col" style="width:2em">ID</th>
		<th scope="col" style="width:4em">Order</th>
		<th scope="col">Message</th>
		</tr>
	</thead>
	<tbody id="the-list">
	<?php
	$alternate=false;
	foreach($statuses as $k=>$v) {
		$alternate = !$alternate;
		?>
		<tr <?php if($alternate) echo 'class="alternate"' ?>>
		 <td style="text-align:center"><input type="hidden" name="id_<?php echo $v->id ?>" value="<?php echo $v->id ?>" /><?php echo $v->id ?></td>
		 <td><input type="text" size="3" name="position_<?php echo $v->id ?>" value="<?php echo $v->position ?>" /></td>
		 <td><input type="text" style="width:95%" maxlength="140" name="message_<?php echo $v->id ?>" value="<?php echo $v->message ?>" /></td>
		</tr>
		<?php
	}
	?>
	<tr <?php if(!$alternate) echo 'class="alternate"' ?>>
	 <td style="text-align:center"><input type="hidden" name="id_0" value="0" /></td>
	 <td><input type="text" size="3" name="position_0" value="" /></td>
	 <td><input type="text" style="width:95%" maxlength="140" name="message_0" value="" /></td>
	</tr>
	</tbody>
</table>
<p style="padding-bottom:1em;"><input type="submit" value="Save" /></p>
</form>

<?php
adminfooter();
?>
