<?php
	class TicketsComponent extends Component {
		function GetUUIDs() {
			$uuids[] = 'admin\/tickets$';
			$uuids[] = 'admin\/tickets\/([^\/]*)';
			return $uuids;
		}

		function Run($page, $matches) {
			global $frameworks_path;
			
			if (!isset($_SESSION['username']))
			{
				$_SESSION['needlogin'] = 1;
				header('Location: /admin/login');
				die();
			}
			
			$mode = _hasflag(FLAG_GLOBALADMIN) && isset($_REQUEST['all']) ? 'all' : 'your';
			$action = isset($matches[1])?$matches[1]:'list';

			if (!isset($_REQUEST['ajax']))
				_page_header(SITE_NAME . ' :: Admin :: '.ucfirst($mode).' tickets');

			if ($action == 'list')
			{
				if (isset($_POST['ajax']))
				{
					$id = intval($_POST['id']);
					$cmd = strip_tags($_POST['ajax']);
					$query = get_db_rows("SELECT * FROM removerequest WHERE ".db_insert_id_field()."='".$id."' AND " . ($mode == 'all' ? "time > 0" : "assigned='" . $_SESSION['uid'] . "'") . " ORDER BY time ASC LIMIT 1");
					if (db_num_rows($query))
					{
						$data = get_db_tuple($query);
						switch($cmd)
						{
							case 'delete':
								get_db_rows("DELETE FROM removerequest WHERE ".db_insert_id_field()."='".$id."'");
								get_db_rows("DELETE FROM ticketmails WHERE ticketid='".$id."'");
								die('ok');
							case 'comments':
								die('<p>'.nl2br($data['remotereason']).'</p>');
						}
					}
					die('error');
				}
			
				if (_hasflag(FLAG_GLOBALADMIN))
				{
					$assigned = array();
					$query = get_db_rows("SELECT id, email, notes FROM rpckey");
					while ($row = get_db_tuple($query))
						$assigned['id'.$row['id']] = $row;
				}
?>
<a href="/">home</a> / <a href="/admin">administrate</a> / <?=$mode?> tickets
<h2><?=ucfirst($mode)?> tickets</h2>
<?php
				$results = array();
				$whereclause = ($mode != 'all' ? " WHERE assigned=" . $_SESSION['uid'] : '');
				$query = get_db_rows("SELECT r.".db_insert_id_field().", r.*, b.type, b.ip, b.port, b.listed, (SELECT COUNT(*) FROM ticketmails WHERE ticketid=r.".db_insert_id_field().") AS mailcount FROM removerequest r LEFT JOIN blacklist b ON b.id=r.incident".$whereclause." ORDER BY r.time ASC");
				while($tuple = get_db_tuple($query))
				{
					if ($tuple['listed'] == '0')
					{
						$oid = $tuple[db_insert_id_field()];
						get_db_rows("DELETE FROM removerequest WHERE id=".$tuple['id']);
						get_db_rows("DELETE FROM ticketmails WHERE ticketid=".$oid);
						continue;
					}
					
					$results[] = $tuple;
				}
				$total = count($results);
				echo '<p>A total of <span id="total">' . $total . '</span> tickets</p>' . PHP_EOL;
?>
<table class="listing2 compact stripe">
	<thead>
		<tr>
			<th class="left">Ticket Id</th>
			<th class="left">Incident</th>
			<th class="left">IP</th>
			<th class="left">Type</th>
			<th class="left">Port</th>
			<th class="left">Date added</th>
<?php
				if (_hasflag(FLAG_GLOBALADMIN))
					echo tab(3).'<th style="text-align:left">Assigned to</th>'.PHP_EOL;
?>
			<th class="left">Request Name</th>
			<th class="left">Request Email</th>
			<th class="left">Options</th>
		</tr>
	</thead>
	<tbody>
<?php
				foreach($results AS $result)
				{
					$oid = $result[db_insert_id_field()];
?>
		<tr id="head<?=$oid?>">
			<td rel="oid" class="link"><?= $oid ?></td>
			<td rel="iid"><?= $result['incident'] ?></td>
			<td rel="ip"><?= $result['ip'] ?></td>
			<td><?= $result['type'] ?></td>
			<td rel="port"><?= $result['port'] != 0 ? $result['port'] : '-' ?></td>
			<td><?= date('d-m-Y H:i:s', $result['time']) ?></td>
<?php
					if (_hasflag(FLAG_GLOBALADMIN))
						echo tab(3).'<td><a href="mailto:'.$assigned['id' . $result['assigned']]['email'].'?subject=[DroneBL%20#'. $oid.']%20Manual%20remove%20request%20incident%20'.$result['incident'].'%20IP:%20'.$result['ip'].'">'.$assigned['id'.$result['assigned']]['notes'].'</a></td>'.PHP_EOL;
?>
			<td><?= $result['remotename'] ?></td>
			<td rel="email"><?= $result['remotemail'] ?></td>
			<td>
				<img src="/images/admin/revoke.png" onclick="Tdelete(<?=$oid?>)" alt="Delete" title="Delete" class="link" />
<?php
					if ($result['mailcount'] > 0)
						echo tab(4).'<img src="/images/admin/email.png" onclick="Tviewmails('.$oid.')" alt="View Mails" title="View Mails ('.$result['mailcount'].')" class="link" />'.PHP_EOL;
?>
			</td>
		</tr>
<?php
				}
?>
	</tbody>
</table>
<script type="text/javascript">

	
	function Tdelete(id)
	{
		if (confirm('Are you sure you want to remove this ticket?'))
		{
			$.ajax({
				method: "POST",
				data: {  ajax: 'delete', id: id }
			})
			.done(function( msg ) {
				if (msg == 'ok')
				{
					table = $('table').DataTable();
					table.rows('#head'+id).remove().draw(false);
					$('#total').text(table.rows().count());
				}
			});
		}
	}
	
	function Tviewmails(id)
	{
		location.assign('/admin/tickets/viewmails?id='+id);
	}
	
	$('td[rel="email"]').each(function(){
		oid = $(this).parent().find('td[rel="oid"]').text();
		iid = $(this).parent().find('td[rel="iid"]').text();
		ip = $(this).parent().find('td[rel="ip"]').text();
		$(this).html('<a href="mailto:ticket@dronebl.org?subject=[DroneBL%20#'+oid+']%20Manual%20remove%20request%20incident%20'+iid+'%20IP:%20'+ip+'">'+$(this).text()+'</a>');
	});
	$('td[rel="ip"]').each(function(){
		$(this).html('<a rel="external" href="/lookup?ip='+$(this).text()+'">'+$(this).text()+'</a>');
	});
	
	$('table tbody').on('click', 'td:nth-child(1)', function () {
		table = $('table').DataTable();
		tr = $(this).closest('tr');
		row = table.row(tr);
		
		$.ajax({
			method: "POST",
			data: { ajax: 'comments', id: $(this).text() }
		})
		.done(function( msg ) {
			if (row.child.isShown())
			{
				row.child.hide();
				tr.removeClass('shown');
			}
			else
			{
				row.child( msg ).show();
				tr.addClass('shown');
			}
		});
	});
</script>
<?php
			}
			else if (isset($_REQUEST['id']) && is_numeric($_REQUEST['id']))
			{
				$id = $_REQUEST['id'];
				$query = get_db_rows("SELECT * FROM removerequest WHERE " . db_insert_id_field() . "='" . $id . "'" . (!_hasflag(FLAG_GLOBALADMIN) ? " AND assigned='" . $_SESSION['uid'] . "'" : '') . " LIMIT 1");
				if (db_num_rows($query) > 0)
				{
					if ($action == 'viewmails')
					{
						require_once($frameworks_path . '/mimeDecode.php');
						
						$result = [];
						$query = get_db_rows("SELECT * FROM ticketmails WHERE ticketid='".$id."'");
						while ($erow = get_db_tuple($query))
						{
							$Parser = new MimeMailParser();
							$Parser->setText($erow['contents']);
							$text =	$Parser->getMessageBody('text');						
							$html =	$Parser->getMessageBody('html');						
							$tmp = [
								'id' => $erow['id'],
								'timestamp' => date('d-m-Y H:i:s', $erow['timestamp']),
								'direction' => ($erow['direction']==0 ? 'Client' : 'Reporter'),
								'subject' => $Parser->getHeader('subject'),
								'source' => $erow['contents'],
								'text' => !empty($text),
								'html' => !empty($html),
								'attachments' => count($Parser->getAttachments())
							];
							$result['id'.$erow['id']] = $tmp;
						}

						if (isset($_REQUEST['ajax']))
						{
							$mid = intval($_REQUEST['mid']);
							if (isset($result['id'.$mid]))
							{
								$Parser = new MimeMailParser();
								$Parser->setText($result['id'.$mid]['source']);	
								$cmd = strip_tags($_REQUEST['ajax']);
								switch($cmd)
								{
									case 'source':
										die('<pre>'.htmlspecialchars($result['id'.$mid][$cmd]).'</pre>');
									case 'text':
										die('<pre>'.htmlspecialchars($Parser->getMessageBody('text')).'</pre>');
									case 'html':
										die('<div>'.htmlspecialchars($Parser->getMessageBody('html')).'</div>');
									case 'attachments':
										$counter = 0;
										foreach ($Parser->getAttachments() as $att)
										{
											$size = 0;
											while ($bytes = $att->read()) $size += strlen($bytes);
											$tmp .= '<tr><td><a href="?id='.$id.'&amp;ajax=dl&amp;mid='.$mid.'&amp;idx='.$counter.'">'.$att->filename.'</a></td><td>'.$att->content_type.'</td><td>'.$size.' bytes</td></tr>';
											$counter++;
										}
										$tmp .= '</tbody></table>';
										die($tmp);
									case 'dl':
										$idx = intval($_REQUEST['idx']);
										$atts = $Parser->getAttachments();
										if ($atts[$idx])
										{
											header('Content-Type: '.$atts[$idx]->content_type);
											header('Content-Transfer-Encoding: Binary'); 
											header('Content-disposition: attachment; filename="'.$atts[$idx]->filename.'"'); 
											while ($bytes = $atts[$idx]->read()) echo $bytes;
											exit;
										}
										break;
								}
							}
							die('error');
						}
						
?>
<a href="/">home</a> / <a href="/admin">administrate</a> / <a href="/admin/tickets">your tickets</a> / view mails
<h2>Overview Mails</h2>
<table class="listing2 compact stripe">
	<thead>
		<tr>
			<th>From</th>
			<th>Date</th>
			<th>Subject</th>
			<th>&nbsp;</th>
		</tr>
	</thead>
	<tbody>
<?php
						foreach($result AS $erow)
						{
?>
		<tr id="row<?=$erow['id']?>">
			<td><?=$erow['direction']?></td>
			<td><?=$erow['timestamp']?></td>
			<td><?=$erow['subject']?></td>
			<td>
				<?=($erow['text'] ? '<button onclick="view(\'text\','.$erow['id'].');">Text</button>':'')?>
				<?=($erow['html'] ? '<button onclick="view(\'html\','.$erow['id'].');">HTML</button>':'')?>
				<?=($erow['attachments'] ? '<button onclick="view(\'attachments\','.$erow['id'].');">Attachments ('.$erow['attachments'].')</button>':'')?>
				<?=($erow['source'] ? '<button onclick="view(\'source\','.$erow['id'].');">Source</button>':'')?>
			</td>
		</tr>
<?php
						}
?>
	</tbody>
</table>
<script type="text/javascript">
	function view(type,id)
	{
		table = $('table').DataTable();
		tr = $('#row'+id).closest('tr');
		row = table.row(tr);
		
		$.ajax({
			method: "POST",
			data: { ajax: type, mid: id }
		})
		.done(function( msg ) {
			if (row.child.isShown() && tr.attr('rel') == type)
				row.child.hide();
			else
			{
				row.child(msg).show();
				tr.attr('rel',type);
			}
		});
	}
</script>
<?php
					}
				}
			}
			else
			{
?>
<p>An unsupported action was requested: <code><?= $action ?></code></p>
<?php
			}

			_page_footer();
		}

	};

	new TicketsComponent;
?>
