<?php

include '../php/classes/page.php';
include 'functions/func_file.php';
include 'functions/func_xml.php';
$page = new Page();
$page->init_user();

# make sure the user is logged in before he has access to the
# admin section
if(!$page->user()->check_role('admin'))
{
	$page->addMessage('You must login to use the administrator pages.');
	$page->display('menu',false);
	$page->content('admin/login.php');
}
else
{
	# get the page element parameter that we want to edit
	# if it doesn't exist, we just display the list of options
	# below
	$what_to_edit = isset($_REQUEST['what']) ? $_REQUEST['what'] : null;

	# gather the appropriate data to send to the template
	# and show the right template based on what page data we're editing
	switch($what_to_edit)
	{
		case 'articles':
			work_articles();
			break;
		case 'books':
			work_books();
			break;
		case 'onleadership':
			work_onleadership();
			break;
		case 'teachingoutlines':
			work_teachingoutlines();
			break;
		case 'toolsforministry':
			work_toolsfor('ministry');
			break;
		case 'toolsforpersonal':
			work_toolsfor('personal');
			break;
		default:
			$page->content('admin/resources.php');
	}
}

$page->attr('title','Discipling the Nations: Administrator Area: Resources');
$page->menu('admin/menu.php');
$page->addCSSFile('admin.css');

$page->process();

