<?php

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

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

$strip = new Strip();
$strip->id = (int)$_REQUEST['strip_id'];
$strip = getstrip($strip->id);

if( $_POST ) {

	// Form Elements
	$strip->new_id = (int)$_POST['strip_new_id'] ? (int)$_POST['strip_new_id'] : $strip->id;
	$strip->published = empty($_POST['strip_date']) ? time() : strtotime( $_POST['strip_date'] );
	$strip->type = (int)$_POST['strip_type'];
	$strip->title = trim($_POST['strip_title']);
	$strip->transcript_posted = $_POST['content'];
	$strip->book = trim($_POST['book']);
	$strip->page = trim($_POST['page']);

	if( '' == $strip->title ) mtdie('Strips must be supplied with titles.');

	$YESTERDAY = mktime(0,0,0, date('m'), date('d')-1, date('Y'));

	switch($_POST['action']) {
		case 'new_comic':

			check_nonce('new-strip');

			// Ensure that dates are not in the past
			if( $strip->published < $YESTERDAY )
				mtdie('Strips may not be backdated. Enter a date today or in the future.');

			if( !is_valid_upload('comicFile') )
			{
				adminlog("Image upload failed.", MTS_STRIP, MTA_ADD, E_WARNING);
				mtdie('If you want to upload a new comic, you must provide said comic.', 'Strip upload failed.');
			}

			// get image type and target extension
			$imagedata = getimagesize($_FILES['comicFile']['tmp_name']);
			$strip->media = $imagedata[2];
			$fileext = $dbConnection->fetchColumn('SELECT extension FROM media_t WHERE id = ?', array($strip->media), 0, array(PDO::PARAM_INT));

			if(strlen($fileext) < 3)
			{
				//bad image upload type
				adminlog("Bad image type upload on new strip. Invalid media type.", MTS_STRIP, MTA_ADD, E_ERROR);
				mtdie('Bad image type upload on new strip. Invalid media type.');
			}

			// Insert new strip into the database, get a real $strip->id
			if(!insertstrip( $strip ))
			{
				adminlog("Error on insertion of new strip: ".$dbConnection->errorCode(), MTS_STRIP, MTA_ADD, E_ERROR);
				mtdie('Error on insertion of new strip: '.$dbConnection->errorCode(), 'SQL Error');
			}

			// Store the uploaded file to xxxx-0.ext
			$basefile = $strip->published <= time() ?
			            sprintf(SITE_PATH_ABS.'/'.SITE_STRIP.'/'.'%04d.%s', $strip->id, $fileext) :
				    sprintf(SITE_PATH_ABS.'/'.SITE_STRIP.'/restricted/'.'%04d.%s', $strip->id, $fileext);
			if(!move_uploaded_file($_FILES['comicFile']['tmp_name'], $basefile))
			{
				adminlog("Filesystem error in storing image.", MTS_STRIP, MTA_ADD, E_ERROR);
				mtdie('There was a problem storing the uploaded strip image. Please <s>harass</s> contact support.','Filesystem Error');
			}

			// Alert Twitter if the strip is for immediate publication
			if( $strip->published <= time() )
				twitterpost("Comic ".$strip->id." posted: ".SITE_HOST.SITE_PATH."/strip/".$strip->id);

			$info.="<p>Comic posted!</p>";
			break;

		case 'edit_comic':
			if( 0 >= $strip->new_id ) mtdie('Strip numbers must be numeric, greater than 0.');
			if( 0 >= $strip->id ) mtdie('Existing strip number, in the form, was zero. This should never happen.');

			// When updating, $strip->id is the old strip number. Update in place first. Possibly adjust strip number later.
			check_nonce('save-strip-'.$strip->id);

			// If uploading, get filetype. If not uploading, filetype got loaded from database earlier.
			if( is_valid_upload('comicFile') ) {
				$imagedata = getimagesize($_FILES['comicFile']['tmp_name']);
				$strip->media = $imagedata[2];
			}
			$fileext = $dbConnection->fetchColumn('SELECT extension FROM media_t WHERE id = ?', array($strip->media), 0, array(PDO::PARAM_INT));

			if(strlen($fileext) < 3)
			{
				//bad image upload type
				adminlog("Bad image type upload on strip ".$strip->id.". Invalid media type.", MTS_STRIP, MTA_UPDATE, E_ERROR);
				mtdie('Bad image type upload on strip '.$strip->id.'. Invalid media type.');
			}

			// Update existing strip
			if(!updatestrip( $strip ) )
			{
				adminlog("Failed to update strip ".$strip->id.".", MTS_STRIP, MTA_UPDATE);
				mtdie('Error updating strip: ' . $dbConnection->errorCode(), 'SQL Error');
			}

			if( is_valid_upload('comicFile') ) {	// If uploading, store the uploaded file to xxxx-n.ext
				$basefile = $strip->published <= time() ?
					    sprintf(SITE_PATH_ABS.'/'.SITE_STRIP.'/'.'%04d.%s', $strip->id, $fileext) :
					    sprintf(SITE_PATH_ABS.'/'.SITE_STRIP.'/restricted/'.'%04d.%s', $strip->id, $fileext);

				if(!move_uploaded_file($_FILES['comicFile']['tmp_name'], $basefile))
				{
					adminlog("Filesystem error in saving image.", MTS_STRIP, MTA_UPDATE, E_ERROR);
					mtdie("There was a problem storing the uploaded strip image. Please <s>harass</s> contact support.", 'Filesystem Error');
				}
				adminlog("Image replaced for comic ".$strip->id.".", MTS_STRIP, MTA_UPDATE);
			}
			// No new file uploaded. Do nuffink.

			// Conditionally broadcast success
			if( $_POST['broadcast'] ) {
				#Limit broadcast message to 60 characters. Compose it now.
				$b_msg = 'Comic ' . $strip->id . ' updated: ' . substr(trim($_REQUEST['broadcast_message']), 0, 60) . ', ' . SITE_HOST . SITE_PATH . "/strip/" . $strip->id;

				rsspost($b_msg, SITE_HOST.SITE_PATH.'/strip/'.$strip->id);
				twitterpost($b_msg);
				$info.="<p>Update broadcasted with message '$b_msg'.</p>";
			}

			$info.="<p>Changes saved. <a href=\"".SITE_HOST.SITE_PATH."/index.php?strip_id=".$strip->id."\">View on site</a>.";
			break;

		default:
			adminlog("User did something strange.", MTS_STRIP, MTA_MODIFY);
			mtdie('You know, it would be <em>really</em> nice if you avoided nonsensical actions.');
	}

	$info = savetranscript($strip) . $info;

	# If the strip number changed, swap strips sequentially to shuffle it into place
	if( $strip->id != $strip->new_id ) {
		$f = fopen(SITE_PATH_ABS.'/'.SITE_STRIP.'/'.SITE_STRIP_LOCK, 'w');
		flock($f, LOCK_EX);

		while( $strip->new_id < $strip->id ) {	// Move this strip backward
			swap_strips( $strip->id - 1, $strip->id );
			$strip->id--;
		}
		while( $strip->id < $strip->new_id ) {	// Move this strip forward
			swap_strips( $strip->id + 1, $strip->id );
			$strip->id++;
		}
		$strip->id = $strip->new_id;
		fclose($f);
	}
}

