<?php
namespace MMP\Menu;

use MMP\Maps_Marker_Pro as MMP;

class Markers extends Menu {
	private $page;

	/**
	 * Sets up the class
	 *
	 * @since 4.26
	 */
	public function __construct() {
		$this->page = null;
	}

	/**
	 * Registers the hooks
	 *
	 * @since 4.0
	 */
	public function init() {
		add_filter('screen_settings', array($this, 'screen_settings'), 10, 2);

		add_action('load-maps-marker-pro_page_mapsmarkerpro_markers', array($this, 'load_page'));
		add_action('admin_enqueue_scripts', array($this, 'load_resources'));
		add_action('wp_ajax_mmp_delete_marker', array($this, 'delete_marker'));
		add_action('wp_ajax_mmp_bulk_action_markers', array($this, 'bulk_action_markers'));
		add_action('wp_ajax_mmp_markers_screen_options', array($this, 'mmp_markers_screen_options'));
	}

	/**
	 * Adds the screen options to the page
	 *
	 * @since 4.8
	 *
	 * @param string $screen_settings Current screen options
	 * @param WP_Screen $screen Current screen object instance
	 */
	public function screen_settings($screen_settings, $screen) {
		$mmp_settings = MMP::get_instance('MMP\Settings');

		if ($screen->id !== 'maps-marker-pro_page_mapsmarkerpro_markers') {
			return $screen_settings;
		}

		$options = get_user_meta(get_current_user_id(), 'mapsmarkerpro_markers_options', true);
		$options = $mmp_settings->validate_markers_screen_settings($options);

		ob_start();
		?>
		<fieldset>
			<legend><?= esc_html__('Columns', 'mmp') ?></legend>
			<label><input type="checkbox" class="mmp-markers-column" value="address" <?= $this->checked(!in_array('address', $options['hiddenColumns'])) ?>/><?= esc_html__('Location', 'mmp') ?></label>
			<label><input type="checkbox" class="mmp-markers-column" value="popup" <?= $this->checked(!in_array('popup', $options['hiddenColumns'])) ?>/><?= esc_html__('Popup', 'mmp') ?></label>
			<label><input type="checkbox" class="mmp-markers-column" value="author" <?= $this->checked(!in_array('author', $options['hiddenColumns'])) ?>/><?= esc_html__('Author', 'mmp') ?></label>
			<label><input type="checkbox" class="mmp-markers-column" value="date" <?= $this->checked(!in_array('date', $options['hiddenColumns'])) ?>/><?= esc_html__('Date', 'mmp') ?></label>
			<label><input type="checkbox" class="mmp-markers-column" value="expiry" <?= $this->checked(!in_array('expiry', $options['hiddenColumns'])) ?>/><?= esc_html__('Expiry', 'mmp') ?></label>
			<label><input type="checkbox" class="mmp-markers-column" value="modified" <?= $this->checked(!in_array('modified', $options['hiddenColumns'])) ?>/><?= esc_html__('Modified', 'mmp') ?></label>
			<label><input type="checkbox" class="mmp-markers-column" value="assigned_to" <?= $this->checked(!in_array('assigned_to', $options['hiddenColumns'])) ?>/><?= esc_html__('Assigned to map', 'mmp') ?></label>
		</fieldset>
		<fieldset>
			<legend><?= esc_html__('Pagination', 'mmp') ?></legend>
			<label for="markers-per-page"><?= esc_html__('Markers per page', 'mmp') ?>:</label>
			<input type="number" id="markers-per-page" min="1" max="1000" step="1" value="<?= $options['perPage'] ?>" />
		</fieldset>
		<p><button type="submit" class="button button-primary"><?= esc_html__('Apply', 'mmp') ?></button></p>
		<?php
		$screen_settings .= ob_get_clean();

		return $screen_settings;
	}

