<?php
/**
 * Site kit export/import – layouts, globals, theme mods.
 *
 * @package EasySite_Pro
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Exportable theme mod keys.
 *
 * @return array
 */
function easysite_kit_theme_mod_keys() {
	return array(
		'easysite_main_color', 'easysite_accent_color', 'easysite_gradient_preset',
		'easysite_gradient_color_1', 'easysite_gradient_color_2', 'easysite_use_gradients',
		'easysite_gradient_buttons', 'easysite_gradient_hero', 'easysite_font_pair',
		'easysite_design_preset', 'easysite_phone', 'easysite_email', 'easysite_address',
		'easysite_footer_text', 'easysite_header_button_text', 'easysite_header_button_link',
		'easysite_form_label_name', 'easysite_form_label_email', 'easysite_form_label_message',
		'easysite_form_label_submit', 'easysite_seo_description',
	);
}

/**
 * Build site kit export data.
 *
 * @param int $home_id Optional front page ID.
 * @return array
 */
function easysite_export_site_kit( $home_id = 0 ) {
	if ( ! $home_id ) {
		$home_id = (int) get_option( 'page_on_front' );
	}
	$mods = array();
	foreach ( easysite_kit_theme_mod_keys() as $key ) {
		$mods[ $key ] = get_theme_mod( $key );
	}
	$mods['custom_logo'] = get_theme_mod( 'custom_logo' );

	return array(
		'version'  => EASYSITE_PRO_VERSION,
		'exported' => time(),
		'layout'   => $home_id ? easysite_get_builder_layout( $home_id ) : array(),
		'globals'  => easysite_get_global_sections(),
		'mods'     => $mods,
		'blogname' => get_option( 'blogname' ),
	);
}

/**
 * Export single page layout.
 *
 * @param int $post_id Post ID.
 * @return array
 */
function easysite_export_page_layout( $post_id ) {
	return array(
		'version' => EASYSITE_PRO_VERSION,
		'layout'  => easysite_get_builder_layout( $post_id ),
		'regions' => array(
			'header_button_text' => easysite_get_mod( 'easysite_header_button_text' ),
			'footer_text'        => easysite_get_mod( 'easysite_footer_text' ),
		),
	);
}

/**
 * Import site kit.
 *
 * @param array $kit Kit data.
 * @param int   $post_id Target page ID.
 * @return true|WP_Error
 */
function easysite_import_site_kit( $kit, $post_id = 0 ) {
	if ( empty( $kit['layout'] ) || ! is_array( $kit['layout'] ) ) {
		return new WP_Error( 'invalid_kit', __( 'Invalid site kit file.', 'easysite-pro' ) );
	}
	if ( ! $post_id ) {
		$post_id = (int) get_option( 'page_on_front' );
	}
	if ( ! $post_id ) {
		return new WP_Error( 'no_page', __( 'No homepage found to import into.', 'easysite-pro' ) );
	}

	$old = easysite_get_builder_layout( $post_id );
	if ( ! empty( $old ) ) {
		easysite_ve_save_revision( $post_id, $old );
	}

	update_post_meta( $post_id, EASYSITE_BUILDER_ENABLED, '1' );
	update_post_meta( $post_id, EASYSITE_BUILDER_META, wp_json_encode( easysite_sanitize_builder_layout( $kit['layout'] ) ) );

	if ( ! empty( $kit['globals'] ) && is_array( $kit['globals'] ) ) {
		update_option( 'easysite_global_sections', $kit['globals'] );
	}
	if ( ! empty( $kit['mods'] ) && is_array( $kit['mods'] ) ) {
		foreach ( $kit['mods'] as $key => $value ) {
			set_theme_mod( $key, $value );
		}
	}
	if ( ! empty( $kit['blogname'] ) ) {
		update_option( 'blogname', sanitize_text_field( $kit['blogname'] ) );
	}

	return true;
}

/**
 * Site kit admin menu.
 */
function easysite_site_kit_menu() {
	if ( ! easysite_bundle_active() ) {
		return;
	}
	add_submenu_page(
		'easysite-setup',
		__( 'Site Kit', 'easysite-pro' ),
		__( 'Site Kit', 'easysite-pro' ),
		'manage_options',
		'easysite-site-kit',
		'easysite_render_site_kit_page'
	);
}
add_action( 'admin_menu', 'easysite_site_kit_menu', 17 );

/**
 * Handle kit export download.
 */
function easysite_site_kit_export_handler() {
	if ( ! isset( $_GET['easysite_export_kit'] ) || ! current_user_can( 'manage_options' ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		return;
	}
	if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'easysite_export_kit' ) ) {
		wp_die( esc_html__( 'Security check failed.', 'easysite-pro' ) );
	}
	$kit = easysite_export_site_kit();
	header( 'Content-Type: application/json' );
	header( 'Content-Disposition: attachment; filename="easysite-site-kit.json"' );
	echo wp_json_encode( $kit );
	exit;
}
add_action( 'admin_init', 'easysite_site_kit_export_handler' );

