<?php 
session_start();
require 'authenticate.user.php';

require 'configuration.php';
require_once 'includes/common.functions.php';
require_once ('classes/database.php');
require_once ('classes/functions.php');
require_once('classes/paging.class.php');
$sqlObj = new mysqlClass;
$funcObj = new funcClass;
$table = "##campaigns";
$ACTION				= 'add';
$ID = intval(isset($_GET['id']) ? $_GET['id'] : '') ;
$isSent = 'IS_SENT IS NOT NULL';

if ($_SESSION['IS_USER_CLIENT'])
{
	die ("Sorry, you are not authorized to access this page");
}

// Fill the dropdown list with clients
$query = "SELECT USER_ID, FULLNAME, EMAIL FROM ##super_user WHERE USER_TYPE = 'CLIENT' ORDER BY FULLNAME";
$clientDropdownResultSet = array();
$clientDropdownResultSet = $funcObj->CustomQuery($query);

// If the accesses are updated then update user campaign permissions
if (isset($_POST['formtype']) && $_POST['formtype'] == 'accessupdate') 
{
	$searchCriteria 	= array();
	$searchCriteria 	= $_POST['chkListingContacts'];
	$searchCriteriaStr	= implode(",", $searchCriteria);

	## delete records from client access table
	$query = "DELETE FROM ##client_access WHERE CAMPAIGN_ID IN ($searchCriteriaStr) AND USER_ID = '$ID'";
	$funcObj->CustomDelete($query);	
	
	## Give access to selected campaigns to the current user
	$selCampaigns = array();
	$selCampaigns = $_POST['chkContacts'];
	
	foreach ($selCampaigns as $rowCampaigns)
	{
		## Insert all rows one by one
		$query = "INSERT INTO ##client_access SET USER_ID='$ID', CAMPAIGN_ID='$rowCampaigns'";
		$insertId = $funcObj->insertQuery($query);
		//echo $rowCampaigns . '<br />';
	}
	$message = "Campaign access has been updated successfully for this user.";
}

## Autofill checkboxes of the campaigns for which 
## the client already has access to
$clientSimpleArray = array();
if ($ID > 0)
{
	$query = "SELECT CAMPAIGN_ID FROM ##client_access WHERE USER_ID = '$ID'";
	$clientCampaignAccess = array();
	$clientCampaignAccess = $funcObj->CustomQuery($query);
	foreach($clientCampaignAccess as $row)
	{
		$clientSimpleArray[] = $row['CAMPAIGN_ID'];
	}
}

//ADD RECORD
$superID = 1;

$searchTxt = trim($funcObj->AppendSlashes(isset($_REQUEST['searchbox']) ? $_REQUEST['searchbox'] : '' ));
$searchArray = 'ID,CAMPAIGN_NAME,FROM_NAME,FROM_EMAIL,SUBJECT';

$resultSet = $funcObj->CountAllRecords("$table",$searchTxt,$searchArray);

$records	= $funcObj->fetchParameterValue('SHOW_RECORDS_PER_PAGE')[0]['FIELDVALUE'];

if($records > 0)
{
	$limit = intval($records);
}
else
{
	$limit = $configAdminPaging;
}

if(isset($_REQUEST['start']))
	$start = $_REQUEST['start'];
else
	$start = 0;
	

$req_id=isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
$req_searchbox=isset($_REQUEST['searchbox']) ? $_REQUEST['searchbox'] : '';
$proCount = $resultSet[0]['count(*)'];
$link = 'clientaccess.php?id='.$req_id.'&amp;searchbox='.$req_searchbox;


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

/* ACTIVATE THE TAB */
$activeTab = 'Manage Users';
?>

