<?php
/**
 * Elementor integration for MuchWOW Shabnam Commerce.
 *
 * The integration keeps the original MuchWOW visual structure as the source
 * of truth while Elementor provides the editing layer.
 *
 * @package Shabnam_MuchWOW
 */

defined( 'ABSPATH' ) || exit;

/**
 * Check whether Elementor is loaded.
 *
 * @return bool
 */
function shabnam_elementor_is_available() {
	return did_action( 'elementor/loaded' ) && class_exists( '\\Elementor\\Plugin' );
}

/**
 * Check whether a document was built with Elementor.
 *
 * @param int $post_id Post ID.
 * @return bool
 */
function shabnam_elementor_is_built_with_elementor( $post_id = 0 ) {
	$post_id = absint( $post_id ? $post_id : get_the_ID() );

	if ( ! $post_id || ! shabnam_elementor_is_available() ) {
		return false;
	}

	$document = \Elementor\Plugin::instance()->documents->get( $post_id );

	return $document && method_exists( $document, 'is_built_with_elementor' ) && $document->is_built_with_elementor();
}

/**
 * Check Elementor editor/preview state. This is important for a page that is
 * being opened in Elementor for the first time, before it has builder meta.
 *
 * @return bool
 */
function shabnam_elementor_is_editor_request() {
	if ( ! shabnam_elementor_is_available() ) {
		return false;
	}

	$plugin = \Elementor\Plugin::instance();
	$editing = isset( $plugin->editor ) && method_exists( $plugin->editor, 'is_edit_mode' ) && $plugin->editor->is_edit_mode();
	$preview = isset( $plugin->preview ) && method_exists( $plugin->preview, 'is_preview_mode' ) && $plugin->preview->is_preview_mode();

	return (bool) ( $editing || $preview );
}

/**
 * Whether a page must expose its raw content area to Elementor.
 *
 * @param int $post_id Post ID.
 * @return bool
 */
function shabnam_elementor_should_render_content( $post_id = 0 ) {
	return shabnam_elementor_is_built_with_elementor( $post_id ) || shabnam_elementor_is_editor_request();
}

/**
 * Add the MuchWOW widget category.
 *
 * @param object $elements_manager Elementor elements manager.
 */
function shabnam_elementor_register_category( $elements_manager ) {
	if ( is_object( $elements_manager ) && method_exists( $elements_manager, 'add_category' ) ) {
		$elements_manager->add_category(
			'shabnam-muchwow',
			array(
				'title' => __( 'MuchWOW / SHABNAM.DEV', 'shabnam-muchwow' ),
				'icon'  => 'fa fa-plug',
			)
		);
	}
}
add_action( 'elementor/elements/categories_registered', 'shabnam_elementor_register_category' );

/**
 * Register the theme's editable homepage sections as Elementor widgets.
 *
 * @param \Elementor\Widgets_Manager $widgets_manager Widgets manager.
 */
function shabnam_elementor_register_widgets( $widgets_manager ) {
	$base = get_template_directory() . '/inc/elementor/widgets/';
	$files = array(
		'class-shabnam-elementor-widget-base.php',
		'class-shabnam-elementor-fragment-widget-base.php',
		'class-shabnam-elementor-semantic-sections.php',
		'class-shabnam-elementor-hero.php',
		'class-shabnam-elementor-marquee.php',
		'class-shabnam-elementor-about.php',
		'class-shabnam-elementor-numbers.php',
		'class-shabnam-elementor-tokenomics.php',
		'class-shabnam-elementor-roadmap.php',
		'class-shabnam-elementor-faq.php',
		'class-shabnam-elementor-shop.php',
		'class-shabnam-elementor-blog.php',
		'class-shabnam-elementor-demo-section.php',
	);

	foreach ( $files as $file ) {
		$path = $base . $file;
		if ( file_exists( $path ) ) {
			require_once $path;
		}
	}

	$classes = array(
		'Shabnam_Elementor_Hero',
		'Shabnam_Elementor_Marquee',
		'Shabnam_Elementor_About',
		'Shabnam_Elementor_Numbers',
		'Shabnam_Elementor_Tokenomics',
		'Shabnam_Elementor_Roadmap',
		'Shabnam_Elementor_FAQ',
		'Shabnam_Elementor_Shop',
		'Shabnam_Elementor_Blog',

		'Shabnam_Elementor_Semantic_Hero',
		'Shabnam_Elementor_Semantic_Marquee',
		'Shabnam_Elementor_Semantic_About',
		'Shabnam_Elementor_Semantic_Numbers',
		'Shabnam_Elementor_Semantic_Tokenomics',
		'Shabnam_Elementor_Semantic_Roadmap',
		'Shabnam_Elementor_Semantic_FAQ',
		'Shabnam_Elementor_Demo_Section',
	);

	foreach ( $classes as $class_name ) {
		if ( class_exists( $class_name ) ) {
			$widgets_manager->register( new $class_name() );
		}
	}
}
add_action( 'elementor/widgets/register', 'shabnam_elementor_register_widgets' );

