<?php

namespace rentsyst\admin\components;

use rentsyst\includes\Rentsyst_CatalogFilter;
use rentsyst\includes\Rentsyst_PluginSettings;
use WP_Post;
use function array_merge;
use function array_values;

class Rentsyst_CatalogVehicles
{
	const POST_TYPE_ID = 'vehicle';
	const TAXONOMY_ID = 'vehicles_group';
	const SYNC_LOCK_OPTION = 'rentsyst_vehicle_sync_lock';
	const SYNC_LOCK_TTL = 1200;

	private static $instance;
	private static $lastSyncWarning = '';
	private static $syncLockMode = '';
	private function __construct()
	{
		$this->registerTaxonomy();
		$this->registerPostType();
		$this->addCustomColumn();
		$this->copyMetaValueFromTemplatePages();
	}

	public static function create()
	{
		if(!self::$instance) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function registerTaxonomy()
	{
		register_taxonomy( self::TAXONOMY_ID, [ self::POST_TYPE_ID ], [
			'label'                 => 'Groups',
			'labels'                => [
				'name'              => 'Groups',
				'singular_name'     => 'Group',
				'search_items'      => 'Search Group',
				'all_items'         => 'All Groups',
				'view_item '        => 'View Group',
				'edit_item'         => 'Edit Genre',
				'update_item'       => 'Update Genre',
				'add_new_item'      => 'Add New Genre',
				'new_item_name'     => 'New Genre Name',
				'menu_name'         => 'Groups',
			],
			'description'           => '',
			'public'                => true,
			'hierarchical'          => false,
			'rewrite'               => true,
			'capabilities'          => array('edit_terms' => false),
			'meta_box_cb'           => null,
			'show_admin_column'     => false,
			'show_in_rest'          => null,
			'rest_base'             => null,
		] );
	}

	private function registerPostType()
	{
		register_post_type(self::POST_TYPE_ID, array(
			'label'  => 'Vehicles',
			'labels' => array(
				'name'               => 'Vehicles',
				'singular_name'      => 'Vehicle',
				'add_new'            => 'Add Vehicle',
				'menu_name'          => 'Vehicles',
			),
			'description'         => '',
			'public'              => true,
			'show_in_menu'        => true,
			'menu_position'       => 30,
			'menu_icon'           => 'dashicons-performance',
			'map_meta_cap' => true,
			'capabilities' => array(
				'edit_post' => true,
				'create_posts' => false,
			),
			'hierarchical'        => false,
			'supports'            => [ 'title', 'editor', 'comments', 'custom-fields', 'thumbnail'],
			'taxonomies'          => ['rentsyst_vehicles_group'],
			'has_archive'         => true,
			'rewrite'             => true,
			'query_var'           => true,
			'show_in_rest' => true,
		) );
	}

	private function addCustomColumn()
	{
		add_filter( 'manage_' . self::POST_TYPE_ID . '_posts_columns', function ($columns) {
			unset( $columns['author'] );
			$columns['year'] = __( 'Year', 'rentsyst' );
			$columns['color'] = __( 'Color', 'rentsyst' );
			$columns['thumbnail'] = __( 'Photo', 'rentsyst' );
			$columns['group'] = __( 'Group', 'rentsyst' );
			$columns['body_type'] = __( 'Body type', 'rentsyst' );
			$columns['fuel'] = __( 'Fuel', 'rentsyst' );
			$columns['transmission'] = __( 'Transmission', 'rentsyst' );
			$columns['price'] = __( 'Base price', 'rentsyst' );
			$columns['number_seats'] = __( 'Number of seats', 'rentsyst' );
			$columns['large_bags'] = __( 'Large bags', 'rentsyst' );
			$columns['small_bags'] = __( 'Small bags', 'rentsyst' );

			return $columns;
		} );

		add_action( 'manage_' . self::POST_TYPE_ID . '_posts_custom_column' , function ($column, $post_id) {
			switch ( $column ) {

				case 'thumbnail' :
					echo '<img class="rentsyst_photo_thumbnails" src="'.  get_post_meta( $post_id , 'thumbnail', true ) . '">';
					break;
				case 'year' :
					echo get_post_meta( $post_id , 'year', true );
					break;
				case 'color' :
					echo '<span class="rentsyst-circle-color" style="background-color: #' . get_post_meta( $post_id , 'color', true ) . '"></span>';
					break;
				case 'group' :
					echo get_post_meta( $post_id , 'group' , true );
					break;
				case 'body_type' :
					echo get_post_meta( $post_id , 'body_type' , true );
					break;
				case 'fuel' :
					echo get_post_meta( $post_id , 'fuel' , true );
					break;
				case 'transmission' :
					echo get_post_meta( $post_id , 'transmission' , true );
					break;
				case 'price' :
					echo get_post_meta( $post_id , 'price' , true );
					break;
				case 'number_seats' :
					echo get_post_meta( $post_id , 'number_seats' , true );
					break;
				case 'number_doors' :
					echo get_post_meta( $post_id , 'number_doors' , true );
					break;
				case 'large_bags' :
					echo get_post_meta( $post_id , 'large_bags' , true );
					break;
				case 'small_bags' :
					echo get_post_meta( $post_id , 'small_bags' , true );
					break;

			}
		}, 10, 2 );

		add_filter('pre_get_posts', function ( $object ) {
			// Only the admin list table may take its status filter from $_GET.
			// pre_get_posts also fires for every get_posts()/WP_Query — without
			// this guard the empty $_GET default used to wipe the explicit
			// post_status of the sync lookups, hiding drafted/trashed vehicles
			// from the matcher and spawning duplicate posts.
			if( !is_admin() || !$object->is_main_query() )
				return;

			if( $object->get('post_type') !== self::POST_TYPE_ID )
				return;

			$object->set('post_status', sanitize_text_field($_GET['post_status'] ?? ''));
		});
	}

	public static function uploadImage( string $post_id )
	{
		$post_name = get_post_meta($post_id, 'brand', true) . ' ' . get_post_meta($post_id, 'mark', true);

		$photos = get_post_meta($post_id, 'photos', true);

		$attachments = [];
		foreach ($photos as $photo) {
			$attachments[] = media_sideload_image(
				$photo,
				0,
				$post_name,
				'id'
			);
		}

		update_post_meta($post_id, 'attachments', $attachments);

		$image = media_sideload_image(
			get_post_meta($post_id, 'thumbnail', true),
			$post_id,
			$post_name,
			'id'
		);
		set_post_thumbnail( $post_id, $image );
	}

	private static function deleteAllVehicles()
	{
		$allposts = get_posts( array( 'post_type' => self::POST_TYPE_ID, 'numberposts' => - 1 ) );
		foreach ( $allposts as $eachpost ) {
			wp_delete_post( $eachpost->ID, true );

		}
	}

	public static function updateVehicles($vehicles)
	{
		Rentsyst_CatalogVehicles::create();
		self::$lastSyncWarning = '';

		if(!is_array($vehicles) || count($vehicles) === 0) {
			throw new \Exception('Vehicle sync aborted: RentSyst returned an empty or unreadable vehicle list, existing posts were left untouched.');
		}

		$payloadIds = self::collectPayloadIds($vehicles);

		if(!self::acquireSyncLock()) {
			throw new \Exception('Vehicle sync is already running in another process; try again in a few minutes.');
		}

		self::trashStaleVehicles($payloadIds);

		$filters = [];
		$prices = [];

		$imagesForUpload = [];

		foreach ($vehicles as $vehicle) {

			$post_category = self::getTaxonomy($vehicle->group);

			$args = array(
				'meta_key' => 'id',
				'meta_value' => $vehicle->id,
				'post_type' => Rentsyst_CatalogVehicles::POST_TYPE_ID,
				// 'any' excludes trash, but a vehicle returning to the feed must
				// reclaim its trashed post instead of spawning a duplicate.
				'post_status' => ['publish', 'future', 'draft', 'pending', 'private', 'trash'],
				'posts_per_page' => -1,
				// Oldest first: the original post owns the clean slug and the
				// SEO history, so it is the copy the sync keeps.
				'orderby' => 'ID',
				'order' => 'ASC',
				// Polylang must never narrow sync queries to one language.
				'lang' => '',
			);
			$existingPosts = get_posts($args);

			// Prefer a live post; resurrect a trashed one only when nothing
			// outside the trash carries this vehicle id.
			$post = null;
			foreach ($existingPosts as $existingPost) {
				if($existingPost->post_status !== 'trash') {
					$post = $existingPost;
					break;
				}
			}
			if(!$post) {
				$post = $existingPosts[0] ?? null;
			}

			if(!$post) {
				$post_id = wp_insert_post( array(
					'post_content' => false,
					'post_title'   =>  $vehicle->brand . ' ' . $vehicle->mark,
					'post_type'    => Rentsyst_CatalogVehicles::POST_TYPE_ID,
					'post_status'  => 'publish',
					'tax_input'      => array( self::TAXONOMY_ID => [$post_category] ),
				) );
				$existingPosts = [];
			} else {
				$post_id = $post->ID;
				self::ensurePublished($post_id);
				wp_update_post([
					'ID' => $post_id,
					'tax_input'      => array( self::TAXONOMY_ID => [$post_category] ),
					'post_title'   =>  $vehicle->brand . ' ' . $vehicle->mark,
				]);
			}

			$targetPostIds = self::ensureTranslations($post_id, $existingPosts, $vehicle, $post_category);

			foreach ($targetPostIds as $targetPostId) {
				self::ensurePublished($targetPostId);
			}

			self::collapseDuplicates($existingPosts, $targetPostIds, $vehicle->id);

			$filters['year'][sanitize_title($vehicle->year)] = $vehicle->year;
			$filters['number_seats'][sanitize_title($vehicle->number_seats)] = $vehicle->number_seats;
			$filters['number_doors'][sanitize_title($vehicle->number_doors)] = $vehicle->number_doors;
			$filters['large_bags'][sanitize_title($vehicle->large_bags)] = $vehicle->large_bags;
			$filters['small_bags'][sanitize_title($vehicle->small_bags)] = $vehicle->small_bags;
			$filters['brand'][sanitize_title($vehicle->brand)] = $vehicle->brand;
			$filters['group'][sanitize_title($vehicle->group)] = $vehicle->group;
			$filters['color'][sanitize_title($vehicle->color->code)] = sanitize_title($vehicle->color->code);
			$filters['body_type'][sanitize_title($vehicle->body_type)] = $vehicle->body_type;
			$filters['fuel'][sanitize_title($vehicle->fuel)] = $vehicle->fuel;
			$period_price = $vehicle->periods_price;
			usort($period_price, function ($element, $nextElement) {
				return $element->period_from > $nextElement->period_from;
			});
			$min_price = $vehicle->price + $vehicle->price * end($period_price)->discount / 100;
			if(isset($vehicle->seasons[0])) {
				$min_price += $min_price * $vehicle->seasons[0]->percent / 100;
			}
			$prices[] = $min_price;

			$filters['transmission'][sanitize_title($vehicle->transmission)] = $vehicle->transmission;

			foreach ($vehicle->options as $option) {
				$filters['options'][sanitize_title($option->name)] = $option->name;
			}

			$hash = hash('md5', json_encode($vehicle));

			foreach ($targetPostIds as $post_id) {
				delete_post_meta($post_id, 'options');
				foreach ($vehicle->options as $option) {
					add_post_meta( $post_id, 'options', $option->name );
				}

				if($hash !== get_post_meta($post_id, 'hash', true)) {
					if(
						get_post_meta($post_id, 'thumbnail', true) !== $vehicle->thumbnail ||
					    get_post_meta($post_id, 'photos', true) !== $vehicle->photos
					) {
						$imagesForUpload[] = $post_id;
					}
					update_post_meta( $post_id, 'hash', $hash );
					update_post_meta( $post_id, 'min_price', number_format( $min_price, 2 ) );
					update_post_meta( $post_id, 'periods_price', $period_price );
					update_post_meta( $post_id, 'seasons', $vehicle->seasons );
					update_post_meta( $post_id, 'custom_fields', $vehicle->custom_fields );
					update_post_meta( $post_id, 'transmission', $vehicle->transmission );
					update_post_meta( $post_id, 'price_tariff', $vehicle->price_tariff );
					update_post_meta( $post_id, 'locations', $vehicle->locations );
					update_post_meta( $post_id, 'options_data', json_encode( $vehicle->options ) );
					update_post_meta( $post_id, 'discount_price', '' );
					update_post_meta( $post_id, 'id', $vehicle->id );
					update_post_meta( $post_id, 'year', $vehicle->year );
					update_post_meta( $post_id, 'number_seats', $vehicle->number_seats );
					update_post_meta( $post_id, 'number_doors', $vehicle->number_doors );
					update_post_meta( $post_id, 'large_bags', $vehicle->large_bags );
					update_post_meta( $post_id, 'small_bags', $vehicle->small_bags );
					update_post_meta( $post_id, 'brand', $vehicle->brand );
					update_post_meta( $post_id, 'mark', $vehicle->mark );
					update_post_meta( $post_id, 'group', $vehicle->group );
					update_post_meta( $post_id, 'color', sanitize_title( $vehicle->color->code ) );
					update_post_meta( $post_id, 'body_type', $vehicle->body_type );
					update_post_meta( $post_id, 'price', $vehicle->price );
					update_post_meta( $post_id, 'volume_tank', $vehicle->volume_tank );
					update_post_meta( $post_id, 'insurance_deposit', $vehicle->insurance_deposit );
					update_post_meta( $post_id, 'volume_engine', $vehicle->volume_engine );
					update_post_meta( $post_id, 'fuel', $vehicle->fuel );
					update_post_meta( $post_id, 'thumbnail', $vehicle->thumbnail );
					update_post_meta( $post_id, 'photos', $vehicle->photos );
					update_post_meta( $post_id, 'odometer', $vehicle->odometer );
					update_post_meta( $post_id, 'link', $vehicle->_links->self->href );
				}
			}

		}
		Rentsyst_CatalogFilter::saveOptions($filters);
		Rentsyst_CatalogFilter::saveRangePrices($prices);

		self::maybeFlushRewriteRules();
		self::releaseSyncLock();

		return $imagesForUpload;
	}

	public static function getLastSyncWarning()
	{
		return self::$lastSyncWarning;
	}

	/**
	 * Serializes sync runs across admin-ajax, WP-CLI and any cron a host adds:
	 * two concurrent runs would each miss the other's uncommitted inserts and
	 * double-create posts. MySQL GET_LOCK releases automatically when the
	 * connection dies, so a fataled run cannot deadlock the next one; the
	 * add_option fallback (atomic thanks to the unique option_name index)
	 * covers environments without GET_LOCK and expires by TTL instead.
	 */
	private static function acquireSyncLock()
	{
		global $wpdb;

		$lock = $wpdb->get_var($wpdb->prepare('SELECT GET_LOCK(%s, 0)', self::syncLockName()));
		if($lock !== null) {
			self::$syncLockMode = (string) $lock === '1' ? 'db' : '';
			return self::$syncLockMode !== '';
		}

		$now = time();
		if(add_option(self::SYNC_LOCK_OPTION, $now, '', 'no')) {
			self::$syncLockMode = 'option';
			return true;
		}
		$startedAt = (int) get_option(self::SYNC_LOCK_OPTION);
		if($startedAt && $now - $startedAt > self::SYNC_LOCK_TTL) {
			update_option(self::SYNC_LOCK_OPTION, $now, 'no');
			self::$syncLockMode = 'option';
			return true;
		}
		return false;
	}

	private static function releaseSyncLock()
	{
		global $wpdb;

		if(self::$syncLockMode === 'db') {
			$wpdb->query($wpdb->prepare('SELECT RELEASE_LOCK(%s)', self::syncLockName()));
		} elseif(self::$syncLockMode === 'option') {
			delete_option(self::SYNC_LOCK_OPTION);
		}
		self::$syncLockMode = '';
	}

	private static function syncLockName()
	{
		global $wpdb;

		return 'rentsyst_vehicle_sync_' . $wpdb->prefix;
	}

	/**
	 * The sync invariant is one post per vehicle id and active language — the
	 * posts ensureTranslations() claimed. Every other post carrying the same id
	 * is a duplicate (a leftover of unserialized runs, or a translation whose
	 * language was removed from Polylang/WPML): it is trashed and its `id` meta
	 * is renamed to `_rentsyst_duplicate_of`, so no later sync can match or
	 * resurrect it and external cleanups stay safe. Skipped entirely when
	 * multilingual data exists in the database while no language plugin is
	 * loaded — trashing real translations because Polylang is momentarily
	 * inactive would be worse than tolerating duplicates for a run.
	 */
	private static function collapseDuplicates(array $existingPosts, array $targetPostIds, $vehicleId)
	{
		if(count($existingPosts) < 2) {
			return;
		}
		if(!apply_filters('rentsyst_sync_collapse_duplicates', true)) {
			return;
		}
		if(!Rentsyst_Language::isMultilingualPluginLoaded() && Rentsyst_Language::hasStoredLanguageData()) {
			return;
		}

		$keepIds = array_map('intval', $targetPostIds);
		foreach ($existingPosts as $existingPost) {
			if(in_array((int) $existingPost->ID, $keepIds, true) || $existingPost->post_status === 'trash') {
				continue;
			}
			delete_post_meta($existingPost->ID, 'id');
			update_post_meta($existingPost->ID, '_rentsyst_duplicate_of', $vehicleId);
			wp_trash_post($existingPost->ID);
		}
	}

	private static function collectPayloadIds(array $vehicles)
	{
		$payloadIds = [];
		foreach ($vehicles as $vehicle) {
			if(isset($vehicle->id) && (string) $vehicle->id !== '') {
				$payloadIds[(string) $vehicle->id] = true;
			}
		}

		if($payloadIds === []) {
			throw new \Exception('Vehicle sync aborted: vehicle list carries no ids, existing posts were left untouched.');
		}

		return $payloadIds;
	}

	/**
	 * Runs before the upsert loop: posts whose vehicle id is gone from the
	 * payload are trashed, which renames their slug to "<slug>__trashed" and
	 * releases the original one before wp_insert_post() picks slugs for
	 * re-created vehicles. Drafts accumulated by the old cleanup are swept the
	 * same way. Trashing the published fleet is skipped when the payload would
	 * wipe most of it at once — a partial API response is more likely than a
	 * legitimate mass removal — and a later healthy sync untrashes matched
	 * posts anyway.
	 */
	private static function trashStaleVehicles(array $payloadIds)
	{
		$posts = get_posts([
			'post_type' => self::POST_TYPE_ID,
			'post_status' => 'any',
			'posts_per_page' => -1,
			// Polylang must never narrow sync queries to one language.
			'lang' => '',
		]);

		$publishedTotal = 0;
		$stalePublished = [];
		$staleHidden = [];
		foreach ($posts as $post) {
			$isPublished = $post->post_status === 'publish';
			if($isPublished) {
				$publishedTotal++;
			}
			if(isset($payloadIds[(string) get_post_meta($post->ID, 'id', true)])) {
				continue;
			}
			if($isPublished) {
				$stalePublished[] = $post->ID;
			} else {
				$staleHidden[] = $post->ID;
			}
		}

		foreach ($staleHidden as $post_id) {
			wp_trash_post($post_id);
		}

		$skipPublished = count($stalePublished) >= 5 && count($stalePublished) * 2 >= $publishedTotal;
		$skipPublished = apply_filters('rentsyst_sync_skip_stale_cleanup', $skipPublished, count($stalePublished), $publishedTotal);

		if($skipPublished) {
			self::$lastSyncWarning = sprintf(
				'Sync kept %1$d of %2$d published vehicles that are missing from the RentSyst response: this looks like a partial response. If the removal is intentional, trash these posts manually or disable the guard with the rentsyst_sync_skip_stale_cleanup filter.',
				count($stalePublished),
				$publishedTotal
			);
			error_log('[rentsyst] ' . self::$lastSyncWarning);
			return;
		}

		foreach ($stalePublished as $post_id) {
			wp_trash_post($post_id);
		}
	}

	/**
	 * A vehicle present in the payload must end up published: this restores
	 * posts drafted by the old cleanup or trashed while the vehicle was absent
	 * from the feed. Trashed posts go through wp_untrash_post() rather than a
	 * bare status update so comments and the original slug kept in
	 * _wp_desired_post_slug are restored too.
	 */
	private static function ensurePublished($post_id)
	{
		$status = get_post_status($post_id);
		if(!$status || $status === 'publish') {
			return;
		}

		if($status === 'trash') {
			wp_untrash_post($post_id);
		}

		if(get_post_status($post_id) !== 'publish') {
			wp_update_post([
				'ID' => $post_id,
				'post_status' => 'publish',
			]);
		}
	}

	/**
	 * Rewrite rules are cached in the `rewrite_rules` option and are only
	 * regenerated on flush. After a plugin update or after the first vehicle
	 * (and its language copies) appear, the single-vehicle rule — including the
	 * language-prefixed variants added by Polylang/WPML — may be missing, which
	 * makes vehicle pages 404 until a manual flush. Flush once, only when the
	 * CPT rule is actually absent (cheap no-op otherwise). Languages are not
	 * hardcoded: presence of the CPT query var in any rule is the signal.
	 */
	private static function maybeFlushRewriteRules()
	{
		$rules = get_option('rewrite_rules');

		if(is_array($rules)) {
			foreach ($rules as $rewrite) {
				if(strpos($rewrite, self::POST_TYPE_ID . '=') !== false) {
					return;
				}
			}
		}

		flush_rewrite_rules();
	}

	private static function ensureTranslations( $post_id, $existingPosts, $vehicle, $post_category )
	{
		// One vehicle post is materialized per language returned here. Sites
		// whose Polylang config lists more languages than they actually publish
		// can pin the real set via the filter; collapseDuplicates() then trashes
		// the copies of the languages that dropped out.
		$languages = apply_filters('rentsyst_sync_languages', Rentsyst_Language::getLanguages());
		if(!is_array($languages) || count($languages) < 2) {
			return [$post_id];
		}

		$default = Rentsyst_Language::getDefaultLanguage();
		if(!in_array($default, $languages, true)) {
			$default = $languages[0];
		}

		$candidateIds = [$post_id];
		foreach ($existingPosts as $existingPost) {
			$candidateIds[] = $existingPost->ID;
		}
		foreach (array_values(Rentsyst_Language::getConnectedPagesId($post_id)) as $connectedId) {
			$candidateIds[] = $connectedId;
		}
		$candidateIds = array_values(array_unique(array_filter($candidateIds)));

		// Two passes so a live post always wins its language slot over a
		// trashed one — otherwise a trashed duplicate could get resurrected
		// while the live translation is collapsed away. Only active languages
		// get a slot: posts of a language removed from the config must fall
		// through to collapseDuplicates() instead of being claimed.
		$byLang = [];
		$unassigned = [];
		foreach ([false, true] as $allowTrashed) {
			foreach ($candidateIds as $candidateId) {
				if((get_post_status($candidateId) === 'trash') !== $allowTrashed) {
					continue;
				}
				$lang = Rentsyst_Language::getPostLanguage($candidateId);
				if($lang && in_array($lang, $languages, true) && !isset($byLang[$lang])) {
					$byLang[$lang] = $candidateId;
				} elseif(!$lang && !$allowTrashed) {
					$unassigned[] = $candidateId;
				}
			}
		}

		if(!isset($byLang[$default]) && !empty($unassigned)) {
			if(in_array($post_id, $unassigned, true)) {
				$byLang[$default] = $post_id;
			} else {
				$byLang[$default] = array_shift($unassigned);
			}
		}

		foreach ($languages as $lang) {
			if(isset($byLang[$lang])) {
				continue;
			}
			$newId = wp_insert_post( array(
				'post_content' => false,
				'post_title'   => $vehicle->brand . ' ' . $vehicle->mark,
				'post_type'    => Rentsyst_CatalogVehicles::POST_TYPE_ID,
				'post_status'  => 'publish',
				'tax_input'    => array( self::TAXONOMY_ID => [$post_category] ),
			) );
			if(!$newId || is_wp_error($newId)) {
				continue;
			}
			update_post_meta($newId, 'id', $vehicle->id);
			$byLang[$lang] = $newId;
		}

		Rentsyst_Language::syncTranslations($byLang, $default);

		return array_values($byLang);
	}

	private static function getTaxonomy( $name )
	{
		$taxonomy = get_term_by('name', $name, self::TAXONOMY_ID);
		if(!$taxonomy) {
			$term_taxonomy_id = wp_insert_term($name, self::TAXONOMY_ID)['term_taxonomy_id'];
		} else {
			$term_taxonomy_id = $taxonomy->term_taxonomy_id;
		}
		return $term_taxonomy_id;
	}

	private function copyMetaValueFromTemplatePages()
	{
		add_action( 'added_post_meta', [$this, 'updateMetaValue'], 10, 4 );
		add_action( 'updated_post_meta', [$this, 'updateMetaValue'], 10, 4 );
	}

	public function updateMetaValue($meta_id, $post_id, $meta_key, $meta_value)
	{
		if($meta_key === '_wp_page_template' && (int) get_option(Rentsyst_PluginSettings::CATALOG_SINGLE_PAGE_ID) === $post_id ) {
			$args = array(
				'posts_per_page'   => -1,
				'post_type'        => Rentsyst_CatalogVehicles::POST_TYPE_ID,
				'suppress_filters' => true
			);
			$posts_array = get_posts( $args );
			foreach($posts_array as $post_array)
			{
				update_post_meta($post_array->ID, '_wp_page_template', $meta_value);
			}
		}
	}


}
