<?php

if (!isset($PathPrefix)) {
	$PathPrefix='../';
}

include($PathPrefix . 'includes/session.php');
$Title=_('System Admin Maintenance Page');
include('includes/header.php');

$sql = "SELECT userid, realname FROM www_users WHERE blocked=0";
$result = DB_query($sql);
while($myrow = DB_fetch_array($result))
{
    $user_list[$myrow['userid']] = $myrow['realname'];
}


if(isset($_POST['approve_list']))
{
	foreach($_POST['id'] as $count => $id)
	{
		if(isset($_POST['reject'][$count]))
		{
			$sql = "UPDATE lms_page SET active = 0, approved = -1 WHERE id = '".$id."'";
			$result = DB_query($sql);
		}
		else if(isset($_POST['approve'][$count]))
		{
			$sql = "UPDATE lms_page SET active = 1, approved = 1 WHERE id = '".$id."'";
			$result = DB_query($sql);
		}
	}
}

// check and get any pending requests for approval
$sql = "SELECT id, url, label, message, userid FROM lms_page WHERE url <> '' AND approved = 0";
$result = DB_query($sql);
while($myrow = DB_fetch_array($result))
{
	$approval_list[$myrow['id']] = array("url" => $myrow['url'], "label" => $myrow['label'], "message" => $myrow['message'], "userid" => $myrow['userid']);
}


if(isset($_POST['user']) && !empty($_POST['user']))
{
	$page_limit = 10;
	$page_list = array();
	$user = $_POST['user'];
	$sql = "SELECT id, url, label, message FROM lms_page WHERE url <> '' AND userid='".$user."' AND active = 1 AND approved = 1 ORDER BY label";
	$result = DB_query($sql);
	while($myrow = DB_fetch_array($result))
	{
		$page_list[$myrow['id']] = array("url" => $myrow['url'], "label" => $myrow['label'], "message" => $myrow['message']);
	}
}