/**
 * Return the default Elementor document data for the homepage.
 *
 * Each original MuchWOW section remains an independent Elementor widget so
 * it can be reordered, duplicated, removed and edited without changing the
 * original visual classes inside the section.
 *
 * @return array
 */
function shabnam_elementor_home_document_data() {
	$widgets = array(
		array( 'id' => 'shbhero1', 'widgetType' => 'shabnam-muchwow-hero', 'settings' => array() ),
		array( 'id' => 'shbmarq1', 'widgetType' => 'shabnam-muchwow-marquee', 'settings' => array( 'variant' => 'secondary' ) ),
		array( 'id' => 'shbabout', 'widgetType' => 'shabnam-muchwow-about', 'settings' => array() ),
		array( 'id' => 'shbnums1', 'widgetType' => 'shabnam-muchwow-numbers', 'settings' => array() ),
		array( 'id' => 'shbtokn1', 'widgetType' => 'shabnam-muchwow-tokenomics', 'settings' => array() ),
		array( 'id' => 'shbmarq2', 'widgetType' => 'shabnam-muchwow-marquee', 'settings' => array( 'variant' => 'primary' ) ),
		array( 'id' => 'shbroad1', 'widgetType' => 'shabnam-muchwow-roadmap', 'settings' => array() ),
		array( 'id' => 'shbmarq3', 'widgetType' => 'shabnam-muchwow-marquee', 'settings' => array( 'variant' => 'secondary' ) ),
		array( 'id' => 'shbshop1', 'widgetType' => 'shabnam-muchwow-shop', 'settings' => array() ),
		array( 'id' => 'shbblog1', 'widgetType' => 'shabnam-muchwow-blog', 'settings' => array() ),
		array( 'id' => 'shbfaq01', 'widgetType' => 'shabnam-muchwow-faq', 'settings' => array() ),
	);

	$elements = array();
	foreach ( $widgets as $widget ) {
		$elements[] = array(
			'id'         => $widget['id'],
			'elType'     => 'widget',
			'widgetType' => $widget['widgetType'],
			'settings'   => $widget['settings'],
			'elements'   => array(),
		);
	}

	return array(
		array(
			'id'       => 'shbhome0',
			'elType'   => 'container',
			'isInner'  => false,
			'settings' => array(
				'content_width'  => 'full',
				'flex_direction' => 'column',
				'gap'            => array( 'unit' => 'px', 'size' => 0, 'sizes' => array() ),
				'padding'        => array( 'unit' => 'px', 'top' => '0', 'right' => '0', 'bottom' => '0', 'left' => '0', 'isLinked' => true ),
				'css_classes'    => 'shabnam-home-elementor-root',
			),
			'elements' => $elements,
		),
	);
}

/**
 * Seed a page with the default MuchWOW Elementor layout.
 *
 * Existing Elementor data is never overwritten.
 *
 * @param int $page_id Page ID.
 * @return bool
 */
function shabnam_elementor_seed_home_page( $page_id ) {
	$page_id = absint( $page_id );
	if ( ! $page_id || ! shabnam_elementor_is_available() ) {
		return false;
	}

	$existing_data = get_post_meta( $page_id, '_elementor_data', true );
	if ( ! empty( $existing_data ) ) {
		return false;
	}

	$data = shabnam_elementor_home_document_data();
	update_post_meta( $page_id, '_elementor_edit_mode', 'builder' );
	update_post_meta( $page_id, '_elementor_template_type', 'wp-page' );
	update_post_meta( $page_id, '_elementor_page_settings', array() );
	update_post_meta( $page_id, '_elementor_data', wp_slash( wp_json_encode( $data ) ) );
	update_post_meta( $page_id, '_shabnam_elementor_home', '1' );

	if ( defined( 'ELEMENTOR_VERSION' ) ) {
		update_post_meta( $page_id, '_elementor_version', ELEMENTOR_VERSION );
	}

	return true;
}

