<?php

$page = $_GET['page'];
$paged = isset($_GET['paged']) ? intval($_GET['paged']) : 1;

$columns = array(
	'id' => 'id',
	'created_on' => 'created_on',
	'submitted' => 'submitted',
	'default' => 'created_on'

);

$orderby = isset($_GET['orderby']) && isset($columns[$_GET['orderby']]) ? $columns[$_GET['orderby']] : $columns['default'];
$order = isset($_GET['order']) && $_GET['order'] == 'asc' ? 'ASC' : 'DESC';

global $wpdb;

if (isset($_GET['delete'])) {
	$wpdb->delete(
		"{$wpdb->prefix}bwsurvey_entries",
		array(
			'id' => $_GET['delete'],
		),
		array(
			'%d',
		)
	);
}

$per_page = 25;


if (isset($_GET['survey'])) {
	$item_count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(id) FROM {$wpdb->prefix}bwsurvey_entries WHERE LENGTH(data) > 6 AND survey_id = %d;", $_GET['survey']));
	$page_count = ceil($item_count / $per_page);

	$paged = isset($_GET['paged']) ? min($page_count, max(1, $paged)) : 1;

	$survey_title = $wpdb->get_var($wpdb->prepare("SELECT title FROM {$wpdb->prefix}bwsurvey_surveys WHERE id = %d;", $_GET['survey']));

	$results = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}bwsurvey_entries
		WHERE LENGTH(data) > 6 AND survey_id = %d
		ORDER BY {$orderby} {$order}
		LIMIT %d OFFSET %d",
		$_GET['survey'],
		$per_page,
		$per_page * ($paged - 1)
	));
} else {
	$item_count = $wpdb->get_var("SELECT COUNT(id) FROM {$wpdb->prefix}bwsurvey_entries WHERE LENGTH(data) > 6;");
	$page_count = ceil($item_count / $per_page);

	$paged = isset($_GET['paged']) ? min($page_count, max(1, $paged)) : 1;

	$results = $wpdb->get_results($wpdb->prepare("SELECT entry.*, survey.title AS survey FROM {$wpdb->prefix}bwsurvey_entries AS entry
		INNER JOIN {$wpdb->prefix}bwsurvey_surveys AS survey ON entry.survey_id = survey.id
		WHERE LENGTH(entry.data) > 6
		ORDER BY {$orderby} {$order}
		LIMIT %d OFFSET %d",
		$per_page,
		$per_page * ($paged - 1)
	));
}