if(isset($_POST['update_list']))
{
	for($i=0; $i <= $page_limit; $i++)
	{
		if(isset($_POST['delete'][$i])) // remove url
		{
			// de-activate old url 
			unset($page_list[$_POST['id'][$i]]);
			$sql = "UPDATE lms_page SET active = 0 WHERE id = '".$_POST['id'][$i]."'";
			$result = DB_query($sql);
		}
		else if(!empty($_POST['url'][$i]) && !empty($_POST['label'][$i]) && !empty($_POST['message'][$i]))
		{

			$url = htmlspecialchars_decode($_POST['url'][$i], ENT_QUOTES);
			$label = htmlspecialchars_decode($_POST['label'][$i], ENT_QUOTES);
			$message = htmlspecialchars_decode($_POST['message'][$i], ENT_QUOTES);

			$id = $_POST['id'][$i];

			if(!empty($id)) // possible edit made
			{
				if($url != $page_list[$id]['url']) // editted url
				{
					// de-activate old url 
					unset($page_list[$id]);
					$sql = "UPDATE lms_page SET active = 0 WHERE id = '".$id."'";
					$result = DB_query($sql);


					// check if url previously added before adding new url
					$sql = "SELECT id FROM lms_page WHERE url = '".DB_escape_string($url)."' AND userid = '".$user."'";
					$result = DB_query($sql);

					if (DB_num_rows($result) > 0)
					{
						$myrow = DB_fetch_array($result);
						$page_id = $myrow['id'];
					
						$sql = "UPDATE lms_page SET label='".DB_escape_string($label)."',
													message='".DB_escape_string($message)."',
													active = 1,
													approved = 1
								WHERE id = '".$page_id."'";
						$result = DB_query($sql);
					}
					else
					{
						$sql = "INSERT INTO lms_page (url, label, message, userid, active, approved)
								VALUES ('".DB_escape_string($url)."', '".DB_escape_string($label)."', '".DB_escape_string($message)."', '".$user."', 1, 1)";
						$result = DB_query($sql);
						$page_id = $_SESSION['LastInsertId'];
					}

					// set new url to active
					// $sql = 'INSERT INTO lms_page (url, label, message, userid, active, approved)
					// 		VALUES ("'. DB_escape_string($url).'", "'.DB_escape_string($label).'", "'.DB_escape_string($message).'", "'.$user.'", 1, 1)
					// 		ON DUPLICATE KEY UPDATE label="'.DB_escape_string($label).'", message="'.DB_escape_string($message).'", active = 1, approved = 1';
					// $result = DB_query($sql);
					// $page_id = $_SESSION['LastInsertId'];


					$page_list[$page_id] = array("url" => $url, "label" => $label, "message" => $message);

					prnMsg('URL: ' . $url . ' has been added successfully','success');
				}
				else if($label != $page_list[$id]['label'] || $message != $page_list[$id]['message']) // editted label and/or message
				{
					$sql = 'UPDATE lms_page SET label = "'.DB_escape_string($label).'", message = "'.DB_escape_string($message).'" WHERE id = "'.$id.'"';
					$result = DB_query($sql);

					$page_list[$id]['label'] = $label;
					$page_list[$id]['message'] = $message;

					prnMsg('Label / Message for URL: ' . $url . ' has been updated successfully','success');
				}
			}
			else // new url
			{
				$sql = "SELECT id FROM lms_page WHERE url = '".DB_escape_string($url)."' AND userid = '".$user."'";
				$result = DB_query($sql);

				if (DB_num_rows($result) > 0)
				{
					$myrow = DB_fetch_array($result);
					$page_id = $myrow['id'];
				
					$sql = "UPDATE lms_page SET label='".DB_escape_string($label)."',
												message='".DB_escape_string($message)."',
												active = 1,
												approved = 1
							WHERE id = '".$page_id."'";
					$result = DB_query($sql);
				}
				else
				{
					$sql = "INSERT INTO lms_page (url, label, message, userid, active, approved)
							VALUES ('".DB_escape_string($url)."', '".DB_escape_string($label)."', '".DB_escape_string($message)."', '".$user."', 1, 1)";
					$result = DB_query($sql);
					$page_id = $_SESSION['LastInsertId'];
				}
				
				// set new url to active
				// $sql = 'INSERT INTO lms_page (url, label, message, userid, active, approved)
				// 		VALUES ("'.DB_escape_string($url).'", "'.DB_escape_string($label).'", "'.DB_escape_string($message).'", "'.$user.'", 1, 1)
				// 		ON DUPLICATE KEY UPDATE label="'.DB_escape_string($label).'", message="'.DB_escape_string($message).'", active = 1, approved = 1';
				// $result = DB_query($sql);
				// $page_id = $_SESSION['LastInsertId'];
				$page_list[$page_id] = array("url" => $url, "label" => $label, "message" => $message);

				prnMsg('URL: ' . $url . ' has been added successfully','success');
			}
		}
	}
}

?>

<div class="row">
	<div class="col-sm-4"></div>
	<div class="col-sm-4">
		<h2>System Admin Maintenance Page</h2>
		<br>
	</div>
	<div class="col-sm-4"></div>
</div>

<br>
<div class="row">
	<div class="col-sm-4"></div>
	<div class="col-sm-4">
		<form method="post">
			<div class="form-group">
				<label for="user">User:</label>
				<select class="form-control" name="user" required>
					<option value="" disabled selected>Please select...</option>
					<?php
					foreach($user_list as $id => $name)
					{
						echo '<option value="'.$id.'">' . $id . ' - ' . $name . '</option>';
					}
					?>
				</select>
			</div>
			<input type="hidden" name="FormID" value="<?php echo $_SESSION['FormID']; ?>" />
			<button type="submit" name="select" class="btn btn-default">Select</button>
		</form>
	</div>
	<div class="col-sm-4"></div>
</div>

<?php

