<?php
  /* STEP 1: LOAD RECORDS - Copy this PHP code block near the TOP of your page */

  // load viewer library
  $libraryPath = 'cmsAdmin/lib/viewer_functions.php';
  $dirsToCheck = array('/usr/local/pem/vhosts/101154/webspace/httpdocs/2011/','','../','../../','../../../');
  foreach ($dirsToCheck as $dir) { if (@include_once("$dir$libraryPath")) { break; }}
  if (!function_exists('getRecords')) { die("Couldn't load viewer library, check filepath in sourcecode."); }

  $tableName       = 'articles';
  $recordNum       = null; // you must set either $recordNum or $preSaveTempId to null
  $preSaveTempId   = @$_REQUEST['preSaveTempId'] ? $_REQUEST['preSaveTempId'] : uniqid('x');
  $errorsAndAlerts = '';

  ### insert record
  if (@$_REQUEST['submitForm']) {

    // error checking
    if (!@$_REQUEST['title'])    { $errorsAndAlerts .= "Please specify title!<br/>\n"; }
	if (!@$_REQUEST['project']) { $errorsAndAlerts .= "You must select your project!<br/>\n"; }
	if (!@$_REQUEST['category']) { $errorsAndAlerts .= "You must select your category!<br/>\n"; }
	
	// Email Form Fields

	  // Get project name, rather than number
	  $listOptions = getListOptions('accounts', 'project');   
	  $emailProject = ""; 
	  if (@$_REQUEST['project']) { 
	  $emailProject = $listOptions[@$_REQUEST['project']];} 

	  // Get category name, rather than number
	  $listOptions = getListOptions('accounts', 'category');   
	  $emailCategory = ""; 
	  if (@$_REQUEST['category']) { 
	  $emailCategory = $listOptions[@$_REQUEST['category']];} 
	  
	  // Get email list of those members with notifications on, and access to the project
	  $accounts  = mysql_query_fetch_all_assoc("SELECT * FROM `{$TABLE_PREFIX}accounts` WHERE notifications = '1' AND project LIKE '%\t".intval(@$_REQUEST['project'])."\t%'"); 
	  $emailList = join(",", array_pluck($accounts, 'email'));
 
	$emailTitle       = @$_REQUEST['title'];
	$emailContent     = @$_REQUEST['content'];
	$emailBy          = @$CURRENT_USER['fullname'];
	$emailSend        = @$CURRENT_USER['email'];
	
    // update record
    if (!@$errorsAndAlerts) {
      mysqlStrictMode(false); // disable Mysql strict errors for when a field isn't defined below (can be caused when fields are added later)
      $query = "INSERT INTO `{$TABLE_PREFIX}$tableName` SET
                    createdDate      = NOW(),
                    createdByUserNum = '" .intval( @$CURRENT_USER['num'] ). "',
                    updatedDate      = NOW(),
                    updatedByUserNum = '" .intval( @$CURRENT_USER['num'] ). "',

                    title            = '".mysql_escape( $_REQUEST['title'] )."',
                    project         = '".mysql_escape( $_REQUEST['project'] )."',
                    category         = '".mysql_escape( $_REQUEST['category'] )."',
					content          = '".mysql_escape( $_REQUEST['content'] )."'";
					
      mysql_query($query) or die("MySQL Error:<br/>\n". htmlspecialchars(mysql_error()) . "\n");
      $newRecordNum = mysql_insert_id();

      // adopt temp uploads (IMPORTANT - DON'T FORGET THIS STEP!!!)
      adoptUploads($tableName, $preSaveTempId, $newRecordNum);
      removeExpiredUploads(); // erase old expired uploads

      // display thanks message and clear form
      $errorsAndAlerts = "Thanks, we've added your record!";
      $_REQUEST      = array();
    
	
	
				// Send email
				$headers	= 'From: noreply@murrays.com.au' . "\r\n" .
							  'MIME-Version: 1.0' . "\r\n" .
							  'Content-type: text/plain; charset=UTF-8' . "\r\n" .	
							  'X-Mailer: PHP/' . phpversion();

				$to			= "$emailList";
				$subject	= "[PORTAL ITEM ADDED] - {$_SERVER['HTTP_HOST']}";

				$message	= "Hi,\n"
							. "$emailBy ($emailSend) just added an item to the portal.\n"
							. "\n"
							. "$emailTitle \n"
							. "$emailContent \n"
							. "\n"
							. "Status: $emailProject \n"
							. "\n"
							. "Category: $emailCategory \n"
							. "\n"
							. "{$_SERVER['HTTP_HOST']}\n";

				$mailResult = @mail($to, $subject, $message, $headers);
				if (!$mailResult) { die("Mail Error: $php_errormsg"); }	
	

	}
  }