	/**
	 * Executes when the page is loaded
	 *
	 * @since 4.26
	 */
	public function load_page() {
		$db = MMP::get_instance('MMP\DB');
		$l10n = MMP::get_instance('MMP\L10n');
		$mmp_settings = MMP::get_instance('MMP\Settings');

		$args = array(
			'page'      => 'mapsmarkerpro_markers',
			'search'    => (isset($_GET['search'])) ? wp_unslash($_GET['search']) : '',
			'map'       => (isset($_GET['map'])) ? intval($_GET['map']) : 0,
			'orderby'   => (isset($_GET['orderby'])) ? wp_unslash($_GET['orderby']) : 'id',
			'sortorder' => (isset($_GET['sortorder']) && $_GET['sortorder'] === 'desc') ? 'desc' : 'asc',
			'paged'     => (isset($_GET['paged'])) ? absint($_GET['paged']) : 1
		);

		$options = get_user_meta(get_current_user_id(), 'mapsmarkerpro_markers_options', true);
		$options = $mmp_settings->validate_markers_screen_settings($options);

		$marker_count = $db->count_markers(array(
			'include_maps' => $args['map'],
			'contains'     => $args['search']
		));

		$page_count = ceil($marker_count / $options['perPage']);
		$args['paged'] = ($args['paged'] < 1) ? 1 : $args['paged'];
		$args['paged'] = ($args['paged'] > $page_count) ? $page_count : $args['paged'];

		$query = http_build_query(array_filter($args), '', '&');
		$url = get_admin_url(null, "admin.php?$query");

		if (!headers_sent() && !$this->compare_page_args($args)) {
			wp_redirect($url);
			die;
		}

		$columns = array('id', 'name', 'icon', 'status', 'author_id');
		if (!in_array('location', $options['hiddenColumns'])) {
			$columns[] = 'address';
		}
		if (!in_array('popup', $options['hiddenColumns'])) {
			$columns[] = 'popup';
		}
		if (!in_array('author', $options['hiddenColumns'])) {
			$columns[] = 'author';
		}
		if (!in_array('date', $options['hiddenColumns'])) {
			$columns[] = 'publish';
		}
		if (!in_array('expiry', $options['hiddenColumns'])) {
			$columns[] = 'expires';
		}
		if (!in_array('modified', $options['hiddenColumns'])) {
			$columns[] = 'modified';
		}
		if (!in_array('maps', $options['hiddenColumns'])) {
			$columns[] = 'maps';
		}
		$markers = $db->get_all_markers(array(
			'columns'      => $columns,
			'include_maps' => $args['map'],
			'contains'     => $args['search'],
			'orderby'      => $args['orderby'],
			'sortorder'    => $args['sortorder'],
			'offset'       => ($args['paged'] - 1) * $options['perPage'],
			'limit'        => $options['perPage']
		));

		$maps = $db->get_all_maps(false, array(
			'columns' => array('id', 'name')
		));

		ob_start();
		?>
		<div class="wrap">
			<h1 class="wp-heading-inline"><?= esc_html__('Markers', 'mmp') ?></h1>
			<a href="<?= get_admin_url(null, 'admin.php?page=mapsmarkerpro_marker') ?>" class="page-title-action"><?= esc_html__('Add new marker', 'mmp') ?></a>
			<form id="markers_filter" method="GET">
				<input type="hidden" name="page" value="<?= $args['page'] ?>" />
				<input type="hidden" name="orderby" value="<?= esc_attr($args['orderby']) ?>" />
				<input type="hidden" name="sortorder" value="<?= $args['sortorder'] ?>" />
				<div class="mmp-tablenav mmp-tablenav-top mmp-tablenav-markers">
					<div><?= esc_html__('Total markers:', 'mmp') ?> <?= $marker_count ?></div>
					<div>
						<input type="text" class="mmp-search" name="search" value="<?= esc_attr($args['search']) ?>" />
						<button type="submit" class="button"><?= esc_html__('Search markers', 'mmp') ?></button>
					</div>
					<div class="mmp-tablenav-filter-map">
						<select id="map" name="map">
							<option value="0" <?= $this->selected($args['map'], 0, false) ?>><?= esc_html__('All maps', 'mmp') ?></option>
							<option value="-1" <?= $this->selected($args['map'], -1, false) ?>><?= esc_html__('Not assigned to any map', 'mmp') ?></option>
							<?php foreach ($maps as $map): ?>
								<option value="<?= $map->id ?>" <?= $this->selected($args['map'], $map->id, false) ?>>[<?= $map->id ?>] <?= esc_html($map->name) ?></option>
							<?php endforeach; ?>
						</select>
					</div>
					<div class="mmp-tablenav-pagination">
						<?php if ($args['paged'] < 2): ?>
							<span class="button disabled">&laquo;</span>
							<span class="button disabled">&lsaquo;</span>
						<?php else: ?>
							<a class="button" href="<?= add_query_arg('paged', 1) ?>">&laquo;</a>
							<a class="button" href="<?= add_query_arg('paged', $args['paged'] - 1) ?>">&lsaquo;</a>
						<?php endif; ?>
						<span><input class="mmp-page" type="text" name="paged" value="<?= $args['paged'] ?>" /> <?= esc_html__('of', 'mmp') ?> <?= $page_count ?></span>
						<?php if ($args['paged'] >= $page_count): ?>
							<span class="button disabled">&rsaquo;</span>
							<span class="button disabled">&raquo;</span>
						<?php else: ?>
							<a class="button" href="<?= add_query_arg('paged', $args['paged'] + 1) ?>">&rsaquo;</a>
							<a class="button" href="<?= add_query_arg('paged', $page_count) ?>">&raquo;</a>
						<?php endif; ?>
					</div>
				</div>
			</form>
			<table class="mmp-table mmp-table-markers">
				<tr>
					<th><input type="checkbox" id="select-all" /></th>
					<th><a href="<?= $this->get_column_sort_link('id', $args) ?>" class="mmp-sortable" title="<?= esc_html__('click to sort', 'mmp') ?>"><?= esc_html__('ID', 'mmp') ?></a></th>
					<th><a href="<?= $this->get_column_sort_link('icon', $args) ?>" class="mmp-sortable" title="<?= esc_html__('click to sort', 'mmp') ?>"><?= esc_html__('Icon', 'mmp') ?></a></th>
					<th><a href="<?= $this->get_column_sort_link('name', $args) ?>" class="mmp-sortable" title="<?= esc_html__('click to sort', 'mmp') ?>"><?= esc_html__('Name', 'mmp') ?></a></th>
					<?php if (!in_array('address', $options['hiddenColumns'])): ?>
						<th><a href="<?= $this->get_column_sort_link('address', $args) ?>" class="mmp-sortable" title="<?= esc_html__('click to sort', 'mmp') ?>"><?= esc_html__('Location', 'mmp') ?></a></th>
					<?php endif; ?>
					<?php if (!in_array('popup', $options['hiddenColumns'])): ?>
						<th><a href="<?= $this->get_column_sort_link('popup', $args) ?>" class="mmp-sortable" title="<?= esc_html__('click to sort', 'mmp') ?>"><?= esc_html__('Popup', 'mmp') ?></a></th>
					<?php endif; ?>
					<?php if (!in_array('author', $options['hiddenColumns'])): ?>
						<th><a href="<?= $this->get_column_sort_link('author', $args) ?>" class="mmp-sortable" title="<?= esc_html__('click to sort', 'mmp') ?>"><?= esc_html__('Author', 'mmp') ?></a></th>
					<?php endif; ?>
					<?php if (!in_array('date', $options['hiddenColumns'])): ?>
						<th><a href="<?= $this->get_column_sort_link('publish', $args) ?>" class="mmp-sortable" title="<?= esc_html__('click to sort', 'mmp') ?>"><?= esc_html__('Date', 'mmp') ?></a></th>
					<?php endif; ?>
					<?php if (!in_array('expiry', $options['hiddenColumns'])): ?>
						<th><a href="<?= $this->get_column_sort_link('expiry', $args) ?>" class="mmp-sortable" title="<?= esc_html__('click to sort', 'mmp') ?>"><?= esc_html__('Expiry', 'mmp') ?></a></th>
					<?php endif; ?>
					<?php if (!in_array('modified', $options['hiddenColumns'])): ?>
						<th><a href="<?= $this->get_column_sort_link('modified', $args) ?>" class="mmp-sortable" title="<?= esc_html__('click to sort', 'mmp') ?>"><?= esc_html__('Modified', 'mmp') ?></a></th>
					<?php endif; ?>
					<?php if (!in_array('assigned_to', $options['hiddenColumns'])): ?>
						<th><?= esc_html__('Assigned to map', 'mmp') ?></th>
					<?php endif; ?>
				</tr>
				<?php if (!count($markers)): ?>
					<tr><td class="mmp-no-results" colspan="<?= 11 - count($options['hiddenColumns']) ?>"><?= esc_html__('No results') ?></td></tr>
				<?php else: ?>
					<?php foreach ($markers as $marker): ?>
						<tr>
							<td class="no-width centered"><input type="checkbox" name="selected[]" value="<?= $marker->id ?>" /></td>
							<td class="no-width centered"><?= $marker->id ?></td>
							<td class="narrow centered"><img src="<?= ($marker->icon) ? MMP::$icons_url . $marker->icon : plugins_url('images/leaflet/marker.png', MMP::$path) ?>" /></td>
							<td class="mmp-has-row-actions">
								<?php if ($marker->author_id == get_current_user_id() || current_user_can('mmp_edit_other_markers')): ?>
									<a href="<?= get_admin_url(null, 'admin.php?page=mapsmarkerpro_marker&id=' . $marker->id) ?>" title="<?= esc_html__('Edit marker', 'mmp') ?>"><?= ($marker->name) ? esc_html($marker->name) : esc_html__('(no name)', 'mmp') ?></a>
								<?php else: ?>
									<?= ($marker->name) ? esc_html($marker->name) : esc_html__('(no name)', 'mmp') ?>
								<?php endif; ?>
								<?php if ($marker->status === 'scheduled'): ?>
									&mdash; <span class="mmp-marker-status-scheduled"><?= esc_html__('Scheduled', 'mmp') ?></span>
								<?php elseif ($marker->status === 'expired'): ?>
									&mdash; <span class="mmp-marker-status-expired"><?= esc_html__('Expired', 'mmp') ?></span>
								<?php endif; ?>
								<div class="mmp-row-actions">
									<ul>
										<?php if ($marker->author_id == get_current_user_id() || current_user_can('mmp_edit_other_markers')): ?>
											<li><a href="<?= get_admin_url(null, 'admin.php?page=mapsmarkerpro_marker&id=' . $marker->id) ?>" title="<?= esc_html__('Edit marker', 'mmp') ?>"><?= esc_html__('Edit', 'mmp') ?></a></li>
										<?php endif; ?>
										<?php if ($marker->author_id == get_current_user_id() || current_user_can('mmp_delete_other_markers')): ?>
											<li><span class="mmp-delete" href="" data-id="<?= $marker->id ?>" data-nonce="<?= wp_create_nonce("mmp-delete-marker-{$marker->id}") ?>" title="<?= esc_html__('Delete marker', 'mmp') ?>"><?= esc_html__('Delete', 'mmp') ?></span></li>
										<?php endif; ?>
										<li>
											<?php if ($l10n->check_ml() === 'wpml'): ?>
												<a href="<?= get_admin_url(null, 'admin.php?page=wpml-string-translation%2Fmenu%2Fstring-translation.php&context=Maps+Marker+Pro') ?>" target="_blank"><?= esc_html__('Translate', 'mmp') ?></a>
											<?php elseif ($l10n->check_ml() === 'pll'): ?>
												<a href="<?= get_admin_url(null, 'admin.php?page=mlang_strings&s=Marker+%28ID+' . $marker->id . '%29&group=Maps+Marker+Pro') ?>" target="_blank"><?= esc_html__('Translate', 'mmp') ?></a>
											<?php else: ?>
												<a href="https://www.mapsmarker.com/multilingual/" target="_blank"><?= esc_html__('Translate', 'mmp') ?></a>
											<?php endif; ?>
										</li>
									</ul>
								</div>
							</td>
							<?php if (!in_array('address', $options['hiddenColumns'])): ?>
								<td><?= esc_html($marker->address) ?></td>
							<?php endif; ?>
							<?php if (!in_array('popup', $options['hiddenColumns'])): ?>
								<td><?= wp_strip_all_tags($marker->popup) ?></td>
							<?php endif; ?>
							<?php if (!in_array('author', $options['hiddenColumns'])): ?>
								<td><?= esc_html($marker->author) ?></td>
							<?php endif; ?>
							<?php if (!in_array('date', $options['hiddenColumns'])): ?>
								<td>
									<?php if ($marker->status === 'scheduled'): ?>
										<span class="mmp-marker-status-scheduled"><?= esc_html__('Scheduled', 'mmp') ?></span><br />
									<?php else: ?>
										<span class="mmp-marker-status-published"><?= esc_html__('Published', 'mmp') ?></span><br />
									<?php endif; ?>
									<abbr class="mmp-datetime" title="<?= $l10n->date('datetime', $marker->publish) ?>"><?= $l10n->date('date', $marker->publish) ?></abbr>
								</td>
							<?php endif; ?>
							<?php if (!in_array('expiry', $options['hiddenColumns'])): ?>
								<td>
									<?php if ($marker->expires): ?>
										<?php if ($marker->status === 'expired'): ?>
											<span class="mmp-marker-status-expired"><?= esc_html__('Expired', 'mmp') ?></span><br />
										<?php else: ?>
											<span class="mmp-marker-status-expires"><?= esc_html__('Expires', 'mmp') ?></span><br />
										<?php endif; ?>
										<abbr class="mmp-datetime" title="<?= $l10n->date('datetime', $marker->expires) ?>"><?= $l10n->date('date', $marker->expires) ?></abbr>
									<?php else: ?>
										<span class="mmp-marker-status-no-expiry"><?= esc_html__('Never', 'mmp') ?></span>
									<?php endif; ?>
								</td>
							<?php endif; ?>
							<?php if (!in_array('modified', $options['hiddenColumns'])): ?>
								<td><abbr class="mmp-datetime" title="<?= $l10n->date('datetime', $marker->modified) ?>"><?= $l10n->date('date', $marker->modified) ?></abbr></td>
							<?php endif; ?>
							<?php if (!in_array('assigned_to', $options['hiddenColumns'])): ?>
								<td>
									<?php if ($marker->maps): ?>
										<?php $map_details = $db->get_maps($marker->maps) ?>
										<?php if (count($map_details)): ?>
											<ul class="mmp-used-in">
												<?php foreach ($map_details as $map_detail): ?>
													<li>
														<a href="<?= get_admin_url(null, 'admin.php?page=mapsmarkerpro_map&id=' . $map_detail->id) ?>" title="<?= esc_attr__('Edit map', 'mmp') ?>"><?= esc_html($map_detail->name) ?> (<?= esc_html__('ID', 'mmp') ?> <?= $map_detail->id ?>)</a>
													</li>
												<?php endforeach; ?>
											</ul>
										<?php else: ?>
											<?= esc_html__('Not assigned to any map', 'mmp') ?>
										<?php endif; ?>
									<?php endif; ?>
								</td>
							<?php endif; ?>
						</tr>
					<?php endforeach; ?>
				<?php endif; ?>
			</table>
			<div class="mmp-tablenav mmp-tablenav-bottom mmp-tablenav-markers">
				<div class="mmp-tablenav-pagination">
					<?php if ($args['paged'] < 2): ?>
						<span class="button disabled">&laquo;</span>
						<span class="button disabled">&lsaquo;</span>
					<?php else: ?>
						<a class="button" href="<?= add_query_arg('paged', 1) ?>">&laquo;</a>
						<a class="button" href="<?= add_query_arg('paged', $args['paged'] - 1) ?>">&lsaquo;</a>
					<?php endif; ?>
					<span><?= $args['paged'] ?> <?= esc_html__('of', 'mmp') ?> <?= $page_count ?></span>
					<?php if ($args['paged'] >= $page_count): ?>
						<span class="button disabled">&rsaquo;</span>
						<span class="button disabled">&raquo;</span>
					<?php else: ?>
						<a class="button" href="<?= add_query_arg('paged', $args['paged'] + 1) ?>">&rsaquo;</a>
						<a class="button" href="<?= add_query_arg('paged', $page_count) ?>">&raquo;</a>
					<?php endif; ?>
				</div>
			</div>
			<?php if (current_user_can('mmp_use_tools')): ?>
				<div class="mmp-bulk">
					<form id="bulk-actions" method="POST">
						<input type="hidden" id="bulk-action-nonce" name="bulk-action-nonce" value="<?= wp_create_nonce('mmp-bulk-action-markers') ?>" />
						<ul>
							<li>
								<label><input type="radio" name="bulk-action" value="duplicate" /><?= esc_html__('Duplicate markers', 'mmp') ?></label>
							</li>
							<li>
								<label><input type="radio" name="bulk-action" value="delete" /><?= esc_html__('Delete markers', 'mmp') ?></label>
							</li>
							<li>
								<label><input type="radio" name="bulk-action" value="assign" /><?= esc_html__('Assign markers to this map', 'mmp') ?></label>
								<select id="assign-target" name="assign-target">
									<?php foreach ($maps as $map): ?>
										<option value="<?= $map->id ?>"><?= "[{$map->id}] " . esc_html($map->name) ?></option>
									<?php endforeach; ?>
								</select>
							</li>
						</ul>
						<button type="submit" class="button button-primary"><?= esc_html__('Apply', 'mmp') ?></button>
					</form>
				</div>
			<?php endif; ?>
		</div>
		<?php
		$this->page = ob_get_clean();
	}