if(isset($page_list))
{
	echo '<br>';
	echo '<h3>'.$user_list[$user].' Page List</h3>';

	echo '<form method="post">
			<table class="table">
				<thead>
					<tr>
						<th>#</th>
						<th>Label</th>
						<th>Message</th>
						<th>URL</th>
						<th>Remove</th>
					</tr>
				</thead>
				<tbody>';

	$page_count = 0;
	$contact_card_url = getNameCardLink($user);
	foreach($page_list as $id => $page)
	{
		$page_count++;

		if($page['url'] == $contact_card_url) // omit contact card url
		{
			echo "<tr class='info'>
					<td><input type='hidden' name='id[".$page_count."]' value='".$id."' />".$page_count."</td>
					<td><input type='text' class='form-control' name='label[".$page_count."]' maxlength='255' placeholder='Label' value='".htmlspecialchars($page["label"], ENT_QUOTES)."'></td>
					<td><input type='text' class='form-control' name='message[".$page_count."]' placeholder='Message' value='".htmlspecialchars($page["message"], ENT_QUOTES)."'></td>
					<td><input type='text' class='form-control' name='url[".$page_count."]' maxlength='500' placeholder='URL' value='".$page["url"]."' readonly></td>
					<td></td>
				</tr>";
		}
		else
		{
			echo "<tr>
					<td><input type='hidden' name='id[".$page_count."]' value='".$id."' />".$page_count."</td>
					<td><input type='text' class='form-control' name='label[".$page_count."]' maxlength='255' placeholder='Label' value='".htmlspecialchars($page["label"], ENT_QUOTES)."'></td>
					<td><input type='text' class='form-control' name='message[".$page_count."]' placeholder='Message' value='".htmlspecialchars($page["message"], ENT_QUOTES)."'></td>
					<td><input type='text' class='form-control' name='url[".$page_count."]' maxlength='500' placeholder='URL' value='".$page["url"]."'></td>
					<td>
						<div class='checkbox'>
							<label><input name='delete[".$page_count."]' type='checkbox'></label>
						</div>
					</td>
				</tr>";
		}
	}

	while($page_count < $page_limit)
	{
		$page_count++;

		echo '<tr>
				<td><input type="hidden" name="id['.$page_count.']" value="" />'.$page_count.'</td>
				<td><input type="text" class="form-control" name="label['.$page_count.']" maxlength="255" placeholder="Label" value=""></td>
				<td><input type="text" class="form-control" name="message['.$page_count.']" placeholder="Message" value=""></td>
				<td><input type="text" class="form-control" name="url['.$page_count.']" maxlength="500" placeholder="URL" value=""></td>
				<td></td>
			</tr>';
	}



	echo '</tbody>
		</table>
		<input type="hidden" name="FormID" value="'.$_SESSION['FormID'].'" />
		<input type="hidden" name="user" value="'.$user.'" />
		<button type="submit" name="update_list" class="btn btn-default">Update</button>
	</form>';
}
else if(count($approval_list) > 0)
{
	echo '<br>';
	echo '<div class="panel panel-primary">
			<div class="panel-heading">Pending Approval</div>
			<div class="panel-body">';

	echo '<form method="post">
			<div class="table-responsive">
				<table class="table table-condensed table-hover table-striped">
					<thead>
						<tr>
							<th>#</th>
							<th>User Id</th>
							<th>Label</th>
							<th>Message</th>
							<th>URL</th>
							<th>Approve</th>
							<th>Reject</th>
						</tr>
					</thead>
					<tbody>';

	$i = 0;
	foreach($approval_list as $id => $page)
	{
		$i++;

		echo '<tr>
				<td><input type="hidden" name="id['.$i.']" value="'.$id.'" />'.$i.'</td>
				<td>'.$page['userid'].'</td>
				<td>'.htmlspecialchars($page['label'], ENT_QUOTES).'</td>
				<td>'.htmlspecialchars($page['message'], ENT_QUOTES).'</td>
				<td>'.htmlspecialchars($page['url']).' <a href="'.$page['url'].'" target="_blank"><span class="glyphicon glyphicon-share"></span></a></td>
				<td>
					<input name="approve['.$i.']" type="checkbox">
				</td>
				<td>
					<input name="reject['.$i.']" type="checkbox">
				</td>
			</tr>';
	}


	echo '</tbody>
		</table>
		</div>
		<input type="hidden" name="FormID" value="'.$_SESSION['FormID'].'" />
		<input type="hidden" name="user" value="'.$user.'" />
		<button type="submit" name="approve_list" class="btn btn-default">Update</button>
	</form>
	</div>
	</div>';
}

include('includes/footer.php');
?>