<?php
/********************************************************************
 * Copyright (C) 2024 Darko Gjorgjijoski (https://darkog.com/)
 * Copyright (C) 2024 IDEOLOGIX MEDIA Dooel (https://ideologix.com/)
 *
 * This file is property of IDEOLOGIX MEDIA Dooel (https://ideologix.com)
 * This file is part of Vimeify Plugin - https://wordpress.org/plugins/vimeify/
 *
 * Vimeify - Formerly "WP Vimeo Videos" is free software: you can redistribute
 * it and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 2 of the License,
 * or (at your option) any later version.
 *
 * Vimeify - Formerly "WP Vimeo Videos" is distributed in the hope that it
 * will be useful, but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this plugin. If not, see <https://www.gnu.org/licenses/>.
 *
 * Code developed by Darko Gjorgjijoski <dg@darkog.com>.
 **********************************************************************/

namespace Vimeify\Core\Backend\Tools\Migrators\Steps;

use WP_Query;

/**
 * Videos Migration Class
 * Migrates videos from legacy 'dgv-upload' post type to new 'vimeify-video' post type
 */
class VideosMigration {

	/**
	 * Number of posts to process per page
	 */
	private $posts_per_page = 50;

	/**
	 * Legacy post type
	 */
	private $legacy_post_type = 'dgv-upload';

	/**
	 * New post type
	 */
	private $new_post_type = 'vimeify-video';

	/**
	 * Meta field mapping (legacy -> new)
	 */
	private $meta_mapping = array(
		'dgv_response' => 'vimeify_response',
		'dgv_context' => 'vimeify_context',
		'dgv_source' => 'vimeify_source',
		'dgv_size' => 'vimeify_size',
		'dgv_link' => 'vimeify_link',
		'dgv_curation' => 'vimeify_duration',
		'dgv_width' => 'vimeify_width',
		'dgv_height' => 'vimeify_height',
		'dgv_playable' => 'vimeify_playable',
		'dgv_embed_link' => 'vimeify_embed_link',
		'pictures' => 'vimeify_pictures',
		'dgv_last_sync_at' => 'vimeify_last_sync_at'
	);

	/**
	 * Constructor
	 */
	public function __construct() {
		// Allow customization of posts per page via filter
		$this->posts_per_page = apply_filters('vimeify_migration_posts_per_page', $this->posts_per_page);
	}

	/**
	 * Get total number of pages for migration
	 *
	 * @return int Number of pages
	 */
	public function get_page_count() {
		$total_posts = $this->get_total_legacy_posts();

		if ($total_posts === 0) {
			return 0;
		}

		return ceil($total_posts / $this->posts_per_page);
	}

	/**
	 * Get total number of legacy posts to migrate
	 *
	 * @return int Total number of posts
	 */
	public function get_total_legacy_posts() {
		$query = new WP_Query(array(
			'post_type' => $this->legacy_post_type,
			'post_status' => 'any',
			'posts_per_page' => -1,
			'fields' => 'ids',
			'meta_query' => array(
				array(
					'key' => 'vimeify_migrated',
					'compare' => 'NOT EXISTS'
				)
			)
		));

		return $query->found_posts;
	}

	/**
	 * Migrate a specific page of videos
	 *
	 * @param int $page_number Page number (1-based)
	 * @return array Results of migration
	 */
	public function migrate_page($page_number) {
		if ($page_number < 1) {
			return array(
				'success' => false,
				'error' => 'Invalid page number. Page numbers start from 1.',
				'migrated' => 0,
				'errors' => array()
			);
		}

		$posts = $this->get_legacy_posts_for_page($page_number);

		if (empty($posts)) {
			return array(
				'success' => true,
				'message' => 'No posts found for this page.',
				'migrated' => 0,
				'errors' => array()
			);
		}

		$migrated_count = 0;
		$errors = array();

		foreach ($posts as $post) {
			$result = $this->migrate_single_video($post);

			if ($result['success']) {
				$migrated_count++;
			} else {
				$errors[] = array(
					'post_id' => $post->ID,
					'error' => $result['error']
				);
			}
		}

		return array(
			'success' => true,
			'migrated' => $migrated_count,
			'total_in_page' => count($posts),
			'errors' => $errors,
			'page' => $page_number
		);
	}

	/**
	 * Get legacy posts for a specific page
	 *
	 * @param int $page_number Page number (1-based)
	 * @return array Array of WP_Post objects
	 */
	private function get_legacy_posts_for_page($page_number) {
		$offset = ($page_number - 1) * $this->posts_per_page;

		$query = new WP_Query(array(
			'post_type' => $this->legacy_post_type,
			'post_status' => 'any',
			'posts_per_page' => $this->posts_per_page,
			'offset' => $offset,
			'meta_query' => array(
				array(
					'key' => 'vimeify_migrated',
					'compare' => 'NOT EXISTS'
				)
			),
			'orderby' => 'ID',
			'order' => 'ASC'
		));

		return $query->posts;
	}

