<?php

namespace Brandy\Database;

use Brandy\Traits\SingletonTrait;

class Migration {
	use SingletonTrait;

	protected function __construct() {
		add_action( 'after_setup_theme', array( $this, 'do_theme_option_migration' ), 1 );
	}

	/**
	 * Migrate settings from the old version
	 * In the old version, we use theme_mod to store settings
	 * In the new version, we use option to store settings
	 */
	public function do_theme_option_migration() {
		$this->migrate_to_1_4_4();
		$this->fix_incorrect_logo_title();
	}

	private function migrate_to_1_4_4() {

		$migrated_versions = get_option( 'brandy_successful_migrations', array() );

		if ( empty( $migrated_versions ) || ! is_array( $migrated_versions ) ) {
			$migrated_versions = array();
		}

		if ( in_array( '1_4_4', $migrated_versions, true ) ) {
			return;
		}

		$new_header_data = get_option( 'brandy_header_settings', null );
		if ( empty( $new_header_data ) ) {
			$legacy_header_data = get_theme_mod( 'header_settings' );
			if ( ! empty( $legacy_header_data['current_template_id'] ) ) {
				$new_header_data = $legacy_header_data;
			}
			set_theme_mod( 'header_settings', time() );
		}

		$new_header_data = $this->migrate_template_data_1_4_4( $new_header_data, 'header' );
		brandy_save_header_settings( $new_header_data );

		$new_footer_data = get_option( 'brandy_footer_settings', null );
		if ( empty( $new_footer_data ) ) {
			$legacy_footer_data = get_theme_mod( 'footer_settings' );
			if ( ! empty( $legacy_footer_data['current_template_id'] ) ) {
				$new_footer_data = $legacy_footer_data;
			}
			set_theme_mod( 'footer_settings', time() );
		}

		$new_footer_data = $this->migrate_template_data_1_4_4( $new_footer_data, 'footer' );
		brandy_save_footer_settings( $new_footer_data );

		update_option( 'brandy_successful_migrations', array_unique( array_merge( $migrated_versions, array( '1_4_4' ) ) ) );
	}

	private function migrate_template_data_1_4_4( $template_data, $builder = 'header' ) {
		$deprecated_elements = array(
			'socials_2',
		);

		$need_update_elements = array(
			'socials_1',
		);

		$default_content_alignment = array(
			'desktop' => 'left',
			'tablet'  => null,
			'mobile'  => null,
		);

		$special_update_elements = array(
			'socials_1' => array(
				'builders' => array( 'header', 'footer' ),
			),
			'html_1'    => array(
				'settings' => array(
					'content_alignment' => $default_content_alignment,
				),
			),
			'html_2'    => array(
				'settings' => array(
					'content_alignment' => $default_content_alignment,
				),
			),
			'html_3'    => array(
				'settings' => array(
					'content_alignment' => $default_content_alignment,
				),
			),
			'html_4'    => array(
				'settings' => array(
					'content_alignment' => $default_content_alignment,
				),
			),
		);

		$all_niches        = \Brandy\Niches\NicheLoader::get_instance()->get_niches();
		$default_templates = array();

		foreach ( $all_niches as $niche ) {
			foreach ( $niche['template_data'][ $builder . 's' ] ?? array() as $template_file ) {
				if ( ! file_exists( $template_file ) ) {
					continue;
				}

				$t_data = json_decode( file_get_contents( $template_file ), true ); //phpcs:ignore
				$default_templates[] = $t_data;
			}
		}

		if ( ! empty( $template_data['templates'] ) ) {
			foreach ( $template_data['templates'] as &$template ) {

				$found_default_template = $default_templates[0];
				foreach ( $default_templates as $default_template ) {
					if ( $template['id'] === $default_template['id'] ) {
						$found_default_template = $default_template;
						break;
					}
				}

				if ( ! $found_default_template ) {
					continue;
				}

				foreach ( array_keys( $template['elements'] ) as $element_id ) {

					if ( in_array( $element_id, $need_update_elements, true ) && isset( $found_default_template['elements'][ $element_id ] ) && isset( $template['elements'][ $element_id ] ) ) {
						$template['elements'][ $element_id ] = wp_parse_args( $found_default_template['elements'][ $element_id ], $template['elements'][ $element_id ] );
					}

					if ( in_array( $element_id, $deprecated_elements, true ) ) {
						unset( $template['elements'][ $element_id ] );
					}

					if ( isset( $special_update_elements[ $element_id ] ) ) {
						$template['elements'][ $element_id ] = wp_parse_args( $special_update_elements[ $element_id ], $template['elements'][ $element_id ] );
					}
				}
				foreach ( $template['placements'] as $device => &$placements ) {
					foreach ( $placements as $row => &$columns ) {
						if ( 'toggle' === $row ) {
							$columns = array_filter(
								$columns,
								function( $element_id ) use ( $deprecated_elements ) {
									return ! in_array( $element_id, $deprecated_elements, true );
								}
							);
							continue;
						}
						foreach ( array_keys( $columns ) as $col_index ) {
							$columns[ $col_index ] = array_filter(
								$columns[ $col_index ],
								function( $element_id ) use ( $deprecated_elements ) {
									return ! in_array( $element_id, $deprecated_elements, true );
								}
							);
						}
					}
				}
			}
		}

		return $template_data;
	}

