<?php
/**
 * MuchWOW demo/page installer and secure account/contact forms.
 *
 * @package Shabnam_MuchWOW
 */

defined( 'ABSPATH' ) || exit;

/**
 * Pages shipped by the original MuchWOW package.
 *
 * @return array<string,array<string,string>>
 */
function shabnam_muchwow_page_definitions() {
	return array(
		'demo-one'       => array( 'title' => 'خانه — طرح 1', 'slug' => 'muchwow-demo-one', 'template' => 'muchwow-home-one.json', 'type' => 'demo' ),
		'sign-in'        => array( 'title' => 'ورود', 'slug' => 'sign-in', 'template' => 'muchwow-page-sign-in.json', 'type' => 'page', 'fallback' => '[shcd_login_form]' ),
		'sign-up'        => array( 'title' => 'ثبت‌نام', 'slug' => 'sign-up', 'template' => 'muchwow-page-sign-up.json', 'type' => 'page', 'fallback' => '[shcd_register_form]' ),
		'reset-password' => array( 'title' => 'بازیابی رمز عبور', 'slug' => 'reset-password', 'template' => 'muchwow-page-reset-password.json', 'type' => 'page', 'fallback' => '[shcd_reset_password_form]' ),
		'contact'        => array( 'title' => 'تماس با ما', 'slug' => 'contact', 'template' => 'muchwow-page-contact.json', 'type' => 'page', 'fallback' => '[shcd_contact_form]' ),
		'blog'           => array( 'title' => 'وبلاگ', 'slug' => 'blog', 'type' => 'blog' ),
		'privacy'        => array( 'title' => 'حریم خصوصی', 'slug' => 'privacy', 'template' => 'muchwow-page-privacy.json', 'type' => 'page' ),
		'terms'          => array( 'title' => 'شرایط استفاده', 'slug' => 'terms', 'template' => 'muchwow-page-terms.json', 'type' => 'page' ),
	);
}

/**
 * Read stored page IDs.
 *
 * @return array<string,int>
 */
function shabnam_muchwow_page_ids() {
	$ids = get_option( 'shcd_muchwow_page_ids', array() );
	return is_array( $ids ) ? array_map( 'absint', $ids ) : array();
}

/**
 * Return a managed page previously created by this theme, even when its slug
 * was changed later by the site owner. This registry is what makes page
 * creation idempotent across theme/plugin activation cycles.
 *
 * @param string $key Page key.
 * @param bool   $restore_trash Whether a trashed theme-managed page may be restored.
 * @return int
 */
function shabnam_muchwow_find_registered_page( $key, $restore_trash = false ) {
	$key = sanitize_key( $key );
	if ( '' === $key ) {
		return 0;
	}

	$posts = get_posts(
		array(
			'post_type'              => 'page',
			'post_status'            => array( 'publish', 'private', 'draft', 'pending', 'future', 'trash' ),
			'posts_per_page'         => 1,
			'fields'                 => 'ids',
			'orderby'                => 'ID',
			'order'                  => 'ASC',
			'meta_key'               => '_shcd_muchwow_page_key',
			'meta_value'             => $key,
			'suppress_filters'       => true,
			'no_found_rows'          => true,
			'update_post_meta_cache' => false,
			'update_post_term_cache' => false,
		)
	);
	if ( empty( $posts[0] ) ) {
		return 0;
	}

	$page_id = absint( $posts[0] );
	if ( 'trash' === get_post_status( $page_id ) ) {
		if ( ! $restore_trash ) {
			return 0;
		}
		$restored = wp_untrash_post( $page_id );
		if ( ! $restored ) {
			return 0;
		}
	}
	return 'page' === get_post_type( $page_id ) ? $page_id : 0;
}

/**
 * Resolve a managed page ID without trusting stale option data.
 *
 * A page is considered present when its stored ID still points to a non-trash
 * page, when a theme registry marker finds it, or when a user-created page
 * already owns the expected slug. A trashed theme-managed page is restored
 * rather than duplicated.
 *
 * @param string $key Page key.
 * @return int
 */
function shabnam_muchwow_get_page_id( $key ) {
	$key  = sanitize_key( $key );
	$defs = shabnam_muchwow_page_definitions();
	if ( ! isset( $defs[ $key ] ) ) {
		return 0;
	}

	$ids = shabnam_muchwow_page_ids();
	if ( ! empty( $ids[ $key ] ) && 'page' === get_post_type( $ids[ $key ] ) && 'trash' !== get_post_status( $ids[ $key ] ) ) {
		return (int) $ids[ $key ];
	}

	$registered = shabnam_muchwow_find_registered_page( $key, true );
	if ( $registered ) {
		return $registered;
	}

	$page = get_page_by_path( $defs[ $key ]['slug'], OBJECT, 'page' );
	return $page instanceof WP_Post && 'trash' !== $page->post_status ? (int) $page->ID : 0;
}

/**
 * Managed page URL.
 *
 * @param string $key Page key.
 * @return string
 */
function shabnam_muchwow_page_url( $key ) {
	$id = shabnam_muchwow_get_page_id( $key );
	return $id ? get_permalink( $id ) : home_url( '/' );
}

/**
 * Current demo key (one/two/three).
 *
 * @return string
 */
function shabnam_muchwow_selected_demo() {
	return 'one';
}

/**
 * Return theme visual variant for the current request.
 * The original inner pages all used theme-two CSS.
 *
 * @return string
 */
function shabnam_muchwow_style_variant() {
	foreach ( array( 'sign-in', 'sign-up', 'reset-password', 'contact', 'privacy', 'terms' ) as $key ) {
		$id = shabnam_muchwow_get_page_id( $key );
		if ( $id && is_page( $id ) ) {
			return 'two';
		}
	}
	return shabnam_muchwow_selected_demo();
}

/**
 * Replace portable placeholders in generated Elementor JSON.
 *
 * @param string $json Raw JSON.
 * @return string
 */
function shabnam_muchwow_resolve_elementor_placeholders( $json ) {
	$json = str_replace( '__SHCD_THEME_URI__', untrailingslashit( get_template_directory_uri() ), $json );
	foreach ( shabnam_muchwow_page_definitions() as $key => $def ) {
		$json = str_replace( '__SHCD_PAGE_URL_' . $key . '__', shabnam_muchwow_page_url( $key ), $json );
	}
	return $json;
}

/**
 * Seed an empty page with portable Elementor JSON.
 * Existing Elementor content is never overwritten.
 *
 * @param int    $page_id Page ID.
 * @param string $template_file JSON filename.
 * @return bool
 */
