<?php

	/*
	** File: admin_departments
	** Description: This screen allows the admin to edit this particular
	**   department ($department), including items and subdepartments.  It also
	**   gives him links to move to the parent department, or any of the 
	**   children departments.  Think recursively.
	** Version: 2.0
	** Created: 7/30/99
	** Author: Shannon -jj Behrens
	** Email: jj@clearink.com
	** CVS Author: $Author: leon $
	** Last Revised: $Date: 2000/03/02 01:12:26 $
	** Copyright (c) 1999 Working Dogs.  All rights reserved.
	**
	** Input: possibly $department, $expandDepartments
	*/

	/* Needed for function DepartmentSelector. */
	require(APPLICATION_ROOT . "/modules/include/department_selector");


	
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ functions

	/*
	** Function: onvalKeyImplode
	** Input: $delimiter, $dataArray
	** Output: String
	** Description: Implodes the keys, but loops through the array based
	**   on the values (so the values had all better be true). When I say implode,
	**   I mean like the function implode().
	*/
	function onvalKeyImplode($delimiter, $dataArray)
	{
		for (reset($dataArray) ; current($dataArray) ; next($dataArray))
		{
			$ret .= key($dataArray) . $delimiter;
		}
		/* Chomp off the last delimiter. */
		return ( substr($ret, 0, strlen($ret)-1) );
	}



	/*
	** Function: directoryTree
	** Input: Int $deptID, String $deptName, Array $departmentStructure, 
	**   Array $expandDepartmentsArray, global $department (readonly).
	** Output: None (uses print())
	** Description: Recurse on $deptID in order to create an expandable 
	**   tree like the left side of Windows Explorer (Win 95, 98). This is the GUI
	**   to show the departments and items.
	*/
	function directoryTree($deptID, $deptName, $departmentStructure, 
		$expandDepartmentsArray)
	{
		global $department;
		$deptID = intval($deptID);
		$doExpand = $expandDepartmentsArray[$deptID];
		$imploded = onvalKeyImplode("|", $expandDepartmentsArray);

		if ($doExpand)
		{
			/* 
			** Do the expand/unexpand link and the link to dir. Note how we add
			** a space to the end of $unexpandImplode so that it doesn't get 
			** set to nothing when closing the root dir. 
			*/
			unset($expandDepartmentsArray[$deptID]); //temporarily
			$unexpandImplode = onvalKeyImplode("|", $expandDepartmentsArray) . " ";
			$expandDepartmentsArray[$deptID] = TRUE;
			print("<A HREF=\"" . ScreenURL("admin_departments"));
			print("&department=$department");
			print("&expandDepartments=$unexpandImplode");				
			print("\"><IMG SRC=\"images/admin/folder_open.gif\" ALT=\"Close\" " . 
				"BORDER=\"0\" WIDTH=\"20\" HEIGHT=\"20\"></A>\n");
			
			print("<A HREF=\"" . ScreenURL("admin_departments"));
			print("&expandDepartments=$imploded");
			print("&department=$deptID");
			print("\">" . prepareText($deptName) . "</A><BR>\n");
			
			/* Show all of the items and sub-departments for this department. */
			$thisDept = $departmentStructure[$deptID];
			if ($thisDept) /* Catch case where the root dir is empty. */
			{
				print("<UL>\n");
				for (reset($thisDept) ; $member=current($thisDept) ; 
					next($thisDept))
				{
					if ($member[0]) /* Is a sub-directory; recursive case. */
					{
						list($isDirectory, $ID, $name) = $member;
						directoryTree($ID, $name, $departmentStructure, 
							$expandDepartmentsArray);
					}
					else /* Is an item. Base case one. Link to item. */
					{
						list($isDirectory, $ID, $name, $active) = $member;
						print("<A HREF=\"" . ScreenURL("admin_item"));
						print("&item=$ID");
						print("&department=$deptID");
						print("\">");
						print("<IMG SRC=\"images/admin/file.gif\" ALT=\"" . 
							prepareText($name) . "\" BORDER=\"0\" WIDTH=\"20\" " . 
							"HEIGHT=\"20\">");
						
						/* Put the item in brackets if the item is inactive. */
						if ($active == "N")
						{
							print("[" . prepareText($name) . "]</A><BR>\n");
						}
						else
						{
							print(prepareText($name) . "</A><BR>\n");
						}
					} 
				}
				print("</UL>\n");
			}
		} /* end of big "if" */
		
		else /* Don't expand. Base case two. */
		{
			$expandImplode = $imploded=="" ? 
				"$deptID" : "$imploded|$deptID";
			print("<A HREF=\"" . ScreenURL("admin_departments"));
			print("&expandDepartments=$expandImplode");
			print("&department=$department");
			print("\"><IMG SRC=\"images/admin/folder.gif\" ALT=\"Open\" " . 
				"BORDER=\"0\" WIDTH=\"20\" HEIGHT=\"20\"></A>\n");
			
			/* Automatically expand unexpanded dirs when user views them. */
			print("<A HREF=\"" . ScreenURL("admin_departments"));
			print("&expandDepartments=$expandImplode");
			print("&department=$deptID");
			print("\">" . prepareText($deptName) . "</A><BR>\n");
		}
	}

		
		
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ main
	
	/* Make sure the user has access. */
	if(!$UserInfo["Permission"]["Administrate"])
	{
		print(L_ADMINDEPARTMENTS_DENIED . "<BR>\n");
	}
	else
	{
		/*
		** Setup the $department variable.
		*/
		$department = isset($department) ? intval($department) : 0;
		
		
		
		/*
		** Get the main information about this department (more information than
		** we care about for the other departments). 
		*/
		if ($department == 0)
		{
			$departmentName = "Root";
		}
		else
		{
			$mainQuery = "SELECT Name, Graphic, Parent, Description, " . 
				"DisplayPrecedence ";
			$mainQuery .= "FROM department WHERE ID = " . $department;
			/* Execute the query. */
			if ( !($mainRecords = mysql_query($mainQuery, $DatabaseLink)) )
			{
				print("<!-- " . mysql_errno() . ":  " . mysql_error() . 
					"   Query was $mainQuery -->\n");
			}
			else
			{
				if ( !($mainRecord = mysql_fetch_row($mainRecords)) )
				{
					print(L_ADMINDEPARTMENTS_DEPTDOESNOTEXIST . "\n");
				}
				else
				{
					list($departmentName, $departmentGraphic, $departmentParent, 
						$departmentDescription, $departmentDisplayPrecedence ) = 
						$mainRecord;
				}
			}
		}
	
	
	
		/* 
		** Start the table, and tell the user where he is.
		*/
		print("<TABLE BORDER=\"1\" WIDTH=\"100%\"><TR><TD>\n");
		print("<B>" . L_ADMINDEPARTMENTS_EDITING . ": " . prepareText($departmentName) . 
			"</B>\n");
		
		/*
		** Give the admin some useful links.
		*/
		print("<UL>\n");
		print("<LI><A HREF=\"" . ScreenURL("admin_menu") . 
			"\">" . L_ADMINDEPARTMENTS_ADMINMENU . "</A>\n");			
		/* If this is not the main department, give the admin links upwards. */
		if ($department != 0)
		{
			print("<LI><A HREF=\"" . ScreenURL("admin_departments") . 
				"&department=0\">" . L_ADMINDEPARTMENTS_ROOT . 
				"</A>\n");	
			print("<LI><A HREF=\"" . ScreenURL("admin_departments") . 
				"&department=$departmentParent\">" . L_ADMINDEPARTMENTS_GOUPONE . 
				"</A>\n");
		}
		/* Otherwise, since there is no bottom section (main department info) 
		** for the root directory, give the admin links to add sub-dirs and 
		** items here.
		*/
		else
		{
			print("<LI><A HREF=\"" . ScreenURL("add_department") . 
				"&department=$department\">" . L_ADMINDEPARTMENTS_ADDSUB . "</A>\n");
			print("<LI><A HREF=\"" . ScreenURL("add_item") . 
				"&department=$department\">" . L_ADMINDEPARTMENTS_ADDANITEM . "</A>\n");
		}
		print("</UL>\n");

		/*
		** Finish up the table for the "navigation" section.
		*/
		print("</TD></TR></TABLE><BR>\n");
		
		
		
		/*
		** Do an expandable tree-like structure to allow the admin to visit all
		** of the various departments (like Windows Explorer works in Windows 98).
		*/
		print("<TABLE BORDER=\"1\" WIDTH=\"100%\"><TR><TD>\n");
		print("<B>" . L_ADMINDEPARTMENTS_STOREDIRECTORY . "</B><BR><BR>\n");
		
		/*
		** Grab the store structure from the database (i.e. all department's name,
		** ID, and parent). 
		*/
		$query = "SELECT ID, Name, Parent FROM department ";
		$query .= "ORDER BY DisplayPrecedence, Name";
		$records = mysql_query($query, $DatabaseLink);
		if(!$records)
		{
			print("<!-- " . mysql_errno() . ":  " . mysql_error() . 
				"   Query was $mainQuery -->\n");
		}
		elseif(mysql_num_rows($records) <= 0)
		{
			print(L_ADMINDEPARTMENTS_NOSUBDEPTDEFINED . "<BR>\n");
		}
		else
		{
			/* 
			** Note the way I'm constructing the array:
			** For each parent department:
			**   Multiple subdepartments of the form:
			**      (IsSubDir=TRUE, ID, Name)
			**   Multiple items of the form: (this is done later)
			**      (IsSubDir=FALSE, ID, Name, Active)
			*/
			while (list($ID, $name, $parent) = mysql_fetch_row($records))
			{
				$departmentStructure[$parent][] = array (TRUE, $ID, $name);
			
				/*
				** In at least one place below (see non-expanded parent bug), we'll need
				** the following: given a department ID, return the department's parent.
				** We'll deal with that here.
				*/
				$departmentParents[$ID] = $parent;
			}
		}
		
		/* 
		** As promised, let's add to $departmentStructure all of the items in the 
		** database (just the names). This is more efficient than making a hit to 
		** the database for every expanded department. 
		*/
		$query = "SELECT i.ID, i.Name, d.Department, i.Active FROM item i, " . 
			"department_item d ";
		$query .= "WHERE d.Item = i.ID ";
		$query .= "ORDER BY i.DisplayPrecedence, i.Name";
		$records = mysql_query($query, $DatabaseLink);
		if (!mysql_num_rows($records))
		{
			print(L_ADMINDEPARTMENTS_NOITEMS . "<P>\n");
		}
		else
		{
			while (list($ID, $name, $dept, $active) = mysql_fetch_row($records))
			{
				$departmentStructure[$dept][] = array(FALSE, $ID, $name, $active);
			}
		}
		
		/*
		** For the sake of efficiency, parse $expandDepartments. Note how 
		** $expandDepartments is just a list of department numbers, separated by
		** "|" 's.
		*/
		/* First time users should automatically have the root dept expanded. */
		if ($expandDepartments == "")
		{
			$expandDepartments = "0";
		}
		$exploded = explode("|", $expandDepartments);
		/*
		** Now, do the following 3 things:
		**   o If ANY of the departments will need to be expanded, the root dept
		**     will also have to be expanded.
		**   o For each department to be expanded, also expand all of its ancestors
		**     (fix for the non-expanded parent bug).
		**   o Invert the array for the sake of convenience. Produces something
		**     like array (0=>TRUE, 5=>TRUE, 13=>TRUE).  
		*/
		$count = count($exploded);
		if ($count)
		{
			$expandDepartmentsArray[0] = TRUE;
		}
		for ($i=0 ; $i<$count ; $i++)
		{
			$dept = intval($exploded[$i]);
			while ($dept)              // 0 is root dir.
			{
				$expandDepartmentsArray[$dept] = TRUE;
				$dept = $departmentParents[$dept];
			}
		}
		
		/*
		** Everyone cross their fingers! Let's do the tree. That's it for this
		** section.
		*/
		directoryTree(0, "Root", $departmentStructure, $expandDepartmentsArray);
		print("</TD></TR></TABLE>\n");



		/*
		** Give the user the main information about this department,
		** unless we're in the root department, which has no main information.
		*/
		if ($department != 0)
		{
			print(StartForm("admin_departments", 'post', 'UPDATE_DEPARTMENT', FALSE, 
				array("department"=>$department)));

			print("<TABLE BORDER=\"1\" WIDTH=\"100%\"><TR><TD>\n");

			/* 
			** Give a heading, and links to add sub-departments and new items.
			** If the admin is editing the root department, he'll never see this
			** section, so these links are repeated in the top section.
			*/
			print("<TABLE>\n");
			print("<TR><TD><B>" . L_ADMINDEPARTMENTS_INFORMATION . "</B></TD>\n");
			print("<TD ALIGN=\"right\">\n");
			print("<A HREF=\"" . ScreenURL("add_department") . 
				"&department=$department\">" . L_ADMINDEPARTMENTS_ADDSUBLOWER . "</A>, &nbsp;\n");
			print("<A HREF=\"" . ScreenURL("add_item") . 
				"&department=$department\">" . L_ADMINDEPARTMENTS_ADDANITEMLOWER . "</A>, &nbsp;\n");
			print("<A HREF=\"" . ScreenURL("department") . 
				"&department=$department\">" . L_ADMINDEPARTMENTS_VIEWDEPARTMENT . "</A>\n");
			print("</TD></TR>\n");

			/*
			** Give the main information about this department. 
			*/
			print("<TR><TD>" . L_ADMINDEPARTMENTS_NAME . "</TD>\n");
			print("<TD><INPUT TYPE=\"text\" NAME=\"inputName\" SIZE=\"32\" ");
			print("VALUE=\"" . prepareText($departmentName) . "\"></TD></TR>\n");

			print("<TR><TD>" . L_ADMINDEPARTMENTS_PARENT . "</TD>\n<TD>");
			DepartmentSelector("inputParent", $departmentParent, FALSE);
			print("</TD></TR>\n");

			print("<TR><TD>" . L_ADMINDEPARTMENTS_GRAPHIC . "</TD>\n");
			print("<TD><INPUT TYPE=\"text\" NAME=\"inputGraphic\" SIZE=\"32\" ");
			print("VALUE=\"$departmentGraphic\"></TD></TR>\n");

			print("<TR><TD>" . L_ADMINDEPARTMENTS_DESCRIPTION . "</TD>\n");
			print("<TD><TEXTAREA NAME=\"inputDescription\" COLS=\"40\" " . 
				"ROWS=\"5\" WRAP=\"soft\">");
			print(prepareText($departmentDescription));
			print("</TEXTAREA></TD></TR>\n");

			print("<TR><TD>" . L_ADMINDEPARTMENTS_DISPLAYPRECEDENCE . "</TD>\n");
			print("<TD><INPUT TYPE=\"text\" NAME=\"inputDisplayPrecedence\" ");
			print("SIZE=\"2\" VALUE=\"$departmentDisplayPrecedence\"></TD></TR>\n");

			print("<TR><TD>\n");
			print("<INPUT TYPE=\"submit\" VALUE=\"" . L_ADMINDEPARTMENTS_UPDATEDEPARTMENT . "\">\n");
			print("<INPUT TYPE=\"reset\" VALUE=\"" . L_ADMINDEPARTMENTS_RESET . "\">\n");
			print("</TD>\n");
			print("<TD ALIGN=\"right\">\n");
			print("<A HREF=\"" . ScreenURL("admin_departments") . 
				"&department=$department&ACTION=DELETE_DEPARTMENT\">" . 
				L_ADMINDEPARTMENTS_DELETEDEPARTMENT . "</A></TD>\n");
			print("</TR>\n");
			print("</TABLE>\n");

			/*
			** Finish up the table for the "main info" section.
			*/
			print("</TD></TR></TABLE><BR>\n");
			print("</FORM>\n");
		}
	} 
		
?>
		

