<?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 Exception;
use WP_Error;

class SettingsMigration {

	private $legacy_settings;
	private $default_profile_id;

	public function __construct() {
		$this->legacy_settings    = get_option( 'dgv_settings', array() );
		$this->default_profile_id = get_option( 'vimeify_default_profile', 0 );
	}

	/**
	 * Main migration function
	 */
	public function migrate() {

		// Check if migration already completed
		if ( get_option( 'vimeify_settings_migration_complete', false ) ) {
			return new WP_Error( 'already_migrated', 'Migration has already been completed.' );
		}

		try {
			// Step 1: Create upload profiles
			$frontend_profile_id = $this->create_frontend_upload_profile();
			$backend_profile_id  = $this->create_backend_upload_profile();

			if ( is_wp_error( $frontend_profile_id ) || is_wp_error( $backend_profile_id ) ) {
				throw new Exception( 'Failed to create upload profiles' );
			}

			// Step 2: Migrate authentication settings
			$this->migrate_auth_settings();

			// Step 3: Migrate main settings
			$this->migrate_main_settings( $frontend_profile_id, $backend_profile_id );

			// Step 4: Mark migration as completed
			update_option( 'vimeify_settings_migration_complete', true );
			update_option( 'vimeify_settings_migration_complete_date', current_time( 'mysql' ) );

			return array(
				'success'             => true,
				'frontend_profile_id' => $frontend_profile_id,
				'backend_profile_id'  => $backend_profile_id,
				'message'             => 'Migration completed successfully'
			);

		} catch ( Exception $e ) {
			return new WP_Error( 'migration_failed', $e->getMessage() );
		}
	}

	/**
	 * Create frontend upload profile
	 */
	private function create_frontend_upload_profile() {
		$profile_data = array(
			'view_privacy'  => $this->get_legacy_setting( 'view_privacy_fe', 'anybody' ),
			'behavior'      => array(
				'store_in_library' => $this->get_legacy_setting( 'save_frontend_uploads', '1' ),
				'use_pull_method'  => $this->get_legacy_setting( 'use_pull_frontend', '0' )
			),
			'folder'        => $this->get_legacy_setting( 'upload_folder_fe', '' ),
			'category'      => '0', // New setting, defaults to 0
			'embed_domains' => $this->get_legacy_setting( 'embed_domains', '' ),
			'embed_preset'  => '0' // New setting, defaults to 0
		);

		return $this->create_upload_profile( 'Front-end uploads', $profile_data );
	}

	/**
	 * Create backend upload profile
	 */
	private function create_backend_upload_profile() {
		$profile_data = array(
			'view_privacy'  => $this->get_legacy_setting( 'view_privacy', 'anybody' ),
			'behavior'      => array(
				'store_in_library' => $this->get_legacy_setting( 'save_frontend_uploads', '1' ),
				'use_pull_method'  => $this->get_legacy_setting( 'use_pull_frontend', '0' )
			),
			'folder'        => $this->get_legacy_setting( 'upload_folder', '' ),
			'category'      => '0', // New setting, defaults to 0
			'embed_domains' => $this->get_legacy_setting( 'embed_domains', '' ),
			'embed_preset'  => '0' // New setting, defaults to 0
		);

		return $this->create_upload_profile( 'Back-end uploads', $profile_data );
	}

	/**
	 * Create upload profile post
	 */
	private function create_upload_profile( $title, $profile_data ) {
		$post_data = array(
			'post_title'  => $title,
			'post_type'   => 'vimeify-profile',
			'post_status' => 'publish',
			'meta_input'  => array(
				'vimeify_profile_settings' => $profile_data
			)
		);

		$post_id = wp_insert_post( $post_data );

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

		return $post_id;
	}

	/**
	 * Migrate authentication settings
	 */
	private function migrate_auth_settings() {
		$auth_settings = array(
			'access_token'    => $this->get_legacy_setting( 'access_token', '' ),
			'connection_type' => 'access_token'
		);

		update_option( 'vimeify_auth', $auth_settings );
	}

