<?php
/**
 * Rate Plans Page
 *
 * @package HBFWC\Admin
 * @version 1.0.0
 */

namespace HBFWC\Admin;

defined( 'ABSPATH' ) || exit;

/**
 * Class HBFWC\Admin\Admin_Rate_Plans.
 */
class Admin_Rate_Plans {

	/**
	 * Edited rate plan ID.
	 *
	 * @var int
	 */
	private static $edited_rate_plan_id;

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

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

		switch ( $action ) {
			case 'add':
				$result = self::process_add_rateplan();
				break;
			case 'edit':
				$result = self::process_edit_rateplan();
				break;
			case 'delete':
				$result = self::process_delete_rateplan();
				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_rateplan();
		} else {
			self::add_rateplan();
		}
	}

	/**
	 * Get and sanitize posted rate plan data.
	 *
	 * @return array
	 */
	private static function get_posted_rateplan() {
		$rateplan = array(
			'rateplan_name'        => isset( $_POST['rateplan_name'] ) ? sanitize_text_field( wp_unslash( $_POST['rateplan_name'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
			'rateplan_features'    => isset( $_POST['rateplan_features'] ) ? sanitize_text_field( wp_unslash( $_POST['rateplan_features'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
			'rateplan_description' => isset( $_POST['rateplan_description'] ) ? wp_kses_post( wp_unslash( $_POST['rateplan_description'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
		);

		$rateplan['rateplan_slug'] = ! empty( $rateplan['rateplan_name'] ) ? sanitize_title( $rateplan['rateplan_name'] ) : '';

		return $rateplan;
	}

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

		$rateplan = self::get_posted_rateplan();
		$args     = array(
			'description' => $rateplan['rateplan_description'],
			'slug'        => $rateplan['rateplan_slug'],
		);

		remove_filter( 'pre_term_description', 'wp_filter_kses' );
		remove_filter( 'pre_link_description', 'wp_filter_kses' );
		remove_filter( 'pre_link_notes', 'wp_filter_kses' );
		remove_filter( 'term_description', 'wp_kses_data' );

		$term = wp_insert_term(
			$rateplan['rateplan_name'],
			'rate_plan',
			$args
		);

		add_filter( 'pre_term_description', 'wp_filter_kses' );
		add_filter( 'pre_link_description', 'wp_filter_kses' );
		add_filter( 'pre_link_notes', 'wp_filter_kses' );
		add_filter( 'term_description', 'wp_kses_data' );

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

		update_term_meta( $term['term_id'], 'features', $rateplan['rateplan_features'] );

		do_action( 'hbfwc_after_process_add_rateplan', $term['term_id'], $_POST );

		return true;
	}

	/**
	 * Edit a rate plan.
	 *
	 * @return bool|WP_Error
	 */
	private static function process_edit_rateplan() {
		$rate_id = isset( $_GET['edit'] ) ? absint( $_GET['edit'] ) : 0;
		check_admin_referer( 'hbfwc-save-rateplan_' . $rate_id );

		$rateplan = self::get_posted_rateplan();
		$args     = array(
			'name'        => $rateplan['rateplan_name'],
			'description' => $rateplan['rateplan_description'],
			'slug'        => $rateplan['rateplan_slug'],
		);

		$default_rate_id = (int) get_option( 'hbfwc_default_rate_id', 0 );
		if ( absint( $default_rate_id ) === $rate_id ) {
			$args['slug'] = 'standard';
		}

		remove_filter( 'pre_term_description', 'wp_filter_kses' );
		remove_filter( 'pre_link_description', 'wp_filter_kses' );
		remove_filter( 'pre_link_notes', 'wp_filter_kses' );
		remove_filter( 'term_description', 'wp_kses_data' );

		$term = wp_update_term(
			$rate_id,
			'rate_plan',
			$args
		);

		add_filter( 'pre_term_description', 'wp_filter_kses' );
		add_filter( 'pre_link_description', 'wp_filter_kses' );
		add_filter( 'pre_link_notes', 'wp_filter_kses' );
		add_filter( 'term_description', 'wp_kses_data' );

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

		self::$edited_rate_plan_id = $rate_id;

		update_term_meta( self::$edited_rate_plan_id, 'features', $rateplan['rateplan_features'] );

		do_action( 'hbfwc_after_process_edit_rateplan', self::$edited_rate_plan_id, $_POST );

		return true;
	}

	/**
	 * Delete a rate plan.
	 *
	 * @return bool
	 */
	private static function process_delete_rateplan() {
		$rate_id = isset( $_GET['delete'] ) ? absint( $_GET['delete'] ) : 0;
		check_admin_referer( 'hbfwc-delete-rateplan_' . $rate_id );

		$default_rate_id = (int) get_option( 'hbfwc_default_rate_id', 0 );
		if ( absint( $default_rate_id ) === $rate_id ) {
			return false;
		}

		delete_term_meta( $rate_id, 'features' );

		do_action( 'hbfwc_after_process_delete_rateplan', $rate_id );

		return wp_delete_term( $rate_id, 'rate_plan' );
	}

	/**
	 * Edit Rate plan admin panel.
	 */
	public static function edit_rateplan() {
		global $wpdb;

		$edit = isset( $_GET['edit'] ) ? absint( wp_unslash( $_GET['edit'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

		$rate_to_edit = get_term( $edit, 'rate_plan' );

		?>
		<div class="wrap woocommerce">
			<h1><?php esc_html_e( 'Edit rate plan', 'hotel-booking-for-woocommerce' ); ?></h1>

			<?php
			if ( ! $rate_to_edit ) {
				echo '<div id="woocommerce_errors" class="error"><p>' . esc_html__( 'Error: non-existing rate plan ID.', 'hotel-booking-for-woocommerce' ) . '</p></div>';
			} else {
				if ( self::$edited_rate_plan_id > 0 ) {
					echo '<div id="message" class="updated"><p>' . esc_html__( 'Rate plan updated successfully', 'hotel-booking-for-woocommerce' ) . '</p><p><a href="' . esc_url( admin_url( 'edit.php?post_type=product&amp;page=rate_plans' ) ) . '">' . esc_html__( 'Back to Rate plans', 'hotel-booking-for-woocommerce' ) . '</a></p></div>';
					self::$edited_rate_plan_id = null;
				}
				?>
				<form action="edit.php?post_type=product&amp;page=rate_plans&amp;edit=<?php echo absint( $edit ); ?>" method="post">
					<table class="form-table">
						<tbody>
							<?php do_action( 'hbfwc_before_edit_rateplan_fields' ); ?>
							<tr class="form-field form-required">
								<th scope="row" valign="top">
									<label for="rateplan_name"><?php esc_html_e( 'Name', 'hotel-booking-for-woocommerce' ); ?></label>
								</th>
								<td>
									<input name="rateplan_name" id="rateplan_name" type="text" value="<?php echo esc_attr( format_to_edit( $rate_to_edit->name ) ); ?>" />
									<p class="description"><?php esc_html_e( 'Name for the rate plan.', 'hotel-booking-for-woocommerce' ); ?></p>
								</td>
							</tr>
							<tr class="form-field form-required">
								<th scope="row" valign="top">
									<label for="rateplan_features"><?php esc_html_e( 'Features', 'hotel-booking-for-woocommerce' ); ?></label>
								</th>
								<td>
									<input name="rateplan_features" id="rateplan_features" type="text" value="<?php echo esc_attr( format_to_edit( get_term_meta( $rate_to_edit->term_id, 'features', true ) ) ); ?>" />
									<p class="description"><?php esc_html_e( 'The rate plan features. Separate the values with a comma. e.g "Non-refundable", "No charge up-to 24H", etc.', 'hotel-booking-for-woocommerce' ); ?></p>
								</td>
							</tr>
							<tr class="form-field form-required">
								<th scope="row" valign="top">
									<label for="rateplan_description"><?php esc_html_e( 'Description', 'hotel-booking-for-woocommerce' ); ?></label>
								</th>
								<td>
									<?php wp_editor( $rate_to_edit->description, 'rateplan_description', array( 'textarea_rows' => 10 ) ); ?>
									<p class="description"><?php esc_html_e( 'The details about the rate plan and its policy.', 'hotel-booking-for-woocommerce' ); ?></p>
								</td>
							</tr>

							<?php do_action( 'hbfwc_after_edit_rateplan_fields', $rate_to_edit, absint( $edit ) ); ?>
						</tbody>
					</table>
					<p class="submit"><button type="submit" name="save_rate_plan" 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-rateplan_' . $edit ); ?>
				</form>
			<?php } ?>
		</div>
		<?php
	}

	/**
	 * Add rate plan admin panel.
	 *
	 * Shows the interface for adding new rate plan.
	 */
	public static function add_rateplan() {
		$default_rate_id = (int) get_option( 'hbfwc_default_rate_id', 0 );
		?>
		<div class="wrap woocommerce">
			<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">
						<table class="widefat attributes-table wp-list-table ui-sortable" style="width:100%">
							<thead>
								<tr>
									<th scope="col"><?php esc_html_e( 'Name', 'hotel-booking-for-woocommerce' ); ?></th>
									<th scope="col"><?php esc_html_e( 'Features', 'hotel-booking-for-woocommerce' ); ?></th>
									<th scope="col" width="40%"><?php esc_html_e( 'Description', 'hotel-booking-for-woocommerce' ); ?></th>
									<th scope="col"><?php esc_html_e( 'Count', 'hotel-booking-for-woocommerce' ); ?></th>
								</tr>
							</thead>
							<tbody>
								<?php
									$plans = hbfwc_get_rateplans();

								if ( $plans ) {
									$i = 1;
									foreach ( $plans as $plan ) {
										$class_name = ( 0 === $i % 2 ) ? '' : 'alternate';
										?>
								<tr id="<?php print esc_attr( "plan-{$plan->term_id}" ); ?>" class="<?php print esc_attr( $class_name ); ?>">
									<td class="name column-name has-row-actions column-primary" data-colname="Name">
										<strong><a href="<?php echo esc_url( add_query_arg( 'edit', $plan->term_id, 'edit.php?post_type=product&amp;page=rate_plans' ) ); ?>"><?php print esc_html( $plan->name ); ?></a></strong>
										<div class="row-actions"><span class="edit"><a href="<?php echo esc_url( add_query_arg( 'edit', $plan->term_id, 'edit.php?post_type=product&amp;page=rate_plans' ) ); ?>"><?php esc_html_e( 'Edit', 'hotel-booking-for-woocommerce' ); ?></a></span>
										<?php if ( absint( $plan->term_id ) !== $default_rate_id ) : ?>
											<span class="delete"> | <a class="delete" href="<?php echo esc_url( wp_nonce_url( add_query_arg( 'delete', $plan->term_id, 'edit.php?post_type=product&amp;page=rate_plans' ), 'hbfwc-delete-rateplan_' . $plan->term_id ) ); ?>"><?php esc_html_e( 'Delete', 'hotel-booking-for-woocommerce' ); ?></a></span>
										<?php endif; ?>
										</div>
									</td>
									<td class="policy column-policy" data-colname="Features">
										<?php print esc_html( get_term_meta( $plan->term_id, 'features', true ) ); ?>
										<?php do_action( 'hbfwc_admin_rateplan_features', $plan->term_id ); ?>
									</td>
									<td class="description column-description" data-colname="Description">
										<?php
										if ( '' !== $plan->description ) {
											print esc_html( wp_trim_words( $plan->description, 22, ' [&hellip;]' ) );
										}
										?>
									</td>
									<td class="count column-count" data-colname="count">
										<?php print esc_html( $plan->count ); ?>
									</td>
								</tr>
											<?php
											++$i;
									}
								}
								?>
							</tbody>
						</table>
					</div>
				</div>
				<div id="col-left">
					<div class="col-wrap">
						<div class="form-wrap">
							<h2><?php esc_html_e( 'Add new rate plan', 'hotel-booking-for-woocommerce' ); ?></h2>
							<p><?php esc_html_e( 'A Rate Plan allows you to sell the same accommodation in different ways (nonrefundable, cancelation allowed with complete/partial refund, breakfast included, etc.)', 'hotel-booking-for-woocommerce' ); ?></p>
							<form action="edit.php?post_type=product&amp;page=rate_plans" method="post">
								<?php do_action( 'hbfwc_before_add_rateplan_fields' ); ?>

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

								<div class="form-field">
									<label for="rateplan_features"><?php esc_html_e( 'Features', 'hotel-booking-for-woocommerce' ); ?></label>
									<input name="rateplan_features" id="rateplan_features" type="text" value="" required />
									<p class="description"><?php esc_html_e( 'The rate plan features. Separate the values with a comma. e.g "Non-refundable", "No charge up-to 24H", etc.', 'hotel-booking-for-woocommerce' ); ?></p>
								</div>

								<div class="form-field">
									<?php wp_editor( '', 'rateplan_description', array( 'textarea_rows' => 10 ) ); ?>

									<p class="description"><?php esc_html_e( 'The details about the rate plan and its policy.', 'hotel-booking-for-woocommerce' ); ?></p>
								</div>

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

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