<?php
/**
 * Manage amenities Page
 *
 * @package HBFWC\Admin
 * @version 1.0.0
 */

namespace HBFWC\Admin;

defined( 'ABSPATH' ) || exit;

/**
 * Class HBFWC\Admin\Admin_Amenities.
 */
class Admin_Amenities {
	/**
	 * Edited amenity ID.
	 *
	 * @var int
	 */
	private static $edited_amenity_id;

	/**
	 * Amenities group data.
	 *
	 * @var array
	 */
	private static $amenities_group;

	/**
	 * Page number, for pagination.
	 *
	 * @var int
	 */
	private static $pagenum;

	/**
	 * Offset, for pagination.
	 *
	 * @var int
	 */
	private static $offset;

	/**
	 * Handles output of the amenities page in admin.
	 */
	public static function output() {
		$result = '';
		$action = '';

		self::$amenities_group = hbfwc_get_amenities_group();

		// phpcs:disable WordPress.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Missing
		// Action to perform: add, edit, delete or none.
		if ( ! empty( $_POST['add_new_amenity'] ) ) {
			$action = 'add';
		} elseif ( ! empty( $_POST['save_amenity'] ) && ! empty( $_GET['edit'] ) ) {
			$action = 'edit';
		} elseif ( ! empty( $_GET['delete'] ) ) {
			$action = 'delete';
		}
		// phpcs:enable

		switch ( $action ) {
			case 'add':
				$result = self::process_add_amenity();
				break;
			case 'edit':
				$result = self::process_edit_amenity();
				break;
			case 'delete':
				$result = self::process_delete_amenity();
				break;
		}

		if ( is_wp_error( $result ) ) {
			echo '<div id="hbfwc_errors" class="error"><p>' . wp_kses_post( $result->get_error_message() ) . '</p></div>';
		}

		// Show admin interface.
		if ( ! empty( $_GET['edit'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			self::edit_amenity();
		} else {
			self::add_amenity();
		}
	}

	/**
	 * Get and sanitize posted amenity data.
	 *
	 * @return array
	 */
	private static function get_posted_amenity() {
		$amenity = array(
			'name'       => isset( $_POST['amenity_name'] ) ? sanitize_text_field( wp_unslash( $_POST['amenity_name'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
			'group'      => isset( $_POST['amenity_group'] ) ? sanitize_text_field( wp_unslash( $_POST['amenity_group'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
			'icon_type'  => isset( $_POST['icon_type'] ) ? sanitize_text_field( wp_unslash( $_POST['icon_type'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
			'icon_class' => isset( $_POST['icon_class'] ) ? sanitize_text_field( wp_unslash( $_POST['icon_class'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
			'icon_svg'   => isset( $_POST['icon_svg'] ) ? wp_kses( wp_unslash( $_POST['icon_svg'] ), hbfwc_get_svg_args() ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
		);

		$amenity['slug'] = ! empty( $amenity['rateplan_name'] ) ? sanitize_title( $amenity['rateplan_name'] ) : '';

		return $amenity;
	}

	/**
	 * Add a rate plan.
	 *
	 * @return bool|WP_Error
	 */
	private static function process_add_amenity() {
		check_admin_referer( 'hbfwc-add-new_amenity' );

		$amenity = self::get_posted_amenity();
		$args    = array(
			'description' => '',
			'slug'        => $amenity['slug'],
		);

		if ( empty( $amenity['group'] ) ) {
			return new \WP_Error( 'error', __( 'Please select an amenities group.', 'hotel-booking-for-woocommerce' ) );
		}

		if ( empty( $amenity['icon_type'] ) ) {
			return new \WP_Error( 'error', __( 'Please select the icon type.', 'hotel-booking-for-woocommerce' ) );
		}

		$group     = $amenity['group'];
		$icon_type = $amenity['icon_type'];

		if ( 'svg' === $icon_type && empty( $amenity['icon_svg'] ) ) {
			return new \WP_Error( 'error', __( 'Please enter the SVG code.', 'hotel-booking-for-woocommerce' ) );
		} elseif ( 'svg' !== $icon_type ) {
			if ( empty( $amenity['icon_class'] ) ) {
				return new \WP_Error( 'error', __( 'Please select an icon.', 'hotel-booking-for-woocommerce' ) );
			}
		}

		$term = wp_insert_term(
			$amenity['name'],
			'amenities',
			$args
		);

		if ( is_wp_error( $term ) ) {
			return $term;
		}

		$icon_svg   = $amenity['icon_svg'];
		$icon_class = $amenity['icon_class'];

		update_term_meta( $term['term_id'], 'group', $group );
		update_term_meta( $term['term_id'], 'icon_type', $icon_type );
		update_term_meta( $term['term_id'], 'icon_svg', $icon_svg );
		update_term_meta( $term['term_id'], 'icon_class', $icon_class );

		return true;
	}

	/**
	 * Edit an amenity.
	 *
	 * @return bool|WP_Error
	 */
	private static function process_edit_amenity() {
		$amenity_id = isset( $_GET['edit'] ) ? absint( $_GET['edit'] ) : 0;
		check_admin_referer( 'hbfwc-save-amenity_' . $amenity_id );

		$amenity = self::get_posted_amenity();
		$args    = array(
			'name'        => $amenity['name'],
			'description' => '',
			'slug'        => $amenity['slug'],
		);

		if ( empty( $amenity['group'] ) ) {
			return new \WP_Error( 'error', __( 'Please select an amenities group.', 'hotel-booking-for-woocommerce' ) );
		}

		if ( empty( $amenity['icon_type'] ) ) {
			return new \WP_Error( 'error', __( 'Please select the icon type.', 'hotel-booking-for-woocommerce' ) );
		}

		$group     = $amenity['group'];
		$icon_type = $amenity['icon_type'];

		if ( 'svg' === $icon_type && empty( $amenity['icon_svg'] ) ) {
			return new \WP_Error( 'error', __( 'Please enter the SVG code.', 'hotel-booking-for-woocommerce' ) );
		} elseif ( 'svg' !== $icon_type ) {
			if ( empty( $amenity['icon_class'] ) ) {
				return new \WP_Error( 'error', __( 'Please select an icon.', 'hotel-booking-for-woocommerce' ) );
			}
		}

		$term = wp_update_term(
			$amenity_id,
			'amenities',
			$args
		);

		if ( is_wp_error( $term ) ) {
			return $term;
		}

		self::$edited_amenity_id = $amenity_id;

		$icon_svg   = $amenity['icon_svg'];
		$icon_class = $amenity['icon_class'];

		update_term_meta( self::$edited_amenity_id, 'group', $group );
		update_term_meta( self::$edited_amenity_id, 'icon_type', $icon_type );
		update_term_meta( self::$edited_amenity_id, 'icon_svg', $icon_svg );
		update_term_meta( self::$edited_amenity_id, 'icon_class', $icon_class );

		return true;
	}

	/**
	 * Delete an amenity.
	 *
	 * @return bool
	 */
	private static function process_delete_amenity() {
		$amenity_id = isset( $_GET['delete'] ) ? absint( $_GET['delete'] ) : 0;
		check_admin_referer( 'hbfwc-delete-amenity_' . $amenity_id );

		delete_term_meta( $amenity_id, 'group' );
		delete_term_meta( $amenity_id, 'icon_type' );
		delete_term_meta( $amenity_id, 'icon_svg' );
		delete_term_meta( $amenity_id, 'icon_class' );

		return wp_delete_term( $amenity_id, 'amenities' );
	}

	/**
	 * Get pagination.
	 */
	private static function get_pagination() {
		self::$pagenum = isset( $_GET['paged'] ) ? absint( $_GET['paged'] ) : 1; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

		$limit        = 10; // Number of rows in page.
		self::$offset = ( self::$pagenum - 1 ) * $limit;
		$total        = count( hbfwc_get_amenities() );

		$num_of_pages = ceil( $total / $limit );
		$page_links   = paginate_links(
			array(
				'base'      => add_query_arg( 'paged', '%#%' ),
				'format'    => '',
				'prev_text' => '&laquo;',
				'next_text' => '&raquo;',
				'total'     => $num_of_pages,
				'current'   => self::$pagenum,
			)
		);

		echo '<div class="tablenav"><div class="tablenav-pages"><span class="total__amenities">' .
			sprintf(
				/* translators: Total amenities */
				_n( '%d item', '%d items', $total, 'hotel-booking-for-woocommerce' ),  // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
				absint( $total )
			) . '</span> ' . wp_kses_post( $page_links ) . '</div></div>';
	}

	/**
	 * Edit aminity admin panel.
	 */
	public static function edit_amenity() {
		$edit = isset( $_GET['edit'] ) ? absint( wp_unslash( $_GET['edit'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

		$amen_groups       = self::$amenities_group;
		$amenity_to_edit   = get_term( $edit, 'amenities' );
		$icon_types_select = array(
			''                     => __( 'Select the icon style', 'hotel-booking-for-woocommerce' ),
			'fontawesome-6-brands' => 'Font awesome 6 brands',
			'fontawesome-6'        => 'Font awesome 6',
			'ionicons'             => 'Ionicons',
			'themify'              => 'Themify icon',
			'svg'                  => __( 'Custom SVG', 'hotel-booking-for-woocommerce' ),
		);

		$font_icons_class = 'svg' !== get_term_meta( $amenity_to_edit->term_id, 'icon_type', true ) ? 'display: table-row' : 'display: none';
		$svg_icons_class  = 'svg' !== get_term_meta( $amenity_to_edit->term_id, 'icon_type', true ) ? 'display: none' : 'display: table-row';
		?>
		<div class="wrap woocommerce">
			<h1><?php esc_html_e( 'Edit amenity', 'hotel-booking-for-woocommerce' ); ?></h1>

			<?php
			if ( ! $amenity_to_edit ) {
				echo '<div id="woocommerce_errors" class="error"><p>' . esc_html__( 'Error: non-existing amenity ID.', 'hotel-booking-for-woocommerce' ) . '</p></div>';
			} else {
				if ( self::$edited_amenity_id > 0 ) {
					echo '<div id="message" class="updated"><p>' . esc_html__( 'Amenity updated successfully', 'hotel-booking-for-woocommerce' ) . '</p><p><a href="' . esc_url( admin_url( 'edit.php?post_type=product&amp;page=amenities' ) ) . '">' . esc_html__( 'Back to Amenities', 'hotel-booking-for-woocommerce' ) . '</a></p></div>';
					self::$edited_amenity_id = null;
				}
				?>
				<form action="edit.php?post_type=product&amp;page=amenities&amp;edit=<?php echo absint( $edit ); ?>" method="post">
					<table class="form-table">
						<tbody>
							<?php do_action( 'hbfwc_before_edit_amenity_fields' ); ?>
							<tr class="form-field form-required">
								<th scope="row" valign="top">
									<label for="amenity_name"><?php esc_html_e( 'Name', 'hotel-booking-for-woocommerce' ); ?></label>
								</th>
								<td>
									<input name="amenity_name" id="amenity_name" type="text" value="<?php echo esc_attr( format_to_edit( $amenity_to_edit->name ) ); ?>" />
									<p class="description"><?php esc_html_e( 'Amenity name.', 'hotel-booking-for-woocommerce' ); ?></p>
								</td>
							</tr>
							<tr class="form-field form-required">
								<th scope="row" valign="top">
									<label for="amenity_group"><?php esc_html_e( 'Group', 'hotel-booking-for-woocommerce' ); ?></label>
								</th>
								<td>
									<select name="amenity_group" id="amenity_group" style="min-width: 50%;">
									<?php
										$group_key = get_term_meta( $amenity_to_edit->term_id, 'group', true );
									foreach ( $amen_groups as $g_key => $g_name ) {
										print '<option value="' . esc_attr( $g_key ) . '" ' . selected( $group_key, $g_key, false ) . '>' . esc_html( $g_name ) . '</option>' . "\n";
									}
									?>
									</select>
								</td>
							</tr>
							<tr class="form-field form-required">
								<th scope="row" valign="top">
									<label for="icon_type"><?php esc_html_e( 'Icon style', 'hotel-booking-for-woocommerce' ); ?></label>
								</th>
								<td>
									<select name="icon_type" id="icon_type" style="min-width: 50%;">
									<?php
										$icon_type_key = get_term_meta( $amenity_to_edit->term_id, 'icon_type', true );
									foreach ( $icon_types_select as $i_key => $i_name ) {
										print '<option value="' . esc_attr( $i_key ) . '" ' . selected( $icon_type_key, $i_key, true ) . '>' . esc_html( $i_name ) . '</option>' . "\n";
									}
									?>
									</select>
								</td>
							</tr>

							<tr class="form-field form-required" id="hbfwc-am-icon" style="<?php echo esc_attr( $font_icons_class ); ?>">
								<th scope="row" valign="top">
									<label><?php esc_html_e( 'Select an icon', 'hotel-booking-for-woocommerce' ); ?></label>
								</th>
								<td>
									<div id="hbfwc-icon-output" data-current="<?php echo esc_attr( get_term_meta( $amenity_to_edit->term_id, 'icon_class', true ) ); ?>"></div>
								</td>
							</tr>

							<tr class="form-field form-required" id="hbfwc-am-svg" style="<?php echo esc_attr( $svg_icons_class ); ?>">
								<th scope="row" valign="top">
									<label for="icon_svg"><?php esc_html_e( 'SVG code', 'hotel-booking-for-woocommerce' ); ?></label>
								</th>
								<td>
									<textarea name="icon_svg" id="icon_svg" rows="6" style="width: 100%;"><?php print wp_kses( wp_unslash( get_term_meta( $amenity_to_edit->term_id, 'icon_svg', true ) ), hbfwc_get_svg_args() ); ?></textarea>
								</td>
							</tr>

							<?php do_action( 'hbfwc_after_edit_amenity_fields' ); ?>
						</tbody>
					</table>
					<p class="submit"><button type="submit" name="save_amenity" id="submit" class="button-primary" value="<?php esc_attr_e( 'Update', 'hotel-booking-for-woocommerce' ); ?>"><?php esc_html_e( 'Update', 'hotel-booking-for-woocommerce' ); ?></button></p>
					<?php wp_nonce_field( 'hbfwc-save-amenity_' . $edit ); ?>
				</form>
			<?php } ?>
		</div>
		<?php
	}

	/**
	 * Add new aminity admin panel.
	 */
	public static function add_amenity() {
		$amen_groups       = self::$amenities_group;
		$icon_types_select = array(
			''                     => __( 'Select the icon style', 'hotel-booking-for-woocommerce' ),
			'fontawesome-6-brands' => 'Font awesome 6 brands',
			'fontawesome-6'        => 'Font awesome 6',
			'ionicons'             => 'Ionicons',
			'themify'              => 'Themify icon',
			'svg'                  => __( 'Custom SVG', 'hotel-booking-for-woocommerce' ),
		);
		?>
		<div class="wrap woocommerce hbfwc-admin-oooyee">
			<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>

			<br class="clear" />
			<div id="col-container">
				<div id="col-right">
					<div class="col-wrap">
						<?php self::get_pagination(); ?>
						<table class="widefat attributes-table wp-list-table ui-sortable" style="width:100%">
							<thead>
								<tr>
									<th scope="col" width="42">&nbsp;</th>
									<th scope="col"><?php esc_html_e( 'Name', 'hotel-booking-for-woocommerce' ); ?></th>
									<th scope="col"><?php esc_html_e( 'Group', 'hotel-booking-for-woocommerce' ); ?></th>
									<th scope="col"><?php esc_html_e( 'Icon type', 'hotel-booking-for-woocommerce' ); ?></th>
									
								</tr>
							</thead>
							<tbody>
								<?php
									$amenities = get_terms(
										array(
											'taxonomy'   => 'amenities',
											'orderby'    => 'term_order',
											'number'     => 10,
											'hide_empty' => false,
											'offset'     => self::$offset,
										)
									);

								if ( $amenities ) {
									$i = 1;
									foreach ( $amenities as $amenity ) {
										$class_name     = ( 0 === $i % 2 ) ? '' : 'alternate';
										$this_icon_type = get_term_meta( $amenity->term_id, 'icon_type', true );
										?>
								<tr id="<?php print esc_attr( "amenity-{$amenity->term_id}" ); ?>" class="<?php print esc_attr( $class_name ); ?>">
									<td class="icon-output column-icon-output" data-colname="Amenity icon">
										<?php
										if ( 'svg' === $this_icon_type ) {
											print wp_kses( wp_unslash( get_term_meta( $amenity->term_id, 'icon_svg', true ) ), hbfwc_get_svg_args() );
										} else {
											print '<i class="' . esc_attr( get_term_meta( $amenity->term_id, 'icon_class', true ) ) . '"></i>';
										}
										?>
									</td>
									<td class="name column-name has-row-actions column-primary" data-colname="Name">
										<strong><a href="<?php echo esc_url( add_query_arg( 'edit', $amenity->term_id, 'edit.php?post_type=product&amp;page=amenities' ) ); ?>"><?php print esc_html( $amenity->name ); ?></a></strong>
										<div class="row-actions"><span class="edit"><a href="<?php echo esc_url( add_query_arg( 'edit', $amenity->term_id, 'edit.php?post_type=product&amp;page=amenities' ) ); ?>"><?php esc_html_e( 'Edit', 'hotel-booking-for-woocommerce' ); ?></a></span>
											<span class="delete"> | <a class="delete" href="<?php echo esc_url( wp_nonce_url( add_query_arg( 'delete', $amenity->term_id, 'edit.php?post_type=product&amp;page=amenities' ), 'hbfwc-delete-amenity_' . $amenity->term_id ) ); ?>"><?php esc_html_e( 'Delete', 'hotel-booking-for-woocommerce' ); ?></a></span>
										</div>
									</td>
									<td class="group column-group" data-colname="Group">
										<?php
										$group_key = get_term_meta( $amenity->term_id, 'group', true );
										print isset( $amen_groups[ $group_key ] ) ? esc_html( $amen_groups[ $group_key ] ) : '&ndash;';
										?>
									</td>
									<td class="icon-type column-icon-type" data-colname="Icon type">
										<?php print isset( $icon_types_select[ $this_icon_type ] ) ? esc_html( $icon_types_select[ $this_icon_type ] ) : '&ndash;'; ?>
									</td>
								</tr>
										<?php
										++$i;
									}
								}
								?>
							</tbody>
						</table>
						<?php self::get_pagination(); ?>
					</div>
				</div>
				<div id="col-left">
					<div class="col-wrap">
						<div class="form-wrap">
							<h2><?php esc_html_e( 'Add new amenity', 'hotel-booking-for-woocommerce' ); ?></h2>
							<p><?php esc_html_e( 'A room amenity is a useful or desirable feature or facility that a guest has access to in a hotel room. Amenities can be found in the room itself, or outside the room in the form of on-property premiums.', 'hotel-booking-for-woocommerce' ); ?></p>
							<form action="edit.php?post_type=product&amp;page=amenities" method="post">
								<?php do_action( 'hbfwc_before_add_amenity_fields' ); ?>

								<div class="form-field">
									<label for="amenity_name"><?php esc_html_e( 'Name', 'hotel-booking-for-woocommerce' ); ?></label>
									<input name="amenity_name" id="amenity_name" type="text" value="" required />
									<p class="description"><?php esc_html_e( 'Amenity name.', 'hotel-booking-for-woocommerce' ); ?></p>
								</div>

								<div class="form-field">
									<label for="amenity_group"><?php esc_html_e( 'Group', 'hotel-booking-for-woocommerce' ); ?></label>
									<select name="amenity_group" id="amenity_group" style="width: 50%;">
										<option value="" disabled selected><?php print esc_html__( 'Select a group', 'hotel-booking-for-woocommerce' ); ?></option>
									<?php
									foreach ( $amen_groups as $g_key => $g_name ) {
										print '<option value="' . esc_attr( $g_key ) . '">' . esc_html( $g_name ) . '</option>' . "\n";
									}
									?>
									</select>
								</div>

								<div class="form-field">
									<label for="icon_type"><?php esc_html_e( 'Icon style', 'hotel-booking-for-woocommerce' ); ?></label>
									<select name="icon_type" id="icon_type" style="width: 50%;">
									<?php
									foreach ( $icon_types_select as $i_key => $i_name ) {
										print '<option value="' . esc_attr( $i_key ) . '">' . esc_html( $i_name ) . '</option>' . "\n";
									}
									?>
									</select>
								</div>

								<div class="form-field" id="hbfwc-am-icon" style="display: none;">
									<label><?php print esc_html__( 'Select an icon', 'hotel-booking-for-woocommerce' ); ?></label>

									<div id="hbfwc-icon-output"></div>
								</div>

								<div class="form-field" id="hbfwc-am-svg" style="display: none;">
									<label for="icon_svg"><?php esc_html_e( 'SVG code', 'hotel-booking-for-woocommerce' ); ?></label>
									<textarea name="icon_svg" id="icon_svg" rows="6" style="width: 100%;"></textarea>
								</div>

								<?php do_action( 'hbfwc_after_add_amenity_fields' ); ?>

								<p class="submit"><button type="submit" name="add_new_amenity" id="submit" class="button button-primary" value="<?php esc_attr_e( 'Add amenity', 'hotel-booking-for-woocommerce' ); ?>"><?php esc_html_e( 'Add amenity', 'hotel-booking-for-woocommerce' ); ?></button></p>
								<?php wp_nonce_field( 'hbfwc-add-new_amenity' ); ?>
							</form>
						</div>
					</div>
				</div>
			</div>
		</div>
		<?php
	}
}