<?php 
session_start();
$ID					= NULL;
$NAME				= NULL;
$DESC 				= NULL;
require 'authenticate.user.php';

require 'configuration.php';
require_once 'includes/common.functions.php';
require_once ('classes/database.php');
require_once ('classes/functions.php');
$sqlObj = new mysqlClass;
$funcObj = new funcClass;
$table = "##addressbook";
$ACTION				= 'add';
require_once ('includes/validate.addressbook.php');

$appendToQuery = "";
## If the client is logged in then 
## give access to only those addressbooks for which
## access has been granted to this user.
$currentUserId 	= intval($_SESSION['SUPER_USER_ID']);

if ($_SESSION['IS_USER_CLIENT'])
{
	$query = "SELECT DISTINCT ADDR_ID FROM smlr_campaign_send_stats WHERE CAMPAIGN_ID IN (SELECT CAMPAIGN_ID FROM smlr_client_access WHERE USER_ID = '$currentUserId')";
	$resultSet = $funcObj->CustomQuery($query);
	
	$inArray = array();
	foreach ($resultSet as $row)
	{
		$inArray[] = $row->ADDR_ID;
	}
	
	if (!count($inArray))
	{
		$inArray[] = '0';
	}
	
	$inArrayStr = implode(",", $inArray);
	
	$appendToQuery = " AND ID IN ($inArrayStr) ";
}

//ADD RECORD
if ((isset($_POST['formaction']) && $_POST['formaction'] == 'add') && (empty($error)))
{
	
	
	# check for duplicate record entry
	$query = "SELECT COUNT(*) FROM $table WHERE NAME = '$NAME'";
	$queryCount=$funcObj->CustomQueryCount($query)[0]['COUNT(*)'];
	
	if ($queryCount == 0)
	{
		$query = "INSERT INTO $table SET NAME='$NAME', DESCRIPTION='$DESC', LAST_UPDATE=NOW()";
		
		$insertId = $funcObj->insertQuery($query);
		
		if ($insertId > 0)
		{
			$message = "Record has been added successfully";
		}
		## RESET THE FORM SO THAT 
		## NO VALUES SHOULD BE SHOWN
		## IF THE FORM IS IN THE ADD
		## MODE
		
	}
	else
	{
		$message = "Same address book already available. Please try with different address book name.";
	}
}

//EDIT RECORD
if ((isset($_POST['formaction']) && $_POST['formaction'] == 'edit') && (empty($error)))
{
	
	
	# check for duplicate record entry
	$query = "SELECT COUNT(*) FROM $table WHERE NAME = '$NAME'";
	$countRecords = $funcObj->CustomQueryCount($query)[0]['COUNT(*)'];
	if ($countRecords < 2)
	{
		$setFields = array();
		$setFields['NAME']		=	$NAME;
		$setFields['DESC']		=	$DESC;
		
		$query = "UPDATE $table SET NAME='$NAME', DESCRIPTION='$DESC'"; 
		$query .= " WHERE ID = {$ID}";
		
		$updateId = $funcObj->updateQuery($query);
		if ($updateId == 1)
		{
			$message = "Record has been successfully updated.";
		}
		
		## RESET THE FORM SO THAT 
		## NO VALUES SHOULD BE SHOWN
		## IF THE FORM IS IN THE ADD
		## MODE
		
		
	}
	else
	{
		$message = "Same address book already available. Please try with different address book name.";
	}
}

## if edit is EDIT
# then load values into the form
if (isset($_GET['action']) && $_GET['action'] == 'edit')
{
	$ID = intval($_GET['id']);
	$whereFields['ID'] = $ID;
	$resultSet = $funcObj->getRecordDetails($table,$whereFields);
	
	$ID					= trim($funcObj->AppendSlashes($resultSet[0]['ID']));
	$NAME				= trim($funcObj->AppendSlashes($resultSet[0]['NAME']));
	$DESC 				= trim($funcObj->AppendSlashes($resultSet[0]['DESCRIPTION']));
	$ACTION				= 'edit';
	
}

