<?php
/**
 * Plugin upgrade utilities.
 *
 * @since 3.0.0
 */

declare( strict_types=1 );

namespace FeData\FastEvents\Core;

defined( 'ABSPATH' ) || exit;

use FeData\FastEvents\Logging\LoggerFactory;
use FeData\FastEvents\Storage\Encryption;
use FeData\FastEvents\Storage\Options;
use FeData\FastEvents\Utilities\JsonUtil;
use FeData\FastEvents\Utilities\SettingsDefaults;
use FeData\FastEvents\Utilities\UniqIds;
use stdClass;

/**
 * A class of plugin upgrade utilities.
 */
class Upgrade {

	/**
	 * Update function per release.
	 *
	 * @since 2.0.3
	 * @var array
	 */
	private static array $fe_updates = array(
		'2.0.3' => array(
			'update_admin',
			'update_203_pdf_meta',
		),
		'2.1.0' => array(
			'update_210_db_qrcode_table',
			'update_210_db_event_table',
			'update_admin',
		),
		'2.2.0' => array(
			'update_220_db_coupons_table',
			'update_220_db_alter_tables',
			'update_admin',
		),
		'2.4.0' => array(
			'update_240_db_options',
			'update_240_db_event_table',
			'update_admin',
		),
		'2.4.1' => array(
			'update_241_db_event_table',
			'update_admin',
		),
		'2.5.0' => array(
			'update_250_db_email_log_table',
			'update_admin',
		),
		'3.0.0' => array(
			'update_300_convert_options',
			'update_admin',
		),
	);


	/**
	 * Upgrade constructor.
	 *
	 * @since 3.0.0
	 *
	 * @param LoggerFactory $logger LoggingFactory class.
	 * @param Options       $options Options class.
	 * @param AdminUI       $admin_ui Admin UI class.
	 * @param Encryption    $encryption Admin UI class.
	 */
	public function __construct(
		private readonly LoggerFactory $logger,
		private readonly Options $options,
		private readonly AdminUI $admin_ui,
		private readonly Encryption $encryption // Used in the 'update_300_convert_options' function.
	) {
	}

	/**
	 * Singletons should not be cloneable.
	 *
	 * @since 2.5.0
	 */
	private function __clone(): void {
	}

	/**
	 * Prevent from being unserialized.
	 *
	 * @since 2.5.0
	 */
	public function __wakeup(): void {
	}

	/**
	 * Plugin upgrade method. Perform any upgrade tasks here
	 *
	 * @param string $installed_version Installed Fast Events version.
	 *
	 * @since 1.0
	 */
	public function upgrade( string $installed_version ): void {
		if ( is_multisite() ) {
			$target_plugin = 'fast-events/fast-events.php';
			foreach ( get_sites( array( 'fields' => 'ids' ) ) as $site_id ) {
				switch_to_blog( $site_id );

				// Determine if the target plugin is active on this site.
				$active_plugins = get_option( 'active_plugins', array() );

				// On multisite, network‑activated plugins also appear in a separate option.
				if ( is_plugin_active_for_network( $target_plugin ) ) {
					$plugin_is_active = true;
				} else {
					$plugin_is_active = in_array( $target_plugin, $active_plugins, true );
				}

				if ( $plugin_is_active ) {
					foreach ( self::$fe_updates as $version => $update_callbacks ) {
						if ( version_compare( $installed_version, $version, '<' ) ) {
							foreach ( $update_callbacks as $method_name ) {
								call_user_func( array( $this, $method_name ) );
							}
						}
					}
				}
				restore_current_blog();
			}
		} else {
			foreach ( self::$fe_updates as $version => $update_callbacks ) {
				if ( version_compare( $installed_version, $version, '<' ) ) {
					foreach ( $update_callbacks as $method_name ) {
						call_user_func( array( $this, $method_name ) );
					}
				}
			}
		}
	}

	/**
	 * Install updates admin interface.
	 *
	 * @since 2.0.3
	 * @since 2.2.0 Renamed function
	 */
	private function update_admin(): void {
		if ( ! is_main_site() ) {
			return;
		}
		$this->admin_ui->install_admin_interface( $this->admin_ui::FE_ADMIN_UI_UPGRADE_PROCESS );
	}

