<?php
/**
 * Export Theme Json
 *
 * @author Jegstudio
 * @since 1.0.0
 * @package gutenverse-themes-builder
 */

namespace Gutenverse_Themes_Builder\Export;

use Gutenverse_Themes_Builder\Database\Database;
use WP_Theme_JSON_Resolver;

/**
 * Class Export Theme Json
 *
 * @package gutenverse-themes-builder
 */
class Export_Theme_Json {

	/**
	 * Create Theme Json File
	 *
	 * @param object $system .
	 * @param array  $data .
	 * @param bool   $include_global_import .
	 */
	public static function create_theme_json( $system, $data, $include_global_import ) {
		$theme       = wp_get_theme();
		$placeholder = $system->get_contents( GUTENVERSE_THEMES_BUILDER_DIR . '/includes/data/theme-json.txt' );
		/**
		 * Generate Color Settings.
		 */
		$colors     = Misc::get_color_settings();
		$fix_colors = array();

		// change colors slug into lowercase to prevent errors.
		$idx = 0;
		foreach ( $colors as $color ) {
			$slug = 'theme-' . $idx;
			if ( $include_global_import ) {
				$slug = gutenverse_themes_builder_to_kebab_case( $color->slug );
			}
			$fix_colors[] = array(
				'slug'  => $slug,
				'name'  => $color->name,
				'color' => $color->color,
			);
			++$idx;
		}

		$theme_id = get_option( 'gtb_active_theme_id' );

		$placeholder = str_replace( '{{theme_color_settings}}', wp_json_encode( $fix_colors ), $placeholder );

		/**
		 * Generate Font Settings.
		 */
		$data_wp_global = WP_Theme_JSON_Resolver::get_user_data_from_wp_global_styles( $theme );
		$data_wp_global = json_decode( $data_wp_global['post_content'] );
		$fonts          = array();
		if ( isset( $data_wp_global->settings->typography->fontFamilies ) ) {
			$fonts = $data_wp_global->settings->typography->fontFamilies->custom;
			foreach ( $fonts as &$font ) {
				$font_faces = $font->fontFace;
				$font_slug  = $font->slug;
				if ( isset( $font->preview ) ) {
					unset( $font->preview );
				}
				foreach ( $font_faces as &$f_face ) {
					$font_src   = $f_face->src;
					$target_dir = gutenverse_themes_builder_theme_built_path() . '/assets/fonts/' . $font_slug . '/';
					if ( ! file_exists( $target_dir ) ) {
						wp_mkdir_p( $target_dir );
					}
					$filename = Misc::download_font( $font_src, $target_dir );

					$new_src     = 'file:./assets/fonts/' . $font_slug . '/' . $filename;
					$f_face->src = $new_src;
					if ( isset( $f_face->preview ) ) {
						unset( $f_face->preview );
					}
				}
			}
		}

		$fonts_string = wp_json_encode( $fonts );
		$placeholder  = str_replace( '{{font_families}}', $fonts_string ? $fonts_string : '[]', $placeholder );

		/**
		 * Get font sizes
		 */
		$fonts_sizes    = $data_wp_global?->settings?->typography?->fontSizes;
		$sizes          = array();
		$arr_size_slugs = array();
		if ( $fonts_sizes && $fonts_sizes->theme ) {
			foreach ( $fonts_sizes->theme as $value ) {
				$size = $value;
				if ( isset( $size->name ) ) {
					$new_slug                      = gutenverse_themes_builder_to_kebab_case( strtolower( $size->name ) );
					$new_slug                      = gutenverse_themes_builder_to_kebab_case( strtolower( $size->name ) );
					$arr_size_slugs[ $size->slug ] = $new_slug;
					$size->slug                    = $new_slug;
				} else {
					$name       = strtoupper( implode( ' ', explode( '-', $size->slug ) ) );
					$size->name = $name;
				}
				$sizes[] = $size;
			}
		}

		if ( $fonts_sizes && $fonts_sizes->custom ) {
			foreach ( $fonts_sizes->custom as $value ) {
				$size = $value;
				if ( isset( $size->name ) ) {
					$new_slug                      = gutenverse_themes_builder_to_kebab_case( strtolower( $size->name ) );
					$new_slug                      = gutenverse_themes_builder_to_kebab_case( strtolower( $size->name ) );
					$arr_size_slugs[ $size->slug ] = $new_slug;
					$size->slug                    = $new_slug;
				} else {
					$name       = strtoupper( implode( ' ', explode( '-', $size->slug ) ) );
					$size->name = $name;
				}
				$sizes[] = $size;
			}
		}

		$placeholder = ! empty( $sizes ) ? str_replace( '{{font_sizes}}', wp_json_encode( $sizes ), $placeholder ) : str_replace( '{{font_sizes}}', '[]', $placeholder );

		$styles     = Misc::get_style_settings();
		$fix_styles = array(
			'spacing' => array(
				'blockGap' => '1.2rem',
			),
		);

		foreach ( $styles as $index => $style ) {
			$fix_styles[ $index ] = $style;
		}

		$fix_styles  = Misc::fix_colors_for_core_style_export( wp_json_encode( $fix_styles ), $include_global_import );
		$fix_styles  = Misc::fix_font_size_for_core_style_export( wp_json_encode( $fix_styles ), $arr_size_slugs );
		$placeholder = str_replace( '{{theme_color_styles}}', json_decode( $fix_styles ), $placeholder );

		/**
		 * Update Layout Size
		 */
		$layout = array(
			'contentSize' => '100%',
			'wideSize'    => '100%',
		);

		$placeholder = str_replace( '{{layout_sizes}}', wp_json_encode( $layout ), $placeholder );

		/**
		 * Add Custom Templates
		 */
		$templates_content = array();
		$templates_db      = Database::instance()->theme_templates;
		$templates_data    = $templates_db->get_data( $theme_id );
		if ( ! empty( $templates_data ) ) {
			foreach ( $templates_data as $template ) {
				if ( ! gutenverse_themes_builder_check_theme_mode( $template['category'], $theme_id ) ) {
					continue;
				}
				if ( 'custom_template' === $template['template_type'] ) {
					$match = array_filter(
						$templates_content,
						function ( $item ) use ( $template ) {
							$template_name = strtolower( str_replace( ' ', '-', $template['name'] ) );
							return isset( $item['name'] ) && $item['name'] === $template_name;
						}
					);
					if ( empty( $match ) ) {
						$templates_content[] = array(
							'name'      => strtolower( str_replace( ' ', '-', $template['name'] ) ),
							'title'     => ucfirst( str_replace( '-', ' ', $template['name'] ) ),
							'postTypes' => array( 'post', 'page' ),
						);
					}
				}
			}
		}
		$placeholder = str_replace( '{{custom_templates}}', wp_json_encode( $templates_content ), $placeholder );

		/**
		 * Put content into file
		 */
		$system->put_contents(
			gutenverse_themes_builder_theme_built_path() . 'theme.json',
			$placeholder,
			FS_CHMOD_FILE
		);
	}
}
