<?php if (!defined('ABSPATH'))
	exit; ?>
<?php

class polylai_Duplicator
{

	private function copy_meta($metas, $id, $title, $override_meta)
	{
		// If $metas has wrong format return false
		if (!(is_array($metas) || is_object($metas)))
			return false;

		// Create empty array for filtered meta data
		$prepared = array(
		);

		// Iterate through every meta index
		foreach ($metas as $meta => $vals) {

			// Conditions
			$e = (mb_substr($meta, 0, 4) == '_wp_') ? true : false;
			$f = ($meta == '_thumbnail_id') ? true : false;
			$h = (strpos($meta, 'elementor') === false) ? false : true;

			// Deny these meta tags (they may cause conflicts with the further post edit)
			$j = (mb_substr($meta, 0, 5) == '_trp_') ? false : true;

			// If any of above condition is true pass the meta tag
			if (($e || $f || $h) && $j) {

				// Prepare data and insert filtered to results
				foreach ($vals as $val) {
					if ($meta == '_elementor_data' && array_key_exists($meta, $override_meta)) {
						$val = $override_meta[$meta];
					}
					$prepared[] = array($meta => $val);
				}

			}
		}

		// Return results
		return $prepared;
	}

	private function insert_post($id, $data)
	{
		global $wpdb;

		$id = esc_sql(intval($id));
		$base_title = $data['post_title'];

		$uploadsDirOld = wp_upload_dir()['basedir'];

		// Insert post with filtered data
		$new = wp_insert_post($data, true);

		// Check if the post is inserted successfully and append array
		if (is_numeric($new)) {

			$uploadsDirNew = wp_upload_dir()['basedir'];

			// Elementor cached CSS
			$oldCssFile = $uploadsDirOld . '/elementor/css/post-' . $id . '.css';
			$newCssFile = $uploadsDirNew . '/elementor/css/post-' . $new . '.css';
			if (file_exists($oldCssFile) && is_file($oldCssFile)) {
				$customCssContent = file_get_contents($oldCssFile);
				$customCssContent = str_replace('-' . $id, '-' . $new, $customCssContent);
				if (!file_exists(dirname($newCssFile))) {
					mkdir(dirname($newCssFile), 0755, true);
				}
				file_put_contents($newCssFile, $customCssContent);
				unset($customCssContent);
			}

		}

		return $new;
	}

	private function insert_post_meta($id, $metas)
	{
		// Create empty array for new id(s) and error(s)
		$results = array('ids' => array(), 'error' => array());
		// Iterate through every meta tag
		foreach ($metas as $meta_id => $meta) {

			// Get individual data from metas array
			foreach ($meta as $key => $val) {
				if (is_serialized($val)) {
					$val = @maybe_unserialize($val);
				} else {
					$val = @wp_slash($val);
				}

				// Insert meta tag
				$res = add_post_meta($id, $key, $val);

				if ($res != false) {
					if (!isset($results['ids'][$id]))
						$results['ids'][$id] = [];
					array_push($results['ids'][$id], array($key, $val));
				} else {
					if (!isset($results['error'][$id]))
						$results['error'][$id] = [];
					array_push($results['error'][$id], array($key, $val));
				}
			}
		}

		// Return the results
		return $results;
	}

	private function clone_woocommerce_tables($sourceID, $newID)
	{

		global $wpdb;
		$tables = $wpdb->get_results('SHOW TABLES;');
		$parsedTables = [];
		foreach ($tables as $names) {
			foreach ($names as $table => $name) {
				$parsedTables[] = $name;
			}
		}

		$affectedTables = [
			'wusp_group_product_price_mapping',
			'wusp_role_pricing_mapping',
			'wusp_user_pricing_mapping'
		];

		for ($i = 0; $i < sizeof($parsedTables); ++$i) {
			$table = $parsedTables[$i];

			for ($j = 0; $j < sizeof($affectedTables); ++$j) {
				$affectTable = $affectedTables[$j];
				if (substr($table, -strlen($affectTable)) == $affectTable) {
					$results = $wpdb->get_results($wpdb->prepare(
						"SELECT * FROM %i WHERE %i = %d",
						array($table, 'product_id', $sourceID)
					));

					foreach ($results as $result => $row) {
						$columns = [];
						$values = [];

						foreach ($row as $column => $value) {
							if ($column == 'id')
								continue;
							$columns[] = $column;
							if ($column == 'product_id')
								$values[] = $newID;
							else
								$values[] = $value;
						}

						$preparedValues = [];
						$preparedValues = array_merge($preparedValues, [$table], $columns, $values);

						$query = $wpdb->get_results($wpdb->prepare(
							"INSERT INTO %i (" . implode(', ', array_fill(0, sizeof($columns), '%i')) . ") VALUES (" . implode(', ', array_fill(0, sizeof($values), '%s')) . ")",
							$preparedValues
						));
					}
				}
			}
		}

	}

	public function duplicate($post_id, $title, $translated_text, $excerpt, $status, $override_meta)
	{
		$post = get_post($post_id)->to_array();
		$meta = get_post_custom($post_id);

		$post_data = array(
			'post_title' => $title,
			'post_content' => $translated_text,
			'post_author' => $post['post_author'],
			'post_date' => $post['post_date'],
			'post_date_gmt' => $post['post_date_gmt'],
			'post_type' => $post['post_type'],
			'post_excerpt' => $excerpt,
			'page_template' => $post['page_template'],
			'menu_order' => $post['menu_order'],
			'post_password' => $post['post_password'],
			'post_status' => $status
		);

		$meta_data = $this->copy_meta($meta, $post_id, $post_data['post_title'], $override_meta);

		$new_post_id = $this->insert_post($post_id, $post_data);
		$inserted_metas = $this->insert_post_meta($new_post_id, $meta_data);

		// Regenerate Elementor cache
		if (is_plugin_active('elementor/elementor.php') && class_exists('\Elementor\Plugin')) {
			try {
				\Elementor\Plugin::$instance->files_manager->clear_cache();
			} catch (\Throwable $e) {
			} catch (\Exception $e) {
			}
		}

		return $new_post_id;
	}

}