?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link href="DataTables-1.8.1/media/css/demo_page.css" rel="stylesheet" type="text/css" />
<link href="DataTables-1.8.1/media/css/demo_table.css" rel="stylesheet" type="text/css" />
</head>
<body id="dt_example" style="padding:50px;">

<h1>Add Record</h1>

<?php if (@$errorsAndAlerts): ?>
  <div style="color: #C00; font-weight: bold; font-size: 14px;"><?php echo $errorsAndAlerts; ?></div>
<?php endif ?>

<form method="post" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>">
<input type="hidden" name="submitForm" value="1" />
<input type="hidden" name="num" value="<?php echo $recordNum ?>" />
<input type="hidden" name="preSaveTempId" value="<?php echo $preSaveTempId ?>" />

<table border="0" cellspacing="0" cellpadding="2">
 <tr>
  <td valign="top">Title</td>
  <td><input class="text-input medium-input" type="text" name="title" value="<?php echo htmlspecialchars(@$_REQUEST['title']) ?>" size="30" /></td>
</tr>
  <tr>
   <td valign="top">Status</td>
   <td>
     <?php $fieldname = 'project'; ?>
     <?php $idCounter = 0;
	 $selectedProjects = explode("\t", trim($CURRENT_USER['project'], "\t"));
	 ?>
     
     <?php foreach (getListOptions('accounts', $fieldname) as $value => $label): ?>
       <?php if (!in_array($value, $selectedProjects)) { continue; } ?> 
	   <?php $idP = "$fieldname." . ++$idCounter; ?>
       <input type="radio" name="<?php echo $fieldname ?>" id="<?php echo $idP ?>"
             value="<?php echo htmlspecialchars($value) ?>" <?php checkedIf(@$_REQUEST[$fieldname], $value) ?> />
       <label for="<?php echo $idP ?>"><?php echo htmlspecialchars($label) ?></label><br/>

     <?php endforeach ?>
   </td>
  </tr>
  <tr>
   <td valign="top">Category</td>
   <td>
     <?php $fieldname = 'category'; ?>
     <?php $idCounter = 0; 
	 $selectedCategories = explode("\t", trim($CURRENT_USER['category'], "\t"));
	 ?>
     <?php foreach (getListOptions('accounts', $fieldname) as $value => $label): ?>
       <?php if (!in_array($value, $selectedCategories)) { continue; } ?> 
	   <?php $id = "$fieldname." . ++$idCounter; ?>
       <input type="radio" name="<?php echo $fieldname ?>" id="<?php echo $id ?>"
             value="<?php echo htmlspecialchars($value) ?>" <?php checkedIf(@$_REQUEST[$fieldname], $value) ?> />
       <label for="<?php echo $id ?>"><?php echo htmlspecialchars($label) ?></label><br/>

     <?php endforeach ?>
   </td>
  </tr>
 <tr>
  <td valign="top">Comment</td>
  <td>
  <textarea name="content" cols="30" rows="3" value="<?php echo htmlspecialchars(@$_REQUEST['content']) ?>"></textarea>
  </td>
</tr>
</table>

<div style="border-bottom: 1px solid #B0BED9; width:100%; margin:10px 0;"></div>
<input class="button" type="submit" name="submitForm" value="Add Record &gt;&gt;" />

</form>

</body>
</html>
