<?php
include("../include/session.php");  
include("setting.class.php");
require_once("../include/checkFormat.php"); 
require_once("../include/accessCheck.php"); 
require_once("../include/mailer.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 displayCategory(){
    global $pageNum;
//paging code below
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++      
$result=setting::showAllCategories();
$nrResults = mysql_numrows($result);

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

//echo "<p><img  SRC=\"../icons/config.png\" >&nbsp;&nbsp;&nbsp;<a href='setting.php?page=config'>Config Display Setting</a></p>";
echo "<p><img  SRC=\"../icons/add.png\" >&nbsp;&nbsp;&nbsp;<a href='setting.php?page=add'>Add New Category</a></p>"; 
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "Database table empty";
return;
}

/* Display table contents */
echo "<table  cellspacing=\"3\" cellpadding=\"2\">";
echo "<tr><th><b>Category Description</b></th><th><b>Comment</b></th><th><b>Action</b></th></tr>\n";
for($i=0; $i<$num_rows; $i++){
    
$categoryID  = mysql_result($result,$i,"categoryID");
$categoryDescription  = mysql_result($result,$i,"categoryDescription");
$categoryComment  = mysql_result($result,$i,"categoryComment");

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

echo '<td class="'.($i%2? "c1":"c2").'">'.$categoryComment.'</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&categoryID=' . $categoryID?>"><img SRC="../icons/Edit.png" title="Edit Category" ALT="Edit Category" border="0"/></a>
    </div>
    <!--    ||||||||||||||||||   --> 
    <div style="float: left; width:30px;">
            <a href="<?php echo $_SERVER['PHP_SELF'] . '?page=display&delCategoryID=' . $categoryID?>" onClick="javascript:return confirm('Are you sure you want to delete this Category?');"><img border="0" SRC="../icons/delete.gif" title="Delete Category" ALT="Delete Category"  ></a>
    </div>
</td>
<?php
echo "</tr>\n";
}
echo "</table><br>";
//Paging code below
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++    
setting::displayPageNav($nrResults,$limit,$pageNum,$_SERVER['PHP_SELF']);

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

 //----------------------------------------------------------------------------------
 if(isset($_POST['updateDisplaySetting']))
 {  
    global $form;
	
    $field = "settingValue";  
    if(!isset($_POST['settingValue']) || strlen(trim($_POST['settingValue'])) == 0){
    $form->setError($field, "* Please select a valid setting value.");
    }
	
	if($form->num_errors > 0){
		$_SESSION['value_array'] = $_POST;
		$_SESSION['error_array'] = $form->getErrorArray();
    }
	else{
		if(setting::updateDisplayConfig($_POST['settingValue']))
		{
			$process_result="<label class='alert_msg'> Display Setting updated successfully.</label> <a href='setting.php'>Go Back</a>...";
            $page="config"; 
		}
		else
		{
            $process_result="<label class='alert_msg'>Failed to update Display Setting</label>";
		}
	}
 }