$searchbox=isset($_REQUEST['searchbox']) ? $_REQUEST['searchbox'] : '';
$status=isset($_REQUEST['status']) ? $_REQUEST['status'] : '';
$ID=isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
$searchTxt = trim($funcObj->AppendSlashes($searchbox));
$searchArray = 'ID,NAME,DESCRIPTION,LAST_UPDATE';

$doUpdation = false;

switch ($status)
{
	case 'activate': 
		$setField	= 'IS_ACTIVE';
		$setValue	= '1';
		$doUpdation = true;
		break;
	case 'deactivate': 
		$setField	= 'IS_ACTIVE';
		$setValue	= '0';
		$doUpdation = true;
		break;
}	

if($doUpdation)
{
	$whereField = "ID";
	$whereValue = $ID;
    $funcObj->UpdateRecord($table,$setField,$setValue,$whereField,$whereValue);
}	

if(isset($_GET['action']) && $_GET['action']=='del')
{
	/*
	Before deleting the addressbook make sure
	that this addressbook has never been used 
	in any of the campaign sent previously.
	*/
	$query 			= "SELECT COUNT(CAMPAIGN_ID) AS TOTALUSED FROM ##campaign_send_stats WHERE ADDR_ID = '$ID'";
	$addrUsedCount 	= $funcObj->CustomQueryCount($query)[0]['TOTALUSED'];
	
	if ($addrUsedCount > 0)
	{
		$message = "Sorry this address book has been used in of the sent campaigns so it cannot be deleted.";	
	}
	else
	{
		$whereField = "ID";
		$whereValue = $ID;
		$funcObj->DeleteRecord($table,$whereField,$whereValue);
		$funcObj->DeleteRecord('##contacts','ADDR_ID',$whereValue);
		$message = "Address book has been deleted successfully";
	}
}
//$resultSet = $funcObj->CountAllRecords("$table",$searchTxt,$searchArray);

$records	= $funcObj->fetchParameterValue('SHOW_RECORDS_PER_PAGE')[0]['FIELDVALUE'];
if($records > 0)
{
	$limit = intval($records);
}
else
{
	$limit = $configAdminPaging;
}
$searchctr='';
if(isset($_REQUEST['start']))
	$start = $_REQUEST['start'];
else
	$start = 0;
	
if(!empty($searchTxt))
{
	$searchctr = " AND (";
	$searchArray1=explode(",",$searchArray);
	
	$searchctr.= "ID = '$searchTxt' OR NAME like '%$searchTxt%' OR LAST_UPDATE LIKE '%$searchTxt%'"; 
	$searchctr .= ") ";
}

$query = "SELECT COUNT(ID) AS COUNT FROM
##addressbook WHERE ID > 0 $searchctr $appendToQuery ORDER BY ID DESC";
$resultSet = $funcObj->CustomQuery($query);

$proCount = $resultSet[0]['COUNT'];
$link = 'addressbook.php?searchbox='.$searchbox;

require_once('classes/paging.class.php');

$pageObj = new Paging( $proCount, $start , $limit);

/* ACTIVATE THE TAB */
$activeTab = 'Contacts';
?>
<!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>Segnant Mailer - Manage Address Books</title>
<link rel="stylesheet" type="text/css" href="includes/css/segnantmailer.css" />
<link rel="stylesheet" href="includes/css/themes/blue/style.css" type="text/css"  media="print, projection, screen" />
<link rel="stylesheet" type="text/css" href="includes/css/paging.css"  />
<script type="text/javascript" src="includes/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="includes/js/jquery.tablesorter.js"></script>
<script type="text/javascript" src="includes/js/common.jquery.js"></script>
<script type="text/javascript" src="includes/js/addressbook.jquery.js"></script>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td height="79" class="headerbg"><?php require_once 'includes/inc.header.php' ?>    
    </td>
  </tr>

  <tr>
    <td class="canvas" height="300" valign="top"><table width="100%" border="0" cellspacing="10" cellpadding="4">
      <tr>
        <td colspan="2" class="heading" height="50" valign="top" >Manage Address Books</td>
        </tr>
      <tr>
        <td colspan="2" bgcolor="#eaeaea" style="padding:10px;">
        <table cellspacing="0" cellpadding="0" class="tabtable">