/**
 * Create an Elementor-editable static front page when a site is still using
 * the "latest posts" homepage. This is a one-time, non-destructive bootstrap:
 * an existing static front page is never replaced.
 */
function shabnam_elementor_bootstrap_home_page() {
	if ( ! shabnam_elementor_is_available() || get_option( 'shabnam_elementor_bootstrap_completed' ) ) {
		return;
	}

	$front_id   = absint( get_option( 'page_on_front' ) );
	$show_front = get_option( 'show_on_front' );
	$created    = false;

	if ( 'page' !== $show_front || ! $front_id || 'page' !== get_post_type( $front_id ) ) {
		$known_id = absint( get_option( 'shabnam_elementor_home_page_id' ) );
		if ( $known_id && 'page' === get_post_type( $known_id ) ) {
			$front_id = $known_id;
		} else {
			$front_id = wp_insert_post(
				array(
					'post_type'    => 'page',
					'post_status'  => 'publish',
					'post_title'   => __( 'خانه', 'shabnam-muchwow' ),
					'post_content' => '',
					'post_name'    => 'home',
				)
			);
			if ( is_wp_error( $front_id ) || ! $front_id ) {
				return;
			}
			update_option( 'shabnam_elementor_home_page_id', (int) $front_id );
			$created = true;
		}

		update_option( 'show_on_front', 'page' );
		update_option( 'page_on_front', (int) $front_id );

		// Preserve access to the posts archive when converting from latest posts.
		if ( ! absint( get_option( 'page_for_posts' ) ) ) {
			$blog_id = wp_insert_post(
				array(
					'post_type'    => 'page',
					'post_status'  => 'publish',
					'post_title'   => __( 'وبلاگ', 'shabnam-muchwow' ),
					'post_content' => '',
					'post_name'    => 'blog',
				)
			);
			if ( ! is_wp_error( $blog_id ) && $blog_id ) {
				update_option( 'page_for_posts', (int) $blog_id );
			}
		}
	}

	$page = get_post( $front_id );
	if ( $page instanceof WP_Post ) {
		$has_elementor = ! empty( get_post_meta( $front_id, '_elementor_data', true ) );
		$is_empty_page = '' === trim( (string) $page->post_content );
		if ( ! $has_elementor && $is_empty_page ) {
			$created = shabnam_elementor_seed_home_page( $front_id ) || $created;
		}
	}

	update_option( 'shabnam_elementor_bootstrap_completed', 1 );

	if ( $created ) {
		set_transient( 'shabnam_elementor_home_setup_notice', (int) $front_id, MINUTE_IN_SECONDS * 10 );
	}
}
add_action( 'init', 'shabnam_elementor_bootstrap_home_page', 30 );

/**
 * Get the Elementor editor URL for a page.
 *
 * @param int $post_id Post ID.
 * @return string
 */
function shabnam_elementor_edit_url( $post_id ) {
	$post_id = absint( $post_id );
	if ( $post_id && shabnam_elementor_is_available() ) {
		$document = \Elementor\Plugin::instance()->documents->get( $post_id );
		if ( $document && method_exists( $document, 'get_edit_url' ) ) {
			return $document->get_edit_url();
		}
	}
	return admin_url( 'post.php?post=' . $post_id . '&action=elementor' );
}

/**
 * Add a direct Elementor edit action for the front page to the admin bar.
 *
 * @param WP_Admin_Bar $wp_admin_bar Admin bar.
 */
function shabnam_elementor_admin_bar_link( $wp_admin_bar ) {
	$front_id = absint( get_option( 'page_on_front' ) );
	if ( ! $front_id || ! current_user_can( 'edit_post', $front_id ) || ! shabnam_elementor_is_available() ) {
		return;
	}

	$wp_admin_bar->add_node(
		array(
			'id'    => 'shabnam-edit-home-elementor',
			'title' => __( 'ویرایش صفحه اصلی با المنتور', 'shabnam-muchwow' ),
			'href'  => shabnam_elementor_edit_url( $front_id ),
		)
	);
}
add_action( 'admin_bar_menu', 'shabnam_elementor_admin_bar_link', 90 );