<!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 Client Campaigns</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/clientaccess.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 Client Campaigns</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='manageusers.php'\"> Manage Users </td>",
		"<td nowrap=\"nowrap\" style=\"cursor:pointer;\" onclick=\"javascript:window.location.href='clientaccess.php'\"> Manage Client Campaigns </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 Client Campaigns</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>Choose Client </strong></td>
                                <td nowrap="nowrap">
                                <select name="id" onchange="clientupdate(this.value)">
                                <option value="0">---- Choose Client ----</option>
                                <?php 
                                foreach ($clientDropdownResultSet as $row)
								{
									$defaultOption = ($ID == $row['USER_ID']) ? 'selected="selected"' : '';
									echo "<option value='{$row["USER_ID"]}' $defaultOption>";
									echo $row['FULLNAME'] . ' (' . $row['EMAIL'] . ')';
									echo "</option>\n";
								}
								?>
                                </select>                                </td>
                                <td width="25" align="center"><strong>|</strong></td>
                                <td nowrap="nowrap"><strong>Search</strong></td>
                                <td><input type="text" placeholder="search" name="searchbox" class="textbox" value="<?=$funcObj->RemoveSlashes($req_searchbox)?>" style="margin-bottom: 2px;" size="20" /></td>
                                <td><input type="submit" name="submit" value="Search" class="button size2" /></td>
                              </tr>
                              <tr>
                                <td colspan="3" nowrap="nowrap" valign="top"><small>Choose client you want to set permissions for.</small></td>
                                <td nowrap="nowrap">&nbsp;</td>
                                <td>&nbsp;</td>
                                <td>&nbsp;</td>
                              </tr>
                            </table>
                          </form></td>
                      </tr>
                      <?php if (!empty($message))
					  echo "
                      <tr>
                        <td class='message'>$message</td>
                      </tr>
					  ";
					  ?>
                      <tr>
                        <td><form name="frmListing" id="frmListing" method="post" style="margin:0; padding: 0" action="">
                          <table cellspacing="1" class="tablesorter">
                        <thead>
                            <tr>
                              <th width="30" align="center"><input type="checkbox" name="chkAll" id="chkAll" onclick="checkAll()" value="1" /></th>
                              <th align="left" width="110"><?= (isset($_GET['show']) && $_GET['show'] == 'sent') ? 'Date Sent' : 'Date Saved' ?></th>
                              <th width="25%" align="left">Name</th>
                              <th align="left">Subject</th>
                              <?php if (isset($_GET['show']) && $_GET['show'] == 'sent') 
                              	echo '<th align="left" width="30%">Address Book(s) Used</th>';
                              ?>
                            </tr>
                            </thead>
                            <tbody>
                            <?php
					$searchctr='';		
					if(!empty($searchTxt))
					{
						$searchctr = " AND (";
						$searchArray1=explode(",",$searchArray);
						
						$searchctr.= "ID = '$searchTxt' OR CAMPAIGN_NAME like '%$searchTxt%' 
						OR FROM_NAME like '%$searchTxt%' 
						OR FROM_EMAIL like '%$searchTxt%' 
						OR SUBJECT like '%$searchTxt%'"; 
						$searchctr .= ") ";
					}
				
					$query = "SELECT ID, CAMPAIGN_NAME, FROM_NAME, FROM_EMAIL, REPLYTO_NAME, REPLYTO_EMAIL, SUBJECT, DATE_CREATED, DATE_SENT FROM
					smlr_campaigns WHERE $isSent $searchctr ORDER BY ID DESC LIMIT {$pageObj->start}, {$pageObj->limit}";		
					$resultSet = $funcObj->CustomQuery($query);		
							
							
					//$resultSet = $funcObj->FetchRecords("$table",$searchTxt,$searchArray,'ID DESC', $pageObj->start, $pageObj->limit);
					$i=1;
					if(count($resultSet)!=0)
					{
					foreach ($resultSet as $row)
					{
						$i++;
						echo "<tr>";
						$checked = '';
						
						if (count($clientSimpleArray))
						{
							if (in_array($row['ID'],$clientSimpleArray))
							{
								$checked = "checked='checked'";
							}
						}

						echo "
						<td align='center'>
						<input type='hidden' name='chkListingContacts[]' value='{$row["ID"]}' />
						<input type='checkbox' name='chkContacts[]' value='{$row["ID"]}' $checked />
						</td>
						<td align='left'>";
						if (isset($_GET['show']) && $_GET['show'] == 'sent')
							echo date("M j, Y", strtotime($row['DATE_SENT']));
						else
							echo date("M j, Y", strtotime($row['DATE_CREATED']));
						echo "</td>
						<td align='left'>{$row['CAMPAIGN_NAME']}</td>
						<td align='left'>{$row['SUBJECT']}</td>";
						
						## only show the address book column for sent campaigns
						if (isset($_GET['show']) && $_GET['show'] == 'sent') 
						{
							echo "<td align='left'>";
							
							$addrUsedResultset = getAddrUsed($row->ID);
							
							$iCount = 1;
							foreach ($addrUsedResultset as $val)
							{
								echo "($iCount). " . "<a href='contacts.php?addrid={$val->ID}'>" . $val->NAME . "</a><br />";
								$iCount++;
							}
							echo "</td>";
						}
							
							echo '</tr>';					
						}
						
					}
					else
					echo "<tr><td colspan='6' align='center' height='30' valign='middle' class='row0'>No Record Found... </td></tr>";
					?>
                         
                          </tbody>
                          <tfoot style="background-color: #ffffff; border-color: #ffffff;">
                          <?php
							if (count($resultSet))
							{
								echo "<tr>
								<td colspan='6' align='left' style='padding-left:10px; height: 30px' valign='top'><img src='images/selarrow.gif' alt='' border='0' /> <a href='javascript:;' onclick='return selaccessupdate()'>Update Campaign Access Permissions for selected client</a></td>
								</tr>";
							}
						  ?>
                          </tfoot>
                          </table>
                          <input type="hidden" name="hdnactiveclient" value="<?php echo intval(isset($_GET['id']) ? $_GET['id'] : '')?>" />
                          <input type="hidden" name="formtype" value="accessupdate" />
                        </form></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>
              </tr>
              </table></td>
      </tr>
    </table></td>
  </tr>
<?php require_once 'includes/inc.footer.php' ?>
</table>
</body>
</html>
