<?php
/** Reusable store theme helpers. @package Fragrance_Trade */

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

function fragrance_trade_get_default( $key, $fallback = '' ) {
	$defaults = fragrance_trade_defaults();
	return array_key_exists( $key, $defaults ) ? $defaults[ $key ] : $fallback;
}

function fragrance_trade_get_mod( $key, $fallback = null ) {
	$default = null === $fallback ? fragrance_trade_get_default( $key ) : $fallback;
	return get_theme_mod( $key, $default );
}

function fragrance_trade_resolve_url( $url ) {
	$url = trim( (string) $url );
	if ( str_starts_with( $url, '/' ) && ! str_starts_with( $url, '//' ) ) {
		return home_url( $url );
	}
	return $url;
}

function fragrance_trade_asset_uri( $relative_path ) {
	return trailingslashit( get_template_directory_uri() ) . 'assets/' . ltrim( $relative_path, '/' );
}

function fragrance_trade_image_uri( $setting, $fallback_filename ) {
	$image = fragrance_trade_get_mod( $setting, '' );
	return $image ? $image : fragrance_trade_asset_uri( 'images/' . $fallback_filename );
}

/**
 * Return the horizontal image used by service cards and carousels.
 *
 * Product seeds use a dedicated landscape cover while their featured image
 * remains the complete parameter poster shown on the service detail page.
 *
 * @param int    $post_id           Service post ID.
 * @param string $fallback_filename Asset path below assets/images/.
 * @return string
 */
function fragrance_trade_service_card_image( $post_id, $fallback_filename = 'products/placeholder-01.svg' ) {
	$post_id    = absint( $post_id );
	$image_attr = array(
		'class'    => 'img-fluid',
		'loading'  => 'lazy',
		'decoding' => 'async',
	);
	$cover_id   = absint( get_post_meta( $post_id, '_fragrance_service_cover_id', true ) );

	if ( $cover_id ) {
		$image = wp_get_attachment_image( $cover_id, 'large', false, $image_attr );
		if ( $image ) {
			return $image;
		}
	}

	$cover_file = (string) get_post_meta( $post_id, '_fragrance_service_cover_file', true );
	if ( ! $cover_file && function_exists( 'fragrance_trade_product_service_seeds' ) ) {
		$seeds    = fragrance_trade_product_service_seeds();
		$seed_key = (string) get_post_meta( $post_id, '_fragrance_product_seed_key', true );

		if ( $seed_key && isset( $seeds[ $seed_key ]['cover'] ) ) {
			$cover_file = $seeds[ $seed_key ]['cover'];
		} else {
			$post_slug = (string) get_post_field( 'post_name', $post_id );
			foreach ( $seeds as $seed ) {
				if ( $post_slug === $seed['slug'] && ! empty( $seed['cover'] ) ) {
					$cover_file = $seed['cover'];
					break;
				}
			}
		}
	}

	if (
		$cover_file
		&& preg_match( '#^[a-zA-Z0-9/_-]+\.(?:jpe?g|png|webp)$#', $cover_file )
		&& is_readable( get_template_directory() . '/assets/images/services/' . $cover_file )
	) {
		return sprintf(
			'<img src="%1$s" alt="%2$s" class="img-fluid" width="1448" height="1086" loading="lazy" decoding="async">',
			esc_url( fragrance_trade_asset_uri( 'images/services/' . $cover_file ) ),
			esc_attr( get_the_title( $post_id ) )
		);
	}

	if ( has_post_thumbnail( $post_id ) ) {
		return (string) get_the_post_thumbnail( $post_id, 'fragrance-capability', $image_attr );
	}

	$legacy_image = get_post_meta( $post_id, '_service_image', true );
	return sprintf(
		'<img src="%1$s" alt="%2$s" class="img-fluid" loading="lazy" decoding="async">',
		esc_url( $legacy_image ? $legacy_image : fragrance_trade_asset_uri( 'images/' . ltrim( $fallback_filename, '/' ) ) ),
		esc_attr( get_the_title( $post_id ) )
	);
}

function fragrance_trade_show_section( $setting ) {
	return (bool) fragrance_trade_get_mod( $setting, true );
}

function fragrance_trade_whatsapp_number() {
	return preg_replace( '/[^0-9]/', '', (string) fragrance_trade_get_mod( 'whatsapp', '' ) );
}

function fragrance_trade_inquiry_email() {
	$email = sanitize_email( fragrance_trade_get_mod( 'inquiry_email', '' ) );
	return is_email( $email ) ? $email : sanitize_email( get_option( 'admin_email' ) );
}

function fragrance_trade_get_inquiry_url( $project = '' ) {
	$message = $project
		? sprintf( __( '您好，我想咨询 %s 的贴膜服务。', 'fragrance-trade' ), $project )
		: __( '您好，我想咨询汽车贴膜服务。', 'fragrance-trade' );
	$number = fragrance_trade_whatsapp_number();
	if ( $number ) {
		return add_query_arg( 'text', $message, 'https://wa.me/' . $number );
	}
	return 'mailto:' . antispambot( fragrance_trade_inquiry_email() ) . '?subject=' . rawurlencode( __( '汽车贴膜服务咨询', 'fragrance-trade' ) ) . '&body=' . rawurlencode( $message );
}