/**
 * Show a one-time setup notice after the editable home page is created.
 */
function shabnam_elementor_setup_notice() {
	$front_id = absint( get_transient( 'shabnam_elementor_home_setup_notice' ) );
	if ( ! $front_id || ! current_user_can( 'edit_post', $front_id ) ) {
		return;
	}
	delete_transient( 'shabnam_elementor_home_setup_notice' );
	?>
	<div class="notice notice-success is-dismissible"><p>
		<?php echo esc_html__( 'صفحه اصلی MuchWOW با همان چیدمان اصلی برای ویرایش با Elementor آماده شد.', 'shabnam-muchwow' ); ?>
		<a class="button button-primary" href="<?php echo esc_url( shabnam_elementor_edit_url( $front_id ) ); ?>"><?php esc_html_e( 'ویرایش با المنتور', 'shabnam-muchwow' ); ?></a>
	</p></div>
	<?php
}
add_action( 'admin_notices', 'shabnam_elementor_setup_notice' );

/**
 * Add an explicit Elementor action on the Pages screen for the front page.
 *
 * @param array   $actions Row actions.
 * @param WP_Post $post    Current post.
 * @return array
 */
function shabnam_elementor_front_page_row_action( $actions, $post ) {
	$front_id = absint( get_option( 'page_on_front' ) );
	if ( $front_id && (int) $post->ID === $front_id && shabnam_elementor_is_available() && current_user_can( 'edit_post', $front_id ) ) {
		$actions['shabnam_elementor'] = '<a href="' . esc_url( shabnam_elementor_edit_url( $front_id ) ) . '">' . esc_html__( 'ویرایش با المنتور', 'shabnam-muchwow' ) . '</a>';
	}
	return $actions;
}
add_filter( 'page_row_actions', 'shabnam_elementor_front_page_row_action', 20, 2 );

/**
 * Add the new store/blog widgets to a homepage previously seeded by this theme.
 * Existing widgets and user edits are preserved; missing dynamic sections are
 * inserted before FAQ only once.
 */
function shabnam_elementor_upgrade_home_dynamic_sections() {
	if ( ! shabnam_elementor_is_available() ) {
		return;
	}

	$front_id = absint( get_option( 'page_on_front' ) );
	if ( ! $front_id ) {
		return;
	}

	$raw = get_post_meta( $front_id, '_elementor_data', true );
	if ( ! is_string( $raw ) || '' === trim( $raw ) ) {
		return;
	}

	$data = json_decode( $raw, true );
	if ( ! is_array( $data ) ) {
		return;
	}

	$encoded = wp_json_encode( $data );
	$looks_like_muchwow = false !== strpos( $encoded, 'shabnam-muchwow-' );
	if ( ! $looks_like_muchwow ) {
		return;
	}
	if ( false !== strpos( $encoded, 'shabnam-muchwow-shop' ) && false !== strpos( $encoded, 'shabnam-muchwow-blog' ) ) {
		return;
	}

	$changed = false;
	foreach ( $data as &$container ) {
		if ( empty( $container['elements'] ) || ! is_array( $container['elements'] ) ) {
			continue;
		}

		$elements = $container['elements'];
		$has_shop = false;
		$has_blog = false;
		foreach ( $elements as $element ) {
			$has_shop = $has_shop || ( isset( $element['widgetType'] ) && 'shabnam-muchwow-shop' === $element['widgetType'] );
			$has_blog = $has_blog || ( isset( $element['widgetType'] ) && 'shabnam-muchwow-blog' === $element['widgetType'] );
		}

		$insert_at = count( $elements );
		foreach ( $elements as $index => $element ) {
			if ( isset( $element['widgetType'] ) && 'shabnam-muchwow-faq' === $element['widgetType'] ) {
				$insert_at = $index;
				break;
			}
		}

		$insert = array();
		if ( ! $has_shop ) {
			$insert[] = array( 'id' => 'shbshop1', 'elType' => 'widget', 'widgetType' => 'shabnam-muchwow-shop', 'settings' => array(), 'elements' => array() );
		}
		if ( ! $has_blog ) {
			$insert[] = array( 'id' => 'shbblog1', 'elType' => 'widget', 'widgetType' => 'shabnam-muchwow-blog', 'settings' => array(), 'elements' => array() );
		}

		if ( $insert ) {
			array_splice( $elements, $insert_at, 0, $insert );
			$container['elements'] = $elements;
			$changed = true;
		}
		break;
	}
	unset( $container );

	if ( $changed ) {
		update_post_meta( $front_id, '_elementor_data', wp_slash( wp_json_encode( $data ) ) );
		if ( isset( \Elementor\Plugin::instance()->files_manager ) && method_exists( \Elementor\Plugin::instance()->files_manager, 'clear_cache' ) ) {
			\Elementor\Plugin::instance()->files_manager->clear_cache();
		}
	}
}
add_action( 'init', 'shabnam_elementor_upgrade_home_dynamic_sections', 60 );