/**
 * Render site kit page.
 */
function easysite_render_site_kit_page() {
	$imported = isset( $_GET['imported'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$error    = isset( $_GET['error'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$export_url = wp_nonce_url( admin_url( 'admin.php?easysite_export_kit=1' ), 'easysite_export_kit' );
	?>
	<div class="wrap">
		<h1><?php esc_html_e( 'Site Kit', 'easysite-pro' ); ?></h1>
		<p><?php esc_html_e( 'Export or import a full site package — homepage layout, saved sections, colors, and contact info.', 'easysite-pro' ); ?></p>
		<?php if ( $imported ) : ?>
			<div class="notice notice-success"><p><?php esc_html_e( 'Site kit imported successfully!', 'easysite-pro' ); ?></p></div>
		<?php elseif ( $error ) : ?>
			<div class="notice notice-error"><p><?php esc_html_e( 'Import failed. Check the file format.', 'easysite-pro' ); ?></p></div>
		<?php endif; ?>
		<h2><?php esc_html_e( 'Export', 'easysite-pro' ); ?></h2>
		<p><a href="<?php echo esc_url( $export_url ); ?>" class="button button-primary"><?php esc_html_e( 'Download site kit (.json)', 'easysite-pro' ); ?></a></p>
		<h2><?php esc_html_e( 'Import', 'easysite-pro' ); ?></h2>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" enctype="multipart/form-data">
			<?php wp_nonce_field( 'easysite_import_kit', 'easysite_kit_nonce' ); ?>
			<input type="hidden" name="action" value="easysite_import_site_kit" />
			<p><input type="file" name="kit_file" accept=".json,application/json" required /></p>
			<p class="submit"><button type="submit" class="button"><?php esc_html_e( 'Import site kit', 'easysite-pro' ); ?></button></p>
		</form>
		<?php if ( function_exists( 'easysite_render_demo_kits_section' ) ) : ?>
			<?php easysite_render_demo_kits_section(); ?>
		<?php endif; ?>
	</div>
	<?php
}

/**
 * Handle kit import upload.
 */
function easysite_handle_import_site_kit() {
	if ( ! isset( $_POST['easysite_kit_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['easysite_kit_nonce'] ) ), 'easysite_import_kit' ) ) {
		wp_die( esc_html__( 'Security check failed.', 'easysite-pro' ) );
	}
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Permission denied.', 'easysite-pro' ) );
	}
	if ( empty( $_FILES['kit_file']['tmp_name'] ) ) {
		wp_safe_redirect( admin_url( 'admin.php?page=easysite-site-kit&error=1' ) );
		exit;
	}
	$raw = file_get_contents( $_FILES['kit_file']['tmp_name'] ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
	$kit = json_decode( $raw, true );
	$result = easysite_import_site_kit( is_array( $kit ) ? $kit : array() );
	$url = $result === true ? 'imported=1' : 'error=1';
	wp_safe_redirect( admin_url( 'admin.php?page=easysite-site-kit&' . $url ) );
	exit;
}
add_action( 'admin_post_easysite_import_site_kit', 'easysite_handle_import_site_kit' );

/**
 * AJAX: export current page layout from VE.
 */
function easysite_ajax_ve_export_page() {
	check_ajax_referer( 'easysite_ve_nonce', 'nonce' );
	$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
	if ( ! $post_id || ! current_user_can( 'edit_post', $post_id ) ) {
		wp_send_json_error();
	}
	wp_send_json_success( easysite_export_page_layout( $post_id ) );
}
add_action( 'wp_ajax_easysite_ve_export_page', 'easysite_ajax_ve_export_page' );

/**
 * AJAX: import page layout from VE.
 */
function easysite_ajax_ve_import_page() {
	check_ajax_referer( 'easysite_ve_nonce', 'nonce' );
	$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
	$raw     = isset( $_POST['kit'] ) ? wp_unslash( $_POST['kit'] ) : ''; // phpcs:ignore
	$data    = json_decode( $raw, true );
	if ( ! $post_id || ! current_user_can( 'edit_post', $post_id ) || ! is_array( $data ) || empty( $data['layout'] ) ) {
		wp_send_json_error();
	}
	$old = easysite_get_builder_layout( $post_id );
	if ( ! empty( $old ) ) {
		easysite_ve_save_revision( $post_id, $old );
	}
	$layout = easysite_sanitize_builder_layout( $data['layout'] );
	update_post_meta( $post_id, EASYSITE_BUILDER_ENABLED, '1' );
	update_post_meta( $post_id, EASYSITE_BUILDER_META, wp_json_encode( $layout ) );
	wp_send_json_success( array( 'layout' => $layout ) );
}
add_action( 'wp_ajax_easysite_ve_import_page', 'easysite_ajax_ve_import_page' );