function shabnam_muchwow_seed_elementor_page( $page_id, $template_file ) {
	$page_id = absint( $page_id );
	if ( ! $page_id || ! function_exists( 'shabnam_elementor_is_available' ) || ! shabnam_elementor_is_available() ) {
		return false;
	}
	if ( '' !== trim( (string) get_post_meta( $page_id, '_elementor_data', true ) ) ) {
		return false;
	}
	$post = get_post( $page_id );
	if ( $post instanceof WP_Post && '' !== trim( (string) $post->post_content ) && ! get_post_meta( $page_id, '_shcd_muchwow_managed_page', true ) ) {
		// A pre-existing user page with real content must never be replaced by the demo installer.
		return false;
	}

	$file = get_template_directory() . '/elementor-templates/' . sanitize_file_name( $template_file );
	if ( ! is_readable( $file ) ) {
		return false;
	}
	$json = file_get_contents( $file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
	if ( ! is_string( $json ) || '' === trim( $json ) ) {
		return false;
	}
	$json = shabnam_muchwow_resolve_elementor_placeholders( $json );
	$data = json_decode( $json, true );
	if ( JSON_ERROR_NONE !== json_last_error() || ! is_array( $data ) ) {
		return false;
	}

	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( 'hide_title' => 'yes' ) );
	update_post_meta( $page_id, '_elementor_data', wp_slash( wp_json_encode( $data ) ) );
	update_post_meta( $page_id, '_shcd_muchwow_seeded', '1' );
	if ( defined( 'ELEMENTOR_VERSION' ) ) {
		update_post_meta( $page_id, '_elementor_version', ELEMENTOR_VERSION );
	}
	return true;
}

/**
 * Create all pages from the original MuchWOW package and seed Elementor data.
 * Existing pages/content are preserved.
 */
function shabnam_muchwow_install_pages() {
	$defs       = shabnam_muchwow_page_definitions();
	$stored_ids = shabnam_muchwow_page_ids();
	$ids        = $stored_ids;

	/*
	 * This reconciler is intentionally idempotent. It never creates a second
	 * copy merely because Elementor, WooCommerce or another plugin was toggled.
	 * A new page is inserted only when no living page and no restorable
	 * theme-managed page exists for that key.
	 */
	foreach ( $defs as $key => $def ) {
		$id      = 0;
		$managed = false;

		if ( ! empty( $ids[ $key ] ) && 'page' === get_post_type( $ids[ $key ] ) && 'trash' !== get_post_status( $ids[ $key ] ) ) {
			$id      = (int) $ids[ $key ];
			$managed = (bool) get_post_meta( $id, '_shcd_muchwow_managed_page', true );
		}

		if ( ! $id ) {
			$id = shabnam_muchwow_find_registered_page( $key, true );
			if ( $id ) {
				$managed = true;
			}
		}

		if ( ! $id ) {
			$existing = get_page_by_path( $def['slug'], OBJECT, 'page' );
			if ( $existing instanceof WP_Post && 'trash' !== $existing->post_status ) {
				$id      = (int) $existing->ID;
				$managed = (bool) get_post_meta( $id, '_shcd_muchwow_managed_page', true );
			}
		}

		/* Reuse the blog page created by older theme builds instead of creating blog-2/blog-3. */
		if ( ! $id && 'blog' === $key ) {
			$legacy_blog = absint( get_option( 'shcd_muchwow_blog_page_id' ) );
			if ( $legacy_blog && 'page' === get_post_type( $legacy_blog ) ) {
				if ( 'trash' === get_post_status( $legacy_blog ) && get_post_meta( $legacy_blog, '_shcd_muchwow_managed_blog', true ) ) {
					wp_untrash_post( $legacy_blog );
				}
				if ( 'trash' !== get_post_status( $legacy_blog ) ) {
					$id      = $legacy_blog;
					$managed = (bool) get_post_meta( $legacy_blog, '_shcd_muchwow_managed_blog', true );
					if ( $managed && ! get_page_by_path( 'blog', OBJECT, 'page' ) ) {
						wp_update_post( array( 'ID' => $legacy_blog, 'post_name' => 'blog', 'post_title' => 'وبلاگ' ) );
					}
				}
			}
		}

		if ( ! $id ) {
			$id = wp_insert_post(
				array(
					'post_type'    => 'page',
					'post_status'  => 'publish',
					'post_title'   => $def['title'],
					'post_name'    => $def['slug'],
					'post_content' => isset( $def['fallback'] ) ? (string) $def['fallback'] : '',
				),
				true
			);
			if ( is_wp_error( $id ) || ! $id ) {
				unset( $ids[ $key ] );
				continue;
			}
			$id      = (int) $id;
			$managed = true;
			update_post_meta( $id, '_shcd_muchwow_managed_page', '1' );
			update_post_meta( $id, '_shcd_muchwow_page_key', $key );
		}

		if ( $id ) {
			$ids[ $key ] = (int) $id;
			if ( $managed ) {
				update_post_meta( $id, '_shcd_muchwow_managed_page', '1' );
				update_post_meta( $id, '_shcd_muchwow_page_key', $key );

				// Rename only untouched theme-managed home pages; custom user titles stay intact.
				$legacy_demo_titles = array(
					'demo-one' => 'خانه — دمو یک',
				);
				if ( isset( $legacy_demo_titles[ $key ] ) ) {
					$page_post = get_post( $id );
					if ( $page_post instanceof WP_Post && $legacy_demo_titles[ $key ] === $page_post->post_title && $def['title'] !== $page_post->post_title ) {
						wp_update_post( array( 'ID' => $id, 'post_title' => $def['title'] ) );
					}
				}

				// Keep a shortcode fallback for functional pages when Elementor is disabled.
				if ( isset( $def['fallback'] ) ) {
					$page_post = get_post( $id );
					if ( $page_post instanceof WP_Post && '' === trim( (string) $page_post->post_content ) ) {
						wp_update_post( array( 'ID' => $id, 'post_content' => (string) $def['fallback'] ) );
					}
				}
			}
		}
	}

	if ( $ids !== $stored_ids ) {
		update_option( 'shcd_muchwow_page_ids', $ids, false );
	}

	// Resolve cross-page links only after every managed ID is known.
	foreach ( $defs as $key => $def ) {
		if ( ! empty( $ids[ $key ] ) && ! empty( $def['template'] ) ) {
			$seeded = shabnam_muchwow_seed_elementor_page( (int) $ids[ $key ], $def['template'] );
			if ( $seeded ) {
				if ( 'demo' === $def['type'] ) {
					update_post_meta( (int) $ids[ $key ], '_shcd_muchwow_builder_schema', '3' );
				} else {
					update_post_meta( (int) $ids[ $key ], '_shcd_muchwow_inner_builder_schema', '2' );
				}
			}
		}
	}

	/*
	 * Keep a canonical /blog posts archive. The page itself is managed by the
	 * same idempotent registry above, so plugin/theme toggles can never create
	 * blog-2, blog-3, ... duplicates. If an older theme build created a
	 * dedicated posts page, reuse it only when it is the registered blog page;
	 * otherwise the canonical managed `blog` page becomes page_for_posts.
	 */
	$blog_page_id = ! empty( $ids['blog'] ) ? absint( $ids['blog'] ) : shabnam_muchwow_get_page_id( 'blog' );
	if ( $blog_page_id && 'page' === get_post_type( $blog_page_id ) && 'trash' !== get_post_status( $blog_page_id ) ) {
		$current_blog = absint( get_option( 'page_for_posts' ) );
		if ( $current_blog !== $blog_page_id ) {
			update_option( 'page_for_posts', $blog_page_id );
		}
		update_option( 'shcd_muchwow_blog_page_id', $blog_page_id, false );
	}

	if ( ! get_option( 'shcd_muchwow_multidemo_installed' ) ) {
		shabnam_muchwow_apply_home_demo( shabnam_muchwow_selected_demo() );
		update_option( 'shcd_muchwow_multidemo_installed', '1', false );
	}
}
add_action( 'init', 'shabnam_muchwow_install_pages', 90 );

