<?php
   @require_once("functions.php");
   require_once('resizer_class.php');
   authenticate();
   $config = getConfig();

   $albumDir = $_GET['album'];
   if ($albumDir == '') {
      die('ERROR: must specify album location');
   }
   preg_match('/(\d*_\d*)_(.*)/', $albumDir, $matches);
   $timestamp = $matches[1];
   $albumDirNoTS = $matches[2];
   $albumPath = 'albums/' . $albumDir;
   if (!file_exists($albumPath)) {
      die('ERROR: directory ' . $albumPath . ' does not exist');
   }
   
   if (isset($_POST['delete'])) {
      if (preg_match("/albums\/.+/", $albumPath)) {
         rmAllDir($albumPath . '/small');
         rmAllDir($albumPath . '/thumbs');
         rmAllDir($albumPath . '/featured');
         rmAllDir($albumPath);
      } else {
         die("ERROR: path to delete '$albumPath' does not seem to represent the location of a an album");
      }
   ?>
		<html>
		   <head>
			  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
			  <title><?php echo $config['galleryName'];?> | delete album</title>
			  <link rel="stylesheet" href="admin.css" type="text/css" />
			  <link rel="stylesheet" href="editalbum.css" type="text/css" />
			  <script type="text/javascript" src="jquery.js"></script>
			  <script type="text/javascript" src="functions.js"></script>
		   </head>
		   <body>
			  <div id="page">
				 <span class="homeLink"><a href="admin.php">&lt;&lt; admin</a></span>
				 <hgroup><h1>Delete album:</h1><h2><?php echo $albumDir;?></h2></hgroup>
				 <div style="height: 30px; margin:10px;">
					<div id="deletemessage" class="updatemessage">Album deleted</div>
					<script type="text/javascript">
					$('#deletemessage').delay(2000).fadeOut(2000)
					</script>
					</div>
				 </div>
		   </body>
		</html>
   <?php
      exit;
   }
   $jsonPath = 'albums/' . $albumDir . '/album.json';
   $updatePerformed = false;
   if (isset($_POST['save'])) {
      $updatePerformed = true;
      $jsonUpdated = array();
      $jsonUpdated['title'] = $_POST['albumname'];
      $jsonUpdated['month'] = $_POST['month'];
      $jsonUpdated['year'] = $_POST['year'];
	  $jsonUpdated['featured'] = null;
	  if (isset($_POST['featured'])) {
         $jsonUpdated['featured'] = $_POST['featured'];
      }
      $jsonUpdated['captions'] = array();

	  // handle any file deletion requests
	  if (isset($_POST['deleteImage'])) {
	     $filesToDelete = $_POST['deleteImage'];
	     foreach ($filesToDelete as $fd) {
	        @unlink('albums/' . $albumDir . '/' . $fd);
	        @unlink('albums/' . $albumDir . '/small/small_' . $fd);
	        @unlink('albums/' . $albumDir . '/thumbs/thumb_' . $fd);
	        @unlink('albums/' . $albumDir . '/featured/featured_' . $fd);
         }
      }
	  
      $files = array();
      foreach (new DirectoryIterator($albumPath) as $file) {
         $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
         if (!$file->isDot() && !$file->isDir() && ($extension == 'jpg' || $extension == 'gif' || $extension == 'png')) {
            $files[] = $file->getFilename();
         }
      }
      foreach ($files as $fileName) {
         $jsonUpdated['captions'][$fileName] = $_POST[preg_replace('/\./', '_', $fileName)];
      }
      $jsonFileName = 'albums/' . $albumDir . '/album.json';
	  writeJSON($jsonFileName, $jsonUpdated);
	  if ($jsonUpdated['featured'] != null) {
         $featuredSourcePath = $albumPath . '/' . $jsonUpdated['featured'];
		 if (file_exists($featuredSourcePath)) {
            $featuredDir = $albumPath . '/featured';
            $featuredResized = $featuredDir . '/featured_' . $jsonUpdated['featured'];
            $resizer = new ImageResizer($featuredSourcePath);
            $resizer->resize(400, 300, 'crop');
            $resizer->saveImage($featuredResized, 100);
         }
      }
	  $postTimestamp = $_POST['timestamp'];
	  if ($postTimestamp != $timestamp) {
	     $newAlbumDir = $postTimestamp . '_' . $albumDirNoTS;
	     if (@rename('albums/' . $albumDir, 'albums/' . $newAlbumDir)) {
	        header('Location: http://' . $_SERVER["SERVER_NAME"] . $_SERVER["SCRIPT_NAME"] . '?album=' . $newAlbumDir);
		    exit;
	     }
      }
   }