	/**
	 * Loads the required resources
	 *
	 * @since 4.0
	 *
	 * @param string $hook The current admin page
	 */
	public function load_resources($hook) {
		if (substr($hook, -strlen('mapsmarkerpro_markers')) !== 'mapsmarkerpro_markers') {
			return;
		}

		$this->load_global_resources($hook);

		wp_enqueue_script('mmp-admin');
		wp_add_inline_script('mmp-admin', 'listMarkersActions();');
	}

	/**
	 * Deletes the marker
	 *
	 * @since 4.0
	 */
	public function delete_marker() {
		$db = MMP::get_instance('MMP\DB');

		$id = absint($_POST['id']);
		if (!$id) {
			wp_send_json_error();
		}

		check_ajax_referer("mmp-delete-marker-$id", 'nonce');

		$marker = $db->get_marker($id);
		if (!$marker) {
			wp_send_json_error();
		}

		if ($marker->author_id != get_current_user_id() && !current_user_can('mmp_delete_other_markers')) {
			wp_send_json_error();
		}

		$delete = $db->delete_marker($id);
		if ($delete === false) {
			wp_send_json_error();
		}

		do_action('mmp_delete_marker', $id);

		wp_send_json_success();
	}

	/**
	 * Executes the marker bulk actions
	 *
	 * @since 4.0
	 */
	public function bulk_action_markers() {
		global $wpdb;
		$db = MMP::get_instance('MMP\DB');

		check_ajax_referer('mmp-bulk-action-markers', 'nonce');

		if (!current_user_can('mmp_use_tools')) {
			wp_send_json_error();
		}

		$selected = (isset($_POST['selected'])) ? $_POST['selected'] : null;
		$bulk_action = (isset($_POST['bulkAction'])) ? $_POST['bulkAction'] : null;
		$assign_target = (isset($_POST['assignTarget'])) ? absint($_POST['assignTarget']) : null;

		$ids = $db->sanitize_ids($selected);
		if ($bulk_action === 'duplicate') {
			foreach ($ids as $id) {
				$marker = $db->get_marker($id, ARRAY_A);
				if (!$marker) {
					continue;
				}
				$insert_id = $db->add_marker((object) $marker);
				if ($insert_id === false) {
					continue;
				}
				do_action('mmp_save_marker', $insert_id, $marker, true);
				do_action('mmp_add_marker', $insert_id, $marker);
			}
		} else if ($bulk_action === 'delete') {
			foreach ($ids as $id) {
				$delete = $db->delete_marker($id);
				if ($delete === false) {
					continue;
				}
				do_action('mmp_delete_marker', $id);
			}
		} else if ($bulk_action === 'assign') {
			$db->assign_markers($assign_target, $ids);
		}

		wp_send_json_success();
	}

	/**
	 * AJAX request for saving the screen options
	 *
	 * @since 4.8
	 */
	public function mmp_markers_screen_options() {
		$mmp_settings = MMP::get_instance('MMP\Settings');

		check_ajax_referer('screen-options-nonce', 'nonce');

		if (!current_user_can('mmp_view_markers')) {
			wp_send_json_error();
		}

		// Workaround for jQuery not sending empty arrays
		if (!isset($_POST['hiddenColumns'])) {
			$_POST['hiddenColumns'] = array();
		}

		$options = $mmp_settings->validate_markers_screen_settings($_POST, false, false);
		update_user_meta(get_current_user_id(), 'mapsmarkerpro_markers_options', $options);

		wp_send_json_success();
	}

	/**
	 * Shows the markers page
	 *
	 * @since 4.0
	 */
	protected function show() {
		echo $this->page;
	}
}