////////////////////// Display Edit Form ////////////////////////
$strip = getstrip($strip->id);
gettranscript($strip);

adminhead('Edit Comic');
adminmenu('manage-comics.php');

?>

<h2>Edit Comic</h2>

<form action="edit-comic.php" method="post" enctype="multipart/form-data" name="post" id="post">
<?php nonce_field('save-strip-'.$strip->id); ?>
<input type="hidden" name="action" value="edit_comic" />
<input type="hidden" name="strip_id" size="40" tabindex="1" value="<?php echo $strip->id; ?>" />
<div id="poststuff">

<div id="moremeta">
<div id="grabit" class="dbx-group">

<fieldset id="slugdiv" class="dbx-box">
<h3 class="dbx-handle">Comic Type</h3>
<div class="dbx-content"><select name="strip_type">
<?php
$types = $dbConnection->fetchAll('SELECT id, description FROM strip_t ORDER BY id');
foreach( $types as $k=>$v )
	printf('<option value="%s" %s>%s</option>', htmlentities($v->id), ($strip->type == $v->id ? 'selected="selected"' : '' ), htmlentities($v->description));

?>
</select></div>
</fieldset>

<fieldset id="pubdatediv" class="dbx-box">
<h3 class="dbx-handle">Post Date</h3>
<div class="dbx-content"> <input type="text" name="strip_date" value="<?php echo htmlentities( date( 'Y-m-d H:i:s', $strip->published )); ?>" /> </div>
</fieldset>

