<?php

namespace EDPW\Core;

use EDPW\Core\Helpers\EmailTemplate;
use EDPW\Core\Helpers\Plugin;
use EDPW\Core\Models\CustomBlocks;
use EDPW\Core\Models\EmailTemplates;

defined( 'ABSPATH' ) || exit;

class Setup {
	/**
	 * Init setup.
	 */
	public static function init() {
		register_activation_hook( EDPW_PLUGIN_FILE, [ __CLASS__, 'activate' ] );
		register_deactivation_hook( EDPW_PLUGIN_FILE, [ __CLASS__, 'deactivate' ] );
		register_uninstall_hook( EDPW_PLUGIN_FILE, [ __CLASS__, 'uninstall' ] );
		add_filter( 'plugin_row_meta', [ __CLASS__, 'getPluginRowMeta' ], 10, 2 );
		add_filter( 'plugin_action_links_' . plugin_basename( EDPW_PLUGIN_FILE ), [
			__CLASS__,
			'getPluginActionLinks'
		] );
		add_action( 'wpmu_new_blog', [ __CLASS__, 'onCreateBlog' ], 10, 6 );
		add_filter( 'wpmu_drop_tables', [ __CLASS__, 'onDeleteBlog' ] );
		add_action( 'plugins_loaded', [ __CLASS__, 'maybeRunMigration' ] );
		add_action( 'upgrader_process_complete', [ __CLASS__, 'maybeRunMigration' ] );
	}

	/**
	 * Run plugin activation scripts.
	 */
	public static function activate() {
		Plugin::checkDependencies( true );
		self::maybeRunMigration();
	}

	/**
	 * Run plugin activation scripts.
	 */
	public static function deactivate() {
		// silence is golden
	}

	/**
	 * Run plugin activation scripts.
	 */
	public static function uninstall() {
		// silence is golden
	}

	/**
	 * Retrieves the plugin row meta to be displayed on the WordPress plugin page.
	 *
	 * @param array $links The existing plugin row meta links.
	 * @param string $file The path to the plugin file.
	 *
	 * @return array
	 */
	public static function getPluginRowMeta( $links, $file ) {
		if ( $file != plugin_basename( EDPW_PLUGIN_FILE ) ) {
			return $links;
		}
		$row_meta = [
			'docs'    => '<a href="' . esc_url( 'https://docs.sparkeditor.com/' ) . '" aria-label="' . esc_attr__( 'Documentation', 'email-editor-plus' ) . '">' . esc_html__( 'Docs', 'email-editor-plus' ) . '</a>',
			'support' => '<a href="' . esc_url( 'https://sparkeditor.com/support/?utm_campaign=sparkeditor-link&utm_medium=pro_url&utm_source=support' ) . '" aria-label="' . esc_attr__( 'Support', 'email-editor-plus' ) . '">' . esc_html__( 'Support', 'email-editor-plus' ) . '</a>',
		];

		return array_merge( $links, $row_meta );
	}

	public static function getPluginActionLinks( $links ) {
		$action_links = [
			'templates' => '<a href="' . admin_url( 'admin.php?page=' . EDPW_PLUGIN_SLUG . '#/templates' ) . '">' . __( 'Templates', 'email-editor-plus' ) . '</a>',
			'settings'  => '<a href="' . admin_url( 'admin.php?page=' . EDPW_PLUGIN_SLUG . '#/settings' ) . '">' . __( 'Settings', 'email-editor-plus' ) . '</a>',
			'add-ons'   => '<a href="' . admin_url( 'admin.php?page=' . EDPW_PLUGIN_SLUG . '#/add-ons' ) . '">' . __( 'Add-ons', 'email-editor-plus' ) . '</a>'
		];
		if ( ! EmailTemplate::isPro() ) {
			$action_links['pro'] = '<a style="color: #4f47eb; font-weight: bold;" target="_blank" href="https://sparkeditor.com/pricing/?utm_campaign=sparkeditor-link&utm_medium=pro_url&utm_source=pricing">' . __( 'Get Pro', 'email-editor-plus' ) . '</a>';
		}
		$action_links = apply_filters( 'edpw_point_action_links', $action_links );

		return array_merge( $action_links, $links );
	}

	/**
	 * Maybe run database migration.
	 */
	public static function maybeRunMigration() {
		$db_version = get_option( 'edpw_version', '0.0.1' );
		if ( version_compare( $db_version, EDPW_PLUGIN_VERSION, '<' ) ) {
			self::runMigration();
			$is_already_migrated = get_option( 'edpw_migration_status', 'no' );
			if ( $is_already_migrated == 'no' && version_compare( $db_version, '1.0.1', '<' ) && self::isOldTableExists() ) {
				//1. Migrate Settings
				self::migrateSettings();
				//2. Migrate Tables
				self::migrateTemplates();
				self::migrateCustomBlocks();
				update_option( 'edpw_migration_status', 'yes' );
			}
			update_option( 'edpw_version', EDPW_PLUGIN_VERSION );
		}
	}