/**
 * Map a source-plan fragment to its semantic Elementor widget.
 *
 * @param string $section_key Source fragment key.
 * @return string
 */
function shabnam_elementor_semantic_widget_type( $section_key ) {
	$section_key = sanitize_key( (string) $section_key );
	$map = array(
		'one-00'=>'shabnam-muchwow-section-hero','one-01'=>'shabnam-muchwow-section-marquee','one-02'=>'shabnam-muchwow-section-about','one-03'=>'shabnam-muchwow-section-numbers','one-04'=>'shabnam-muchwow-section-tokenomics','one-05'=>'shabnam-muchwow-section-marquee','one-06'=>'shabnam-muchwow-section-roadmap','one-07'=>'shabnam-muchwow-section-marquee','one-08'=>'shabnam-muchwow-section-faq',
	);
	return isset( $map[ $section_key ] ) ? $map[ $section_key ] : '';
}

/** Recursively replace only the widget type; user-edited settings stay intact. */
function shabnam_elementor_semanticize_elements( &$elements, &$changed ) {
	if ( ! is_array( $elements ) ) { return; }
	foreach ( $elements as &$element ) {
		if ( ! is_array( $element ) ) { continue; }
		if ( isset( $element['widgetType'] ) && 'shabnam-muchwow-demo-section' === $element['widgetType'] ) {
			$key  = isset( $element['settings']['section_key'] ) ? $element['settings']['section_key'] : '';
			$type = shabnam_elementor_semantic_widget_type( $key );
			if ( $type ) { $element['widgetType'] = $type; $changed = true; }
		}
		if ( ! empty( $element['elements'] ) && is_array( $element['elements'] ) ) {
			shabnam_elementor_semanticize_elements( $element['elements'], $changed );
		}
	}
	unset( $element );
}

/**
 * Upgrade existing managed plan pages to semantic widgets without rebuilding
 * or replacing their Elementor document.
 */
function shabnam_elementor_upgrade_semantic_plan_widgets() {
	if ( ! function_exists( 'shabnam_muchwow_get_page_id' ) ) { return; }
	$any_changed = false;
	foreach ( array( 'demo-one' ) as $key ) {
		$page_id = absint( shabnam_muchwow_get_page_id( $key ) );
		if ( ! $page_id ) { continue; }
		$raw = (string) get_post_meta( $page_id, '_elementor_data', true );
		if ( '' === trim( $raw ) || false === strpos( $raw, 'shabnam-muchwow-demo-section' ) ) {
			update_post_meta( $page_id, '_shcd_muchwow_semantic_widget_schema', '1' );
			continue;
		}
		$data = json_decode( $raw, true );
		if ( JSON_ERROR_NONE !== json_last_error() || ! is_array( $data ) ) { continue; }
		$changed = false;
		shabnam_elementor_semanticize_elements( $data, $changed );
		if ( $changed ) {
			if ( ! metadata_exists( 'post', $page_id, '_shcd_muchwow_pre_semantic_backup' ) ) {
				add_post_meta( $page_id, '_shcd_muchwow_pre_semantic_backup', wp_slash( $raw ), true );
			}
			update_post_meta( $page_id, '_elementor_data', wp_slash( wp_json_encode( $data ) ) );
			$any_changed = true;
		}
		update_post_meta( $page_id, '_shcd_muchwow_semantic_widget_schema', '1' );
	}
	if ( $any_changed && shabnam_elementor_is_available() ) {
		$plugin = \Elementor\Plugin::instance();
		if ( isset( $plugin->files_manager ) && method_exists( $plugin->files_manager, 'clear_cache' ) ) { $plugin->files_manager->clear_cache(); }
	}
}
add_action( 'init', 'shabnam_elementor_upgrade_semantic_plan_widgets', 135 );