	private function fix_incorrect_logo_title() {
		// TODO: Open version check after Brandy sites update new version
		// $migrated_versions = get_option( 'brandy_successful_migrations', array() );

		// if ( empty( $migrated_versions ) || ! is_array( $migrated_versions ) ) {
		// 	$migrated_versions = array();
		// }

		// if ( in_array( '1_5_4', $migrated_versions, true ) ) {
		// 	return;
		// }

		$new_header_data = get_option( 'brandy_header_settings', null );
		$has_incorrect_header_logo = false;
		$has_incorrect_footer_logo = false;
		$new_footer_data = get_option( 'brandy_footer_settings', null );

		if ( ! empty( $new_header_data ) ) {
			foreach ( $new_header_data['templates'] as &$template ) {
				if ( ! empty( $template['elements']['logo_1']['settings']['title']['text'] ) && 'Trace development' === $template['elements']['logo_1']['settings']['title']['text'] ) {
					$template['elements']['logo_1']['settings']['title']['text'] = '';
					$has_incorrect_header_logo = true;
				}
				if ( ! empty( $template['elements']['logo_1']['settings']['tagline']['text'] ) && 'taglines' === $template['elements']['logo_1']['settings']['tagline']['text'] ) {
					$template['elements']['logo_1']['settings']['tagline']['text'] = '';
					$has_incorrect_header_logo = true;
				}
			}
			if ( $has_incorrect_header_logo ) {
				update_option( 'brandy_header_settings', $new_header_data );
			}
		}

		if ( ! empty( $new_footer_data ) ) {
			foreach ( $new_footer_data['templates'] as &$template ) {
				if ( ! empty( $template['elements']['logo_2']['settings']['title']['text'] ) && 'Trace development' === $template['elements']['logo_2']['settings']['title']['text'] ) {
					$template['elements']['logo_2']['settings']['title']['text'] = '';
					$has_incorrect_footer_logo = true;
				}
				if ( ! empty( $template['elements']['logo_2']['settings']['tagline']['text'] ) && 'taglines' === $template['elements']['logo_2']['settings']['tagline']['text'] ) {
					$template['elements']['logo_2']['settings']['tagline']['text'] = '';
					$has_incorrect_footer_logo = true;
				}
			}
			if ( $has_incorrect_footer_logo ) {
				update_option( 'brandy_footer_settings', $new_footer_data );
			}
		}


		// update_option( 'brandy_successful_migrations', array_unique( array_merge( $migrated_versions, array( '1_5_4' ) ) ) );
	}

}

Migration::get_instance();