if(isset($_POST['updateMail']))
 {  
     
    global $form;
         $check=new checkFormat();
         
         $emailCheck=$check-> checkEmailFormat($_POST['mailFromEmail']);

    
    $field = "mailFromEmail";  
    if(!isset($_POST['mailFromEmail']) || strlen(trim($_POST['mailFromEmail'])) == 0  || !$emailCheck){
    $form->setError($field, "* Please enter a valid Email.");
    }
    $field = "mailFromName";  
    if(!isset($_POST['mailFromName']) || strlen(trim($_POST['mailFromName'])) == 0 ){
    $form->setError($field, "* Please enter a valid Name.");
    }
    
    /* Errors exist, have user correct them */
    if($form->num_errors > 0){
    $_SESSION['value_array'] = $_POST;
    $_SESSION['error_array'] = $form->getErrorArray();
    $page="mail";
    }
    /* No errors, update mail information in the database*/
    else
    {
      
           if(setting::updateMailConfig($_POST['mailer'],$_POST['sendmailPath'],$_POST['auth'],$_POST['username'],$_POST['password'],$_POST['host'],$_POST['mailFromName'],$_POST['mailFromEmail']))
           {
                $process_result="Mail informaiton updated successfully.";
                $page="mail"; 
           }    
            else{
                $process_result="Failed to update mail information";
                }

    }
 }
 if(isset($_POST['testMail']))
 {  
     
    global $form;
         $check=new checkFormat();
         
         $emailCheck=$check-> checkEmailFormat($_POST['testEmail']);

    
    $field = "testEmail";  
    if(!isset($_POST['testEmail']) || strlen(trim($_POST['testEmail'])) == 0  || !$emailCheck){
    $form->setError($field, "* Please enter a valid Email.");
    }
    /* Errors exist, have user correct them */
    if($form->num_errors > 0){
    $_SESSION['value_array'] = $_POST;
    $_SESSION['error_array'] = $form->getErrorArray();
    $page="testMail";
    }
    /* No errors, update mail information in the database*/
    else
    {
      
           if(mailer::sendMail($_POST['testEmail'],"Test message from Suggestion Dashboard", "This is a test message sent at your request. Please discard it."))
           {
                $process_result="E-mail message sent successfully. Please check your mail.";
                $page="testMail"; 
           }    
            else{
                $process_result="Failed to send a test e-mail message. Please check e-mail settings.";
                $page="testMail";
            }

    }
 }
 //----------------------------------------------------------------------------------
 if(isset($_POST['addCategory']))
 {  
    global $form;		 
	
    $field = "categoryDescription";  
    if(!isset($_POST['categoryDescription']) || strlen(trim($_POST['categoryDescription'])) == 0){
    $form->setError($field, "* Please enter a valid category Description.");
    }
	
    /* Errors exist, have category correct them */
    if($form->num_errors > 0){
	
    $_SESSION['value_array'] = $_POST;
    $_SESSION['error_array'] = $form->getErrorArray();
    }
    /* No errors, add the new category to the database table*/
    else
    {   
       if(setting::categoryDescriptionDuplicateCheck($_POST['categoryDescription']))
       {
             $process_result="<label class='alert_msg'>An category with this description already exists in the system.</label>";
       }
       else
       { 
           if(setting::addCategory($_POST['categoryDescription'],$_POST['categoryComment']))
           {
                $process_result="<label class='alert_msg'>category added to the database successfully.</label>";
                unset($_POST);
                $page="display";
           }    
            else
                $process_result="<label class='alert_msg'>Failed to add the new category to the database.</label>";
				
       }

    }
 }

 //----------------------------------------------------------------------------------
 if(isset($_GET['delCategoryID']))
 {  
    if(setting::queryCategory($_GET['delCategoryID'])!=false)
    { 
        $deleteResult=setting::deleteCategory($_GET['delCategoryID']);
        
        if($deleteResult)
            $process_result="<label class='alert_msg'>The selected Category has been removed successfully.</label>";
        else
            $process_result="<label class='alert_msg'>Failed to remove the Category from the database.</label>";
    }

 }
  //----------------------------------------------------------------------------------

  
if(isset($_POST['editCategory']))
 {  
 	
    global $form;
	
	$field = "categoryDescription";  
    if(!isset($_POST['categoryDescription']) || strlen(trim($_POST['categoryDescription'])) == 0){
    $form->setError($field, "* Please enter a valid category Description.");
    }
	
    /* Errors exist, have category correct them */
    if($form->num_errors > 0){
    $_SESSION['value_array'] = $_POST;
    $_SESSION['error_array'] = $form->getErrorArray();
	$page="edit";
    }
    /* No errors, update category information in the database*/
    else
    {
       if(setting::categoryUpdateDuplicateCheck($_POST['categoryID'], $_POST['categoryDescription']))
       {
             $process_result="<label class='alert_msg'>An category with this description already exists in the system.</label>";
			 $page="edit";
       }
       else
       { 
           if(setting::updateCategory($_POST['categoryID'],$_POST['categoryDescription'],$_POST['categoryComment']))
           {
                $process_result="<label class='alert_msg'>".$_POST['categoryDescription']." updated successfully.</label> <a href='setting.php'>Go Back</a>...";
                $page="edit"; 
           }    
            else{
                $process_result="<label class='alert_msg'>Failed to update.".$_POST['categoryDescription']."</label>";
				}
       }

    }
 }