/**
 * Trial edition cleanup: remove only the theme-managed pages that belong to
 * Pro-only home plans. User-created pages are never touched.
 */
function shabnam_muchwow_trial_remove_pro_pages() {
	if ( '1' === get_option( 'shcd_muchwow_trial_pro_pages_removed' ) ) {
		return;
	}

	$ids = shabnam_muchwow_page_ids();
	foreach ( array( 'demo-two', 'demo-three' ) as $key ) {
		$page_id = ! empty( $ids[ $key ] ) ? absint( $ids[ $key ] ) : shabnam_muchwow_find_registered_page( $key, false );
		if ( $page_id && get_post_meta( $page_id, '_shcd_muchwow_managed_page', true ) && $key === get_post_meta( $page_id, '_shcd_muchwow_page_key', true ) ) {
			wp_delete_post( $page_id, true );
		}
		unset( $ids[ $key ] );
	}
	update_option( 'shcd_muchwow_page_ids', $ids, false );

	$settings = get_option( 'shcd_shabnam_framework', array() );
	if ( is_array( $settings ) ) {
		$settings['home_demo'] = 'one';
		update_option( 'shcd_shabnam_framework', $settings, false );
	}

	shabnam_muchwow_apply_home_demo( 'one' );
	update_option( 'shcd_muchwow_trial_pro_pages_removed', '1', false );
}
add_action( 'init', 'shabnam_muchwow_trial_remove_pro_pages', 95 );


/**
 * Switch the actual WordPress front page to the requested demo page.
 *
 * @param string $demo one|two|three.
 * @return int Selected page ID.
 */
function shabnam_muchwow_apply_home_demo( $demo ) {
	$id = shabnam_muchwow_get_page_id( 'demo-one' );
	if ( $id ) {
		update_option( 'show_on_front', 'page' );
		update_option( 'page_on_front', $id );
	}
	return $id;
}

/**
 * Account URL used by the header icon.
 *
 * @return string
 */
function shabnam_muchwow_account_url() {
	if ( is_user_logged_in() ) {
		if ( function_exists( 'wc_get_page_permalink' ) ) {
			$url = wc_get_page_permalink( 'myaccount' );
			if ( $url ) {
				return $url;
			}
		}
		return admin_url( 'profile.php' );
	}
	return shabnam_muchwow_page_url( 'sign-in' );
}

/**
 * Build a safe feedback URL for auth forms.
 *
 * @param string $page_key Managed page key.
 * @param string $status Status token.
 * @return string
 */
function shabnam_muchwow_form_feedback_url( $page_key, $status ) {
	return add_query_arg( 'shcd_status', sanitize_key( $status ), shabnam_muchwow_page_url( $page_key ) );
}

/**
 * Feedback message renderer.
 *
 * @param string $context Form context.
 */
