<?php
include("../include/session.php");  
include("app.class.php");
require_once("../include/accessCheck.php");   

if(!$session->logged_in || $session->userlevel!=1)     //Not logged in or not Super Admin
{
    echo accessDeniedMsg;
    exit;
}

if (isset($_GET['page'])){ //find out what the sub page is
	$page = $_GET['page'];
	}
else{$page = 'display';}

global $pageNum;
if(isset($_GET['pageNum']))
        $pageNum=$_GET['pageNum']; //Get the current page number
    else
        $pageNum=1;
        
/**
* displayApps - Displays the app database table in
* a nicely formatted html table.
*/
function displayApps(){
    global $pageNum;
//paging code below
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++      
$result=app::showAllApps();
$nrResults = mysql_numrows($result);

$limit=20; // Limit of result per page 
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++  
$result = app::showAllApps($pageNum,$limit);
$num_rows = mysql_numrows($result);

echo "<p><img  SRC=\"../icons/add.png\" >&nbsp;&nbsp;&nbsp;<a href='app.php?page=add'>Add New Application</a></p>"; 
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "No record.";
return;
}

/* Display table contents */
echo "<table  cellspacing=\"3\" cellpadding=\"2\">";
echo "<tr><th><b>Organization Name</b></th><th><b>Application Name</b></th><th><b>Sub Locations</b></th><th><b>Action</b></th></tr>\n";
for($i=0; $i<$num_rows; $i++){
    
$appID  = mysql_result($result,$i,"appID");
$organizationName  = mysql_result($result,$i,"organizationName");
$appName  = mysql_result($result,$i,"appName"); 

echo '<tr><td class="'.($i%2? "c1":"c2").'">'.$organizationName.'</td>';

echo '<td class="'.($i%2? "c1":"c2").'">'.$appName.'</td>';  
echo '<td class="'.($i%2? "c1":"c2").'"><a href="appSubLocation.php?appID='.$appID.'" >Manage Sub Locations</a></td>';  
?> 
<script type="text/javascript">

function submitForm(form)
{
    document.getElementById(form).submit();
    return true;  
}
</script>                   
<td align="center" class="<?php echo ($i%2? "c1":"c2") ?>">
    <div style="float: left; width:30px;"> 
            <a href="<?php echo $_SERVER['PHP_SELF'] . '?page=edit&subeditappID=' . $appID?>"><img SRC="../icons/Edit.png" title="Edit Application" ALT="Edit Application" border="0"/></a>
    </div>
    <!--    ||||||||||||||||||   --> 
    <div style="float: left; width:30px;">
            <a href="<?php echo $_SERVER['PHP_SELF'] . '?page=display&subdelappID=' . $appID?>" onClick="javascript:return confirm('When you delete this application, all of its sub locations will also be removed. Are you sure you want to delete this application?');"><img border="0" SRC="../icons/delete.gif" title="Delete Application" ALT="Delete Application"  ></a>
    </div>
</td>
<?php

echo "</tr>\n";
}
echo "</table><br>";
//Paging code below
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++    
app::displayPageNav($nrResults,$limit,$pageNum,$_SERVER['PHP_SELF']);

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++  
}

 //----------------------------------------------------------------------------------
 if(isset($_POST['subaddapp']))
 {  
    global $form;

    $field = "app_name";  
    if(!isset($_POST['app_name']) || strlen(trim($_POST['app_name'])) == 0){
    $form->setError($field, "* Please enter a valid application name.");
    }
    $field = "organization_id";  
    if(!isset($_POST['organization_id']) || strlen(trim($_POST['organization_id'])) == 0){
    $form->setError($field, "* Please select a valid organization.");
    }
    /* Errors exist, have user correct them */
    if($form->num_errors > 0){
    $_SESSION['value_array'] = $_POST;
    $_SESSION['error_array'] = $form->getErrorArray();
    }
    /* No errors, add the new application to the database table*/
    else
    {
       
       if(app::appDuplicateCheck($_POST['app_name'],$_POST['organization_id']))
       {
             $process_result="An application with this name already exists in the system for the selected organization.";
       }
       else
       { 
           if(app::addApp($_POST['app_name'],$_POST['app_description'],$_POST['app_comment'],$_POST['organization_id']))
           {
                $process_result="Application added to the database successfully.";
                unset($_POST);
                $page="display";
           }    
            else
                $process_result="Failed to add the new application to the database.";
       }

    }
 }

 //----------------------------------------------------------------------------------
 if(isset($_GET['subdelappID']))
 {  
    if(app::queryApp($_GET['subdelappID'])!=false)
    { 
        $deleteResult=app::deleteApp($_GET['subdelappID']);
        
        if($deleteResult)
            $process_result="The selected application has been removed successfully.";
        else
            $process_result="Failed to remove the application from the database.";
    }

 }
  //----------------------------------------------------------------------------------