?>
<!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 Categories</P>
				<?php if(isset($process_result)) {echo $process_result;}
				displayCategory();
				?>
			</div>
		<?php 
		break; //end display page
		
		case 'config': //begin config page ?>
		<div id="panel-left" class="box panel">
			<p class="veryLargeBlue">Change Display Setting</p>
			 <?php $configInfo=setting::queryDisplayConfig(); ?>
			 <?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="c2">Instructions:</td>
                            <td class="c2">
                                <ul>
                                    <li>To hide all suggestions from public, change this setting to Private. </li>
                                    <li>To display all suggestions to public (except those marked as private by suggestion admin), change this setting to Public.</li>
                                    <li>If a suggestion is marked as Private by suggestion admin, then the suggestion will always be hidden from public.</li>
                                    <li>If a suggestion is marked as Public by suggestion admin, then the suggestion display behavior will be decided by this setting.</li>
                                </ul>
                
                            </td>
                        </tr>
                        <tr>
                            <td class="c1">Default Suggestion Display Setting:*</td>
                            <td class="c1">
                            <?php if($configInfo->settingValue == "Public") {?>
                                    <input type="radio" name="settingValue" value="Public" checked="checked">Public</input>
                                   
                                    <input type="radio" name="settingValue" value="Private">Private</input>
             
                            <?php }
                            else {?>
                                    <input type="radio" name="settingValue" value="Public">Public</input>
                                 
                                    <input type="radio" name="settingValue" value="Private" checked="checked">Private</input>
                                    <br /> 
                            <?php } ?>
                            </td>
                        </tr>    
                        <input type="hidden" name="testMail" value="1">
                       
                        <tr>
                            <td></td>
                            <td>
                                <div style="float:left;"><button name="updateDisplaySetting" type="submit" >Update</button></div> 
                                <div style="float:left;"><button type="button" onClick="window.location='setting.php'">Cancel</button>
                            </td>
                        </tr>
   
                </table>
			
            </form>
		</div>
		<?php
		break; //end config page
		
        case 'mail': //begin mail page ?>
        <div id="panel-left" class="box panel">
            <p class="veryLargeBlue">Change Mail Settings</p>
             <?php $configInfo=setting::queryMailConfig(); ?>
              <div id="updateMail">  
             <?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="c2">Important Note:</td>
                            <td class="c2">Please note that email notification can be disabled completely as follows:<br>
                                            - In this application's home directory, go to "include" folder and then open "constants.php" file.<br>
                                            - Look for <b>define("enableEmail", 1);</b> setting and change the value to 0 from 1 
                                            </td>
                        </tr>
                        <tr>
                            <td class="c1">Mailer:*</td>
                            <td class="c1">
                            
                            <?php 
                            //In the following mysql_result code, zero indicates 1st row fetched from configTable. The settingValue of mailer is pulled form first row
                            //The order of rows [settingName] is as follows:
                            /*
                              mailer,
                              sendMailPath,
                              authentication,
                              SMTPUser,
                              SMTPPass,
                              SMTPHost,
                              mailFromName, 
                              mailFromEmail
                            */
                            $currentMailer= mysql_result($configInfo, 0,"settingValue");  ?>
                            
                            <select class="style01"  name="mailer" size="1" >
                             
                                <?php     
                                                if($currentMailer=="mail")
                                                {
                                                    echo "<option selected value='mail' >PHP Mail</option>";
                                                    echo "<option value='SMTP' >SMTP Server</option>"; 
                                                }
                                                else
                                                {
                                                    echo "<option value='mail' >PHP Mail</option>";
                                                    echo "<option selected value='SMTP' >SMTP Server</option>";
                                                
                                                }
                                ?>
                                </select>
                                <?php echo $form->error("mailer"); ?>
                            </td>
                        </tr>
                        <tr>
                            <td class="c2">Sendmail Path: <br> (Reserved for future use)</td>
                            <td class="c2"><input type="text"  name="sendmailPath" maxlength="255" size="60" value="<?php if(isset($_POST['sendmailPath'])) echo $_POST['sendmailPath']; else echo mysql_result($configInfo, 1,"settingValue"); ?>">
                            <?php echo $form->error("sendmailPath"); ?></td>
                        </tr>
                        <tr>
                            <td class="c1">SMTP Authentication: <br>(Required for SMTP)</td>
                            <td class="c1">
                            
                            <?php 

                            $currentAuth= mysql_result($configInfo, 2,"settingValue");  ?>
                            
                            <select class="style01"  name="auth" size="1" >
                             
                                <?php     
                                                if($currentAuth=="NO")
                                                {
                                                    echo "<option selected value='NO' >No</option>";
                                                    echo "<option value='YES' >Yes</option>"; 
                                                }
                                                else
                                                {
                                                    echo "<option value='NO' >No</option>";
                                                    echo "<option selected value='YES' >Yes</option>"; 
                                                
                                                }
                                ?>
                                </select>
                                <?php echo $form->error("auth"); ?>
                            </td>
                        </tr>
                         <tr>
                            <td class="c2">SMTP Username: <br>(Required for SMTP)</td>
                            <td class="c2"><input type="text"  name="username" maxlength="100" size="60" value="<?php if(isset($_POST['username'])) echo $_POST['username']; else echo mysql_result($configInfo, 3,"settingValue"); ?>">
                            <?php echo $form->error("username"); ?></td>
                        </tr>
                         <tr>
                            <td class="c1">SMTP Password: <br>(Required for SMTP)</td>
                            <td class="c1"><input type="text"  name="password" maxlength="100" size="60" value="<?php if(isset($_POST['password'])) echo $_POST['password']; else echo mysql_result($configInfo, 4,"settingValue"); ?>">
                            <?php echo $form->error("password"); ?></td>
                        </tr>
                         <tr>
                            <td class="c2">Mail Host:* <br></td>
                            <td class="c2"><input type="text"  name="host" maxlength="255" size="60" value="<?php if(isset($_POST['host'])) echo $_POST['host']; else echo mysql_result($configInfo, 5,"settingValue"); ?>">
                            <?php echo $form->error("host"); ?></td>
                        </tr>
                         <tr>
                            <td class="c1">Mail From Name:*</td>
                            <td class="c1"><input type="text"  name="mailFromName" maxlength="100" size="60" value="<?php if(isset($_POST['mailFromName'])) echo $_POST['mailFromName']; else echo mysql_result($configInfo, 6,"settingValue"); ?>">
                            <?php echo $form->error("mailFromName"); ?></td>
                        </tr>
                        <tr>
                            <td class="c2">Mail From E-mail:*</td>
                            <td class="c2"><input type="text"  name="mailFromEmail" maxlength="255" size="60" value="<?php if(isset($_POST['mailFromEmail'])) echo $_POST['mailFromEmail']; else echo mysql_result($configInfo, 7,"settingValue"); ?>">
                            <?php echo $form->error("mailFromEmail"); ?></td>
                        </tr>    
                        <input type="hidden" name="updateMail" value="1">
                       
                        <tr>
                            <td></td>
                            <td>
                                <div style="float:left;"><button name="updateMailSetting" type="submit" >Update</button></div> 
                               
                                <div style="float:left;"><button type="button" onClick="window.location='setting.php'">Cancel</button>
                            </td>
                        </tr>
   
                        </table>
                        </form>
                         </div>
        </div>
        <?php
        break; //end mail page
       
         case 'testMail': //begin mail test page ?>
        <div id="panel-left" class="box panel">
            <p class="veryLargeBlue">Test Mail Settings</p>
              <div id="testMailSetting">  
             <?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">Instructions:</td>
                            <td class="c1">Please enter your email below to receive a test email. <br>If your email does not arrive within 5 minutes, please check the email settings.</td>
                        </tr> 
                        <tr>
                            <td class="c2">Your E-mail:*</td>
                            <td class="c2"><input type="text"  name="testEmail" maxlength="255" size="60" value="<?php if(isset($_POST['testEmail'])) echo $_POST['testEmail']; ?>">
                            <?php echo $form->error("testEmail"); ?></td>
                        </tr>    
                        <input type="hidden" name="testMail" value="1">
                       
                        <tr>
                            <td></td>
                            <td>
                                <div style="float:left;"><button name="testEmailSetting" type="submit" >Test</button></div> 
                               
                                <div style="float:left;"><button type="button" onClick="window.location='setting.php'">Cancel</button>
                            </td>
                        </tr>
   
                        </table>
                   </form>
               </div>
        </div>
        <?php
        break; //end mail test page
        
		case 'edit': //begin edit page?>
            <div id="panel-left" class="box panel">
            <P class=veryLargeBlue>Update Category</P> 
                <?php
                if(isset($_REQUEST['categoryID']))
                {
                $categoryInfo=setting::queryCategory($_REQUEST['categoryID']);
				
                ?>
                <div id="editCategory">
                    <?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">Category Description:</td>
                            <td class="c1"><input type="text"  name="categoryDescription" maxlength="100" size="40" value="<?php if(isset($_POST['categoryDescription'])) echo $_POST['categoryDescription']; else echo $categoryInfo->categoryDescription; ?>" />
							<label class="alert_msg"><?php echo $form->error("categoryDescription"); ?></label></td>   
                        </tr>
                         <tr>
                            <td class="c1">Comment:</td>
                            <td class="c1"><textarea  name="categoryComment" cols="70" rows="6" ><?php if(isset($_POST['categoryComment'])) echo $_POST['categoryComment']; else echo $categoryInfo->categoryComment; ?></textarea>
                            </td>
                        </tr>
						<input type="hidden" name="editCategory" value="1">
                        <input type="hidden" name="categoryID" value="<?php echo $categoryInfo->categoryID; ?>">
                        <tr>
                            <td></td>
                            <td>
                                <div style="float:left;"><button name="editCategory" type="submit" >Update Category</button></div> 
                               
                                <div style="float:left;"><button type="button" onClick="window.location='setting.php'">Cancel</button>
                            </td>
                        </tr>
   
                        </table>
                        </form>
           <?php } ?>
                </div>
            </div>
		<?php break; //end edit page
		case 'add':  //begin add page ?>
                <!--Add New Category form START-->
                <div id="panel-left" class="box panel">
                <P class=veryLargeBlue>Add Category</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="c1">Category Description:</td>
                            <td class="c1"><input type="text"  name="categoryDescription" maxlength="100" size="40" value="<?php if(isset($_POST['categoryDescription'])) echo $_POST['categoryDescription'];?>" />
							<label class="alert_msg"><?php echo $form->error("categoryDescription"); ?></label></td>
                            
                        </tr>
                         <tr>
                            <td class="c1">Comment:</td>
                            <td class="c1"><textarea  name="categoryComment" cols="70" rows="6" ><?php if(isset($_POST['categoryComment'])) echo $_POST['categoryComment'];?></textarea>
                            </td>
                        </tr>
						<input type="hidden" name="addCategory" value="1">
                                            
                        <tr>
                            <td></td>
                            <td>
                                <div style="float:left;"><button name="addCategory" type="submit" >Add Category</button></div> 
                                
                                <div style="float:left;"><button type="button" onClick="window.location='setting.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>