/** Return the configured WordPress posts-page URL with a stable fresh-site fallback. */
function fragrance_trade_news_url() {
	$posts_page_id = absint( get_option( 'page_for_posts', 0 ) );
	$posts_page    = $posts_page_id ? get_post( $posts_page_id ) : null;
	if ( $posts_page && 'page' === $posts_page->post_type ) {
		$url = get_permalink( $posts_page_id );
		if ( $url ) {
			return $url;
		}
	}
	return home_url( '/news/' );
}

/** Keep news grids aligned without changing the site's global reading option. */
function fragrance_trade_news_posts_per_page( $query ) {
	if ( is_admin() || ! $query->is_main_query() || $query->is_feed() ) {
		return;
	}
	if ( $query->is_home() || $query->is_category() || $query->is_tag() || $query->is_date() || $query->is_author() ) {
		$query->set( 'posts_per_page', 9 );
	}
}
add_action( 'pre_get_posts', 'fragrance_trade_news_posts_per_page' );

function fragrance_trade_primary_menu_fallback() {
	$links = array(
		array( 'label' => __( '首页', 'fragrance-trade' ), 'url' => home_url( '/' ) ),
		array( 'label' => __( '服务项目', 'fragrance-trade' ), 'url' => get_post_type_archive_link( 'service' ) ?: home_url( '/services/' ) ),
		array( 'label' => __( '案例作品', 'fragrance-trade' ), 'url' => get_post_type_archive_link( 'case' ) ?: home_url( '/cases/' ) ),
		array( 'label' => __( '新闻资讯', 'fragrance-trade' ), 'url' => fragrance_trade_news_url() ),
		array( 'label' => __( '关于门店', 'fragrance-trade' ), 'url' => home_url( '/about/' ) ),
		array( 'label' => __( '常见问题', 'fragrance-trade' ), 'url' => home_url( '/faq/' ) ),
		array( 'label' => __( '联系我们', 'fragrance-trade' ), 'url' => home_url( '/contact/' ) ),
	);

	echo '<ul class="navbar-nav justify-content-end flex-grow-1 gap-xl-4 pe-xl-3">';
	foreach ( $links as $link ) {
		printf(
			'<li class="nav-item"><a class="nav-link" href="%s">%s</a></li>',
			esc_url( $link['url'] ),
			esc_html( $link['label'] )
		);
	}
	echo '</ul>';
}

add_action(
	'admin_notices',
	function () {
		if ( ! current_user_can( 'edit_theme_options' ) ) {
			return;
		}

		$locations = get_nav_menu_locations();
		$menu_id   = isset( $locations['primary'] ) ? $locations['primary'] : 0;
		if ( ! $menu_id ) {
			printf(
				'<div class="notice notice-warning is-dismissible"><p><strong>%s</strong> %s <a href="%s">%s</a></p></div>',
				esc_html__( '尚未分配主导航菜单', 'fragrance-trade' ),
				esc_html__( '前台暂时显示主题默认导航。请创建正式菜单并分配到“主导航”。', 'fragrance-trade' ),
				esc_url( admin_url( 'nav-menus.php' ) ),
				esc_html__( '配置菜单', 'fragrance-trade' )
			);
			return;
		}
		$items = wp_get_nav_menu_items( $menu_id );
		$count = $items ? count( $items ) : 0;
		if ( $count < 2 ) {
			printf(
				'<div class="notice notice-warning is-dismissible"><p><strong>%s</strong> %s <a href="%s">%s</a></p></div>',
				esc_html__( '主导航菜单项过少', 'fragrance-trade' ),
				esc_html__( '手机端和桌面端导航目前只显示一个菜单项。请前往后台添加：首页、服务项目、案例作品、新闻资讯、关于门店、常见问题、联系我们。', 'fragrance-trade' ),
				esc_url( admin_url( 'nav-menus.php' ) ),
				esc_html__( '编辑菜单', 'fragrance-trade' )
			);
		}

		$news_page_id = absint( get_option( 'page_for_posts', 0 ) );
		$news_page    = $news_page_id ? get_post( $news_page_id ) : null;
		if ( ! $news_page || 'publish' !== $news_page->post_status ) {
			return;
		}

		$news_url      = untrailingslashit( fragrance_trade_news_url() );
		$has_news_link = false;
		foreach ( (array) $items as $item ) {
			if (
				( 'page' === $item->object && $news_page_id === (int) $item->object_id )
				|| $news_url === untrailingslashit( $item->url )
			) {
				$has_news_link = true;
				break;
			}
		}
		if ( ! $has_news_link ) {
			printf(
				'<div class="notice notice-warning is-dismissible"><p><strong>%s</strong> %s <a href="%s">%s</a></p></div>',
				esc_html__( '主导航尚未包含新闻资讯', 'fragrance-trade' ),
				esc_html__( '主题不会自动修改已分配的菜单，请将 WordPress 文章页添加到“主导航”。', 'fragrance-trade' ),
				esc_url( admin_url( 'nav-menus.php' ) ),
				esc_html__( '编辑菜单', 'fragrance-trade' )
			);
		}
	}
);