if(isset($_POST['subeditapp']) && isset($_POST['subeditappID']))
 {  
    global $form;
   
    $field = "app_name";  
    if(!isset($_POST['app_name']) || strlen(trim($_POST['app_name'])) == 0){
    $form->setError($field, "* Please enter a valid application name.");
    }
    
    /* Errors exist, have user correct them */
    if($form->num_errors > 0){
    $_SESSION['value_array'] = $_POST;
    $_SESSION['error_array'] = $form->getErrorArray();
    $page="edit";
    }
    /* No errors, update application information in the database*/
    else
    {
 
       if(strcasecmp(trim($_POST['app_name']),$_POST['original_app_name'])!=0 && app::appDuplicateCheck($_POST['app_name'],$_POST['organization_id']))
       {
             $process_result="An application with this name already exists in the system for the selected organization.";
             $page="edit";
       }
       else
       { 
       
           if(app::updateApp($_POST['subeditappID'],$_POST['app_name'],$_POST['app_description'],$_POST['app_comment']))
           {
                $process_result=$_POST['app_name'].": Application updated successfully. <a href='app.php'>Go Back</a>...";
                $page="edit";
           }    
            else
                $process_result="Failed to update.".$_POST['app_name'];
       }

    }
 }
//print_r($_POST)  ;

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<title><?php echo TITLE; ?></title>
<link rel="stylesheet" type="text/css" href="../style.css"/>       


</head>
<body >

<div id="layout">
	<?php require('../include/header.php');   ?>
        