	/**
	 * Migrate main settings
	 */
	private function migrate_main_settings( $frontend_profile_id, $backend_profile_id ) {
		$new_settings = array(
			'admin'           => array(
				'upload_forms'      => array(
					'enable_view_privacy' => $this->get_legacy_setting( 'enable_privacy_option_media', '1' ),
					'enable_folders'      => '0' // New setting, defaults to 0
				),
				'gutenberg'         => array(
					'enable_view_privacy'      => $this->get_legacy_setting( 'enable_privacy_option_gt', '1' ),
					'enable_folders'           => '0', // New setting, defaults to 0
					'enable_account_search'    => $this->get_legacy_setting( 'gtb_enable_account_search', '1' ),
					'enable_local_search'      => $this->get_legacy_setting( 'mce_enable_local_search', '1' ),
					'show_author_uploads_only' => $this->get_legacy_setting( 'author_uploads_only', '1' )
				),
				'tinymce'           => array(
					'enable_view_privacy'      => $this->get_legacy_setting( 'enable_privacy_option_mce', '1' ),
					'enable_folders'           => '0', // New setting, defaults to 0
					'enable_account_search'    => $this->get_legacy_setting( 'mce_enable_account_search', '1' ),
					'enable_local_search'      => $this->get_legacy_setting( 'mce_enable_local_search', '1' ),
					'show_author_uploads_only' => $this->get_legacy_setting( 'author_uploads_only', '1' )
				),
				'video_management'  => array(
					'enable_embed_presets' => $this->get_legacy_setting( 'enable_embed_presets_management', '1' ),
					'enable_embed_privacy' => $this->get_legacy_setting( 'enable_embed_privacy_management', '1' ),
					'enable_folders'       => $this->get_legacy_setting( 'enable_folders_management', '1' )
				),
				'videos_list_table' => array(
					'enable_thumbnails'        => $this->get_legacy_setting( 'exp_thumbs_support', '1' ),
					'show_author_uploads_only' => $this->get_legacy_setting( 'author_uploads_only', '1' )
				)
			),
			'frontend'        => array(
				'behavior' => array(
					'enable_single_pages' => $this->get_legacy_setting( 'enable_single_pages', '1' )
				)
			),
			'upload_profiles' => array(
				'default'               => (string) $this->default_profile_id,
				'admin_gutenberg'       => (string) $backend_profile_id,
				'admin_tinymce'         => (string) $backend_profile_id,
				'admin_other'           => (string) $backend_profile_id,
				'frontend_wpforms'      => (string) $frontend_profile_id,
				'frontend_gravityforms' => (string) $frontend_profile_id
			)
		);

		update_option( 'vimeify_settings', $new_settings );
	}

	/**
	 * Get legacy setting value with fallback
	 */
	private function get_legacy_setting( $key, $default = '' ) {
		return isset( $this->legacy_settings[ $key ] ) ? $this->legacy_settings[ $key ] : $default;
	}

	/**
	 * Check if migration is needed
	 */
	public function is_migration_needed() {
		return ! empty( $this->legacy_settings ) && ! get_option( 'vimeify_settings_migration_complete', false );
	}

	/**
	 * Get migration status
	 */
	public function get_migration_status() {
		if ( get_option( 'vimeify_settings_migration_complete', false ) ) {
			return array(
				'status'  => 'completed',
				'date'    => get_option( 'vimeify_settings_migration_complete_date', '' ),
				'message' => 'Migration has been completed successfully.'
			);
		}

		if ( ! empty( $this->legacy_settings ) ) {
			return array(
				'status'  => 'needed',
				'message' => 'Legacy settings found. Migration is required.'
			);
		}

		return array(
			'status'  => 'not_needed',
			'message' => 'No legacy settings found. Migration is not needed.'
		);
	}

	/**
	 * Reset migration (for testing purposes)
	 */
	public function reset_migration() {
		delete_option( 'vimeify_settings_migration_complete' );
		delete_option( 'vimeify_settings_migration_complete_date' );

		// Optionally remove migrated settings
		delete_option( 'vimeify_settings' );
		delete_option( 'vimeify_auth' );

		// Remove created upload profiles
		$profiles = get_posts( array(
			'post_type'      => 'vimeify-profile',
			'meta_query'     => array(
				array(
					'key'     => 'migrated_from_legacy',
					'value'   => true,
					'compare' => '='
				)
			),
			'posts_per_page' => - 1
		) );

		foreach ( $profiles as $profile ) {
			wp_delete_post( $profile->ID, true );
		}

		return true;
	}
}