<?php
/**
 * Import a Site Kit into WordPress (pages + theme parts + globals).
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Templates;

use AuraBuilder\Document\DocumentSanitizer;
use AuraBuilder\Globals\SiteGlobals;
use AuraBuilder\Storage\DocumentRepository;
use AuraBuilder\Theme\ThemeBuilder;

final class KitImporter {

	/**
	 * @param array<string, mixed> $options
	 * @return array<string, mixed>|\WP_Error
	 */
	public function import( string $kit_id, array $options = array() ) {
		$kit = CoreLibrary::get_kit( $kit_id );
		if ( ! $kit ) {
			return new \WP_Error( 'ab_kit', 'Kit não encontrado.', array( 'status' => 404 ) );
		}
		$path = (string) ( $kit['path'] ?? '' );
		if ( $path === '' || ! is_dir( $path ) ) {
			return new \WP_Error( 'ab_kit_path', 'Pasta do kit inválida.', array( 'status' => 404 ) );
		}

		$manifest = is_array( $kit['manifest'] ?? null )
			? $kit['manifest']
			: ( CoreLibrary::read_json( $path . '/manifest.json' ) ?: array() );

		$import_globals = ! empty( $options['globals'] ) || ! empty( $options['design_system'] );
		$import_header  = ! isset( $options['header'] ) || ! empty( $options['header'] );
		$import_footer  = ! isset( $options['footer'] ) || ! empty( $options['footer'] );
		$import_pages   = ! isset( $options['pages'] ) || ! empty( $options['pages'] );
		$set_home       = ! empty( $options['set_home'] );
		// Optional list of page keys to import; empty = all.
		$page_keys = is_array( $options['page_keys'] ?? null ) ? $options['page_keys'] : array();

		$import_single = ! isset( $options['single'] ) || ! empty( $options['single'] );

		$result = array(
			'kit'     => $kit_id,
			'globals' => false,
			'header'  => false,
			'footer'  => false,
			'single'  => false,
			'pages'   => array(),
			'home'    => 0,
		);

		// Design system.
		if ( $import_globals ) {
			$ds_file = $path . '/design-system.json';
			$ds      = CoreLibrary::read_json( $ds_file );
			if ( is_array( $ds ) ) {
				$current = SiteGlobals::get();
				$merged  = $this->merge_globals( $current, $ds );
				SiteGlobals::save( $merged );
				$result['globals'] = true;
			}
		}

		// Header / footer.
		if ( $import_header ) {
			$h = CoreLibrary::read_json( $path . '/templates/header.json' );
			if ( is_array( $h ) ) {
				$doc = is_array( $h['document'] ?? null ) ? $h['document'] : $h;
				$doc = TemplateTokens::apply( $doc );
				$doc = DocumentSanitizer::sanitize( $doc )->to_array();
				ThemeBuilder::save_part(
					'header',
					array(
						'enabled'  => true,
						'display'  => 'all',
						'source'   => 'builder',
						'document' => $doc,
					)
				);
				$result['header'] = true;
			}
		}
		if ( $import_footer ) {
			$f = CoreLibrary::read_json( $path . '/templates/footer.json' );
			if ( is_array( $f ) ) {
				$doc = is_array( $f['document'] ?? null ) ? $f['document'] : $f;
				$doc = TemplateTokens::apply( $doc );
				$doc = DocumentSanitizer::sanitize( $doc )->to_array();
				ThemeBuilder::save_part(
					'footer',
					array(
						'enabled'  => true,
						'display'  => 'all',
						'source'   => 'builder',
						'document' => $doc,
					)
				);
				$result['footer'] = true;
			}
		}

		// Dynamic single post template (if kit provides templates/single.json).
		if ( $import_single ) {
			$sfile = $path . '/templates/single.json';
			$sraw  = CoreLibrary::read_json( $sfile );
			if ( is_array( $sraw ) ) {
				$doc = is_array( $sraw['document'] ?? null ) ? $sraw['document'] : $sraw;
				$doc = TemplateTokens::apply( $doc );
				$doc = DocumentSanitizer::sanitize( $doc )->to_array();
				ThemeBuilder::save_part(
					'single',
					array(
						'enabled'  => true,
						'display'  => 'singular',
						'source'   => 'builder',
						'document' => $doc,
					)
				);
				$result['single'] = true;
			}
		}

		// Pages from manifest.pages or templates/*.json excluding header/footer/single.
		if ( $import_pages ) {
			$pages_meta = is_array( $manifest['pages'] ?? null ) ? $manifest['pages'] : array();
			if ( ! $pages_meta ) {
				// Auto-discover.
				$files = glob( $path . '/templates/*.json' ) ?: array();
				foreach ( $files as $file ) {
					$base = pathinfo( $file, PATHINFO_FILENAME );
					if ( in_array( $base, array( 'header', 'footer', 'single' ), true ) ) {
						continue;
					}
					$pages_meta[] = array(
						'key'   => $base,
						'title' => ucfirst( str_replace( array( '-', '_' ), ' ', $base ) ),
						'file'  => 'templates/' . $base . '.json',
						'home'  => $base === 'home',
					);
				}
			}

			$repo = new DocumentRepository();
			$map  = get_option( 'aptb_kit_page_map', array() );
			if ( ! is_array( $map ) || ! $map ) {
				$map = get_option( 'aura_builder_kit_page_map', array() );
			}
			if ( ! is_array( $map ) ) {
				$map = array();
			}
			if ( ! is_array( $map ) ) {
				$map = array();
			}
			$kit_map = is_array( $map[ $kit_id ] ?? null ) ? $map[ $kit_id ] : array();

			foreach ( $pages_meta as $pmeta ) {
				if ( ! is_array( $pmeta ) ) {
					continue;
				}
				$key = sanitize_key( (string) ( $pmeta['key'] ?? '' ) );
				if ( $key === '' ) {
					continue;
				}
				if ( $page_keys && ! in_array( $key, $page_keys, true ) ) {
					continue;
				}
				$rel  = (string) ( $pmeta['file'] ?? ( 'templates/' . $key . '.json' ) );
				$file = $path . '/' . ltrim( str_replace( '..', '', $rel ), '/' );
				$raw  = CoreLibrary::read_json( $file );
				if ( ! $raw ) {
					continue;
				}
				$doc = is_array( $raw['document'] ?? null ) ? $raw['document'] : $raw;
				$doc = TemplateTokens::apply( $doc );
				$doc = DocumentSanitizer::sanitize( $doc )->to_array();

				$title = sanitize_text_field( (string) ( $pmeta['title'] ?? $raw['name'] ?? $key ) );
				$post_id = (int) ( $kit_map[ $key ] ?? 0 );
				if ( $post_id > 0 && get_post( $post_id ) ) {
					wp_update_post(
						array(
							'ID'         => $post_id,
							'post_title' => $title,
						)
					);
				} else {
					$post_id = (int) wp_insert_post(
						array(
							'post_type'   => 'page',
							'post_status' => 'publish',
							'post_title'  => $title,
							'post_content'=> '<!-- Aura Builder -->',
						),
						true
					);
					if ( is_wp_error( $post_id ) || $post_id <= 0 ) {
						continue;
					}
				}
				$repo->save( $post_id, DocumentSanitizer::sanitize( $doc ), true );
				$kit_map[ $key ] = $post_id;
				$result['pages'][] = array(
					'key'    => $key,
					'id'     => $post_id,
					'title'  => $title,
					'edit'   => admin_url( 'admin.php?page=aura-builder&post=' . $post_id ),
					'view'   => get_permalink( $post_id ),
				);

				if ( $set_home && ! empty( $pmeta['home'] ) ) {
					update_option( 'show_on_front', 'page' );
					update_option( 'page_on_front', $post_id );
					update_option( 'aptb_home_page', $post_id );
					$result['home'] = $post_id;
				}
			}

			$map[ $kit_id ] = $kit_map;
			update_option( 'aptb_kit_page_map', $map, false );
		}

		$result['ok']      = true;
		$result['message'] = 'Kit importado. Tudo permanece editável no Aura Builder.';
		return $result;
	}

	/**
	 * @param array<string, mixed> $current
	 * @param array<string, mixed> $ds
	 * @return array<string, mixed>
	 */
	private function merge_globals( array $current, array $ds ): array {
		foreach ( array( 'colors', 'typography', 'radius', 'layout', 'chrome' ) as $group ) {
			if ( empty( $ds[ $group ] ) || ! is_array( $ds[ $group ] ) ) {
				continue;
			}
			if ( ! is_array( $current[ $group ] ?? null ) ) {
				$current[ $group ] = array();
			}
			foreach ( $ds[ $group ] as $k => $v ) {
				if ( is_scalar( $v ) && (string) $v !== '' ) {
					$current[ $group ][ $k ] = $v;
				}
			}
		}
		return $current;
	}
}