function shabnam_muchwow_render_form_feedback( $context ) {
	$status = isset( $_GET['shcd_status'] ) ? sanitize_key( wp_unslash( $_GET['shcd_status'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$messages = array(
		'login-failed'       => array( 'error', 'نام کاربری، ایمیل یا رمز عبور صحیح نیست.' ),
		'reg-disabled'       => array( 'error', 'ثبت‌نام در حال حاضر غیرفعال است.' ),
		'reg-invalid'        => array( 'error', 'اطلاعات واردشده کامل یا معتبر نیست.' ),
		'reg-exists'         => array( 'error', 'برای این ایمیل از قبل حساب کاربری وجود دارد.' ),
		'reg-password'       => array( 'error', 'رمز عبور و تکرار آن یکسان نیست.' ),
		'reg-success'        => array( 'success', 'حساب کاربری ساخته شد؛ اکنون می‌توانید وارد شوید.' ),
		'reset-sent'         => array( 'success', 'اگر حسابی با این مشخصات وجود داشته باشد، راهنمای بازیابی رمز عبور ارسال می‌شود.' ),
		'reset-invalid'      => array( 'error', 'ایمیل یا نام کاربری معتبر وارد کنید.' ),
		'contact-sent'       => array( 'success', 'پیام شما با موفقیت ارسال شد.' ),
		'contact-failed'     => array( 'error', 'ارسال پیام انجام نشد. لطفاً دوباره تلاش کنید.' ),
		'contact-invalid'    => array( 'error', 'نام، شماره تماس، ایمیل و متن پیام را به‌درستی وارد کنید.' ),
		'contact-rate'       => array( 'error', 'تعداد درخواست‌های شما در مدت کوتاه زیاد بوده است. چند دقیقه دیگر دوباره تلاش کنید.' ),
	);
	if ( $status && isset( $messages[ $status ] ) ) {
		$type = $messages[ $status ][0];
		$text = $messages[ $status ][1];
		echo '<div class="shabnam-form-notice is-' . esc_attr( $type ) . '">' . esc_html( $text ) . '</div>';
	}
}

/** Login form shortcode. */
function shabnam_muchwow_login_form() {
	ob_start();
	if ( is_user_logged_in() ) {
		echo '<div class="shabnam-auth-form panel text-center"><p>' . esc_html__( 'شما وارد حساب کاربری خود شده‌اید.', 'shabnam-muchwow' ) . '</p><a class="btn btn-secondary border border-2 border-black" href="' . esc_url( shabnam_muchwow_account_url() ) . '">' . esc_html__( 'مشاهده حساب کاربری', 'shabnam-muchwow' ) . '</a></div>';
		return ob_get_clean();
	}
	shabnam_muchwow_render_form_feedback( 'login' );
	?>
	<div class="panel w-100 sm:w-350px mx-auto shabnam-auth-form">
	<form class="vstack gap-2" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
		<input type="hidden" name="action" value="shcd_muchwow_login">
		<?php wp_nonce_field( 'shcd_muchwow_login', 'shcd_nonce' ); ?>
		<input class="form-control h-48px w-full bg-white text-black" name="login" placeholder="ایمیل یا نام کاربری" autocomplete="username" required>
		<input class="form-control h-48px w-full bg-white text-black" name="password" placeholder="رمز عبور" type="password" autocomplete="current-password" required>
		<div class="hstack justify-between gap-2 text-start"><label class="form-check"><input class="form-check-input" name="remember" value="1" type="checkbox"> <span class="form-check-label fs-6">مرا به خاطر بسپار</span></label><a class="uc-link border-bottom" href="<?php echo esc_url( shabnam_muchwow_page_url( 'reset-password' ) ); ?>">رمز عبور را فراموش کرده‌اید؟</a></div>
		<button class="btn btn-md btn-secondary border border-2 border-black contrast-shadow-sm mt-2" type="submit">ورود</button>
	</form>
	<p class="text-center mt-2">هنوز حساب کاربری ندارید؟ <a class="uc-link border-bottom" href="<?php echo esc_url( shabnam_muchwow_page_url( 'sign-up' ) ); ?>">ثبت‌نام</a></p>
	</div>
	<?php
	return ob_get_clean();
}
add_shortcode( 'shcd_login_form', 'shabnam_muchwow_login_form' );

/** Registration form shortcode. */
function shabnam_muchwow_register_form() {
	$enabled = function_exists( 'shabnam_get_setting' ) ? (bool) shabnam_get_setting( 'auth_registration_enabled', false ) : false;
	ob_start();
	shabnam_muchwow_render_form_feedback( 'register' );
	if ( ! $enabled ) {
		echo '<div class="shabnam-form-notice is-error">' . esc_html__( 'ثبت‌نام از تنظیمات پوسته غیرفعال است.', 'shabnam-muchwow' ) . '</div>';
		return ob_get_clean();
	}
	?>
	<div class="panel w-100 sm:w-350px mx-auto shabnam-auth-form">
	<form class="vstack gap-2" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
		<input type="hidden" name="action" value="shcd_muchwow_register">
		<?php wp_nonce_field( 'shcd_muchwow_register', 'shcd_nonce' ); ?>
		<input class="form-control h-48px w-full bg-white text-black" name="display_name" placeholder="نام و نام خانوادگی" required>
		<input class="form-control h-48px w-full bg-white text-black" name="email" placeholder="ایمیل شما" type="email" autocomplete="email" required>
		<input class="form-control h-48px w-full bg-white text-black" name="password" placeholder="رمز عبور" type="password" autocomplete="new-password" minlength="8" required>
		<input class="form-control h-48px w-full bg-white text-black" name="password_confirm" placeholder="تکرار رمز عبور" type="password" autocomplete="new-password" minlength="8" required>
		<label class="form-check text-start"><input class="form-check-input" name="terms" value="1" type="checkbox" required> <span class="form-check-label fs-6">شرایط استفاده و سیاست حریم خصوصی را می‌پذیرم.</span></label>
		<button class="btn btn-md btn-secondary border border-2 border-black contrast-shadow-sm mt-2" type="submit">ایجاد حساب کاربری</button>
	</form>
	<p class="text-center mt-2">قبلاً حساب کاربری ساخته‌اید؟ <a class="uc-link border-bottom" href="<?php echo esc_url( shabnam_muchwow_page_url( 'sign-in' ) ); ?>">ورود</a></p>
	</div>
	<?php
	return ob_get_clean();
}
add_shortcode( 'shcd_register_form', 'shabnam_muchwow_register_form' );

/** Reset-password form shortcode. */
function shabnam_muchwow_reset_password_form() {
	ob_start();
	shabnam_muchwow_render_form_feedback( 'reset' );
	?>
	<div class="panel w-100 sm:w-350px mx-auto shabnam-auth-form"><form class="vstack gap-2" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"><input type="hidden" name="action" value="shcd_muchwow_reset_password"><?php wp_nonce_field( 'shcd_muchwow_reset_password', 'shcd_nonce' ); ?><input class="form-control h-48px w-full bg-white text-black" name="user_login" placeholder="ایمیل یا نام کاربری" required><button class="btn btn-md btn-secondary border border-2 border-black contrast-shadow-sm mt-2" type="submit">بازیابی رمز عبور</button></form><p class="text-center mt-2">رمز عبور خود را به یاد دارید؟ <a class="uc-link border-bottom" href="<?php echo esc_url( shabnam_muchwow_page_url( 'sign-in' ) ); ?>">ورود</a></p></div>
	<?php
	return ob_get_clean();
}
add_shortcode( 'shcd_reset_password_form', 'shabnam_muchwow_reset_password_form' );

/** Contact form shortcode. */
function shabnam_muchwow_contact_form() {
	ob_start();
	shabnam_muchwow_render_form_feedback( 'contact' );
	?>
	<div class="shabnam-contact-shell">
		<div class="shabnam-contact-intro">
			<span class="shabnam-contact-kicker"><?php esc_html_e( 'ارتباط با تیم', 'shabnam-muchwow' ); ?></span>
			<h2><?php esc_html_e( 'پیام خود را برای ما بفرستید', 'shabnam-muchwow' ); ?></h2>
			<p><?php esc_html_e( 'نام، شماره تماس و توضیح کوتاهی از درخواستتان را وارد کنید. پیام در پنل مدیریت ثبت می‌شود تا پیگیری آن ساده و قابل رهگیری باشد.', 'shabnam-muchwow' ); ?></p>
		</div>
		<form class="shabnam-contact-form" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
			<input type="hidden" name="action" value="shcd_muchwow_contact">
			<?php wp_nonce_field( 'shcd_muchwow_contact', 'shcd_nonce' ); ?>
			<input name="website" tabindex="-1" autocomplete="off" class="shabnam-hp" aria-hidden="true">
			<div class="shabnam-form-grid">
				<label><span><?php esc_html_e( 'نام و نام خانوادگی', 'shabnam-muchwow' ); ?></span><input name="name" autocomplete="name" required></label>
				<label><span><?php esc_html_e( 'شماره تماس', 'shabnam-muchwow' ); ?></span><input name="phone" inputmode="tel" autocomplete="tel" placeholder="0912…" required></label>
				<label><span><?php esc_html_e( 'ایمیل', 'shabnam-muchwow' ); ?></span><input name="email" type="email" autocomplete="email" required></label>
				<label><span><?php esc_html_e( 'موضوع', 'shabnam-muchwow' ); ?></span><input name="subject" placeholder="موضوع پیام"></label>
			</div>
			<label class="shabnam-form-message"><span><?php esc_html_e( 'متن پیام', 'shabnam-muchwow' ); ?></span><textarea name="message" rows="6" placeholder="درخواست یا پرسش خود را بنویسید…" required></textarea></label>
			<button class="shabnam-contact-submit" type="submit"><span><?php esc_html_e( 'ثبت و ارسال پیام', 'shabnam-muchwow' ); ?></span><span aria-hidden="true">↗</span></button>
		</form>
	</div>
	<?php
	return ob_get_clean();
}
add_shortcode( 'shcd_contact_form', 'shabnam_muchwow_contact_form' );

/** Login handler. */
function shabnam_muchwow_handle_login() {
	check_admin_referer( 'shcd_muchwow_login', 'shcd_nonce' );
	$login    = isset( $_POST['login'] ) ? sanitize_text_field( wp_unslash( $_POST['login'] ) ) : '';
	$password = isset( $_POST['password'] ) ? (string) wp_unslash( $_POST['password'] ) : '';
	$remember = ! empty( $_POST['remember'] );
	$user = wp_signon( array( 'user_login' => $login, 'user_password' => $password, 'remember' => $remember ), is_ssl() );
	if ( is_wp_error( $user ) ) {
		wp_safe_redirect( shabnam_muchwow_form_feedback_url( 'sign-in', 'login-failed' ) );
		exit;
	}
	$destination = function_exists( 'shabnam_get_setting' ) && 'home' === shabnam_get_setting( 'auth_login_redirect', 'account' ) ? home_url( '/' ) : shabnam_muchwow_account_url();
	wp_safe_redirect( $destination );
	exit;
}
add_action( 'admin_post_nopriv_shcd_muchwow_login', 'shabnam_muchwow_handle_login' );
add_action( 'admin_post_shcd_muchwow_login', 'shabnam_muchwow_handle_login' );

/** Registration handler. */
function shabnam_muchwow_handle_register() {
	check_admin_referer( 'shcd_muchwow_register', 'shcd_nonce' );
	$enabled = function_exists( 'shabnam_get_setting' ) ? (bool) shabnam_get_setting( 'auth_registration_enabled', false ) : false;
	if ( ! $enabled ) {
		wp_safe_redirect( shabnam_muchwow_form_feedback_url( 'sign-up', 'reg-disabled' ) ); exit;
	}
	$email = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
	$name  = isset( $_POST['display_name'] ) ? sanitize_text_field( wp_unslash( $_POST['display_name'] ) ) : '';
	$pass  = isset( $_POST['password'] ) ? (string) wp_unslash( $_POST['password'] ) : '';
	$pass2 = isset( $_POST['password_confirm'] ) ? (string) wp_unslash( $_POST['password_confirm'] ) : '';
	if ( ! is_email( $email ) || '' === $name || strlen( $pass ) < 8 || empty( $_POST['terms'] ) ) {
		wp_safe_redirect( shabnam_muchwow_form_feedback_url( 'sign-up', 'reg-invalid' ) ); exit;
	}
	if ( $pass !== $pass2 ) {
		wp_safe_redirect( shabnam_muchwow_form_feedback_url( 'sign-up', 'reg-password' ) ); exit;
	}
	if ( email_exists( $email ) ) {
		wp_safe_redirect( shabnam_muchwow_form_feedback_url( 'sign-up', 'reg-exists' ) ); exit;
	}
	$base = sanitize_user( strstr( $email, '@', true ), true );
	$base = $base ? $base : 'user';
	$username = $base;
	$counter = 1;
	while ( username_exists( $username ) ) {
		$username = $base . $counter;
		++$counter;
	}
	$user_id = wp_create_user( $username, $pass, $email );
	if ( is_wp_error( $user_id ) ) {
		wp_safe_redirect( shabnam_muchwow_form_feedback_url( 'sign-up', 'reg-invalid' ) ); exit;
	}
	wp_update_user( array( 'ID' => $user_id, 'display_name' => $name, 'nickname' => $name ) );
	wp_safe_redirect( shabnam_muchwow_form_feedback_url( 'sign-in', 'reg-success' ) ); exit;
}
add_action( 'admin_post_nopriv_shcd_muchwow_register', 'shabnam_muchwow_handle_register' );

/** Reset-password handler. */
function shabnam_muchwow_handle_reset_password() {
	check_admin_referer( 'shcd_muchwow_reset_password', 'shcd_nonce' );
	$login = isset( $_POST['user_login'] ) ? sanitize_text_field( wp_unslash( $_POST['user_login'] ) ) : '';
	if ( '' === $login ) {
		wp_safe_redirect( shabnam_muchwow_form_feedback_url( 'reset-password', 'reset-invalid' ) ); exit;
	}
	// retrieve_password() intentionally returns a generic result to avoid account enumeration.
	$result = retrieve_password( $login );
	$status = is_wp_error( $result ) ? 'reset-sent' : 'reset-sent';
	wp_safe_redirect( shabnam_muchwow_form_feedback_url( 'reset-password', $status ) ); exit;
}
add_action( 'admin_post_nopriv_shcd_muchwow_reset_password', 'shabnam_muchwow_handle_reset_password' );

/** Contact handler. */
function shabnam_muchwow_handle_contact() {
	check_admin_referer( 'shcd_muchwow_contact', 'shcd_nonce' );
	if ( ! empty( $_POST['website'] ) ) {
		wp_safe_redirect( shabnam_muchwow_form_feedback_url( 'contact', 'contact-sent' ) );
		exit;
	}

	$remote_ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
	$rate_key  = 'shcd_contact_' . substr( wp_hash( $remote_ip ), 0, 20 );
	$rate_hits = absint( get_transient( $rate_key ) );
	if ( $rate_hits >= 5 ) {
		wp_safe_redirect( shabnam_muchwow_form_feedback_url( 'contact', 'contact-rate' ) );
		exit;
	}

	$name    = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
	$phone   = isset( $_POST['phone'] ) ? sanitize_text_field( wp_unslash( $_POST['phone'] ) ) : '';
	$email   = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
	$subject = isset( $_POST['subject'] ) ? sanitize_text_field( wp_unslash( $_POST['subject'] ) ) : '';
	$message = isset( $_POST['message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['message'] ) ) : '';
	$phone_compact = strtr( $phone, array( '۰' => '0', '۱' => '1', '۲' => '2', '۳' => '3', '۴' => '4', '۵' => '5', '۶' => '6', '۷' => '7', '۸' => '8', '۹' => '9', '٠' => '0', '١' => '1', '٢' => '2', '٣' => '3', '٤' => '4', '٥' => '5', '٦' => '6', '٧' => '7', '٨' => '8', '٩' => '9' ) );
	$phone_compact = preg_replace( '/[^0-9+]/', '', $phone_compact );

	if ( '' === $name || ! is_email( $email ) || '' === $message || ! is_string( $phone_compact ) || strlen( $phone_compact ) < 7 || strlen( $phone_compact ) > 18 ) {
		wp_safe_redirect( shabnam_muchwow_form_feedback_url( 'contact', 'contact-invalid' ) );
		exit;
	}

	$post_id = wp_insert_post(
		array(
			'post_type'    => 'shcd_contact_message',
			'post_status'  => 'publish',
			'post_title'   => wp_trim_words( $name . ' — ' . $phone, 12, '' ),
			'post_content' => $message,
		),
		true
	);

	if ( is_wp_error( $post_id ) || ! $post_id ) {
		wp_safe_redirect( shabnam_muchwow_form_feedback_url( 'contact', 'contact-failed' ) );
		exit;
	}

	update_post_meta( $post_id, '_shcd_contact_name', $name );
	update_post_meta( $post_id, '_shcd_contact_phone', $phone );
	update_post_meta( $post_id, '_shcd_contact_phone_normalized', $phone_compact );
	update_post_meta( $post_id, '_shcd_contact_email', $email );
	update_post_meta( $post_id, '_shcd_contact_subject', $subject );
	update_post_meta( $post_id, '_shcd_contact_unread', '1' );
	update_post_meta( $post_id, '_shcd_contact_ip_hash', wp_hash( $remote_ip ) );
	set_transient( $rate_key, $rate_hits + 1, 10 * MINUTE_IN_SECONDS );

	// Email is a secondary notification channel; the message remains safely stored even if mail delivery fails.
	$to           = sanitize_email( get_option( 'admin_email' ) );
	$mail_subject = $subject ? $subject : __( 'پیام جدید از فرم تماس سایت', 'shabnam-muchwow' );
	$body         = "نام: {$name}\nشماره تماس: {$phone}\nایمیل: {$email}\n\n{$message}";
	$headers      = array( 'Reply-To: ' . $name . ' <' . $email . '>' );
	wp_mail( $to, $mail_subject, $body, $headers );

	wp_safe_redirect( shabnam_muchwow_form_feedback_url( 'contact', 'contact-sent' ) );
	exit;
}
add_action( 'admin_post_nopriv_shcd_muchwow_contact', 'shabnam_muchwow_handle_contact' );
add_action( 'admin_post_shcd_muchwow_contact', 'shabnam_muchwow_handle_contact' );

/**
 * Upgrade demo pages created by earlier theme builds to the native editable
 * section widgets. A backup of the previous Elementor document is kept in
 * post meta before migration, so the operation is reversible by a developer.
 */
function shabnam_muchwow_upgrade_demo_builder_schema() {
	$defs    = shabnam_muchwow_page_definitions();
	$changed = false;

	foreach ( array( 'demo-one' ) as $key ) {
		if ( empty( $defs[ $key ] ) ) {
			continue;
		}
		$page_id = shabnam_muchwow_get_page_id( $key );
		if ( ! $page_id || ! get_post_meta( $page_id, '_shcd_muchwow_managed_page', true ) ) {
			continue;
		}

		$page_schema = absint( get_post_meta( $page_id, '_shcd_muchwow_builder_schema', true ) );
		if ( $page_schema >= 3 ) {
			continue;
		}

		$raw = (string) get_post_meta( $page_id, '_elementor_data', true );
		if ( '' === trim( $raw ) ) {
			continue;
		}

		/*
		 * Older builds placed whole source-code blocks inside Elementor. The new
		 * schema uses native MuchWOW section widgets with explicit text/image/link
		 * controls. Only pages created by this theme are migrated automatically.
		 */
		$is_legacy = false !== strpos( $raw, '"widgetType":"html"' ) || false === strpos( $raw, '"widgetType":"shabnam-muchwow-demo-section"' );
		if ( ! $is_legacy ) {
			update_post_meta( $page_id, '_shcd_muchwow_builder_schema', '3' );
			continue;
		}

		$template = trailingslashit( get_template_directory() ) . 'elementor-templates/' . sanitize_file_name( $defs[ $key ]['template'] );
		if ( ! is_readable( $template ) ) {
			continue;
		}
		$new_json = file_get_contents( $template ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
		if ( ! is_string( $new_json ) || '' === trim( $new_json ) ) {
			continue;
		}
		$new_json = shabnam_muchwow_resolve_elementor_placeholders( $new_json );
		$decoded  = json_decode( $new_json, true );
		if ( JSON_ERROR_NONE !== json_last_error() || ! is_array( $decoded ) ) {
			continue;
		}

		if ( ! metadata_exists( 'post', $page_id, '_shcd_muchwow_legacy_builder_backup' ) ) {
			add_post_meta( $page_id, '_shcd_muchwow_legacy_builder_backup', wp_slash( $raw ), true );
		}
		update_post_meta( $page_id, '_elementor_data', wp_slash( wp_json_encode( $decoded ) ) );
		update_post_meta( $page_id, '_shcd_muchwow_builder_schema', '3' );
		$changed = true;
	}

	update_option( 'shcd_muchwow_demo_builder_schema', 3, false );
	if ( $changed && function_exists( 'shabnam_elementor_is_available' ) && 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_muchwow_upgrade_demo_builder_schema', 120 );


/**
 * Bring theme-managed inner pages to the current native Elementor structure.
 * Existing user-created pages are never touched. Each legacy document is
 * backed up once before migration, then a per-page schema marker prevents any
 * repeat overwrite on later theme/plugin activations.
 */
function shabnam_muchwow_upgrade_inner_page_schema() {
	$defs    = shabnam_muchwow_page_definitions();
	$changed = false;

	foreach ( array( 'sign-in', 'sign-up', 'reset-password', 'contact', 'privacy', 'terms' ) as $key ) {
		if ( empty( $defs[ $key ]['template'] ) ) {
			continue;
		}
		$page_id = shabnam_muchwow_get_page_id( $key );
		if ( ! $page_id || ! get_post_meta( $page_id, '_shcd_muchwow_managed_page', true ) ) {
			continue;
		}
		if ( absint( get_post_meta( $page_id, '_shcd_muchwow_inner_builder_schema', true ) ) >= 2 ) {
			continue;
		}

		$template = trailingslashit( get_template_directory() ) . 'elementor-templates/' . sanitize_file_name( $defs[ $key ]['template'] );
		if ( ! is_readable( $template ) ) {
			continue;
		}
		$new_json = file_get_contents( $template ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
		if ( ! is_string( $new_json ) || '' === trim( $new_json ) ) {
			continue;
		}
		$new_json = shabnam_muchwow_resolve_elementor_placeholders( $new_json );
		$decoded  = json_decode( $new_json, true );
		if ( JSON_ERROR_NONE !== json_last_error() || ! is_array( $decoded ) ) {
			continue;
		}

		$raw = (string) get_post_meta( $page_id, '_elementor_data', true );
		if ( '' !== trim( $raw ) && ! metadata_exists( 'post', $page_id, '_shcd_muchwow_legacy_inner_backup' ) ) {
			add_post_meta( $page_id, '_shcd_muchwow_legacy_inner_backup', wp_slash( $raw ), true );
		}
		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( 'hide_title' => 'yes' ) );
		update_post_meta( $page_id, '_elementor_data', wp_slash( wp_json_encode( $decoded ) ) );
		update_post_meta( $page_id, '_shcd_muchwow_inner_builder_schema', '2' );
		$changed = true;
	}

	update_option( 'shcd_muchwow_inner_builder_schema', 2, false );
	if ( $changed && function_exists( 'shabnam_elementor_is_available' ) && 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_muchwow_upgrade_inner_page_schema', 125 );

/**
 * Register the internal contact inbox. Messages are never public.
 */
function shabnam_muchwow_register_contact_inbox() {
	$capabilities = array(
		'edit_post'              => 'manage_options',
		'read_post'              => 'manage_options',
		'delete_post'            => 'manage_options',
		'edit_posts'             => 'manage_options',
		'edit_others_posts'      => 'manage_options',
		'publish_posts'          => 'manage_options',
		'read_private_posts'     => 'manage_options',
		'delete_posts'           => 'manage_options',
		'delete_private_posts'   => 'manage_options',
		'delete_published_posts' => 'manage_options',
		'delete_others_posts'    => 'manage_options',
		'edit_private_posts'     => 'manage_options',
		'edit_published_posts'   => 'manage_options',
		'create_posts'           => 'do_not_allow',
	);
	register_post_type(
		'shcd_contact_message',
		array(
			'labels' => array(
				'name'          => __( 'پیام‌های تماس', 'shabnam-muchwow' ),
				'singular_name' => __( 'پیام تماس', 'shabnam-muchwow' ),
				'menu_name'     => __( 'پیام‌های تماس', 'shabnam-muchwow' ),
				'edit_item'     => __( 'مشاهده پیام تماس', 'shabnam-muchwow' ),
				'not_found'     => __( 'هنوز پیامی ثبت نشده است.', 'shabnam-muchwow' ),
			),
			'public'              => false,
			'publicly_queryable'  => false,
			'exclude_from_search' => true,
			'show_ui'             => true,
			'show_in_menu'        => 'shcd-muchwow-theme',
			'show_in_admin_bar'   => false,
			'show_in_rest'        => false,
			'map_meta_cap'        => false,
			'capabilities'        => $capabilities,
			'supports'            => array( 'title' ),
			'menu_icon'           => 'dashicons-email-alt2',
		)
	);
}
add_action( 'init', 'shabnam_muchwow_register_contact_inbox', 20 );

/** Return number of unread contact messages. */
function shabnam_muchwow_unread_contact_count() {
	$query = new WP_Query(
		array(
			'post_type'              => 'shcd_contact_message',
			'post_status'            => 'publish',
			'posts_per_page'         => 1,
			'fields'                 => 'ids',
			'no_found_rows'          => false,
			'update_post_meta_cache' => false,
			'update_post_term_cache' => false,
			'meta_key'               => '_shcd_contact_unread',
			'meta_value'             => '1',
		)
	);
	return absint( $query->found_posts );
}

/** Add unread badge to the contact submenu generated by the post type. */
function shabnam_muchwow_contact_menu_badge() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	$count = shabnam_muchwow_unread_contact_count();
	if ( $count < 1 ) {
		return;
	}
	global $menu, $submenu;
	$badge = ' <span class="awaiting-mod count-' . absint( $count ) . '"><span class="pending-count">' . absint( $count ) . '</span></span>';

	if ( ! empty( $submenu['shcd-muchwow-theme'] ) && is_array( $submenu['shcd-muchwow-theme'] ) ) {
		foreach ( $submenu['shcd-muchwow-theme'] as &$item ) {
			if ( isset( $item[2] ) && 'edit.php?post_type=shcd_contact_message' === $item[2] ) {
				$item[0] .= $badge;
				break;
			}
		}
		unset( $item );
	}

	if ( is_array( $menu ) ) {
		foreach ( $menu as &$top_item ) {
			if ( isset( $top_item[2] ) && 'shcd-muchwow-theme' === $top_item[2] ) {
				$top_item[0] .= $badge;
				break;
			}
		}
		unset( $top_item );
	}
}
add_action( 'admin_menu', 'shabnam_muchwow_contact_menu_badge', 999 );

/** Admin-bar notification for unread messages. */
function shabnam_muchwow_contact_admin_bar_notice( $bar ) {
	if ( ! is_admin_bar_showing() || ! current_user_can( 'manage_options' ) ) {
		return;
	}
	$count = shabnam_muchwow_unread_contact_count();
	if ( $count < 1 ) {
		return;
	}
	$bar->add_node(
		array(
			'id'    => 'shcd-contact-inbox',
			'title' => '<span class="ab-icon dashicons dashicons-email-alt2"></span><span class="ab-label">' . esc_html( sprintf( __( '%d پیام جدید', 'shabnam-muchwow' ), $count ) ) . '</span>',
			'href'  => admin_url( 'edit.php?post_type=shcd_contact_message' ),
		)
	);
}
add_action( 'admin_bar_menu', 'shabnam_muchwow_contact_admin_bar_notice', 85 );

/** Dashboard notice for unread messages. */
function shabnam_muchwow_contact_admin_notice() {
	if ( ! current_user_can( 'manage_options' ) || get_current_screen() && 'shcd_contact_message' === get_current_screen()->post_type ) {
		return;
	}
	$count = shabnam_muchwow_unread_contact_count();
	if ( $count < 1 ) {
		return;
	}
	printf(
		'<div class="notice notice-info"><p><strong>%1$s</strong> <a href="%2$s">%3$s</a></p></div>',
		esc_html( sprintf( _n( 'یک پیام تماس جدید دارید.', '%d پیام تماس جدید دارید.', $count, 'shabnam-muchwow' ), $count ) ),
		esc_url( admin_url( 'edit.php?post_type=shcd_contact_message' ) ),
		esc_html__( 'مشاهده پیام‌ها', 'shabnam-muchwow' )
	);
}
add_action( 'admin_notices', 'shabnam_muchwow_contact_admin_notice' );

/** Mark a message as read when an administrator opens it. */
function shabnam_muchwow_mark_contact_read() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	$post_id = isset( $_GET['post'] ) ? absint( $_GET['post'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
	if ( $post_id && 'shcd_contact_message' === get_post_type( $post_id ) ) {
		update_post_meta( $post_id, '_shcd_contact_unread', '0' );
	}
}
add_action( 'load-post.php', 'shabnam_muchwow_mark_contact_read' );

/** Contact inbox columns. */
function shabnam_muchwow_contact_columns( $columns ) {
	return array(
		'cb'      => isset( $columns['cb'] ) ? $columns['cb'] : '<input type="checkbox">',
		'title'   => __( 'فرستنده', 'shabnam-muchwow' ),
		'phone'   => __( 'شماره تماس', 'shabnam-muchwow' ),
		'email'   => __( 'ایمیل', 'shabnam-muchwow' ),
		'subject' => __( 'موضوع', 'shabnam-muchwow' ),
		'status'  => __( 'وضعیت', 'shabnam-muchwow' ),
		'date'    => __( 'زمان ثبت', 'shabnam-muchwow' ),
	);
}
add_filter( 'manage_shcd_contact_message_posts_columns', 'shabnam_muchwow_contact_columns' );

function shabnam_muchwow_contact_column_content( $column, $post_id ) {
	if ( 'phone' === $column ) {
		echo esc_html( get_post_meta( $post_id, '_shcd_contact_phone', true ) );
	} elseif ( 'email' === $column ) {
		$email = sanitize_email( get_post_meta( $post_id, '_shcd_contact_email', true ) );
		echo $email ? '<a href="mailto:' . esc_attr( $email ) . '">' . esc_html( $email ) . '</a>' : '—';
	} elseif ( 'subject' === $column ) {
		echo esc_html( get_post_meta( $post_id, '_shcd_contact_subject', true ) ?: '—' );
	} elseif ( 'status' === $column ) {
		$unread = '1' === (string) get_post_meta( $post_id, '_shcd_contact_unread', true );
		echo '<span class="shcd-message-status ' . ( $unread ? 'is-unread' : 'is-read' ) . '">' . esc_html( $unread ? __( 'جدید', 'shabnam-muchwow' ) : __( 'خوانده‌شده', 'shabnam-muchwow' ) ) . '</span>';
	}
}
add_action( 'manage_shcd_contact_message_posts_custom_column', 'shabnam_muchwow_contact_column_content', 10, 2 );

/** Read-only details box for a stored message. */
function shabnam_muchwow_contact_meta_boxes() {
	add_meta_box( 'shcd-contact-details', __( 'جزئیات پیام', 'shabnam-muchwow' ), 'shabnam_muchwow_contact_details_box', 'shcd_contact_message', 'normal', 'high' );
}
add_action( 'add_meta_boxes_shcd_contact_message', 'shabnam_muchwow_contact_meta_boxes' );

function shabnam_muchwow_contact_details_box( $post ) {
	$name    = get_post_meta( $post->ID, '_shcd_contact_name', true );
	$phone   = get_post_meta( $post->ID, '_shcd_contact_phone', true );
	$email   = get_post_meta( $post->ID, '_shcd_contact_email', true );
	$subject = get_post_meta( $post->ID, '_shcd_contact_subject', true );
	?>
	<div class="shcd-contact-admin-card" dir="rtl">
		<p><strong><?php esc_html_e( 'نام:', 'shabnam-muchwow' ); ?></strong> <?php echo esc_html( $name ); ?></p>
		<p><strong><?php esc_html_e( 'شماره تماس:', 'shabnam-muchwow' ); ?></strong> <a href="tel:<?php echo esc_attr( get_post_meta( $post->ID, '_shcd_contact_phone_normalized', true ) ?: preg_replace( '/[^0-9+]/', '', $phone ) ); ?>"><?php echo esc_html( $phone ); ?></a></p>
		<p><strong><?php esc_html_e( 'ایمیل:', 'shabnam-muchwow' ); ?></strong> <a href="mailto:<?php echo esc_attr( $email ); ?>"><?php echo esc_html( $email ); ?></a></p>
		<p><strong><?php esc_html_e( 'موضوع:', 'shabnam-muchwow' ); ?></strong> <?php echo esc_html( $subject ?: '—' ); ?></p>
		<hr>
		<div class="shcd-contact-message-body"><?php echo nl2br( esc_html( $post->post_content ) ); ?></div>
	</div>
	<?php
}

/**
 * Small visual layer for the private contact inbox.
 */
function shabnam_muchwow_contact_admin_styles() {
	if ( ! is_admin() || ! function_exists( 'get_current_screen' ) ) {
		return;
	}
	$screen = get_current_screen();
	if ( ! $screen || 'shcd_contact_message' !== $screen->post_type ) {
		return;
	}
	$font_url = esc_url( get_template_directory_uri() . '/assets/fonts/Shabnam-FD.woff2' );
	?>
	<style>
	@font-face{font-family:"SHCD Shabnam Admin";src:url("<?php echo $font_url; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>") format("woff2");font-display:swap}
	.post-type-shcd_contact_message #wpbody-content,.post-type-shcd_contact_message #wpbody-content input,.post-type-shcd_contact_message #wpbody-content button,.post-type-shcd_contact_message #wpbody-content select{font-family:"SHCD Shabnam Admin",Tahoma,sans-serif}
	.shcd-message-status{display:inline-flex;align-items:center;justify-content:center;min-width:70px;padding:4px 9px;border-radius:999px;font-weight:800;font-size:12px}.shcd-message-status.is-unread{background:#ede1ff;color:#54208e}.shcd-message-status.is-read{background:#e8f7ee;color:#17623a}
	.shcd-contact-admin-card{padding:16px;border:1px solid #dfd4ef;border-radius:16px;background:linear-gradient(145deg,#fff,#f8f3ff);box-shadow:0 12px 30px rgba(70,35,105,.08)}.shcd-contact-admin-card p{font-size:14px}.shcd-contact-message-body{margin-top:12px;padding:14px;border-radius:12px;background:#fff;line-height:2;font-size:14px}
	</style>
	<?php
}
add_action( 'admin_head', 'shabnam_muchwow_contact_admin_styles' );
