<?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 Vimeify\Core\Abstracts\Interfaces\SystemInterface;

/**
 * Forms Migration Class
 * Migrates GravityForms and WPForms data from legacy structure to new structure
 */
class FormsMigration {

	/**
	 * WordPress database instance
	 */
	private $wpdb;

	/**
	 * System interface instance
	 * @var SystemInterface
	 */
	private $system;

	/**
	 * Constructor
	 */
	public function __construct(SystemInterface $system) {
		global $wpdb;
		$this->wpdb = $wpdb;
		$this->system = $system;
	}

	/**
	 * Check if any form migration is needed
	 *
	 * @return array Status of both form types
	 */
	public function is_migration_needed() {
		return array(
			'gravityforms' => $this->is_gravityforms_migration_needed(),
			'wpforms' => $this->is_wpforms_migration_needed(),
			'overall' => $this->is_gravityforms_migration_needed() || $this->is_wpforms_migration_needed()
		);
	}

	/**
	 * Get complete migration status
	 *
	 * @return array Detailed migration status
	 */
	public function get_migration_status() {
		$gf_status = $this->get_gravityforms_status();
		$wpf_status = $this->get_wpforms_status();

		return array(
			'gravityforms' => $gf_status,
			'wpforms' => $wpf_status,
			'overall_completed' => $gf_status['completed'] && $wpf_status['completed'],
			'migration_needed' => $gf_status['migration_needed'] || $wpf_status['migration_needed']
		);
	}