<fieldset id="pubdatediv" class="dbx-box">
<h3 class="dbx-handle">Strip Number</h3>
<div class="dbx-content"> <input type="text" name="strip_new_id" size="6" value="<?php echo $strip->id; ?>" id="strip_id" /> </div>
</fieldset>

<fieldset id="stripdiv" class="dbx-box">
<h3 class="dbx-handle">Replace Comic</h3>
<div class="dbx-content"> <input type="hidden" name="MAX_FILE_SIZE" value="10000000" /><input name="comicFile" type="file" tabindex="2" size="12"/> </div>
</fieldset>

<fieldset id="broadcastdiv" class="dbx-box">
<h3 class="dbx-handle">Broadcast Update</h3>
<div class="dbx-content">
	<label><input type="radio" name="broadcast" value="0" checked="checked" />No</label>
	<label><input type="radio" name="broadcast" value="1" />Yes</label>
	<input type="text" name="broadcast_message" maxlength="60" size="15" />
</div>
</fieldset>

<?php
$file = get_stripimage_filename( $strip );
if( file_exists( SITE_PATH_ABS.'/'.$file ) ){
	?>
		<fieldset id="pubdatediv" class="dbx-box">
		<h3 class="dbx-handle">Strip</h3>
		<div class="dbx-content"> <a target="_new" href="<?php echo SITE_HOST.SITE_PATH; ?>/index.php?strip_id=<?php echo $strip->id;
			?>"><img src="<?php echo SITE_HOST.SITE_PATH.'/'.$file; ?>" width="170" /></a> </div>
		</fieldset>
	<?php
}
?>

<fieldset id="bookpagenumberdiv" class="dbx-box">
	<h3 class="dbx-handle">Book Page Number</h3>
	<div class="dbx-content"> <input type="text" name="book" size="3" value="<?php echo $strip->book; ?>" />-<input type="text" name="page" size="4" value="<?php echo $strip->page; ?>" /></div>
</fieldset>
</div>
</div>

<fieldset id="titlediv">
	<legend>Title</legend>
	<div><input type="text" name="strip_title" size="40" tabindex="1" value="<?php echo numeric_entities(utfentities($strip->title)) ?>" id="title" /></div>
</fieldset>

<fieldset id="postdivrich">
	<legend>Transcript</legend>
	<style type="text/css">
		#postdivrich table, #postdivrich #quicktags {border-top: none;}
		#quicktags {border-bottom: none; padding-bottom: 2px; margin-bottom: -1px;}
		#edButtons {border-bottom: 1px solid #ccc;}
	</style>
	<div><textarea class="mceEditor" rows="27" cols="40" name="content" tabindex="3" id="content"><?php	echo htmlentities($strip->transcript, ENT_COMPAT, 'UTF-8'); ?></textarea></div>
</fieldset>

<p class="submit">
 <input name="edit_comic" type="submit" id="edit_comic" tabindex="4" accesskey="s" value="Save Changes" />
</p>

</div>
</form>

<?php
adminfooter();
?>
