<?php

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

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

if( isset($_GET['delete'])  && (int)$_GET['delete'] ) {
	check_nonce('delete-type-' . (int)$_GET['delete']);
	if(! $mtdb->query( 'DELETE FROM strip_t WHERE id=' . (int)$_GET['delete'] ) )
	{
		adminlog("Error deleting type ".(int)$_GET['delete'], MTS_TYPE, MTA_DELETE, E_WARNING);
		mtdie("Error on deletion of existing type: " . htmlentities(mysql_error()), 'SQL Error');
	}
	if(! $mtdb->query( 'DELETE FROM meta WHERE type=' . (int)$_GET['delete'] ) )
	{
		adminlog("Error on deletion of type ".(int)$_GET['delete']."'s metadata.", MTS_TYPE, MTA_DELETE, E_WARNING);
		mtdie("Error on deletion of existing type's metadata: " . htmlentities(mysql_error()), 'SQL Error');
	}
	$info.='<p>Deleted type successfully.<p>';
	adminlog("Deleted type ".(int)$_GET['delete'], MTS_TYPE, MTA_DELETE);
}

if( isset($_POST['action']) && $_POST['action'] == 'new_type' ) {
	check_nonce('new-type');
	
	$name = trim($_POST['name']);
	$desc = trim($_POST['description']);
	
	if( check_type_name($name) ) {
		if(! $mtdb->query( sprintf( 'INSERT INTO strip_t(name, description) VALUES("%s", "%s")', mysql_real_escape_string($name), mysql_real_escape_string($desc)) ) )
		{
			adminlog("Error on insertion of new type.", MTS_TYPE, MTA_INSERT, E_WARNING);
			mtdie("Error on insertion of new type: ". htmlentities(mysql_error()), 'SQL Error');
		}
	}
	$info.='<p>New type created successfully.<p>';
	adminlog("Type '".$name."' created successfully.", MTS_TYPE, MTA_ADD);
}

if( isset($_POST['action']) && $_POST['action'] == 'edit_type' ) {
	
	$id = (int)$_POST['type_id'];
	check_nonce("save-type-$id");

	$name = trim($_POST['name']);
	$desc = trim($_POST['description']);
	
	$meta = $_POST['meta'];

	$m_delete = $mtdb->getAll("SELECT meta FROM meta WHERE type = $id");
		
	$m_insert = array();
	
	// Key listed in both Insert and Delete lists, so remove from both == Do Nothing	
	foreach( $m_delete as $k=>$v ) {		
		if( array_key_exists( $v->meta, $meta ) ) {
			unset($m_delete[$k]);
			unset($meta[$v->meta]);
		} else {
			$m_delete[$k] = 'meta=' . (int)$v->meta;
		}		
	}

	// Key listed only in Insert list, make proper format
	foreach( $meta as $k=>$v ) {
		$m_insert[] = "($id," . (int)$k . ')';
	}

	if( check_type_name( $name ) ) {
		if( !$mtdb->query( sprintf( 'UPDATE strip_t SET name = "%s", description = "%s" WHERE id = %s', mysql_real_escape_string($name), mysql_real_escape_string($desc), $id)) )
		{
			adminlog("Error on updating type ".$id, MTS_TYPE, MTA_UPDATE, E_WARNING);
			mtdie("Error on update of existing type: ". htmlentities(mysql_error()), 'SQL Error');
		}
			
		$sql_insert = "INSERT INTO meta (type,meta) VALUES " . implode(',',$m_insert);
		$sql_delete = "DELETE FROM meta WHERE type=$id AND ( " . implode(' OR ',$m_delete) . ' )';

		$mtdb->query('START TRANSACTION');
		
		if( count($m_insert) )
			if(! $mtdb->query( $sql_insert ) )
			{
				adminlog("Error inserting new metatype association data for type ".$id, MTS_TYPE, MTA_INSERT, E_WARNING);
				mtdie("There was an error inserting new metatype association data. Transaction aborted. $sql_insert");
			}
		if( count($m_delete) )
			if(! $mtdb->query( $sql_delete ) )
			{
				adminlog("Error deleting old metatype association data for type ".$id, MTS_TYPE, MTA_REMOVE, E_WARNING);
				mtdie("There was an error deleting old metatype data. Transaction aborted. $sql_delete");
			}
			
		$mtdb->query('COMMIT');
		
	} else {
		$error.='<p>Invalid type name!</p>';
	}
	$info.='<p>Changes to type saved successfully.<p>';
	adminlog("Type ".$id." updated.", MTS_TYPE, MTA_UPDATE);
}

//display all types
$types = $mtdb->getAll("SELECT strip_t.id AS id, strip_t.name AS name, strip_t.description AS description, COUNT(strip.id) AS strips FROM strip_t LEFT JOIN strip ON strip.type = strip_t.id GROUP BY strip_t.id");

adminhead('Types');
adminmenu();

?>

<h2>Type Management</h2>
<p>Make changes to the types which categorize the comics.</p>

<table class="widefat">
	<thead>
	<tr>
	<th scope="col" style="text-align: center;">Type #</th>
	<th scope="col">Name</th>
	<th scope="col">Description</th>
	<th scope="col">Strips</th>
	<th scope="col">Metatypes</th>
	<th scope="col"></th>
	<th scope="col"></th>
	</tr>
	</thead>

	<tbody id="the-list">
	<?php
	$alternate=false;
	foreach( $types as $s ) {
		$alternate=!$alternate;
		
		$metas = $mtdb->getAll("SELECT meta_t.name AS name FROM strip_t
			JOIN meta ON meta.type = strip_t.id JOIN meta_t ON meta.meta = meta_t.id
			WHERE strip_t.id = $s->id");
			
		$meta = implode(', ',  array_map('_getMetaNameFromObject', $metas) );
		
		?>
		<tr id="comic-<?php echo $s->id; ?>" <?php if($alternate) echo 'class="alternate"'; ?>>
		 <th scope="row" style="text-align: center;"><?php echo $s->id; ?></th>
		 <td><?php echo htmlentities($s->name); ?></td>
		 <td><?php echo htmlentities($s->description); ?></td>
		 <td><?php echo $s->strips ?></td>
		 <td><?php echo htmlentities($meta); ?> </td>
		 <td style="text-align: center;"><a href="edit-type.php?edit=<?php echo (int)$s->id; ?>">Edit</a></td>
		 <td style="text-align: center;"><a class="delete" href="?delete=<?php echo (int)$s->id; ?>">Delete</a></td>
		</tr>
		<?php
	}
	?>
	</tbody>
</table>


<form enctype="multipart/form-data" name="create-user" id="create-user" action="manage-types.php" method="post">
<?php nonce_field('new-type'); ?>
<input type="hidden" name="action" value="new_type" />

<h2>Create New Type</h2>
<div class="narrow">
	<table class="editform" width="100%" cellspacing="2" cellpadding="5">
	<tr>
	<th scope="row" width="33%">Name</th>
	<td width="66%"><input name="name" type="text" id="name" value="" /></td>
	</tr>
	<tr>
	<th scope="row" width="33%">Description</th>
	<td width="66%"><input name="description" type="text" id="description" value="" /></td>
	</tr>
	</table>
	
	<p class="submit"><input type="submit" value="Create &raquo;" name="submit" /></p>
</div>
</form>

<?php
adminfooter();
?>
