<?php
if ( ! defined( 'ABSPATH' ) ) {
	die( 'Direct access forbidden.' );
}

class BrizyPro_Admin_AiCore {
	use Brizy_Editor_Trait_Sanitize;

	const nonce = 'brizy-api';

	const AJAX_CREATE_SESSION = '_ai_create_session';
	const AJAX_GET_TEMPLATE = '_ai_get_template';
	const AJAX_IMPORT_DELETE = '_ai_import_delete';
	const AJAX_IMPORT_KEEP = '_ai_import_keep';
	const AJAX_GET_POST = '_ai_get_post';
	const AJAX_IMPORT_PAGE = '_ai_import_page';

	public static function _init() {
		static $instance;
		if ( ! $instance ) {
			$instance = new self();
		}

		return $instance;
	}

	public function __construct() {
		$this->initializeApiActions();
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueueAiScript' ) );
	}

	public function enqueueAiScript() {
		if ( ! Brizy_Editor_User::is_user_allowed() ) {
			return;
		}
		wp_enqueue_script( 'brizy-pro-admin-ai-js', BRIZY_PRO_PLUGIN_URL . '/admin/static/js/ai.js', array(
				Brizy_Editor::get_slug() . '-admin-js',
				'jquery'
			), BRIZY_PRO_VERSION, true );
		
		$isLicenseValid = false;
		if ( class_exists('BrizyPro_Admin_License') ) {
			$isLicenseValid = BrizyPro_Admin_License::_init()->isValidLicense();
		}
		
		$proData = array(
			'aiActions' => array(
				'createSession' => self::AJAX_CREATE_SESSION,
				'getTemplate'   => self::AJAX_GET_TEMPLATE,
				'importDelete'  => self::AJAX_IMPORT_DELETE,
				'importKeep'    => self::AJAX_IMPORT_KEEP,
				'getPost'       => self::AJAX_GET_POST,
				'aiImportPage'  => self::AJAX_IMPORT_PAGE,
			),
			'isLicenseValid'      => $isLicenseValid,
			'aiPostTitleRequired' => __( 'Please add the post title before continuing.', 'brizy-pro' ),
		);
		
		wp_add_inline_script( 'brizy-pro-admin-ai-js', '
			if (typeof Brizy_Admin_Data !== "undefined") {
				Object.assign(Brizy_Admin_Data, ' . json_encode( $proData ) . ');
			}
		', 'after' );
	}

	protected function initializeApiActions() {
		$pref = 'wp_ajax_' . Brizy_Editor::prefix();
		if ( ! Brizy_Editor_User::is_user_allowed() ) {
			return;
		}
		add_action( $pref . self::AJAX_CREATE_SESSION, array( $this, 'aiCreateSession' ) );
		add_action( $pref . self::AJAX_GET_TEMPLATE, array( $this, 'aiGetTemplate' ) );
		add_action( $pref . self::AJAX_IMPORT_DELETE, array( $this, 'aiImportDelete' ) );
		add_action( $pref . self::AJAX_IMPORT_KEEP, array( $this, 'aiImportKeep' ) );
		add_action( $pref . self::AJAX_GET_POST, array( $this, 'aiGetPost' ) );
		add_action( $pref . self::AJAX_IMPORT_PAGE, array( $this, 'aiImportPage' ) );
	}

	protected function getRequestNonce() {
		return isset( $_REQUEST['hash'] ) ? sanitize_text_field( $_REQUEST['hash'] ) : null;
	}

	protected function verifyNonce( $action ) {
		$nonce = $this->getRequestNonce();
		if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, $action ) ) {
			wp_send_json_error( 'Invalid token, please refresh page and try again.', 400 );

			return null;
		}
	}

	private function getLicenseKey() {
		if ( ! class_exists( 'BrizyPro_Admin_License' ) ) {
			return null;
		}
		$licenseData = BrizyPro_Admin_License::_init()->getCurrentLicense();

		return ! empty( $licenseData['key'] ) ? $licenseData['key'] : null;
	}

	private function requireLicenseKey() {
		$licenseKey = $this->getLicenseKey();
		if ( empty( $licenseKey ) ) {
			wp_send_json_error( 'License key is required.', 403 );
		}

		return $licenseKey;
	}

	private function sessionIdParam( $request ) {
		$sessionId = isset( $request['sessionId'] ) ? sanitize_text_field( $request['sessionId'] ) : '';
		if ( empty( $sessionId ) ) {
			wp_send_json_error( 'sessionId parameter is required', 400 );

			return null;
		}

		return $sessionId;
	}

	public function aiCreateSession() {
		$this->verifyNonce( self::nonce );
		if ( ! Brizy_Editor_User::is_user_allowed() ) {
			wp_send_json_error( 'Unauthorized access.', 403 );

			return;
		}
		$httpClient = new Brizy_Editor_Http_Client();
		$licenseKey = $this->requireLicenseKey();
		$contentType = isset( $_REQUEST['contentType'] ) ? sanitize_text_field( $_REQUEST['contentType'] ) : '';
		$page = isset( $_REQUEST['page'] ) ? $_REQUEST['page'] : '';
		if ( is_array( $page ) ) {
			$page = array_map( 'sanitize_text_field', array_filter( $page ) );
		} elseif ( ! empty( $page ) ) {
			$page = [ sanitize_text_field( $page ) ];
		} else {
			$page = [];
		}
		try {
			$headers = [
				'X-API-Key'    => $licenseKey,
				'Content-Type' => 'application/json'
			];
			$options = [
				'headers' => $headers,
			];
			$bodyData = [];
			if ( $contentType == 'keep' ) {
				$projectStyle = $this->sendProjectStyle();
				$bodyData = json_decode( $projectStyle, true );
			} else {
				$bodyData = [ 'data' => [] ];
			}
			$bodyData['data']['pages'] = $page;
			$bodyData['data']['isWithHeaderAndFooter'] = ( $contentType !== 'keep' );
			if ( $contentType === 'delete' ) {
				$aiMenu = $this->getOrCreateAiMenu();
				if ( $aiMenu ) {
					$bodyData['data']['menuId'] = $aiMenu['brizy_uid'];
				}
			}
			$options['body'] = json_encode( $bodyData );
			$response = $httpClient->request( BrizyPro_Config::getAiCreateSessionUrl(), $options, 'POST' );
			$createSession = $response->get_response_body();
			if ( ! $createSession ) {
				wp_send_json_error( 'No response received from the API.', 400 );

				return null;
			}
			$aiUrl = isset( $createSession['aiUrl'] ) ? $createSession['aiUrl'] : '';
			if ( empty( $aiUrl ) ) {
				wp_send_json_error( 'aiUrl parameter is required', 400 );

				return null;
			}
			$this->sessionIdParam( $createSession );
			$createSession['aiUrl'] = $createSession['aiUrl'] . '&callbackUrl=' . get_site_url();
			wp_send_json_success( $createSession );
		} catch ( Exception $e ) {
			wp_send_json_error( $e->getMessage(), 500 );
		}
	}

	private function sendProjectStyle() {
		$projectColors     = $this->getProjectColors();
		$projectTypography = $this->getProjectTypography();
		$dataArray = [];
		if ( ! empty( $projectColors ) ) {
			$dataArray['color'] = $projectColors;
		}
		if ( ! empty( $projectTypography ) ) {
			$dataArray['typography'] = $projectTypography;
		}
		if ( empty( $dataArray ) ) {
			return null;
		}

		return json_encode( [
			'data' => $dataArray,
		] );
	}

	private function editorPageUrl(
		$imported
	) {
		if ( empty( $imported ) ) {
			wp_send_json_error( 'postId parameter is required', 400 );

			return null;
		}
		$postId = $imported[0]['id'];
		foreach ( $imported as $page ) {
			if ( $page['title'] == 'Home' || $page['slug'] == 'home' ) {
				$postId = $page['id'];
			}
		}

		return admin_url( 'post.php?action=in-front-editor&post=' . $postId );
	}

	public function aiGetTemplate() {
		$this->verifyNonce( self::nonce );
		$licenseKey = $this->requireLicenseKey();
		$sessionId = $this->sessionIdParam( $_REQUEST );
		$httpClient = new Brizy_Editor_Http_Client();
		try {
			$headers = [
				'X-API-Key'    => $licenseKey,
				'Content-Type' => 'application/json'
			];
			$options = [
				'headers' => $headers
			];
			$response = $httpClient->request( BrizyPro_Config::getAiCreateSessionUrl() . '/' . urlencode( $sessionId ), $options, 'GET' );
			$body = $response->get_response_body();
			if ( ! $body ) {
				wp_send_json_error( 'No response received from the API.', 400 );

				return null;
			}
			wp_send_json_success( $body );
		} catch ( Exception $e ) {
			wp_send_json_error( $e->getMessage(), 500 );
		}
	}

	public function aiImportDelete() {
		$this->verifyNonce( self::nonce );
		if ( ! Brizy_Editor_User::is_user_allowed() ) {
			wp_send_json_error( 'Unauthorized access.', 403 );

			return;
		}
		$body = isset( $_REQUEST['body'] ) ? $_REQUEST['body'] : '';
		if ( empty( $body ) ) {
			wp_send_json_error( 'body parameter is required', 400 );

			return null;
		}
		$body = json_decode( stripslashes( $_REQUEST['body'] ), true );
		if ( ! $body ) {
			wp_send_json_error( 'Invalid JSON in body parameter', 400 );

			return null;
		}
		$this->deletePageData();
		$imported = $this->importPagesData( $body );
		if ( ! $imported ) {
			wp_send_json_error( 'Error importing pages', 400 );

			return null;
		}
		$projectData = $this->importProjectDataDelete( $body );
		if ( ! $projectData ) {
			wp_send_json_error( 'Error importing project', 400 );

			return null;
		}
		$postId = 0;
		if ( is_array( $imported ) && ! empty( $imported ) ) {
			$postId = (int) $imported[0]['id'];
			foreach ( $imported as $page ) {
				if ( isset( $page['id'] ) ) {
					$this->compilePage( (int) $page['id'] );
				}
			}
		}
		$this->syncAiMenuItems( array_reverse( $imported ) );
		$editPageUrl = $this->editorPageUrl( $imported );
		wp_send_json_success( array(
			'pages'       => $imported,
			'pageId'      => $postId,
			'projectData' => $projectData,
			'editPageUrl' => $editPageUrl,
		) );
	}

	public function aiImportKeep() {
		$this->verifyNonce( self::nonce );
		if ( ! Brizy_Editor_User::is_user_allowed() ) {
			wp_send_json_error( 'Unauthorized access.', 403 );

			return;
		}
		$body = isset( $_REQUEST['body'] ) ? $_REQUEST['body'] : '';
		if ( empty( $body ) ) {
			wp_send_json_error( 'body parameter is required', 400 );

			return null;
		}
		$body = json_decode( stripslashes( $_REQUEST['body'] ), true );
		if ( ! $body ) {
			wp_send_json_error( 'Invalid JSON in body parameter', 400 );

			return null;
		}
		$imported = $this->importPagesData( $body );
		if ( ! $imported ) {
			wp_send_json_error( 'Error importing pages', 400 );

			return null;
		}
		$projectData = $this->importProjectDataKeep( $body );
		if ( ! $projectData ) {
			wp_send_json_error( 'Error importing project', 400 );

			return null;
		}
		$postId = 0;
		if ( is_array( $imported ) && ! empty( $imported ) ) {
			$postId = (int) $imported[0]['id'];
			foreach ( $imported as $page ) {
				if ( isset( $page['id'] ) ) {
					$this->compilePage( (int) $page['id'] );
				}
			}
		}
		$this->syncAiMenuItems( array_reverse( $imported ) );
		$editPageUrl = $this->editorPageUrl( $imported );
		wp_send_json_success( array(
			'pages'       => $imported,
			'pageId'      => $postId,
			'projectData' => $projectData,
			'editPageUrl' => $editPageUrl,
		) );
	}

	private function importProjectDataKeep(
		$importedProjectData
	) {
		$currentProjectInstance = Brizy_Editor_Project::get();
		$existingProjectData        = $currentProjectInstance->getDecodedData();
		$importedProjectDataDecoded = json_decode( $importedProjectData['project'], true );
		if ( $importedProjectDataDecoded === null ) {
			wp_send_json_error( 'Invalid project data in import', 400 );

			return null;
		}
		if ( is_array( $existingProjectData ) ) {
			$existingProjectData = (object) $existingProjectData;
		}
		if ( is_array( $importedProjectDataDecoded ) ) {
			$importedProjectDataDecoded = (object) $importedProjectDataDecoded;
		}
		$projectStorageInstance = Brizy_Editor_Storage_Project::instance( $currentProjectInstance->getWpPost()->ID );
		update_post_meta( $currentProjectInstance->getWpPost()->ID, 'brizy-project-import-backup-' . md5( time() ), $projectStorageInstance->get_storage() );
		$mergedProjectData = json_decode( json_encode( $importedProjectDataDecoded ) );
		$styleFieldsToPreserve = [
			'styles',
			'selectedStyle',
			'fonts',
			'extraStyles',
			'extraFontStyles',
			'selectedKit',
			'font'
		];
		foreach ( $styleFieldsToPreserve as $field ) {
			if ( isset( $existingProjectData->$field ) ) {
				$mergedProjectData->$field = $existingProjectData->$field;
			}
		}
		$currentProjectInstance->setDataAsJson( json_encode( $mergedProjectData ) );
		$currentProjectInstance->saveStorage();

		return $mergedProjectData;
	}

	private function importProjectDataDelete(
		$body
	) {
		$project = Brizy_Editor_Project::get();
		if ( ! isset( $body['project'] ) ) {
			wp_send_json_error( 'Invalid project structure', 400 );

			return null;
		}
		$project->setDataAsJson( $body['project'] );
		$current_data_version = $project->getCurrentDataVersion();
		$project->setDataVersion( $current_data_version + 1 );
		$project->set_compiler( Brizy_Editor_Entity::COMPILER_EXTERNAL );
		$project->set_uses_editor( true );
		$project->save( 0 );
		$project->savePost();
		$project = $project->getDataAsJson();

		return json_decode( $project );
	}

	private function importPagesData( $body ) {
		if ( ! isset( $body['pages'] ) ) {
			wp_send_json_error( 'Invalid pages structure', 400 );

			return null;
		}
		$imported = [];
		foreach ( $body['pages'] as $page ) {
			$page = json_decode( $page, true );
			if ( $page === null ) {
				continue;
			}
			$pageTitle = sanitize_text_field( isset( $page['title'] ) && trim( $page['title'] ) !== '' ? $page['title'] : 'default title' );
			$pageSlug  = sanitize_text_field( isset( $page['slug'] ) && trim( $page['slug'] ) !== '' ? $page['slug'] : 'default-slug' );
			$pageData  = $this->sanitizeJson( isset( $page['pageData'] ) ? $page['pageData'] : '{"items":[]}' );
			$pageStructure = array(
				'post_title'     => $pageTitle,
				'post_name'      => $pageSlug,
				'post_status'    => 'publish',
				'post_type'      => 'page',
				'post_author'    => get_current_user_id() ? get_current_user_id() : 1,
				'comment_status' => 'closed',
				'page_template'  => Brizy_Config::BRIZY_BLANK_TEMPLATE_FILE_NAME,
				'post_content' => '<div class="brz-root__container"></div>'
			);
			$postId        = wp_insert_post( $pageStructure );
			if ( ! $postId || is_wp_error( $postId ) ) {
				continue;
			}

            if ( $this->importPageDataToPost( $postId, $pageData ) ) {
				$imported[] = array(
					'id'           => $postId,
					'title'        => $pageTitle,
					'slug'         => $pageSlug,
					'data'         => $pageData,
				);
			}
		}

		return $imported;
	}

	private function deletePageData() {
		if ( ! current_user_can( 'delete_posts' ) ) {
			return;
		}
		$existing_pages = get_posts( array(
			'post_type'   => 'page',
			'post_status' => 'any',
			'numberposts' => - 1,
			'fields'      => 'ids',
		) );
		if ( ! empty( $existing_pages ) ) {
			foreach ( $existing_pages as $existing_page_id ) {
				if ( Brizy_Editor_Entity::isBrizyEnabled( $existing_page_id ) ) {
					if ( current_user_can( 'delete_post', $existing_page_id ) ) {
						wp_trash_post( $existing_page_id );
					}
				}
			}
		}
	}

	private function getOrCreateAiMenu() {
		$aiMenuName = 'brz-ai-menu';
		$existing = get_term_by( 'name', $aiMenuName, 'nav_menu' );
		if ( $existing ) {
			$termId = $existing->term_id;
		} else {
			$result = wp_create_nav_menu( $aiMenuName );
			if ( is_wp_error( $result ) ) {
				return null;
			}
			$termId = (int) $result;
		}
		$menuUid = get_term_meta( $termId, 'brizy_uid', true );
		if ( empty( $menuUid ) ) {
			$menuUid = md5( $termId . time() );
			update_term_meta( $termId, 'brizy_uid', $menuUid );
		}

		return array(
			'term_id'   => $termId,
			'brizy_uid' => $menuUid,
		);
	}

	private function syncAiMenuItems( $importedPages ) {
		$menu = $this->getOrCreateAiMenu();
		if ( ! $menu ) {
			return;
		}
		$termId = $menu['term_id'];
		$existingItems = wp_get_nav_menu_items( $termId );
		if ( ! empty( $existingItems ) ) {
			foreach ( $existingItems as $item ) {
				wp_delete_post( $item->ID, true );
			}
		}
		$position = 1;
		foreach ( $importedPages as $page ) {
			$postId    = isset( $page['id'] ) ? (int) $page['id'] : 0;
			$pageTitle = isset( $page['title'] ) ? $page['title'] : '';
			if ( ! $postId ) {
				continue;
			}
			wp_update_nav_menu_item( $termId, 0, array(
				'menu-item-title'     => $pageTitle,
				'menu-item-object'    => 'page',
				'menu-item-object-id' => $postId,
				'menu-item-type'      => 'post_type',
				'menu-item-status'    => 'publish',
				'menu-item-position'  => $position,
			) );
			$position ++;
		}
	}

	private function getProjectColors() {
		$project     = Brizy_Editor_Project::get();
		$projectData = $project->getDecodedData();
		$colors = [];
		if ( ! is_object( $projectData ) ) {
			return $colors;
		}
		if ( ! isset( $projectData->styles ) || ! is_array( $projectData->styles ) ) {
			return $colors;
		}
		$selectedStyleId = isset( $projectData->selectedStyle ) ? $projectData->selectedStyle : null;
		if ( empty( $selectedStyleId ) ) {
			return $colors;
		}
		$selectedStyle = null;
		foreach ( $projectData->styles as $style ) {
			if ( is_object( $style ) && isset( $style->id ) && $style->id === $selectedStyleId ) {
				$selectedStyle = $style;
				break;
			}
		}
		if ( ! $selectedStyle || ! isset( $selectedStyle->colorPalette ) || ! is_array( $selectedStyle->colorPalette ) ) {
			return $colors;
		}
		foreach ( $selectedStyle->colorPalette as $color ) {
			if ( ! is_object( $color ) ) {
				continue;
			}
			if ( ! isset( $color->id ) || ! isset( $color->hex ) ) {
				continue;
			}
			$colors[] = [
				'hex' => $color->hex,
				'id'  => $color->id
			];
		}

		return $colors;
	}

	private function formatFontFamilyName( $fontFamily ) {
		if ( empty( $fontFamily ) || ! is_string( $fontFamily ) ) {
			return '';
		}
		
		$formatted = str_replace( '_', ' ', $fontFamily );
		
		$formatted = ucwords( strtolower( $formatted ) );
		
		return $formatted;
	}

	private function getProjectTypography() {
		$project     = Brizy_Editor_Project::get();
		$projectData = $project->getDecodedData();
		$typography = [];
		if ( ! is_object( $projectData ) ) {
			return $typography;
		}
		if ( ! isset( $projectData->styles ) || ! is_array( $projectData->styles ) ) {
			return $typography;
		}
		$selectedStyleId = isset( $projectData->selectedStyle ) ? $projectData->selectedStyle : null;
		if ( empty( $selectedStyleId ) ) {
			return $typography;
		}
		$selectedStyle = null;
		foreach ( $projectData->styles as $style ) {
			if ( is_object( $style ) && isset( $style->id ) && $style->id === $selectedStyleId ) {
				$selectedStyle = $style;
				break;
			}
		}
		if ( ! $selectedStyle || ! isset( $selectedStyle->fontStyles ) || ! is_array( $selectedStyle->fontStyles ) ) {
			return $typography;
		}
		foreach ( $selectedStyle->fontStyles as $fontStyle ) {
			if ( ! is_object( $fontStyle ) ) {
				continue;
			}
			if ( ! isset( $fontStyle->id ) || ! isset( $fontStyle->title ) ) {
				continue;
			}
			$rawFontFamily = isset( $fontStyle->fontFamily ) ? $fontStyle->fontFamily : '';
			$formattedStyle = [
				'deletable'            => isset( $fontStyle->deletable ) ? $fontStyle->deletable : 'off',
				'id'                   => $fontStyle->id,
				'title'                => $fontStyle->title,
				'fontFamily'           => $this->formatFontFamilyName( $rawFontFamily ),
				'fontFamilyType'       => isset( $fontStyle->fontFamilyType ) ? $fontStyle->fontFamilyType : 'google',
				'fontSize'             => isset( $fontStyle->fontSize ) ? $fontStyle->fontSize : 16,
				'fontSizeSuffix'       => isset( $fontStyle->fontSizeSuffix ) ? $fontStyle->fontSizeSuffix : 'px',
				'fontWeight'           => isset( $fontStyle->fontWeight ) ? $fontStyle->fontWeight : 400,
				'lineHeight'           => isset( $fontStyle->lineHeight ) ? $fontStyle->lineHeight : 1.3,
				'letterSpacing'        => isset( $fontStyle->letterSpacing ) ? $fontStyle->letterSpacing : 0,
				'tabletFontSize'       => isset( $fontStyle->tabletFontSize ) ? $fontStyle->tabletFontSize : ( isset( $fontStyle->fontSize ) ? $fontStyle->fontSize : 16 ),
				'tabletFontSizeSuffix' => isset( $fontStyle->tabletFontSizeSuffix ) ? $fontStyle->tabletFontSizeSuffix : ( isset( $fontStyle->fontSizeSuffix ) ? $fontStyle->fontSizeSuffix : 'px' ),
				'tabletFontWeight'     => isset( $fontStyle->tabletFontWeight ) ? $fontStyle->tabletFontWeight : ( isset( $fontStyle->fontWeight ) ? $fontStyle->fontWeight : 400 ),
				'tabletLineHeight'     => isset( $fontStyle->tabletLineHeight ) ? $fontStyle->tabletLineHeight : ( isset( $fontStyle->lineHeight ) ? $fontStyle->lineHeight : 1.3 ),
				'tabletLetterSpacing'  => isset( $fontStyle->tabletLetterSpacing ) ? $fontStyle->tabletLetterSpacing : ( isset( $fontStyle->letterSpacing ) ? $fontStyle->letterSpacing : 0 ),
				'mobileFontSize'       => isset( $fontStyle->mobileFontSize ) ? $fontStyle->mobileFontSize : ( isset( $fontStyle->fontSize ) ? $fontStyle->fontSize : 16 ),
				'mobileFontSizeSuffix' => isset( $fontStyle->mobileFontSizeSuffix ) ? $fontStyle->mobileFontSizeSuffix : ( isset( $fontStyle->fontSizeSuffix ) ? $fontStyle->fontSizeSuffix : 'px' ),
				'mobileFontWeight'     => isset( $fontStyle->mobileFontWeight ) ? $fontStyle->mobileFontWeight : ( isset( $fontStyle->fontWeight ) ? $fontStyle->fontWeight : 400 ),
				'mobileLineHeight'     => isset( $fontStyle->mobileLineHeight ) ? $fontStyle->mobileLineHeight : ( isset( $fontStyle->lineHeight ) ? $fontStyle->lineHeight : 1.3 ),
				'mobileLetterSpacing'  => isset( $fontStyle->mobileLetterSpacing ) ? $fontStyle->mobileLetterSpacing : ( isset( $fontStyle->letterSpacing ) ? $fontStyle->letterSpacing : 0 ),
				'bold'                 => isset( $fontStyle->bold ) ? $fontStyle->bold : false,
				'italic'               => isset( $fontStyle->italic ) ? $fontStyle->italic : false,
				'underline'            => isset( $fontStyle->underline ) ? $fontStyle->underline : false,
				'strike'               => isset( $fontStyle->strike ) ? $fontStyle->strike : false,
				'uppercase'            => isset( $fontStyle->uppercase ) ? $fontStyle->uppercase : false,
				'lowercase'            => isset( $fontStyle->lowercase ) ? $fontStyle->lowercase : false,
			];
			$typography[] = $formattedStyle;
		}

		return $typography;
	}

	private function importPageDataToPost( $postId, $pageData ) {
		try {
			$post = Brizy_Editor_Post::get( $postId );
			if ( ! $post ) {
				return false;
			}
			$post->enable_editor();
			$current_data_version = $post->getCurrentDataVersion();
			$post->setDataVersion( $current_data_version + 1 );
			$post->set_editor_data( $pageData );
			$post->enable_editor();
			$post->set_editor_version( BRIZY_EDITOR_VERSION );
			$post->set_plugin_version( BRIZY_VERSION );
			$post->set_pro_plugin_version( defined( 'BRIZY_PRO_VERSION' ) ? BRIZY_PRO_VERSION : null );
			$post->set_compiler( Brizy_Editor_Entity::COMPILER_EXTERNAL );
			$post->set_compiler_version( 0 );
			$post->set_needs_compile( true );
			$post->saveStorage();
			$post->save( 0 );
			$post->savePost( true );
			
			return true;
		} catch ( Exception $e ) {
			Brizy_Logger::instance()->error( $e->getMessage(), [ $e ] );
			return false;
		}
	}

	private function compilePage( $postId ) {
		try {
			$post = Brizy_Editor_Post::get( $postId );
			if ( ! $post ) {
				return;
			}
			$post->compile_page();
		} catch ( Exception $e ) {
			 Brizy_Logger::instance()->error($e->getMessage(), [$e]);
		}
	}

	public function aiGetPost() {
		$this->verifyNonce( self::nonce );
		if ( ! Brizy_Editor_User::is_user_allowed() ) {
			wp_send_json_error( 'Unauthorized access.', 403 );

			return;
		}
		$postId = isset( $_REQUEST['postId'] ) ? intval( $_REQUEST['postId'] ) : 0;
		if ( empty( $postId ) ) {
			wp_send_json_error( 'postId parameter is required', 400 );

			return;
		}
		$post = get_post( $postId );
		if ( ! $post ) {
			wp_send_json_error( 'Post not found', 404 );

			return;
		}
		$slug = $post->post_name;
		if ( empty( $slug ) ) {
			$slugSource = ! empty( $post->post_title ) ? $post->post_title : 'page-' . $postId;
			$slug = sanitize_title( $slugSource );
			$slug = wp_unique_post_slug( $slug, $postId, $post->post_status, $post->post_type, $post->post_parent );
			wp_update_post( array(
				'ID'        => $postId,
				'post_name' => $slug,
			) );
		}
		wp_send_json_success( array(
			'slug' => $slug,
		) );
	}

	public function aiImportPage() {
		$this->verifyNonce( self::nonce );

		if ( ! Brizy_Editor_User::is_user_allowed() ) {
			wp_send_json_error( 'Unauthorized access.', 403 );
			return;
		}

		$postId = isset( $_REQUEST['postId'] ) ? intval( $_REQUEST['postId'] ) : 0;
		if ( empty( $postId ) ) {
			wp_send_json_error( 'postId parameter is required', 400 );
			return;
		}
		$existingPost = get_post( $postId );
		if ( ! $existingPost ) {
			wp_send_json_error( 'Post not found', 404 );
			return;
		}

		$body = isset( $_REQUEST['body'] ) ? $_REQUEST['body'] : '';
		if ( empty( $body ) ) {
			wp_send_json_error( 'body parameter is required', 400 );
			return;
		}

		$body = json_decode( stripslashes( $body ), true );
		if ( ! $body ) {
			wp_send_json_error( 'Invalid JSON in body parameter', 400 );
			return;
		}

		if ( ! isset( $body['pages'] ) || ! is_array( $body['pages'] ) || empty( $body['pages'] ) ) {
			wp_send_json_error( 'No pages found in template data', 400 );
			return;
		}

		$currentSlug    = $existingPost->post_name;
		$matchedPage    = null;
		$remainingPages = array();

		foreach ( $body['pages'] as $rawPage ) {
			$decoded = json_decode( $rawPage, true );
			if ( $decoded === null ) {
				continue;
			}
			$pageSlug = isset( $decoded['slug'] ) ? sanitize_text_field( $decoded['slug'] ) : '';
			if ( ! $matchedPage && $pageSlug === $currentSlug ) {
				$matchedPage = $decoded;
			} else {
				$remainingPages[] = $rawPage;
			}
		}

		if ( ! $matchedPage ) {
			$firstDecoded = json_decode( $body['pages'][0], true );
			if ( $firstDecoded === null ) {
				wp_send_json_error( 'Invalid first page data', 400 );
				return;
			}
			$matchedPage    = $firstDecoded;
			$remainingPages = array();
			foreach ( array_slice( $body['pages'], 1 ) as $rawPage ) {
				$remainingPages[] = $rawPage;
			}
		}

		$pageData = isset( $matchedPage['pageData'] ) ? $matchedPage['pageData'] : '{"items":[]}';
		$pageData = $this->sanitizeJson( $pageData );
		$matchedTitle = isset( $matchedPage['title'] ) && trim( $matchedPage['title'] ) !== ''
			? sanitize_text_field( $matchedPage['title'] )
			: $existingPost->post_title;

		update_post_meta( $postId, '_wp_page_template', Brizy_Config::BRIZY_BLANK_TEMPLATE_FILE_NAME );

		if ( ! $this->importPageDataToPost( $postId, $pageData ) ) {
			wp_send_json_error( 'Error importing page data', 500 );
			return;
		}

		if ( $matchedTitle !== $existingPost->post_title ) {
			wp_update_post( array(
				'ID'         => $postId,
				'post_title' => $matchedTitle,
			) );
		}

		$importedPages = array(
			array(
				'id'    => $postId,
				'title' => $matchedTitle,
				'slug'  => $currentSlug,
			),
		);

		if ( ! empty( $remainingPages ) ) {
			$remainingBody = array( 'pages' => $remainingPages );
			$newPages = $this->importPagesData( $remainingBody );
			if ( is_array( $newPages ) ) {
				$importedPages = array_merge( $importedPages, $newPages );
			}
		}

		$contentType = isset( $_REQUEST['contentType'] ) ? sanitize_text_field( $_REQUEST['contentType'] ) : 'keep';
		if ( $contentType === 'delete' ) {
			$projectData = $this->importProjectDataDelete( $body );
		} else {
			$projectData = $this->importProjectDataKeep( $body );
		}

		foreach ( $importedPages as $importedPage ) {
			$this->compilePage( (int) $importedPage['id'] );
		}

		$this->syncAiMenuItems( $importedPages );

		$editPageUrl = admin_url( 'post.php?action=in-front-editor&post=' . $postId );

		wp_send_json_success( array(
			'postId'      => $postId,
			'pages'       => $importedPages,
			'projectData' => $projectData,
			'editPageUrl' => $editPageUrl,
		) );
	}
}