	/**
	 * Run database migration.
	 */
	private static function runMigration() {
		$models = [
			new EmailTemplates(),
			new CustomBlocks()
		];
		foreach ( $models as $model ) {
			if ( is_a( $model, '\EDPW\Core\Models\BaseModel' ) ) {
				$model->create();
			}
		}
	}

	/**
	 * Is old table available?
	 *
	 * @return bool
	 */
	public static function isOldTableExists() {
		global $wpdb;
		$tables = [
			$wpdb->prefix . 'eca_templates',
			$wpdb->prefix . 'eca_custom_blocks',
		];
		foreach ( $tables as $table ) {
			if ( $wpdb->get_var( "SHOW TABLES LIKE '{$table}'" ) ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Migrate settings.
	 *
	 * @return void
	 */
	protected static function migrateSettings() {
		$settings         = get_option( 'eca_settings' );
		$data             = [];
		$default_settings = EmailTemplate::getDefaultSettings();
		foreach ( $default_settings as $key => $value ) {
			$data[ $key ] = $settings[ $key ] ?? $value;
		}
		update_option( 'edpw_settings', $data, true );
	}

	/**
	 * Migrate templates.
	 *
	 * @return void
	 */
	protected static function migrateTemplates() {
		global $wpdb;
		$templates = $wpdb->get_results( "SELECT * FROM `{$wpdb->prefix}eca_templates`", ARRAY_A );
		if ( empty( $templates ) ) {
			return;
		}
		$default_data = [
			'type'              => null,
			'is_active'         => 0,
			'language'          => null,
			'styles'            => null,
			'elements'          => null,
			'css'               => null,
			'html'              => null,
			'mjml'              => null,
			'extra'             => null,
			'global_styles'     => null,
			'mj_component_data' => null
		];
		try {
			foreach ( $templates as $template ) {
				$insert_data = [];
				foreach ( $default_data as $key => $value ) {
					$insert_data[ $key ] = ! empty( $template[ $key ] ) ? $template[ $key ] : $value;
				}
				if ( ! empty( $insert_data['type'] ) && ! empty( $insert_data['language'] ) ) {
					$new_template = EmailTemplates::getTemplateBasedLang( $insert_data['language'], $insert_data['type'] );
					if ( ! empty( $new_template ) ) {
						continue;
					}
					EmailTemplates::saveNewTemplate( $insert_data );
				}
			}
		} catch ( \Exception $e ) {

		}
	}

	/**
	 * Migrate Custom blocks.
	 *
	 * @return void
	 */
	protected static function migrateCustomBlocks() {
		global $wpdb;
		$custom_blocks = $wpdb->get_results( "SELECT * FROM `{$wpdb->prefix}eca_custom_blocks`", ARRAY_A );
		if ( empty( $custom_blocks ) ) {
			return;
		}
		try {
			$default_data = [
				'title'         => null,
				'title_content' => null,
				'block_id'      => null,
				'content'       => null,
				'category'      => null,
			];
			foreach ( $custom_blocks as $block ) {
				$insert_data = [];
				foreach ( $default_data as $key => $value ) {
					$insert_data[ $key ] = ! empty( $block[ $key ] ) ? $block[ $key ] : $value;
				}
				CustomBlocks::saveCustomBlock( $insert_data );
			}
		} catch ( \Exception $e ) {

		}
	}

	/**
	 * Run blog migration.
	 *
	 * @param $blog_id
	 * @param $user_id
	 * @param $domain
	 * @param $path
	 * @param $site_id
	 * @param $meta
	 *
	 * @return void
	 */
	public static function onCreateBlog( $blog_id, $user_id, $domain, $path, $site_id, $meta ) {
		if ( is_plugin_active_for_network( EDPW_PLUGIN_FILE ) ) {
			switch_to_blog( $blog_id );
			self::runMigration();
			restore_current_blog();
		}
	}

	/**
	 * Drop table list.
	 *
	 * @param array $tables Drop tables.
	 *
	 * @return array
	 */
	public static function onDeleteBlog( array $tables ): array {
		$templates_model = new EmailTemplates();
		$tables[]        = $templates_model->getTableName();
		$tables[]        = $templates_model->getTableName();

		return $tables;
	}
}