	/**
	 * Set the post-metadata for pdf-tickets and pdf-invoices
	 *
	 * @since 2.0.3
	 */
	private function update_203_pdf_meta(): void {
		global $wpdb;

		$tickets   = array();
		$invoices  = array();
		$pdf_infos = $wpdb->get_results( "SELECT pdf_info FROM {$wpdb->prefix}fe_events" );
		if ( ! empty( $pdf_infos ) ) {
			foreach ( $pdf_infos as $value ) {
				$info = json_decode( $value->pdf_info );
				if ( ! empty( $info ) ) {
					$tickets[]  = $info->ticket->id;
					$invoices[] = $info->invoice->id;
					if ( ! empty( $info->ticket->types ) ) {
						foreach ( $info->ticket->types as $attachment_id ) {
							$tickets[] = $attachment_id;
						}
					}
				}
			}
			foreach ( array_unique( $tickets, SORT_NUMERIC ) as $ticket_id ) {
				add_post_meta( $ticket_id, 'fast_events_template_type', 'ticket', true );
			}
			foreach ( array_unique( $invoices, SORT_NUMERIC ) as $invoice_id ) {
				add_post_meta( $invoice_id, 'fast_events_template_type', 'invoice', true );
			}
		}
	}

	/**
	 * Update qrcode table for personalized input fields
	 *
	 * @since 2.1.0
	 */
	private function update_210_db_qrcode_table(): void {
		global $wpdb;

		$table = $wpdb->prefix . 'fe_event_qrcodes';
		//phpcs:disable
		$wpdb->query( "ALTER TABLE $table CHANGE created_at created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP" );
		$wpdb->query( "ALTER TABLE $table ADD personalised_input VARCHAR(512) NULL DEFAULT NULL AFTER qrcode" );
		//phpcs:enable
	}

	/**
	 * Update event table for personalized input fields
	 *
	 * @since 2.1.0
	 * @since 2.3.0 Use fast_events_json_encode.
	 */
	private function update_210_db_event_table(): void {
		global $wpdb;

		$results = $wpdb->get_results( "SELECT id, input_fields FROM {$wpdb->prefix}fe_events" );
		if ( ! empty( $results ) ) {
			foreach ( $results as $result ) {
				$inp = json_decode( $result->input_fields );

				// Convert fields.
				if ( ! empty( $inp->fields ) ) {
					foreach ( $inp->fields as $index => $value ) {
						$inp->fields[ $index ]->min         = '';
						$inp->fields[ $index ]->max         = '';
						$inp->fields[ $index ]->personalise = 0;
					}
				} elseif ( ! isset( $inp->fields ) ) {
					$inp->fields = array();
				}

				// Convert tickets.
				if ( ! empty( $inp->tickets ) ) {
					foreach ( $inp->tickets as $index => $value ) {
						$inp->tickets[ $index ]->personalise = '';
						$inp->tickets[ $index ]->layout      = '';
					}
				} elseif ( ! isset( $inp->tickets ) ) {
					$inp->tickets = array();
				}

				// Check submit.
				if ( ! isset( $inp->submit ) ) {
					$inp->submit = new stdClass();
				}
				if ( ! isset( $inp->submit->name ) ) {
					$inp->submit->name = __( 'Pay', 'fast-events' );
				}

				// Check unique users.
				if ( ! isset( $inp->unique_users ) ) {
					$inp->unique_users = new stdClass();
				}
				if ( ! isset( $inp->unique_users->master_eventids ) ) {
					$inp->unique_users->master_eventids = '';
				}

				// Check user group.
				if ( ! isset( $inp->user_group ) ) {
					$inp->user_group = new stdClass();
				}
				if ( ! isset( $inp->user_group->id ) ) {
					$inp->user_group->id = 0;
				}
				if ( ! isset( $inp->user_group->event_id ) ) {
					$inp->user_group->event_id = '';
				}
				if ( ! isset( $inp->user_group->roles ) ) {
					$inp->user_group->roles = '';
				}
				if ( ! isset( $inp->user_group->rest_url ) ) {
					$inp->user_group->rest_url = '';
				}
				if ( ! isset( $inp->user_group->rest_header ) ) {
					$inp->user_group->rest_header = '';
				}

				$wpdb->update(
					$wpdb->prefix . 'fe_events',
					array( 'input_fields' => JsonUtil::fast_events_json_encode( $inp ) ),
					array( 'id' => $result->id ),
				);
			}
		}
	}