<tr>
<?php
$file = basename($_SERVER['PHP_SELF']);

## ADD EXCEPTIONS

$tabArray = array("<td nowrap=\"nowrap\" style=\"cursor:pointer;\" onclick=\"javascript:window.location.href='addressbook.php'\"> Address Books </td>",
		"<td nowrap=\"nowrap\" style=\"cursor:pointer;\" onclick=\"javascript:window.location.href='contacts.php'\"> Contacts </td>");
foreach ($tabArray as $key => $val)
{
	$strpos = strpos($val, $file);

	if ($strpos > 0)
	{
		$newString = str_replace('style="cursor:pointer;"','style="cursor:pointer;" class="active" ',$val);
		echo $newString;
	}
	else
	{
		echo $val;
	}	
}
?>
</tr>
</table>
        <table width="100%" border="0" cellspacing="0" cellpadding="4">
                <tr>
                  <td height="405" bgcolor="#FFFFFF" valign="top"><table width="100%" border="0" cellspacing="1" cellpadding="1">
                      <tr>
                        <td class="pageHeading">Manage Address Books</td>
                      </tr>
                      <tr>
                        <td height="55" valign="top" align="right"><form name="formsearch" method="get" style="margin: 0;" action="">
                            <table border="0" cellspacing="2" cellpadding="2" align="right">
                              <tr>
                                <td nowrap="nowrap"><strong>Search</strong></td>
                                <td><input type="text" name="searchbox" placeholder="search" class="textbox" value="<?=$funcObj->RemoveSlashes($searchbox)?>" style="margin-bottom: 2px;" size="20" /></td>
                                <td><input type="submit" name="submit" value="Search" class="button size2" /></td>
                              </tr>
                            </table>
                          </form></td>
                      </tr>
                      <?php if (!empty($message))
					  echo "
                      <tr>
                        <td class='message'>$message</td>
                      </tr>
					  ";
					  ?>
                      <tr>
                        <td><table cellspacing="1" class="tablesorter">
                            <thead>
                            <tr>
                              <th width="6%" align="center">ID</th>
                              <th align="left">Name</th>
                              <th width="10%" align="center">Contacts</th>
                              <th width="13%" nowrap="nowrap" align="center">Modified</th>
                              <th width="13%" align="center" nowrap="nowrap">Action</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php
							$qry = "SELECT count(*) FROM ##addressbook";
							if(!empty($searchTxt))
							{
								$searchctr = " AND (";
								$searchArray1=explode(",",$searchArray);
								
								$searchctr.= "ID = '$searchTxt' OR NAME like '%$searchTxt%' OR LAST_UPDATE LIKE '%$searchTxt%'"; 
								$searchctr .= ") ";
							}
						
							$query = "SELECT ID, NAME, LAST_UPDATE FROM
							##addressbook WHERE ID > 0 $searchctr $appendToQuery ORDER BY ID DESC
							LIMIT {$pageObj->start}, {$pageObj->limit}";
					$resultSet = $funcObj->CustomQuery($query);
					$i=1;
					if(count($resultSet)!=0)
					{
					foreach ($resultSet as $row)
					{
						$addid=$row['ID'];
						$query = "SELECT COUNT(*) FROM ##contacts WHERE ADDR_ID = $addid AND IS_DELETED = 0";
						$countContacts = $funcObj->CustomQueryCount($query)[0]['COUNT(*)'];
					
						$i++;
						echo "<tr>";
						echo "
						<td align='center'>{$row['ID']} </td>
						<td align='left'>";
						echo $row['NAME']; 
						echo "</td>
						<td align='center'><a href='contacts.php?addrid={$row["ID"]}'>{$countContacts}</a></td>
						<td align='center'>";
						echo date("M j, Y", strtotime($row['LAST_UPDATE']));
						echo "</td>
						<td align='center'>
						<a href='contacts.php?action=addcontact&amp;defaddrid={$row["ID"]}'><img src='images/addcontact.gif' alt='Add Contact' title='Add Contact' border='0' /></a>
						&nbsp;&nbsp;<a href='addressbook.php?action=edit&amp;id={$row["ID"]}'><img src='images/edit.gif' alt='Edit' title='Edit' border='0' /></a>&nbsp;&nbsp;&nbsp;";
						echo "<a href='javascript:confirmAction(\"Are you sure you want to delete this record?\",\"addressbook.php?action=del&amp;id={$row["ID"]}\")'><img src='images/delete.gif' alt='Delete' title='Delete' border='0' /></a>";
						echo "</td>
						</tr>
						";
						}
					}
					else
					echo "<tr><td colspan='5' align='center' height='30' valign='middle' class='row0'>No Record Found... </td></tr>";
					?>
                          </tbody>
                          </table></td>
                      </tr>
                      <tr>
                        <td class="pagingTD"><table cellspacing='0' cellpadding='0'  width='100%'>
                            <tr>
                              <td style="text-align:left" class="form_base_header"><span class="pagenav">
                                <?=$pageObj->ShowPageInfo()?>
                                </span></td>
                              <td style="text-align:right" class="form_base_header"><span class="pagenav">
                                <?=$pageObj->Show($link)?>
                                </span></td>
                            </tr>
                          </table></td>
                      </tr>
                    </table></td>
                  <td valign="top" align="left" width="240">                  
                  <form name="formaddressbook" method="post" action="<?php echo $_SERVER['PHP_SELF']?>" style="margin: 0;">
                  <table width="100%" border="0" cellspacing="1" cellpadding="1" class="inputformtable">
                      <tr>
                        <td class="pageHeadingRt"><?php echo ucwords($ACTION) ?> Address Book
                        <?php if ($ACTION == 'edit') { echo "&nbsp;&nbsp;<small>(<a href='{$_SERVER["PHP_SELF"]}'>Cancel Edit</a>)</small>"; } ?>
                        </td>
                      </tr>
					  <?php if(isset($errorMsg)){?>
                      <tr>
                        <td height="25" valign="top" <?= (! empty ($errorMsg)) ? 'class="error"' : '' ?>><?php
				   errorMessage($errorMsg);
				   ?></td>
                      </tr>
					  <?php }?>
                      <tr>
                        <td class="inputlabel">Name *</td>
                      </tr>
                      <tr>
                        <td><input type="text" name="txtname" class="textbox" value="<?=$funcObj->RemoveSlashes($NAME)?>" maxlength="50" style="width: 220px" /></td>
                      </tr>
                      <tr>
                        <td class="inputlabel">Description <small>(Maximum 255 Characters)</small></td>
                      </tr>
                      <tr>
                        <td><textarea name="txtdescription" class="textarea" rows="6" style="width: 220px" maxlength="255"><?=$funcObj->RemoveSlashes($DESC)?></textarea>
                        <br /><small>Give your address book a description so you know what contacts it contains, for future reference.</small>
                        </td>
                      </tr>
                      <tr>
                        <td height="35"><input type="submit" name="submit" value="Save" class="button size1" /></td>
                      </tr>
                      <tr>
                        <td height="45">Fields marked with * are mandatory.</td>
                      </tr>
                    </table>
                    <input type="hidden" name="ID" value="<?php echo isset($_GET['id']) ? $_GET['id'] : ''?>" />
                    <input type="hidden" name="formaction" value="<?php echo $ACTION?>" />
                    </form>
                    </td>
                </tr>
              </table></td>
      </tr>
    </table></td>
  </tr>
<?php require_once 'includes/inc.footer.php' ?>
</table>
</body>
</html>
