<?php

namespace SmartSlotAppointmentScheduler;

use SmartSlotAppointmentScheduler\Schedule_Posttype;

if (! defined('ABSPATH')) {
	exit;
}

if (! class_exists('\SmartSlotAppointmentScheduler\Add_Posttype_Field')) {

	/**
	 * Class to register a meta box for the CPT for provider's unavailable dates.
	 */
	class Add_Posttype_Field {

		/**
		 * Initialize hooks.
		 *
		 * @return void
		 */
		public static function init() {
			add_action('add_meta_boxes', [__CLASS__, 'add_post_field']);
			add_action('save_post', [__CLASS__, 'save_post']);
		}

		/**
		 * Register meta box.
		 *
		 * @return void
		 */
		public static function add_post_field() {

			add_meta_box(
				'schedule_provider_availability',
				__('Provider Information', 'smartslot-appointment-scheduler'),
				[__CLASS__, 'meta_field_html'],
				Schedule_Posttype::SLUG,
				'normal',
				'default'
			);
		}

		/**
		 * Display field HTML.
		 *
		 * @param WP_Post $post Current post object.
		 * @return void
		 */
		public static function meta_field_html($post) {

			$famous_service = get_post_meta($post->ID, '_famous_service', true);

			if (! is_array($famous_service)) {
				$famous_service = [];
			}

			$venue = get_post_meta($post->ID, '_venue', true);

			// Get all service categories.
			$services = get_terms(
				[
					'taxonomy'   => 'ssas_services',
					'hide_empty' => false,
				]
			);

			if (is_wp_error($services)) {
				$services = [];
			}

			wp_nonce_field(
				'save_schedule_meta_box',
				'schedule_meta_box_nonce'
			);

			$values = get_post_meta(
				$post->ID,
				'_provider_availability',
				true
			);

			$organiser_name = get_post_meta(
				$post->ID,
				'_organiser_name',
				true
			);

			if (! is_array($values)) {
				$values = [];
			}
			?>

			<table class="form-table">

				<tr>
					<th>
						<label for="organiser_name">
							<?php esc_html_e('Organizer Name', 'smartslot-appointment-scheduler'); ?>
						</label>
					</th>

					<td>
						<input
							type="text"
							id="organiser_name"
							name="organiser_name"
							class="regular-text"
							value="<?php echo esc_attr($organiser_name); ?>"
						/>
					</td>
				</tr>

				<tr>
					<th>
						<label for="famous_service">
							<?php esc_html_e('Famous Service', 'smartslot-appointment-scheduler'); ?>
						</label>
					</th>

					<td>

						<select
							id="famous_service"
							name="famous_service[]"
							class="regular-text"
							multiple
							size="6"
						>

							<?php foreach ($services as $service) : ?>

								<option
									value="<?php echo esc_attr($service->term_id); ?>"
									<?php selected(in_array((int) $service->term_id, $famous_service, true)); ?>
								>
									<?php echo esc_html($service->name); ?>
								</option>

							<?php endforeach; ?>

						</select>

						<p class="description">
							<?php esc_html_e('Hold Ctrl (Windows) or Cmd (Mac) to select multiple services.', 'smartslot-appointment-scheduler'); ?>
						</p>

					</td>
				</tr>

				<tr>
					<th>
						<label for="venue">
							<?php esc_html_e('Venue', 'smartslot-appointment-scheduler'); ?>
						</label>
					</th>

					<td>
						<input
							type="text"
							id="venue"
							name="venue"
							class="regular-text"
							value="<?php echo esc_attr($venue); ?>"
						/>
					</td>
				</tr>

				<tr>
					<th>
						<label for="availability-wrapper">
							<?php esc_html_e('Unavailable Dates', 'smartslot-appointment-scheduler'); ?>
						</label>
					</th>

					<td>
						<div
							id="availability-wrapper"
							data-name="provider_availability[]"
						>

							<?php if (empty($values)) : ?>

								<div
									class="availability-row"
									style="margin-bottom:10px;"
								>
									<input
										type="date"
										min="<?php echo esc_attr(current_time('Y-m-d')); ?>"
										name="provider_availability[]"
									/>

									<button
										type="button"
										class="button remove-row"
									>
										<?php esc_html_e('Remove', 'smartslot-appointment-scheduler'); ?>
									</button>
								</div>

							<?php else : ?>

								<?php foreach ($values as $date) : ?>

									<div
										class="availability-row"
										style="margin-bottom:10px;"
									>
										<input
											type="date"
											min="<?php echo esc_attr(current_time('Y-m-d')); ?>"
											name="provider_availability[]"
											value="<?php echo esc_attr($date); ?>"
										/>

										<button
											type="button"
											class="button remove-row"
										>
											<?php esc_html_e('Remove', 'smartslot-appointment-scheduler'); ?>
										</button>
									</div>

								<?php endforeach; ?>

							<?php endif; ?>

						</div>

						<button
							type="button"
							class="button"
							id="add-row"
						>
							<?php esc_html_e('Add Date', 'smartslot-appointment-scheduler'); ?>
						</button>

					</td>
				</tr>

			</table>

			<?php
		}

		/**
		 * Save custom field data.
		 *
		 * @param int $post_id Post ID.
		 * @return void
		 */
		public static function save_post($post_id) {

			// Verify nonce.
			if (
				! isset($_POST['schedule_meta_box_nonce']) ||
				! wp_verify_nonce(
					sanitize_text_field(
						wp_unslash($_POST['schedule_meta_box_nonce'])
					),
					'save_schedule_meta_box'
				)
			) {
				return;
			}

			// Check post type.
			if (get_post_type($post_id) !== Schedule_Posttype::SLUG) {
				return;
			}

			// Check autosave.
			if (
				defined('DOING_AUTOSAVE') &&
				DOING_AUTOSAVE
			) {
				return;
			}

			// Check permissions.
			if (! current_user_can('edit_post', $post_id)) {
				return;
			}

			// Save unavailable dates.
			$dates = [];

			if (isset($_POST['provider_availability'])) {

				$dates = array_map(
					'sanitize_text_field',
					(array) wp_unslash($_POST['provider_availability'])
				);

				$dates = array_filter($dates);
			}

			update_post_meta(
				$post_id,
				'_provider_availability',
				$dates
			);

			// Save Organizer Name.
			if (isset($_POST['organiser_name'])) {

				update_post_meta(
					$post_id,
					'_organiser_name',
					sanitize_text_field(
						wp_unslash($_POST['organiser_name'])
					)
				);
			}

			// Save Famous Service.
			if (isset($_POST['famous_service'])) {

				$selected_services = array_map(
					'absint',
					(array) wp_unslash($_POST['famous_service'])
				);

				update_post_meta(
					$post_id,
					'_famous_service',
					$selected_services
				);
			}

			// Save Venue.
			if (isset($_POST['venue'])) {

				update_post_meta(
					$post_id,
					'_venue',
					sanitize_text_field(
						wp_unslash($_POST['venue'])
					)
				);
			}
		}
	}

	add_action(
		'init',
		['\SmartSlotAppointmentScheduler\Add_Posttype_Field', 'init'],
		11
	);
}