?>
<div class="wrap">
	<h1 class="wp-heading-inline">Entries</h1>
	<hr class="wp-header-end">
	
	<div>
		<div class="tablenav top">
			<div class="tablenav-pages <?php if ($page_count == 1) echo 'one-page'; ?>">
				<span class="displaying-num"><?php echo $item_count; ?> <?php echo $item_count == 1 ? 'item' : 'items'; ?></span>
				<span class="pagination-links">
					<?php if ($paged > 1): ?>
						<a class="tablenav-pages-navspan button" href="<?php echo add_query_arg('paged', 1); ?>" aria-hidden="true">«</a>
						<a class="tablenav-pages-navspan button" href="<?php echo add_query_arg('paged', $paged - 1); ?>" aria-hidden="true">‹</a>
					<?php else: ?>
						<span class="tablenav-pages-navspan button disabled" aria-hidden="true">«</span>
						<span class="tablenav-pages-navspan button disabled" aria-hidden="true">‹</span>
					<?php endif; ?>
					<span class="paging-input">
						<span class="tablenav-paging-text"><?php echo $paged; ?> of <span class="total-pages"><?php echo $page_count; ?></span>
						</span>
					</span>
					<?php if ($paged < $page_count): ?>
						<a class="tablenav-pages-navspan button" href="<?php echo add_query_arg('paged', $paged + 1); ?>" aria-hidden="true">›</a>
						<a class="tablenav-pages-navspan button" href="<?php echo add_query_arg('paged', $page_count); ?>" aria-hidden="true">»</a>
					<?php else: ?>
						<span class="tablenav-pages-navspan button disabled" aria-hidden="true">›</span>
						<span class="tablenav-pages-navspan button disabled" aria-hidden="true">»</span>
					<?php endif; ?>
				</span>
			</div>
			<br class="clear">
		</div>
		<h2 class="screen-reader-text">Survey Pages list</h2>
		<table class="wp-list-table widefat fixed striped table-view-list posts">
			<thead>
				<tr>
					<th scope="col" class="manage-column column-date column-primary sortable <?php echo $orderby == 'created_on' && $order == 'ASC' ? 'desc' : 'asc'; ?>">
						<a href="<?php echo add_query_arg(array(
							'orderby' => 'created_on',
							'order' => $orderby == 'created_on' && $order == 'ASC' ? 'desc' : 'asc'
						)); ?>">
							<span>Date</span>
							<span class="sorting-indicator"></span>
						</a>
					</th>
					<th scope="col" class="manage-column column-id">Survey</th>
					<th scope="col" class="manage-column column-id sortable <?php echo $orderby == 'submitted' && $order == 'ASC' ? 'desc' : 'asc'; ?>">
						<a href="<?php echo add_query_arg(array(
							'orderby' => 'id',
							'order' => $orderby == 'submitted' && $order == 'ASC' ? 'desc' : 'asc'
						)); ?>">
							<span>Status</span>
							<span class="sorting-indicator"></span>
						</a>
					</th>
				</tr>
			</thead>
			<tbody id="the-list">
				<?php foreach ($results as $result) : ?>
					<?php
						if (isset($result->survey)) $survey_title = $result->survey;
						$data = unserialize($result->data);
						$length = empty($data) ? 0 : count($data);
					?>
					<tr id="post-5" class="iedit author-self level-0 post-5 type-survey status-publish hentry">
						<td class="title column-date has-row-actions column-primary page-title" data-colname="Title">
							<strong>
								<a class="row-title" href="<?php echo add_query_arg(array(
									'page' => $page,
									'view' => $result->id
								), admin_url('admin.php')); ?>" aria-label="“<?php echo $result->id; ?>” (View)"><?php echo $result->created_on; ?></a>
							</strong>
							<div class="row-actions">
								<span class="edit">
									<a href="<?php echo add_query_arg(array(
										'page' => $page,
										'view' => $result->id
									), admin_url('admin.php')); ?>" aria-label="View “<?php echo $result->id; ?>”">View</a> | </span>
								<span class="delete">
									<a href="<?php echo add_query_arg(array(
										'page' => $page,
										'delete' => $result->id
									), admin_url('admin.php')); ?>" class="submitdelete" aria-label="Delete “<?php echo $result->id; ?>”">Delete</a>
								</span>
							</div>
						</td>
						<td><?php echo $survey_title; ?></td>
						<td><?php echo $result->submitted ? 'Submitted' : 'Not Submitted'; ?> (<?php echo $length; ?>)</td>
					</tr>
				<?php endforeach; ?>
			</tbody>
			<tfoot>
				<tr>
					<th scope="col" class="manage-column column-date column-primary sortable <?php echo $orderby == 'created_on' && $order == 'ASC' ? 'desc' : 'asc'; ?>">
						<a href="<?php echo add_query_arg(array(
							'orderby' => 'created_on',
							'order' => $orderby == 'created_on' && $order == 'ASC' ? 'desc' : 'asc'
						)); ?>">
							<span>Date</span>
							<span class="sorting-indicator"></span>
						</a>
					</th>
					<th scope="col" class="manage-column column-id">Survey</th>
					<th scope="col" class="manage-column column-id sortable <?php echo $orderby == 'submitted' && $order == 'ASC' ? 'desc' : 'asc'; ?>">
						<a href="<?php echo add_query_arg(array(
							'orderby' => 'id',
							'order' => $orderby == 'submitted' && $order == 'ASC' ? 'desc' : 'asc'
						)); ?>">
							<span>Status</span>
							<span class="sorting-indicator"></span>
						</a>
					</th>
				</tr>
			</tfoot>
		</table>
		<div class="tablenav bottom">
			<div class="tablenav-pages <?php if ($page_count == 1) echo 'one-page'; ?>">
				<span class="displaying-num"><?php echo $item_count; ?> <?php echo $item_count == 1 ? 'item' : 'items'; ?></span>
				<span class="pagination-links">
					<?php if ($paged > 1): ?>
						<a class="tablenav-pages-navspan button" href="<?php echo add_query_arg('paged', 1); ?>" aria-hidden="true">«</a>
						<a class="tablenav-pages-navspan button" href="<?php echo add_query_arg('paged', $paged - 1); ?>" aria-hidden="true">‹</a>
					<?php else: ?>
						<span class="tablenav-pages-navspan button disabled" aria-hidden="true">«</span>
						<span class="tablenav-pages-navspan button disabled" aria-hidden="true">‹</span>
					<?php endif; ?>
					<span class="paging-input">
						<span class="tablenav-paging-text"><?php echo $paged; ?> of <span class="total-pages"><?php echo $page_count; ?></span>
						</span>
					</span>
					<?php if ($paged < $page_count): ?>
						<a class="tablenav-pages-navspan button" href="<?php echo add_query_arg('paged', $paged + 1); ?>" aria-hidden="true">›</a>
						<a class="tablenav-pages-navspan button" href="<?php echo add_query_arg('paged', $page_count); ?>" aria-hidden="true">»</a>
					<?php else: ?>
						<span class="tablenav-pages-navspan button disabled" aria-hidden="true">›</span>
						<span class="tablenav-pages-navspan button disabled" aria-hidden="true">»</span>
					<?php endif; ?>
				</span>
			</div>
			<br class="clear">
		</div>
	</div>
	<div class="clear"></div>

	<div class="csv-export">
		<h4>CSV Export</h4>
		<?php

			$results = $wpdb->get_results("SELECT id, title FROM {$wpdb->prefix}bwsurvey_surveys ORDER BY title");
			$survey_id = isset( $_GET['survey'] ) ? intval( $_GET['survey'] ) :  ( isset( $results[0] ) ? $results[0]->id : 0 );
		?>
		<?php if ( !empty( $results ) ) : ?>
			<label>Survey:
				<select class="export-survey" style="display: block; margin: 4px 0 8px;">
					<?php foreach ( $results as $survey ) : ?>
						<option
							value="<?php echo $survey->id; ?>"
							<?php if ($survey->id == $survey_id) echo 'selected'?>
						>
							<?php echo $results[0]->title; ?>
						</option>
					<?php endforeach; ?>
				</select>
			</label>
		<?php endif; ?>
		<label>Page:
			<input
				class="export-page"
				type="number"
				min="1"
				value="1"
				style="display: block; margin: 4px 0 8px;"
			/>
		</label>
		<a
			class="export-button button"
			href="/downloads/<?php echo $survey_id; ?>/entries.csv"
			download
			style="display: block; margin-top: 14px; width: fit-content;"
		>
			Download CSV
		</a>
		<script>
			(() => {
				const eachElem = (query, callback) => Array.prototype.forEach.call(document.querySelectorAll(query), callback)

				const fields = {
					surveyId: <?php echo intval( $survey_id ); ?>,
					page: 1
				}

				const handleChange = (field) => (event) => {
					fields[field] = event.target.value
					updateLinks()
				}

				const updateLinks = () => {
					eachElem('.csv-export a.export-button', elem => {
						elem.setAttribute('href', `/downloads/${fields.surveyId}/entries.csv?page=${fields.page}`)
					})
				}

				const addEventListeners = () => {
					eachElem('.csv-export select.export-survey', elem => {
						elem.addEventListener('change', handleChange('surveyId'))
					})
					eachElem('.csv-export input.export-page', elem => {
						elem.addEventListener('change', handleChange('page'))
					})
				}

				addEventListener('DOMContentLoaded', (event) => {
					addEventListeners()
				});
			})()
		</script>
	</div>
</div>