	/**
	 * Migrate a single video post
	 *
	 * @param \WP_Post $post The post to migrate
	 * @return array Result of migration
	 */
	private function migrate_single_video($post) {
		try {
			// Update post type
			$updated = wp_update_post(array(
				'ID' => $post->ID,
				'post_type' => $this->new_post_type
			), true);

			if (is_wp_error($updated)) {
				throw new \Exception('Failed to update post type: ' . $updated->get_error_message());
			}

			// Migrate meta fields
			$this->migrate_post_meta($post->ID);

			// Mark as migrated
			update_post_meta($post->ID, 'vimeify_migrated', true);
			update_post_meta($post->ID, 'vimeify_migration_date', current_time('mysql'));

			// Store original post type for reference
			update_post_meta($post->ID, 'vimeify_original_post_type', $this->legacy_post_type);

			return array(
				'success' => true,
				'post_id' => $post->ID
			);

		} catch (\Exception $e) {
			return array(
				'success' => false,
				'error' => $e->getMessage(),
				'post_id' => $post->ID
			);
		}
	}

	/**
	 * Migrate meta fields for a post
	 *
	 * @param int $post_id Post ID
	 */
	private function migrate_post_meta($post_id) {
		foreach ($this->meta_mapping as $old_key => $new_key) {
			$value = get_post_meta($post_id, $old_key, true);

			if ($value !== '') { // Only migrate if value exists
				update_post_meta($post_id, $new_key, $value);

				// Optionally remove old meta (uncomment if you want to clean up)
				delete_post_meta($post_id, $old_key);
			}
		}
	}

	/**
	 * Get migration progress
	 *
	 * @return array Progress information
	 */
	public function get_migration_progress() {
		$total_posts = $this->get_total_posts_count();
		$migrated_posts = $this->get_migrated_posts_count();
		$remaining_posts = $total_posts - $migrated_posts;

		$progress_percentage = $total_posts > 0 ? ($migrated_posts / $total_posts) * 100 : 100;

		return array(
			'total_posts' => $total_posts,
			'migrated_posts' => $migrated_posts,
			'remaining_posts' => $remaining_posts,
			'progress_percentage' => round($progress_percentage, 2),
			'total_pages' => $this->get_page_count(),
			'completed' => $remaining_posts === 0
		);
	}

	/**
	 * Get total count of all legacy posts (including already migrated)
	 *
	 * @return int Total count
	 */
	private function get_total_posts_count() {
		$query = new WP_Query(array(
			'post_type' => $this->legacy_post_type,
			'post_status' => 'any',
			'posts_per_page' => -1,
			'fields' => 'ids'
		));

		return $query->found_posts;
	}

	/**
	 * Get count of already migrated posts
	 *
	 * @return int Migrated count
	 */
	private function get_migrated_posts_count() {
		$query = new WP_Query(array(
			'post_type' => $this->legacy_post_type,
			'post_status' => 'any',
			'posts_per_page' => -1,
			'fields' => 'ids',
			'meta_query' => array(
				array(
					'key' => 'vimeify_migrated',
					'value' => true,
					'compare' => '='
				)
			)
		));

		return $query->found_posts;
	}

	/**
	 * Check if migration is needed
	 *
	 * @return bool True if migration is needed
	 */
	public function is_migration_needed() {
		return $this->get_total_legacy_posts() > 0;
	}

	/**
	 * Reset migration (for testing purposes)
	 * Removes migration markers and reverts post types
	 *
	 * @return array Result of reset operation
	 */
	public function reset_migration() {
		// Get all posts that were migrated
		$query = new WP_Query(array(
			'post_type' => $this->new_post_type,
			'post_status' => 'any',
			'posts_per_page' => -1,
			'meta_query' => array(
				array(
					'key' => 'vimeify_migrated',
					'value' => true,
					'compare' => '='
				)
			)
		));

		$reset_count = 0;
		$errors = array();

		foreach ($query->posts as $post) {
			try {
				// Revert post type
				wp_update_post(array(
					'ID' => $post->ID,
					'post_type' => $this->legacy_post_type
				));

				// Remove new meta fields
				foreach ($this->meta_mapping as $old_key => $new_key) {
					delete_post_meta($post->ID, $new_key);
				}

				// Remove migration markers
				delete_post_meta($post->ID, 'vimeify_migrated');
				delete_post_meta($post->ID, 'vimeify_migration_date');
				delete_post_meta($post->ID, 'vimeify_original_post_type');

				$reset_count++;

			} catch (\Exception $e) {
				$errors[] = array(
					'post_id' => $post->ID,
					'error' => $e->getMessage()
				);
			}
		}

		return array(
			'success' => true,
			'reset_count' => $reset_count,
			'errors' => $errors
		);
	}

	/**
	 * Migrate all videos (convenience method)
	 *
	 * @return array Complete migration results
	 */
	public function migrate_all() {
		$total_pages = $this->get_page_count();
		$total_migrated = 0;
		$all_errors = array();

		for ($page = 1; $page <= $total_pages; $page++) {
			$result = $this->migrate_page($page);
			$total_migrated += $result['migrated'];
			$all_errors = array_merge($all_errors, $result['errors']);
		}

		return array(
			'success' => true,
			'total_migrated' => $total_migrated,
			'total_pages_processed' => $total_pages,
			'errors' => $all_errors
		);
	}

	/**
	 * Set posts per page for migration
	 *
	 * @param int $posts_per_page Number of posts per page
	 */
	public function set_posts_per_page($posts_per_page) {
		$this->posts_per_page = max(1, intval($posts_per_page));
	}

	/**
	 * Get posts per page setting
	 *
	 * @return int Posts per page
	 */
	public function get_posts_per_page() {
		return $this->posts_per_page;
	}
}