<?php    switch ($page){ //what page to load
		case 'display':  //begin display page?>
			<div id="displayApp" class="in"> 
            <P class=veryLargeBlue>Manage Applications</P>
				<?php if(isset($process_result)) {echo $process_result;}
				displayApps();
				?>
			</div>
		<?php
		break; //end display page
		
		case 'edit': //begin edit page?>
            <div id="panel-left" class="box panel">
            <P class=veryLargeBlue>Update Application</P> 
                <?php
                if(isset($_REQUEST['subeditappID']))
                {
                $appInfo=app::queryApp($_REQUEST['subeditappID']);
                ?>
                <div id="editApp">
                    <?php if(isset($process_result)) {echo $process_result;}?>
                    <form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
                        <table align="left" border="0" cellspacing="0" cellpadding="3">

                        <tr>
                            <td class="c1">Organization Name:</td>
                            <td class="c1"><?php echo $appInfo->organizationName; ?></td>
                           
                            <input type="hidden" name="original_app_name" value="<?php echo $appInfo->appName; ?>">
                            <input type="hidden" name="organization_id" value="<?php echo $appInfo->organizationID; ?>">  
                        </tr>
                
                         <tr>
                            <td class="c2">Application Name:*</td>
                            <td class="c2"><input type="text"  name="app_name" maxlength="100" size="40" value="<?php if(isset($_POST['app_name'])) echo $_POST['app_name']; else echo $appInfo->appName; ?>">
                            <?php echo $form->error("app_name"); ?></td>
                        </tr>
                         <tr>
                            <td class="c1">Application Description:</td>
                            <td class="c1"><textarea  name="app_description" cols="70" rows="6" ><?php if(isset($_POST['app_description'])) echo $_POST['app_description']; else echo $appInfo->appDescription; ?></textarea>
                            <?php // echo $form->error("organization_comment"); ?></td>
                        </tr>
                        <tr>
                            <td class="c2">Comment:</td>
                            <td class="c2"><textarea  name="app_comment" cols="70" rows="6" ><?php if(isset($_POST['app_comment'])) echo $_POST['app_comment']; else echo $appInfo->appComment; ?></textarea>
                            <?php // echo $form->error("organization_comment"); ?></td>
                        </tr>
                       
                        <input type="hidden" name="subeditapp" value="1"> 
                        <input type="hidden" name="subeditappID" value="<?php echo $appInfo->appID; ?>">
                        <tr>
                            <td></td>
                            <td>
                                <div style="float:left;"><button name="editApp" type="submit" >Update Application</button></div> 
                               
                                <div style="float:left;"><button type="button" onclick="window.location='app.php'">Cancel</button>
                            </td>
                        </tr>
   
                        </table>
                        </form>
           <?php } ?>
                </div>
            </div>
		<?php break; //end edit page
		case 'add':  //begin add page ?>
                <!--Add New Application form START-->
                <div id="panel-left" class="box panel">
                <P class=veryLargeBlue>Add Application</P> 
                <div enctype="multipart/form-data" id="addApp">
                <?php if(isset($process_result)) {echo $process_result;} ?>
                
                
                    <form name="addForm" action="<?php $_SERVER['PHP_SELF'];?>" method="POST">
                    <table align="left" border="0" > 
                       <tr>
                            <td class="c2">Organization Name:*</td>
                            <td class="c2">
                            <?php $organizationList=app::showAllOrganizations(); ?>
                            <select class="style01"  name="organization_id" size="1" >
                             
                                <?php while ($row = mysql_fetch_object($organizationList))
                                            {
                                                        echo "<option value='$row->organizationID' >$row->organizationName</option>";
                                            }
                                ?>
                                </select>
                                <?php echo $form->error("organization_id"); ?>
                            </td>
                        </tr>
                        <tr>
                            <td class="c1" >Application Name:*</td>
                            <td class="c1" ><input type="text"  name="app_name" maxlength="100" size="40" value="<?php if(isset($_POST['app_name'])) echo $_POST['app_name']; ?>">
                            <?php  echo $form->error("app_name"); ?></td>
                        </tr>
                        
                        <tr>
                            <td class="c2">Application Description:</td>
                            <td class="c2"><textarea  name="app_description" cols="70" rows="6" ><?php if(isset($_POST['app_description'])) echo $_POST['app_description'];?></textarea>
                           
                        </tr>
                        
                        <tr>
                            <td class="c1">Comment:</td>
                            <td class="c1"><textarea  name="app_comment" cols="70" rows="6" ><?php if(isset($_POST['app_comment'])) echo $_POST['app_comment'];?></textarea>
                           
                        </tr>
                        
                        <input type="hidden" name="subaddapp" value="1"> 
                        <tr>
                            <td></td>
                            <td>
                                <div style="float:left;"><button name="addApp" type="submit" >Add Application</button></div> 
                                
                                <div style="float:left;"><button type="button" onclick="window.location='app.php'">Cancel</button></div>
                            </td>
                        </tr>
                        </table> 
                       </form>  
            </div>
        </div>
        <!--Add New App form END-->
	<?php break; } //end add page and end switch page?> 
<?php require('../include/footer.php'); ?>
</div>
<?php
 unset($_SESSION['error_array']); 
?>
</body>
</html>