	/**
	 * Migrate GravityForms data
	 *
	 * @return array Migration results
	 */
	public function migrate_gravityforms() {
		if (!$this->is_gravityforms_available()) {

			$this->system->logger()->log('GravityForms is not available for migration', 'migration');

			return array(
				'success' => false,
				'error' => 'GravityForms is not active or available'
			);
		}

		try {
			$results = array(
				'addon_feeds' => $this->migrate_gf_addon_feeds(),
				'form_meta' => $this->migrate_gf_form_meta(),
				'confirmations' => $this->migrate_gf_confirmations(),
				'notifications' => $this->migrate_gf_notifications()
			);

			$total_migrated = array_sum(array_column($results, 'migrated'));
			$errors = array();

			foreach ($results as $type => $result) {
				if (!$result['success']) {
					$errors[] = $type . ': ' . $result['error'];
				}
			}

			if (!empty($errors)) {
				return array(
					'success' => false,
					'error' => implode(', ', $errors),
					'results' => $results
				);
			}

			return array(
				'success' => true,
				'total_migrated' => $total_migrated,
				'results' => $results
			);

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

	/**
	 * Migrate WPForms data
	 *
	 * @return array Migration results
	 */
	public function migrate_wpforms() {
		if (!$this->is_wpforms_available()) {
			return array(
				'success' => false,
				'error' => 'WPForms is not active or available'
			);
		}

		try {
			$results = array(
				'entries' => $this->migrate_wpforms_entries(),
				'forms' => $this->migrate_wpforms_forms()
			);

			$total_migrated = array_sum(array_column($results, 'migrated'));
			$errors = array();

			foreach ($results as $type => $result) {
				if (!$result['success']) {
					$errors[] = $type . ': ' . $result['error'];
				}
			}

			if (!empty($errors)) {
				return array(
					'success' => false,
					'error' => implode(', ', $errors),
					'results' => $results
				);
			}

			return array(
				'success' => true,
				'total_migrated' => $total_migrated,
				'results' => $results
			);

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

	/**
	 * Migrate GravityForms addon feeds using MySQL REPLACE
	 *
	 * @return array Migration results
	 */
	private function migrate_gf_addon_feeds() {
		$table = $this->wpdb->prefix . 'gf_addon_feed';

		// Check if table exists
		if ($this->wpdb->get_var("SHOW TABLES LIKE '$table'") !== $table) {
			return array('success' => true, 'migrated' => 0, 'message' => 'Table does not exist');
		}

		// Get count of records that will be affected
		$count = $this->wpdb->get_var("SELECT COUNT(*) FROM $table WHERE meta LIKE '%dgv_%'");

		if ($count == 0) {
			return array('success' => true, 'migrated' => 0, 'message' => 'No records to migrate');
		}

		// Use MySQL REPLACE to update all dgv_ references
		$result = $this->wpdb->query("
            UPDATE $table 
            SET meta = REPLACE(meta, 'dgv_', 'vimeify_') 
            WHERE meta LIKE '%dgv_%'
        ");

		return array('success' => true, 'migrated' => $result !== false ? $count : 0);
	}

	/**
	 * Migrate GravityForms form meta display_meta using MySQL REPLACE
	 *
	 * @return array Migration results
	 */
	private function migrate_gf_form_meta() {
		$table = $this->wpdb->prefix . 'gf_form_meta';

		if ($this->wpdb->get_var("SHOW TABLES LIKE '$table'") !== $table) {
			$this->system->logger()->log('No GravityForms form meta table present', 'migration');

			return array('success' => true, 'migrated' => 0, 'message' => 'Table does not exist');
		}

		// Get count of records that will be affected
		$count = $this->wpdb->get_var("SELECT COUNT(*) FROM $table WHERE display_meta LIKE '%dgv_%'");

		if ($count == 0) {
			$this->system->logger()->log('No GravityForms form meta to migrate', 'migration');
			return array('success' => true, 'migrated' => 0, 'message' => 'No records to migrate');
		}

		// Replace field types first (order matters - specific before general)
		$queries = [
			// Replace dgv_vimeo_upload → vimeify_upload, and style:classic → vimeifyType:dropzone (classic is now dropzone)
			"
    UPDATE $table
    SET display_meta = REPLACE(
        REPLACE(display_meta, '\"type\":\"dgv_vimeo_upload\"', '\"type\":\"vimeify_upload\"'),
        '\"style\":\"classic\"',
        '\"vimeifyType\":\"dropzone\"'
    )
    WHERE display_meta LIKE '%\"type\":\"dgv_vimeo_upload\"%' OR display_meta LIKE '%\"style\":\"classic\"%'
    ",

			// Replace dgv_vimeo_upload_modern → vimeify_upload, and style:modern → vimeifyType:dropzone
			"
    UPDATE $table
    SET display_meta = REPLACE(
        REPLACE(display_meta, '\"type\":\"dgv_vimeo_upload_modern\"', '\"type\":\"vimeify_upload\"'),
        '\"style\":\"modern\"',
        '\"vimeifyType\":\"dropzone\"'
    )
    WHERE display_meta LIKE '%\"type\":\"dgv_vimeo_upload_modern\"%' OR display_meta LIKE '%\"style\":\"modern\"%'
    ",

			// Migrate existing vimeifyType:modern → vimeifyType:dropzone
			"
    UPDATE $table
    SET display_meta = REPLACE(display_meta, '\"vimeifyType\":\"modern\"', '\"vimeifyType\":\"dropzone\"')
    WHERE display_meta LIKE '%\"vimeifyType\":\"modern\"%'
    ",

			// Migrate existing vimeifyType:classic → vimeifyType:dropzone
			"
    UPDATE $table
    SET display_meta = REPLACE(display_meta, '\"vimeifyType\":\"classic\"', '\"vimeifyType\":\"dropzone\"')
    WHERE display_meta LIKE '%\"vimeifyType\":\"classic\"%'
    "
		];

		foreach ($queries as $query) {
			$this->system->logger()->log('Executing query: ' . $query, 'migration');
			$result = $this->wpdb->query($query);
			$this->system->logger()->log('Query results: ' . $result, 'migration');

		}

		return array('success' => true, 'migrated' => $count);
	}

	/**
	 * Migrate GravityForms confirmations using MySQL REPLACE
	 *
	 * @return array Migration results
	 */
	private function migrate_gf_confirmations() {
		$table = $this->wpdb->prefix . 'gf_form_meta';

		if ($this->wpdb->get_var("SHOW TABLES LIKE '$table'") !== $table) {
			return array('success' => true, 'migrated' => 0, 'message' => 'Table does not exist');
		}

		// Get count of records that will be affected
		$count = $this->wpdb->get_var("SELECT COUNT(*) FROM $table WHERE confirmations LIKE '%dgv_%'");

		if ($count == 0) {
			return array('success' => true, 'migrated' => 0, 'message' => 'No records to migrate');
		}

		// Use MySQL REPLACE to update all dgv_ references in confirmations
		$result = $this->wpdb->query("
            UPDATE $table 
            SET confirmations = REPLACE(confirmations, 'dgv_', 'vimeify_') 
            WHERE confirmations LIKE '%dgv_%'
        ");

		return array('success' => true, 'migrated' => $result !== false ? $count : 0);
	}

	/**
	 * Migrate GravityForms notifications using MySQL REPLACE
	 *
	 * @return array Migration results
	 */
	private function migrate_gf_notifications() {
		$table = $this->wpdb->prefix . 'gf_form_meta';

		if ($this->wpdb->get_var("SHOW TABLES LIKE '$table'") !== $table) {
			return array('success' => true, 'migrated' => 0, 'message' => 'Table does not exist');
		}

		// Get count of records that will be affected
		$count = $this->wpdb->get_var("SELECT COUNT(*) FROM $table WHERE notifications LIKE '%dgv_%'");

		if ($count == 0) {
			return array('success' => true, 'migrated' => 0, 'message' => 'No records to migrate');
		}

		// Use MySQL REPLACE to update all dgv_ references in notifications
		$result = $this->wpdb->query("
            UPDATE $table 
            SET notifications = REPLACE(notifications, 'dgv_', 'vimeify_') 
            WHERE notifications LIKE '%dgv_%'
        ");

		return array('success' => true, 'migrated' => $result !== false ? $count : 0);
	}

	/**
	 * Migrate WPForms entries using MySQL REPLACE
	 *
	 * @return array Migration results
	 */
	private function migrate_wpforms_entries() {
		$table = $this->wpdb->prefix . 'wpforms_entries';

		if ($this->wpdb->get_var("SHOW TABLES LIKE '$table'") !== $table) {
			return array('success' => true, 'migrated' => 0, 'message' => 'Table does not exist');
		}

		// Get count of records that will be affected
		$count = $this->wpdb->get_var("SELECT COUNT(*) FROM $table WHERE fields LIKE '%wp-vimeo-upload%'");

		if ($count == 0) {
			return array('success' => true, 'migrated' => 0, 'message' => 'No records to migrate');
		}

		// Use MySQL REPLACE to update wp-vimeo-upload to vimeify-upload
		$result = $this->wpdb->query("
            UPDATE $table 
            SET fields = REPLACE(fields, 'wp-vimeo-upload', 'vimeify-upload') 
            WHERE fields LIKE '%wp-vimeo-upload%'
        ");

		return array('success' => true, 'migrated' => $result !== false ? $count : 0);
	}

	/**
	 * Migrate WPForms form content using MySQL REPLACE
	 *
	 * @return array Migration results
	 */
	private function migrate_wpforms_forms() {
		// Get count of records that will be affected for field type migration
		$count = $this->wpdb->get_var("
            SELECT COUNT(*) FROM {$this->wpdb->posts}
            WHERE post_type = 'wpforms' AND post_content LIKE '%wp-vimeo-upload%'
        ");

		if ($count > 0) {
			// Use MySQL REPLACE to update wp-vimeo-upload to vimeify-upload in WPForms
			$this->wpdb->query("
				UPDATE {$this->wpdb->posts}
				SET post_content = REPLACE(post_content, 'wp-vimeo-upload', 'vimeify-upload')
				WHERE post_type = 'wpforms' AND post_content LIKE '%wp-vimeo-upload%'
			");
		}

		// Migrate WPForms theme values: modern → dropzone, modern_popup → popup
		$theme_count = $this->migrate_wpforms_theme_values();

		return array('success' => true, 'migrated' => $count + $theme_count);
	}

	/**
	 * Migrate WPForms theme values from old to new naming
	 *
	 * @return int Number of records migrated
	 */
	private function migrate_wpforms_theme_values() {
		$migrated = 0;

		// Migrate theme:modern → theme:dropzone
		$count_modern = $this->wpdb->get_var("
			SELECT COUNT(*) FROM {$this->wpdb->posts}
			WHERE post_type = 'wpforms' AND post_content LIKE '%\"theme\":\"modern\"%'
		");

		if ($count_modern > 0) {
			$this->wpdb->query("
				UPDATE {$this->wpdb->posts}
				SET post_content = REPLACE(post_content, '\"theme\":\"modern\"', '\"theme\":\"dropzone\"')
				WHERE post_type = 'wpforms' AND post_content LIKE '%\"theme\":\"modern\"%'
			");
			$migrated += $count_modern;
		}

		// Migrate theme:modern_popup → theme:popup
		$count_popup = $this->wpdb->get_var("
			SELECT COUNT(*) FROM {$this->wpdb->posts}
			WHERE post_type = 'wpforms' AND post_content LIKE '%\"theme\":\"modern_popup\"%'
		");

		if ($count_popup > 0) {
			$this->wpdb->query("
				UPDATE {$this->wpdb->posts}
				SET post_content = REPLACE(post_content, '\"theme\":\"modern_popup\"', '\"theme\":\"popup\"')
				WHERE post_type = 'wpforms' AND post_content LIKE '%\"theme\":\"modern_popup\"%'
			");
			$migrated += $count_popup;
		}

		// Migrate theme:classic → theme:dropzone
		$count_classic = $this->wpdb->get_var("
			SELECT COUNT(*) FROM {$this->wpdb->posts}
			WHERE post_type = 'wpforms' AND post_content LIKE '%\"theme\":\"classic\"%'
		");

		if ($count_classic > 0) {
			$this->wpdb->query("
				UPDATE {$this->wpdb->posts}
				SET post_content = REPLACE(post_content, '\"theme\":\"classic\"', '\"theme\":\"dropzone\"')
				WHERE post_type = 'wpforms' AND post_content LIKE '%\"theme\":\"classic\"%'
			");
			$migrated += $count_classic;
		}

		return $migrated;
	}

	/**
	 * Check if GravityForms migration is needed
	 *
	 * @return bool
	 */
	private function is_gravityforms_migration_needed() {
		if (!$this->is_gravityforms_available()) {
			return false;
		}

		// Check addon feeds
		$table = $this->wpdb->prefix . 'gf_addon_feed';
		if ($this->wpdb->get_var("SHOW TABLES LIKE '$table'") === $table) {
			$count = $this->wpdb->get_var("SELECT COUNT(*) FROM $table WHERE meta LIKE '%dgv_%'");
			if ($count > 0) return true;
		}

		// Check form meta for old prefixes
		$table = $this->wpdb->prefix . 'gf_form_meta';
		if ($this->wpdb->get_var("SHOW TABLES LIKE '$table'") === $table) {
			$count = $this->wpdb->get_var("
                SELECT COUNT(*) FROM $table
                WHERE display_meta LIKE '%dgv_%'
                OR confirmations LIKE '%dgv_%'
                OR notifications LIKE '%dgv_%'
            ");
			if ($count > 0) return true;

			// Check for old vimeifyType:modern values that need migration to dropzone
			$count = $this->wpdb->get_var("
                SELECT COUNT(*) FROM $table
                WHERE display_meta LIKE '%\"vimeifyType\":\"modern\"%'
            ");
			if ($count > 0) return true;

			// Check for old vimeifyType:classic values that need migration to dropzone
			$count = $this->wpdb->get_var("
                SELECT COUNT(*) FROM $table
                WHERE display_meta LIKE '%\"vimeifyType\":\"classic\"%'
            ");
			if ($count > 0) return true;
		}

		return false;
	}

	/**
	 * Check if WPForms migration is needed
	 *
	 * @return bool
	 */
	private function is_wpforms_migration_needed() {
		if (!$this->is_wpforms_available()) {
			return false;
		}

		// Check entries
		$table = $this->wpdb->prefix . 'wpforms_entries';
		if ($this->wpdb->get_var("SHOW TABLES LIKE '$table'") === $table) {
			$count = $this->wpdb->get_var("SELECT COUNT(*) FROM $table WHERE fields LIKE '%wp-vimeo-upload%'");
			if ($count > 0) return true;
		}

		// Check forms for old field type
		$count = $this->wpdb->get_var("
            SELECT COUNT(*) FROM {$this->wpdb->posts}
            WHERE post_type = 'wpforms' AND post_content LIKE '%wp-vimeo-upload%'
        ");
		if ($count > 0) return true;

		// Check forms for old theme values (modern → dropzone, modern_popup → popup, classic → dropzone)
		$count = $this->wpdb->get_var("
            SELECT COUNT(*) FROM {$this->wpdb->posts}
            WHERE post_type = 'wpforms' AND (
                post_content LIKE '%\"theme\":\"modern\"%'
                OR post_content LIKE '%\"theme\":\"modern_popup\"%'
                OR post_content LIKE '%\"theme\":\"classic\"%'
            )
        ");
		if ($count > 0) return true;

		return false;
	}

	/**
	 * Get GravityForms migration status
	 *
	 * @return array
	 */
	private function get_gravityforms_status() {
		$available = $this->is_gravityforms_available();
		$migration_needed = $this->is_gravityforms_migration_needed();
		$completed = get_option('vimeify_gravityforms_migration_completed', false);

		return array(
			'available' => $available,
			'migration_needed' => $migration_needed,
			'completed' => $completed,
			'status' => !$available ? 'not_available' : ($completed ? 'completed' : ($migration_needed ? 'needed' : 'not_needed'))
		);
	}

	/**
	 * Get WPForms migration status
	 *
	 * @return array
	 */
	private function get_wpforms_status() {
		$available = $this->is_wpforms_available();
		$migration_needed = $this->is_wpforms_migration_needed();
		$completed = get_option('vimeify_wpforms_migration_completed', false);

		return array(
			'available' => $available,
			'migration_needed' => $migration_needed,
			'completed' => $completed,
			'status' => !$available ? 'not_available' : ($completed ? 'completed' : ($migration_needed ? 'needed' : 'not_needed'))
		);
	}

	/**
	 * Check if GravityForms is available
	 *
	 * @return bool
	 */
	private function is_gravityforms_available() {
		return class_exists('GFForms');
	}

	/**
	 * Check if WPForms is available
	 *
	 * @return bool
	 */
	private function is_wpforms_available() {
		return class_exists('WPForms');
	}

	/**
	 * Reset forms migration (for testing)
	 *
	 * @return array
	 */
	public function reset_migration() {
		delete_option('vimeify_forms_migration_completed');
		delete_option('vimeify_forms_migration_date');
		delete_option('vimeify_gravityforms_migration_completed');
		delete_option('vimeify_wpforms_migration_completed');

		return array(
			'success' => true,
			'message' => 'Forms migration has been reset'
		);
	}
}