?>
<html>
   <head>
      <meta http-equiv="Content-type" content="text/html; charset=utf-8">
      <title><?php echo $config['galleryName'];?> | edit album</title>
      <link rel="stylesheet" href="admin.css" type="text/css" />
      <link rel="stylesheet" href="editalbum.css" type="text/css" />
      <script type="text/javascript" src="jquery.js"></script>
      <script type="text/javascript" src="functions.js"></script>
   </head>
   <body>
      <div id="page">
         <span class="homeLink"><a href="admin.php">&lt;&lt; admin</a></span>
<?php
$albumInfo = readJSON($jsonPath);
$albumName = $albumMonth = $albumYear = $featured = null;
if ($albumInfo) {
   $albumName = $albumInfo['title'];
   $albumMonth = $albumInfo['month'];
   $albumYear = $albumInfo['year'];
   if (isset($albumInfo['featured'])) {
      $featured = $albumInfo['featured'];
	  $featuredPath = 'albums/' . $albumDir . '/featured/featured_' . $featured;
	  if (!file_exists($featuredPath)) {
	     $featured = null;
      }
   }
}
echo "<hgroup><h1>Editing album:</h1><h2>$albumDirNoTS</h2></hgroup>\n";
?>
<form name="edit_album" action="editalbum.php?album=<?php echo $albumDir; ?>" method="post">
<div class="lineInput"><span class="textLabel">Title: </span><input class="textbox" type="text" name="albumname" size="100" value="<?php echo $albumName; ?>"/></div>
<div class="lineInput"><span class="textLabel">Month: </span><input class="textbox" type="text" name="month" value="<?php echo $albumMonth; ?>"/></div>
<div class="lineInput"><span class="textLabel">Year: </span><input class="textbox" type="text" name="year" value="<?php echo $albumYear; ?>"/></div>
<div class="lineInput"><span class="textLabel">Timestamp: </span><input class="textbox" type="text" name="timestamp" value="<?php echo $timestamp; ?>"/></div><span class="textNote">The timestamp determines the order in which your albums will appear in the main albums page.<br/> The timestamp is set by default to the creation time of the album, in the format 'YYYYMMDD_HHMM'.</span>
<div>
<input class="bigbutton" type="submit" name="save" value="Save all changes" onclick="return editAlbum_validate()"/>
<input class="deletebutton" type="submit" name="delete" value="Delete album"
       onclick="return confirm('Are you sure you want to delete the album \'<?php echo $albumDir;?>\' ? This cannot be undone.')"/>
<?php
if ($updatePerformed) {
   echo '<div style="height: 30px; margin:10px;">
            <div id="updatemessage" class="updatemessage">Changes saved</div>
         </div>
         <script type="text/javascript">
            $(\'#updatemessage\').delay(2000).fadeOut(2000)
         </script>
   ';
}
$files = array();
foreach (new DirectoryIterator($albumPath) as $file) {
   $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
   if (!$file->isDot() && !$file->isDir() && ($extension == 'jpg' || $extension == 'gif' || $extension == 'png')) {
      $files[] = $file->getFilename();
   }
}
if (empty($files)) {
   echo '<div class="textNote">There are currently no images in this album.</div>';
} else {
	sort($files);
	echo '<p><div class="featuredHeading">Featured image?</div>' . "\n";
	echo '<div class="deleteHeading">Delete image?</div></p>' . "\n";
	echo '<ul id="captions">' . "\n";
	foreach ($files as $fileName) {
	   if ($featured == null || $featured == "") {
		  $featured = $fileName;  // default to first image
	   }
	   $caption = null;
	   if (isset($albumInfo['captions'][$fileName])) {
		  $caption = $albumInfo['captions'][$fileName];
	   }
	   echo '<li><label for="' . $fileName . '"><span class="';
	   if ($fileName == $featured) {
		  echo 'featuredContainer';
	   } else {
		  echo 'nonFeaturedContainer';
	   }
	   echo '">';
	   echo '<input type="radio" class="featuredRadio" name="featured" id="' . $fileName . '" value="' . $fileName . '"';
	   if ($fileName == $featured) {
		  echo ' checked="checked"';
	   }
	   echo ' onclick="editAlbum_updateRadio()"/>';
	   echo '</span>';
	   echo '</label>';
	   echo '<div class="fileName">' . $fileName . '</div><a target="_blank" href="' . $albumPath . '/small/small_' . $fileName . '">';
	   echo '<img src="' . $albumPath . '/thumbs/thumb_' . $fileName . '"/></a>' . "\n";
	   echo '<textarea rows="10" cols="70" name="' . $fileName . '" class="captiontext">' . htmlspecialchars($caption) . '</textarea>';
	   echo '<input class="deleteCheckbox" type="checkbox" name="deleteImage[]" value="' . $fileName . '"/>';
	   echo '</li>' . "\n";
	}
	echo '</ul>';
}
?>
<input class="bigbutton" type="submit" name="save" value="Save all changes"/>
</form>
</div>
</body>
</html>