	/**
	 * Add coupons table
	 *
	 * @since 2.2.0
	 */
	private function update_220_db_coupons_table(): void {
		global $wpdb;

		$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}fe_event_coupons" );
		$wpdb->query(
			"CREATE TABLE {$wpdb->prefix}fe_event_coupons (
			id BIGINT NOT NULL AUTO_INCREMENT,
			code VARCHAR(32) NOT NULL,
			description VARCHAR(100) NOT NULL,
			date_created DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
			date_modified DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
			type ENUM('percent','fixed') NOT NULL DEFAULT 'fixed',
			amount DECIMAL(10,2) NOT NULL,
			usage_limit INT UNSIGNED NOT NULL DEFAULT '1',
			usage_limit_per_user INT UNSIGNED NOT NULL DEFAULT '1',
			used INT UNSIGNED NOT NULL DEFAULT '0',
			last_used DATETIME NULL,
			start_date DATETIME NOT NULL,
			end_date DATETIME NOT NULL,
			events VARCHAR(64) NULL,
			tickets VARCHAR(256) NULL,
			minimum_tickets INT UNSIGNED NULL,
			maximum_tickets INT UNSIGNED NULL,
			minimum_amount DECIMAL(10,2) NULL,
			maximum_amount DECIMAL(10,2) NULL,
			email VARCHAR(100) NULL,
			PRIMARY KEY (id), 
			UNIQUE code_index (code)
		) ENGINE=InnoDB DEFAULT CHARSET=$wpdb->charset COLLATE=$wpdb->collate;"
		);
	}

	/**
	 * Update events and order table for coupons
	 *
	 * @since 2.1.0
	 */
	private function update_220_db_alter_tables(): void {
		global $wpdb;

		$etable = $wpdb->prefix . 'fe_events';
		$otable = $wpdb->prefix . 'fe_event_orders';
		//phpcs:disable
		$wpdb->query( "ALTER TABLE $etable ADD coupons_needed TINYINT(1) NOT NULL DEFAULT '0' AFTER tracking_needed" );
		$wpdb->query( "ALTER TABLE $otable ADD discount DECIMAL(10,4) NOT NULL DEFAULT '0.0000' AFTER total" );
		$wpdb->query( "ALTER TABLE $otable CHANGE created_at created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP" );
		//phpcs:enable
	}

	/**
	 * Update the options table for new 'smtp2go' values.
	 *
	 * @since 2.4.0
	 */
	private function update_240_db_options(): void {
		$option_key = 'fast_events_options';
		$options    = get_option( $option_key, array() );

		// Set the new values.
		$options['smtp2go_server']  = 'https://api.smtp2go.com/v3/email/send';
		$options['smtp2go_api_key'] = '';

		update_option( $option_key, $options );
	}

	/**
	 * Update the event table for a new flag ('remain') to tickets
	 *
	 * @since 2.4.0
	 */
	private function update_240_db_event_table(): void {
		global $wpdb;

		$results = $wpdb->get_results( "SELECT id, input_fields FROM {$wpdb->prefix}fe_events" );
		if ( ! empty( $results ) ) {
			foreach ( $results as $result ) {
				$inp = json_decode( $result->input_fields );

				// Convert tickets.
				if ( ! empty( $inp->tickets ) ) {
					foreach ( $inp->tickets as $index => $value ) {
						$inp->tickets[ $index ]->remain = 0;
					}
				} elseif ( ! isset( $inp->tickets ) ) {
					$inp->tickets = array();
				}

				$wpdb->update(
					$wpdb->prefix . 'fe_events',
					array( 'input_fields' => JsonUtil::fast_events_json_encode( $inp ) ),
					array( 'id' => $result->id ),
				);
			}
		}
		$this->logger->info( 'v2.4.0: Updated the event table for a new flag (remain) to tickets' );
	}

	/**
	 * Update event table tickets (set the default layout fields if it's empty)
	 *
	 * @since 2.4.1
	 */
	private function update_241_db_event_table(): void {
		global $wpdb;

		$results = $wpdb->get_results( "SELECT id, input_fields FROM {$wpdb->prefix}fe_events" );
		if ( ! empty( $results ) ) {
			foreach ( $results as $result ) {
				$inp = json_decode( $result->input_fields );

				// Convert tickets layout.
				if ( ! empty( $inp->tickets ) ) {
					foreach ( $inp->tickets as $index => $value ) {
						if ( empty( $inp->tickets[ $index ]->layout ) ) {
							$inp->tickets[ $index ]->layout = 'Order-id,Name,Email';
						}
					}
				} elseif ( ! isset( $inp->tickets ) ) {
					$inp->tickets = array();
				}

				$wpdb->update(
					$wpdb->prefix . 'fe_events',
					array( 'input_fields' => JsonUtil::fast_events_json_encode( $inp ) ),
					array( 'id' => $result->id ),
				);
			}
		}
		$this->logger->info( 'v2.4.1: Updated the event table tickets (set the default layout fields if it\'s empty)' );
	}

	/**
	 * Add the email_log table
	 *
	 * @since 2.5.0
	 */
	private function update_250_db_email_log_table(): void {
		global $wpdb;

		$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}fe_event_email_log" );
		$wpdb->query(
			"CREATE TABLE {$wpdb->prefix}fe_event_email_log (
			id BIGINT NOT NULL AUTO_INCREMENT,
			event_id BIGINT(20) UNSIGNED NOT NULL,
			order_id BIGINT(20) UNSIGNED NOT NULL,
			date_created DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
			date_modified DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
			provider_id ENUM('local','smtp','amazon','brevo','mailgun','mailjet','postmark','sendgrid','smtp2go','sparkpost') NOT NULL DEFAULT 'local',
			email_type ENUM('normal','confirm','free') NOT NULL DEFAULT 'normal',
			provider_email_id VARCHAR(100) NOT NULL,
			sender_email VARCHAR(100) NOT NULL,
			receiver_email VARCHAR(100) NOT NULL,
			email_subject VARCHAR(100) NOT NULL,
			email_events TEXT NOT NULL,
			PRIMARY KEY (id),
			UNIQUE KEY provider_email_id_index (provider_email_id),
			UNIQUE KEY order_date_index (order_id, date_created)
		) ENGINE=InnoDB DEFAULT CHARSET=$wpdb->charset COLLATE=$wpdb->collate;"
		);
		$this->logger->info( 'v2.5.0: Added the email_log table' );
	}

	/**
	 * Convert the plugin settings to the new format.
	 *
	 * @since 3.0.0
	 */
	private function update_300_convert_options(): void {
		global $wpdb;

		static $email_type = array( 'local', 'smtp', 'amazon', 'brevo', 'mailgun', 'mailjet', 'postmark', 'sendgrid', 'smtp2go', 'sparkpost' );

		// Get the old option values.
		$raw_value = get_option( 'fast_events_options' );
		if ( is_string( $raw_value ) ) {
			$raw_value   = $this->encryption->decrypt( $raw_value );
			$old_options = json_decode( $raw_value, true );
			if ( json_last_error() !== JSON_ERROR_NONE ) { // Invalid JSON.
				$old_options = array(); // Reset settings.
			}
		} else {
			$old_options = is_array( $raw_value ) ? $raw_value : array();
		}

		$new_options = SettingsDefaults::default_settings();

		// Convert Mollie to new values.
		$new_options->payment_provider = wp_json_encode(
			array(
				'type'     => 'payment',
				'provider' => array(
					'class'    => 'FeData\\FastEvents\\Payment\\Provider\\MollieProvider',
					'live_key' => $old_options['mollie_live'] ?? '',
					'test_key' => $old_options['mollie_test'] ?? '',
				),
			)
		);

		$new_options->payment_config->currency_symbol     = $old_options['ideal_currency'] ?? '€';
		$new_options->payment_config->refund_costs        = (float) $old_options['refund_costs'] ?? 2.25;
		$new_options->payment_config->refund_per          = (int) $old_options['refund_per'] ?? 1;
		$new_options->payment_config->errorpage           = $old_options['mollie_errorpage'] ?? '';
		$new_options->payment_config->saas_mode           = ( (int) $old_options['saas_mode'] ?? 0 ) === 1;
		$new_options->payment_config->saas_client_id      = $old_options['saas_client_id'] ?? '';
		$new_options->payment_config->saas_client_secret  = $old_options['saas_client_secret'] ?? '';
		$new_options->payment_config->saas_client_fee     = (float) $old_options['saas_client_fee'] ?? 0.05;
		$new_options->payment_config->saas_client_fee_per = (int) $old_options['saas_client_fee_per'] ?? 1;
		$new_options->selected_mail_provider              = $email_type[ (int) ( $old_options['email_type'] ?? 0 ) ];
		$new_options->email_sender->name                  = $old_options['smtp_sender_name'] ?? '';
		$new_options->email_sender->email                 = $old_options['smtp_sender_email'] ?? '';
		$new_options->email_retries->enabled              = ( (int) ( $old_options['email_retries'] ?? 0 ) ) === 1;
		$new_options->email_retries->retry_scheme         = $old_options['email_retry_scheme'] ?? '2,4,8,16,32,64,128';
		$new_options->email_retries->webhooks             = (int) ( $old_options['email_webhooks'] ?? 0 ) === 1;

		$tmp = array(
			'type'     => 'mailer',
			'provider' => array(
				'class'   => 'FeData\\FastEvents\\Mail\\Provider\\%Mailer',
				'server'  => '',
				'api_key' => '',
			),
		);

		$type = (int) ( $old_options['email_type'] ?? 0 );
		if ( 0 === $type ) {
			$tmp['provider']['class'] = str_replace( '%', 'Local', $tmp['provider']['class'] );
			unset( $tmp['provider']['server'], $tmp['provider']['api_key'] );
		} elseif ( 1 === $type ) {
			$tmp['provider']['class'] = str_replace( '%', 'Smtp', $tmp['provider']['class'] );
			unset( $tmp['provider']['api_key'] );
			$tmp['provider']['server']      = $old_options['smtp_server'] ?? '';
			$tmp['provider']['user']        = $old_options['smtp_user'] ?? '';
			$tmp['provider']['password']    = $old_options['smtp_password'] ?? '';
			$tmp['provider']['verify_peer'] = ( (int) $old_options['smtp_verify_peer'] ?? 0 ) === 1;
			$tmp['provider']['protocol']    = $old_options['smtp_protocol'] ?? 'ssl';
			$tmp['provider']['port']        = (int) ( $old_options['smtp_port'] ?? 465 );
		} elseif ( 2 === $type ) {
			$tmp['provider']['class']   = str_replace( '%', 'Mailgun', $tmp['provider']['class'] );
			$tmp['provider']['server']  = $old_options['mailgun_server'] ?? '';
			$tmp['provider']['api_key'] = $old_options['mailgun_api_key'] ?? '';
		} elseif ( 3 === $type ) {
			$tmp['provider']['class']   = str_replace( '%', 'Mailjet', $tmp['provider']['class'] );
			$tmp['provider']['server']  = $old_options['mailjet_server'] ?? '';
			$tmp['provider']['api_key'] = $old_options['mailjet_api_key'] ?? '';
		} elseif ( 4 === $type ) {
			$tmp['provider']['class']   = str_replace( '%', 'Postmark', $tmp['provider']['class'] );
			$tmp['provider']['server']  = $old_options['postmark_server'] ?? '';
			$tmp['provider']['api_key'] = $old_options['postmark_api_key'] ?? '';
		} elseif ( 5 === $type ) {
			$tmp['provider']['class']   = str_replace( '%', 'Sendgrid', $tmp['provider']['class'] );
			$tmp['provider']['server']  = $old_options['sendgrid_server'] ?? '';
			$tmp['provider']['api_key'] = $old_options['sendgrid_api_key'] ?? '';
		} elseif ( 6 === $type ) {
			$tmp['provider']['class']   = str_replace( '%', 'Brevo', $tmp['provider']['class'] );
			$tmp['provider']['server']  = $old_options['sendinblue_server'] ?? '';
			$tmp['provider']['api_key'] = $old_options['sendinblue_api_key'] ?? '';
		} elseif ( 7 === $type ) {
			$tmp['provider']['class']   = str_replace( '%', 'Sparkpost', $tmp['provider']['class'] );
			$tmp['provider']['server']  = $old_options['sparkpost_server'] ?? '';
			$tmp['provider']['api_key'] = $old_options['sparkpost_api_key'] ?? '';
		} elseif ( 8 === $type ) {
			$tmp['provider']['class']      = str_replace( '%', 'Amazon', $tmp['provider']['class'] );
			$tmp['provider']['region']     = $old_options['amazon_region'] ?? '';
			$tmp['provider']['access_key'] = $old_options['amazon_access_key'] ?? '';
			$tmp['provider']['secret_key'] = $old_options['amazon_secret_key'] ?? '';
			unset( $tmp['provider']['server'], $tmp['provider']['api_key'] );
		} elseif ( 9 === $type ) {
			$tmp['provider']['class']   = str_replace( '%', 'Smtp2Go', $tmp['provider']['class'] );
			$tmp['provider']['server']  = $old_options['smtp2go_server'] ?? '';
			$tmp['provider']['api_key'] = $old_options['smtp2go_api_key'] ?? '';
		}
		$new_options->mail_provider = wp_json_encode( $tmp );

		$new_options->captcha->provider                    = (int) ( $old_options['captcha_provider'] ?? 0 );
		$new_options->captcha->site_key                    = $old_options['captcha_site_key'] ?? '';
		$new_options->captcha->secret_key                  = $old_options['captcha_secret_key'] ?? '';
		$new_options->fe_admin_api_key                     = $old_options['fe_admin_api_key'] ?? UniqIds::uniq_id();
		$new_options->action_scheduler->purge_days         = (int) ( $old_options['as_purge_days'] ?? 30 );
		$new_options->action_scheduler->time_limit         = (int) ( $old_options['as_time_limit'] ?? 30 );
		$new_options->action_scheduler->batch_size         = (int) ( $old_options['as_batch_size'] ?? 25 );
		$new_options->action_scheduler->concurrent_batches = (int) ( $old_options['as_concurrent_batches'] ?? 1 );
		$new_options->action_scheduler->additional_runners = (int) ( $old_options['as_additional_runners'] ?? 0 );
		$new_options->logging->log_retention_days          = (int) ( $old_options['log_retention_days'] ?? 30 );
		$new_options->misc->orders_cleanup                 = (int) ( $old_options['orders_cleanup'] ?? 0 ) === 1;
		$new_options->misc->ordering_api                   = (int) ( $old_options['ordering_api'] ?? 0 ) === 1;
		$new_options->misc->stats_queries_cache_time       = (int) ( $old_options['stats_queries_cache_time'] ?? 60 );
		$new_options->misc->order_form_cache_time          = (int) ( $old_options['order_form_cache_time'] ?? 60 );
		$new_options->misc->custom_order_status            = $old_options['misc_custom_order_status'] ?? 'processing,shipped';

		$this->options->set_plugin_settings( $new_options );
		$this->logger->info( 'v3.0.0: Converted the plugin settings to the new format.' );

		$wpdb->query( "ALTER TABLE {$wpdb->prefix}fe_event_orders CHANGE payment_id payment_id VARCHAR(255)" );
		$this->logger->info( 'v3.0.0: Changed size of the payment_id column in the orders table.' );

		// Convert old ordering API Shortcodes.
		$lines = explode( "\r\n", $old_options['ordering_shortcodes'] ?? '' );
		foreach ( $lines as $line ) {

			// Search for the token in this line?
			$parts = explode( ':', $line );
			if ( ! empty( $parts[0] ) && ! empty( $parts[1] ) ) {
				$shortcode                 = array();
				$shortcode['option_name']  = 'fast_events_ordering_' . $parts[0];
				$shortcode['option_value'] = $parts[1];
				$shortcode['autoload']     = 'off';
				$wpdb->insert( $wpdb->options, $shortcode );
			}
		}
		if ( 0 !== count( $lines ) ) {
			$this->logger->info( 'v3.0.0: Converted ' . count( $lines ) . ' ordering API Shortcodes.' );
		}
	}
}