###################################################### FUNCTION: work_articles #
function work_articles()
{
	global $DOCROOT, $page;
	$file_path = $DOCROOT.'/site/data/resources/articles.xml';
	$articles = xml_get_from_file($file_path);
	
	# get commands from get, if there is nothing there, get
	# them from the post
	$do = isset($_REQUEST['do']) ? $_REQUEST['do'] : null;
	$which = isset($_REQUEST['which']) ? $_REQUEST['which'] : null;
	
	# add, edit and delete just display a form or other template page
	# so we can just lump them all together here
	if($do == 'add' || $do == 'edit' || $do == 'delete')
	{
		# if we are editing or deleting, the template needs the article data
		if($do != 'add')
		{
			$c = 0;
			while(($articles->article[$c]['id'] != $_GET['which'])
							&& isset($articles->article[$c]))
				$c++;
			$page->data('article',$articles->article[$c]);
		}
		$page->content('admin/resources/articles/'.$do.'.php');
	}
	# add the article and return to the list
	else if($do == 'doadd')
	{
		# make sure the file gets uploaded and moved correctly
		if($new_link = file_process_upload('file',$DOCROOT.'/site/data/resources/articles'))
		{
			# get the last id from the file
			$last_id = $articles->article[count($articles->article) - 1]['id'];
					
			$new_title = isset($_POST['title']) ? $_POST['title'] : $_FILES['file']['name'];
			$new_article = $articles->addChild('article');
			$new_article->addChild('title',$new_title);
			$new_article->addChild('link',$new_link);
			$new_article->addAttribute('id',$last_id + 1);
			
			file_put_contents($file_path,$articles->asXML());
			
			$page->addMessage('Article successfully added.');
			$page->data('articles',$articles);
			$page->content('admin/resources/articles/list.php');
		}
		else
		{
			$page->addError('An error occurred while uploading the file.  Please try again.');
			$page->content('admin/resources/articles/add.php');
		}
	}	
	# edit the article and return to the list
	else if($do == 'doedit')
	{
		# find the article with the right id
		$c = 0;
		while(isset($articles->article[$c])
						&& ($articles->article[$c]['id'] != $_POST['which']))
			$c++;
			
		# if a new file is specified then delete the old one and replace
		# the new one
		if($_FILES['file']['name'] !== '')
		{
			# delete old file
			unlink($DOCROOT.'/site/data/resources/articles/'.$articles->article[$c]->link);
			# try to upload the new file
			if($new_link = file_process_upload('file',$DOCROOT.'/site/data/resources/articles'))
			{
				$articles->article[$c]->title = isset($_POST['title']) ? $_POST['title'] : $_FILES['file']['name'];
				$articles->article[$c]->link = $new_link;
				
				file_put_contents($file_path,$articles->asXML());
				$page->addMessage('Article successfully edited.');
				$page->data('articles',$articles);
				$page->content('admin/resources/articles/list.php');
			}
			else
			{
				$page->addError('An error occurred while uploading the file.  Please try again.');
				$page->content('admin/resources/articles/edit.php');
			}			
		}
		# if no new file is uploaded
		else
		{
			if($_POST['title'] !== '')
				$articles->article[$c]->title = $_POST['title'];
				
			file_put_contents($file_path,$articles->asXML());
			$page->addMessage('Article successfully edited.');
			$page->data('articles',$articles);
			$page->content('admin/resources/articles/list.php');
		}
	}
	# perform the deletion of the specified article
	else if($do == 'dodelete')
	{
		# find the article with the right id
		$c = 0;
		while(($articles->article[$c]['id'] != $_POST['which'])
						&& isset($articles->article[$c]))
			$c++;
			
		$file_name = $DOCROOT.'/site/data/resources/articles/'.$articles->article[$c]->link;
		if(unlink($file_name))
		{
			unset($articles->article[$c]);
			file_put_contents($file_path,$articles->asXML());
			$page->addMessage('Article successfully deleted.');
		}
		else
		{
			$page->addError('Could not delete article.');
		}
		$page->data('articles',$articles);	
		$page->content('admin/resources/articles/list.php');
	}
	# display the list of articles
	else
	{
		$page->data('articles',$articles);
		$page->content('admin/resources/articles/list.php');
	}
}
######################################################### FUNCTION: work_books #
function work_books()
{
	global $DOCROOT, $page;
	$file_path = $DOCROOT.'/site/data/resources/books.xml';
	$categories = xml_get_from_file($file_path);

	# get commands from get, if there is nothing there, get
	# them from the post
	$do = isset($_REQUEST['do']) ? $_REQUEST['do'] : null;
	$which = isset($_REQUEST['which']) ? $_REQUEST['which'] : null;

	# take the appropriate action according to what we are "doing"
	if($do == 'addcat')
		$page->content('admin/resources/books/addcat.php');
	else if($do == 'addfile')
	{
		$page->data('categories',$categories);
		$page->content('admin/resources/books/addfile.php');
	}
	else if($do == 'deletecat' || $do == 'editcat')
	{
		$c = 0;
		while(($categories->category[$c]['id'] != $_GET['which'])
						&& isset($categories->category[$c]))
			$c++;
			
		$page->data('category',$categories->category[$c]);
		$page->content('admin/resources/books/'.$do.'.php');
	}
	else if($do == 'deletefile')
	{
		$c = 0;
		while(($categories->category[$c]['id'] != $_GET['cat'])
						&& isset($categories->category[$c]))
			$c++;
			
		$page->data('category',$categories->category[$c]);
		$page->data('file',$_GET['which']);
		$page->content('admin/resources/books/deletefile.php');
	}
	# add the category and return to the list
	else if($do == 'doaddcat')
	{
		$last_id = $categories->category[count($categories->category) - 1]['id'];
		$new_cat = $categories->addChild('category');
		$new_cat->addAttribute('id',$last_id + 1);
		$new_cat->addChild('name',$_POST['name']);
		
		if(file_put_contents($file_path,$categories->asXML()))
		{
			$page->addMessage('Category added successfully.');
			$page->data('categories',$categories);
			$page->content('admin/resources/books/list.php');
		}
		else
		{
			$page->addError('Could not add category.');
			$page->content('admin/resources/books/addcat.php');
		}
	}
	else if($do == 'doaddfile')
	{	
		# make sure the file gets uploaded and moved correctly
		if($new_link = file_process_upload('file',$DOCROOT.'/site/data/resources/books'))
		{
			$c = 0;
			while(($categories->category[$c]['id'] != $_POST['which'])
							&& isset($categories->category[$c]))
				$c++;
			
			$new_file = $categories->category[$c]->addChild('file',$new_link);

			if(file_put_contents($file_path,$categories->asXML()))
			{
				$page->addMessage('File successfully added.');
				$page->content('admin/resources/books/list.php');
			}
		}
		else
		{
			$page->addError('An error occurred while uploading the file.  Please try again.');
			$page->content('admin/resources/books/addfile.php');
		}
		$page->data('categories',$categories);
	}	
	# edit the article and return to the list
	else if($do == 'doeditcat')
	{
		# find the article with the right id
		$c = 0;
		while(($categories->category[$c]['id'] != $_POST['which'])
						&& isset($categories->category[$c]))
			$c++;

		if(empty($_POST['name']))
		{
			$page->addError('You cannot leave the category name blank.');
			$page->data('category',$categories->category[$c]);
			$page->content('admin/books/deletecat.php');
		}
		else
		{
			$categories->category[$c]->name = $_POST['name'];
			
			file_put_contents($file_path,$categories->asXML());
			
			$page->addMessage('Category successfully updated.');
			$page->data('categories',$categories);
			$page->content('admin/resources/books/list.php');
		}
	}
	# perform the deletion of a file from a category
	else if($do == 'dodeletefile')
	{
		# find the category with the right id
		$c = 0;
		while(($categories->category[$c]['id'] != $_POST['cat'])
						&& isset($categories->category[$c]))
			$c++;
			
		# if we can unlink the file
		if(unlink($DOCROOT.'/site/data/resources/books/'.$_POST['which']))
		{
			# find the file in the category and delete it
			$k = 0;
			while(($categories->category[$c]->file[$k] != $_POST['which'])
							&& isset($categories->category[$c]->file[$k]))
				$k++;
			
			# make sure we only delete the file if it's found
			if($categories->category[$c]->file[$k] == $_POST['which'])
				unset($categories->category[$c]->file[$k]);
			
			file_put_contents($file_path,$categories->asXML());
			$page->addMessage('File successfully deleted.');
		}
		else
			$page->addError('Could not delete file.');
		
		$page->data('categories',$categories);
		$page->content('admin/resources/books/list.php');
	}
	# perform the deletion of the specified article
	else if($do == 'dodeletecat')
	{
		# find the category with the right id
		$c = 0;
		while(($categories->category[$c]['id'] != $_POST['which'])
						&& isset($categories->category[$c]))
			$c++;

		# delete each of the files in this category
		foreach($categories->category[$c]->file as $file)
		{
			if(!unlink($DOCROOT.'/site/data/resources/books/'.$file))
				$page->addError('File could not be deleted: '.$file);
		}
		# if we can successfully unset the category, then print a success message
		unset($categories->category[$c]);
		if(!isset($categories->category[$c]))
		{
			$page->addMessage('Category successfully deleted.');
			file_put_contents($file_path,$categories->asXML());
		}
		else
		{
			$page->addError('Could not delete this category.');
		}	
		$page->data('categories',$categories);
		$page->content('admin/resources/books/list.php');
	}
	# display the list of book categories
	else
	{
		$page->data('categories',$categories);
		$page->content('admin/resources/books/list.php');
	}
}
################################################## FUNCTION: work_onleadership #
function work_onleadership()
{
	global $DOCROOT, $page;
	$file_path = $DOCROOT.'/site/data/resources/onleadership.xml';
	$files = xml_get_from_file($file_path);
	
	# get commands from get, if there is nothing there, get
	# them from the post
	$do = isset($_REQUEST['do']) ? $_REQUEST['do'] : null;
	$which = isset($_REQUEST['which']) ? $_REQUEST['which'] : null;
	
	# add, edit and delete just display a form or other template page
	# so we can just lump them all together here
	if($do == 'add' || $do == 'delete')
	{
		# if we are deleting, the template needs the file data
		if($do != 'add')
		{
			$c = 0;
			while(($files->file[$c]['id'] != $_GET['which'])
							&& isset($files->file[$c]))
				$c++;
			$page->data('file',$files->file[$c]);
		}
		$page->content('admin/resources/onleadership/'.$do.'.php');
	}
	# add the file and return to the list
	else if($do == 'doadd')
	{
		# make sure the file gets uploaded and moved correctly
		if($new_link = file_process_upload('file',$DOCROOT.'/site/data/resources/onleadership'))
		{
			# get the last id from the file
			$last_id = $files->file[count($files->file) - 1]['id'];
				
			$new_file = $files->addChild('file',$new_link);
			$new_file->addAttribute('id',$last_id + 1);
			
			file_put_contents($file_path,$files->asXML());
			
			$page->addMessage('File successfully added.');
			$page->data('files',$files);
			$page->content('admin/resources/onleadership/list.php');
		}
		else
		{
			$page->addError('An error occurred while uploading the file.  Please try again.');
			$page->content('admin/resources/onleadership/add.php');
		}
	}	
	# perform the deletion of the specified file
	else if($do == 'dodelete')
	{
		# find the file with the right id
		$c = 0;
		while(($files->file[$c]['id'] != $_POST['which'])
						&& isset($files->file[$c]))
			$c++;
			
		$file_name = $DOCROOT.'/site/data/resources/onleadership/'.$files->file[$c];
		if(unlink($file_name))
		{
			unset($files->file[$c]);
			file_put_contents($file_path,$files->asXML());
			$page->addMessage('File successfully deleted.');
		}
		else
		{
			$page->addError('Could not delete file.');
		}
		$page->data('files',$files);	
		$page->content('admin/resources/onleadership/list.php');
	}
	# display the list of files
	else
	{
		$page->data('files',$files);
		$page->content('admin/resources/onleadership/list.php');
	}
}
############################################## FUNCTION: work_teachingoutlines #
function work_teachingoutlines()
{
	global $DOCROOT, $page;
	$file_path = $DOCROOT.'/site/data/resources/teachingoutlines.xml';
	$files = xml_get_from_file($file_path);

	# get commands from get, if there is nothing there, get
	# them from the post
	$do = isset($_REQUEST['do']) ? $_REQUEST['do'] : null;
	$which = isset($_REQUEST['which']) ? $_REQUEST['which'] : null;

	# add, edit and delete just display a form or other template page
	# so we can just lump them all together here
	if($do == 'add' || $do == 'delete')
	{
		# if we are deleting, the template needs the file data
		if($do != 'add')
		{
			$c = 0;
			while(($files->file[$c]['id'] != $_GET['which'])
							&& isset($files->file[$c]))
				$c++;
			$page->data('file',$files->file[$c]);
		}
		$page->content('admin/resources/teachingoutlines/'.$do.'.php');
	}
	# add the file and return to the list
	else if($do == 'doadd')
	{
		# make sure the file gets uploaded and moved correctly
		if($new_link = file_process_upload('file',$DOCROOT.'/site/data/resources/teachingoutlines'))
		{
			# get the last id from the file
			$last_id = $files->file[count($files->file) - 1]['id'];

			$new_file = $files->addChild('file',$new_link);
			$new_file->addAttribute('id',$last_id + 1);

			file_put_contents($file_path,$files->asXML());

			$page->addMessage('File successfully added.');
			$page->data('files',$files);
			$page->content('admin/resources/teachingoutlines/list.php');
		}
		else
		{
			$page->addError('An error occurred while uploading the file.  Please try again.');
			$page->content('admin/resources/teachingoutlines/add.php');
		}
	}	
	# perform the deletion of the specified file
	else if($do == 'dodelete')
	{
		# find the file with the right id
		$c = 0;
		while(($files->file[$c]['id'] != $_POST['which'])
						&& isset($files->file[$c]))
			$c++;

		$file_name = $DOCROOT.'/site/data/resources/teachingoutlines/'.$files->file[$c];
		if(unlink($file_name))
		{
			unset($files->file[$c]);
			file_put_contents($file_path,$files->asXML());
			$page->addMessage('File successfully deleted.');
		}
		else
		{
			$page->addError('Could not delete file.');
		}
		$page->data('files',$files);	
		$page->content('admin/resources/teachingoutlines/list.php');
	}
	# display the list of files
	else
	{
		$page->data('files',$files);
		$page->content('admin/resources/teachingoutlines/list.php');
	}
}
###################################################### FUNCTION: work_toolsfor #
function work_toolsfor($type)
{
	global $DOCROOT, $page;
	$file_path = $DOCROOT."/site/data/resources/toolsfor$type.xml";
	$categories = xml_get_from_file($file_path);

	# get commands from get, if there is nothing there, get
	# them from the post
	$do = isset($_REQUEST['do']) ? $_REQUEST['do'] : null;
	$which = isset($_REQUEST['which']) ? $_REQUEST['which'] : null;

	# take the appropriate action according to what we are "doing"
	if($do == 'addcat')
		$page->content("admin/resources/toolsfor$type/addcat.php");
	else if($do == 'addfile')
	{
		$page->data('categories',$categories);
		$page->content("admin/resources/toolsfor$type/addfile.php");
	}
	else if($do == 'deletecat' || $do == 'editcat')
	{
		$c = 0;
		while(($categories->category[$c]['id'] != $_GET['which'])
						&& isset($categories->category[$c]))
			$c++;

		if($do == 'editcat')
			$page->data('categories',$categories);
		$page->data('category',$categories->category[$c]);
		$page->content("admin/resources/toolsfor$type/$do.php");
	}
	else if($do == 'deletefile')
	{
		$c = 0;
		while(($categories->category[$c]['id'] != $_GET['cat'])
						&& isset($categories->category[$c]))
			$c++;

		$page->data('category',$categories->category[$c]);
		$page->data('file',$_GET['which']);
		$page->content("admin/resources/toolsfor$type/deletefile.php");
	}
	# add the category and return to the list
	else if($do == 'doaddcat')
	{
		$last_id = $categories->category[count($categories->category) - 1]['id'];
		$new_cat = $categories->addChild('category');
		$new_cat->addAttribute('id',$last_id + 1);
		$new_cat->addChild('name',$_POST['name']);
		$new_cat->addChild('subcategoryof',$_POST['subcategoryof']);
		$new_cat->addChild('subcategories');
		
		$folder_name = preg_replace("/[^A-Za-z0-9]+/",'_',$new_cat->name);
		$new_cat->addChild('folder',$folder_name);

		if(file_put_contents($file_path,$categories->asXML()))
		{
			mkdir($DOCROOT.'/site/data/resources/toolsfor'.$type.'/'.$folder_name);
			$page->addMessage('Category added successfully.');
			$page->data('categories',$categories);
			$page->content("admin/resources/toolsfor$type/list.php");
		}
		else
		{
			$page->addError('Could not add category.');
			$page->content("admin/resources/toolsfor$type/addcat.php");
		}
	}
	else if($do == 'doaddfile')
	{		
		$c = 0;
		while(($categories->category[$c]['id'] != $_POST['which'])
						&& isset($categories->category[$c]))
			$c++;
		# make sure the file gets uploaded and moved correctly
		if($new_link = file_process_upload('file',$DOCROOT.'/site/data/resources/toolsfor'.$type.'/'.$categories->category[$c]->folder))
		{
			$new_file = $categories->category[$c]->addChild('file',$new_link);

			if(file_put_contents($file_path,$categories->asXML()))
			{
				$page->addMessage('File successfully added.');
				$page->content("admin/resources/toolsfor$type/list.php");
			}
		}
		else
		{
			$page->addError('An error occurred while uploading the file.  Please try again.');
			$page->content("admin/resources/toolsfor$type/addfile.php");
		}
		$page->data('categories',$categories);
	}	
	# edit the article and return to the list
	else if($do == 'doeditcat')
	{
		# find the article with the right id
		$c = 0;
		while(($categories->category[$c]['id'] != $_POST['which'])
						&& isset($categories->category[$c]))
			$c++;

		if(empty($_POST['name']))
		{
			$page->addError('You cannot leave the category name blank.');
			$page->data('category',$categories->category[$c]);
			$page->content("admin/resources/toolsfor'.$type.'/deletecat.php");
		}
		else
		{
			# do the following of the new name is different than the old
			if((string)$categories->category[$c]->name != $_POST['name'])
			{
				# update the folder with the new name
				$old_folder_name = (string)$categories->category[$c]->folder;
				$new_folder_name = preg_replace("/[^A-Za-z0-9]+/",'_',$_POST['name']);
				$categories->category[$c]->folder = $new_folder_name;
				# rename the folder
				rename($DOCROOT.'/site/data/resources/toolsfor'.$type.'/'.$old_folder_name,
							$DOCROOT.'/site/data/resources/toolsfor'.$type.'/'.$new_folder_name);
				# update the name
				$categories->category[$c]->name = $_POST['name'];
			}
			
			# if the category has been placed under a different parent category
			# has been updated
			if((int)$categories->category[$c]->subcategoryof != $_POST['subcategoryof'])
			{
				$previous_parent_id = $categories->category[$c]->subcategoryof;
				
				# find the previous parent
				for($k = 0; $k < count($categories->category); $k++)
				{
					if((int)$categories->category[$k]['id'] == $previous_parent_id)
					{
						# now find the subcategory entry that is now invalid and delete it
						for($j = 0; $j < count($categories->category[$k]->subcategories->subcategory); $j++)
						{
							if((int)$categories->category[$k]->subcategories->subcategory[$j] == (int)$categories->category[$c]['id'])
							{
								unset($categories->category[$k]->subcategories->subcategory[$j]);
								break;
							}
						}
						break;
					}
				}
				
				# find the new parent and add a new subcategory entry
				for($k = 0; $k < count($categories->category); $k++)
				{
					if((int)$categories->category[$k]['id'] == $_POST['subcategoryof'])
					{
						$categories->category[$k]->subcategories->addChild('subcategory',$categories->category[$c]['id']);
						break;
					}
				}
				
				$categories->category[$c]->subcategoryof = $_POST['subcategoryof'];
			}

			file_put_contents($file_path,$categories->asXML());

			$page->addMessage('Category successfully updated.');
			$page->data('categories',$categories);
			$page->content("admin/resources/toolsfor$type/list.php");
		}
	}
	# perform the deletion of a file from a category
	else if($do == 'dodeletefile')
	{
		# find the category with the right id
		$c = 0;
		while(($categories->category[$c]['id'] != $_POST['cat'])
						&& isset($categories->category[$c]))
			$c++;

		# if we can unlink the file
		if(unlink($DOCROOT.'/site/data/resources/toolsfor'.$type.'/'.$categories->category[$c]->folder.'/'.$_POST['which']))
		{
			# find the file in the category and delete it
			$k = 0;
			while(($categories->category[$c]->file[$k] != $_POST['which'])
							&& isset($categories->category[$c]->file[$k]))
				$k++;

			# make sure we only delete the file if it's found
			if($categories->category[$c]->file[$k] == $_POST['which'])
				unset($categories->category[$c]->file[$k]);

			file_put_contents($file_path,$categories->asXML());
			$page->addMessage('File successfully deleted.');
		}
		else
			$page->addError('Could not delete file.');

		$page->data('categories',$categories);
		$page->content("admin/resources/toolsfor$type/list.php");
	}
	# perform the deletion of the specified article
	else if($do == 'dodeletecat')
	{
		# find the category with the right id
		$c = 0;
		while(($categories->category[$c]['id'] != $_POST['which'])
						&& isset($categories->category[$c]))
			$c++;

		# delete each of the files in this category
		foreach($categories->category[$c]->file as $file)
		{
			if(!unlink($DOCROOT.'/site/data/resources/toolsfor'.$type.'/'.$categories->category[$c]->folder.'/'.$file))
				$page->addError('File could not be deleted: '.$file);
		}
		# delete the folder
		rmdir($DOCROOT.'/site/data/resources/toolsfor'.$type.'/'.$categories->category[$c]->folder);
		# if we can successfully unset the category, then print a success message
		unset($categories->category[$c]);
		if(!isset($categories->category[$c]))
		{
			$page->addMessage('Category successfully deleted.');
			file_put_contents($file_path,$categories->asXML());
		}
		else
		{
			$page->addError('Could not delete this category.');
		}	
		$page->data('categories',$categories);
		$page->content("admin/resources/toolsfor$type/list.php");
	}
	# display the list of book categories
	else
	{
		$page->data('categories',$categories);
		$page->content("admin/resources/toolsfor$type/list.php");
	}
}

?>