<?php
/**
 * Footer context: single entry for all footer template data.
 *
 * @package PufferGo
 */

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

/**
 * Contact channel types (same as SiteProfileForm CONTACT_CHANNEL_TYPES).
 *
 * @return array List of type values: WhatsApp, WeChat, LinkedIn, Facebook, Twitter, YouTube, Other.
 */
function puffergo_get_contact_channel_types() {
	return array( 'WhatsApp', 'WeChat', 'LinkedIn', 'Facebook', 'Twitter', 'YouTube', 'Other' );
}

/**
 * Map channel type to icon slug for templates (SVG/custom per type).
 *
 * @param string $type Channel type from site profile (e.g. LinkedIn, Facebook).
 * @return string Icon slug: linkedin, facebook, twitter, youtube, whatsapp, or link.
 */
function puffergo_footer_channel_icon_slug( $type ) {
	$map = array(
		'LinkedIn'         => 'linkedin',
		'Facebook'         => 'facebook',
		'Twitter'           => 'twitter',
		'YouTube'          => 'youtube',
		'WhatsApp'         => 'whatsapp',
		'WeChat'           => 'link',
		'Other'            => 'link',
	);
	return isset( $map[ $type ] ) ? $map[ $type ] : 'link';
}

/**
 * Build href for a contact channel value (URL, tel:, or relative from home).
 * Used by all footer templates; value comes from site profile contact.channels[].value.
 *
 * @param string $value Raw value (URL, phone number, or path).
 * @param string $home  Home URL with trailing slash.
 * @return string Safe href.
 */
function puffergo_footer_channel_href( $value, $home ) {
	$value = trim( (string) $value );
	if ( $value === '' ) {
		return $home;
	}
	if ( strpos( $value, 'http' ) === 0 || strpos( $value, '//' ) !== false ) {
		return $value;
	}
	if ( preg_match( '/^[0-9+\-\s\(\)]+$/', $value ) ) {
		return 'tel:' . $value;
	}
	return $home . ltrim( $value, '/' );
}

/**
 * Get footer context for template use.
 *
 * Reads PufferGo footer nav menu (classic menu location), site profile (contact),
 * and merges with logo/brand so all footer variants share one data shape.
 * Footer menu mapping:
 * - Top-level items: section titles
 * - Children: links under each section
 *
 * contact_channels items include type, value, href (unified), and icon (slug for templates).
 *
 * @return array {
 *   sections          array Footer sections from nav menu.
 *   copyright_text    string Copyright line from option (may be empty).
 *   home_url          string Home URL with trailing slash.
 *   year              string Current year (GMT).
 *   brand_name        string Brand or site name.
 *   logo_url          string Logo URL（由站点信息 assets.logo_attachment_id 派生）。
 *   contact_email     string From site profile contact.email.
 *   contact_phone     string From site profile contact.phone.
 *   contact_address   string From site profile contact.address.
 *   contact_channels  array List of { type, value, href, icon } from site profile contact.channels.
 * }
 */
function puffergo_get_footer_context() {
	$sections  = puffergo_get_footer_sections_from_menu();
	$copyright = (string) get_option( 'puffergo_site_footer_copyright', '' );

	$home        = trailingslashit( home_url( '/' ) );
	$year        = gmdate( 'Y' );

	// 品牌信息统一来自共享入口，不再单独读 option（缓存已在 puffergo_get_site_brand_identity() 内）。
	$brand      = puffergo_get_site_brand_identity();
	$brand_name = $brand['brand_name'];
	$logo_url   = $brand['logo_url'];
	$logo_alt   = $brand['logo_alt'];

	$contact      = $brand['contact'];
	$email        = $contact['email'];
	$phone        = $contact['phone'];
	$address      = $contact['address'];
	$channels     = array();
	$wechat_value = '';
	$raw_channels = $contact['channels'];
	if ( ! empty( $raw_channels ) ) {
		foreach ( $raw_channels as $ch ) {
			$type  = isset( $ch['type'] ) ? sanitize_text_field( $ch['type'] ) : '';
			$raw_value = isset( $ch['value'] ) ? (string) $ch['value'] : '';
			$raw_value = trim( $raw_value );
			if ( $type === '' || $raw_value === '' ) {
				continue;
			}

			// WeChat: NOT a link, display as plain text under phone in footer-3.
			if ( 'WeChat' === $type ) {
				$wechat_value = sanitize_text_field( $raw_value );
				continue;
			}

			// WhatsApp: MUST be https URL to be clickable.
			if ( 'WhatsApp' === $type ) {
				$whats = $raw_value;
				// Normalize protocol to https.
				if ( stripos( $whats, 'http://' ) === 0 ) {
					$whats = 'https://' . substr( $whats, strlen( 'http://' ) );
				} elseif ( stripos( $whats, 'https://' ) !== 0 && 0 === strpos( $whats, '//' ) ) {
					$whats = 'https:' . $whats;
				} elseif ( preg_match( '/^(wa\.me|www\.wa\.me|api\.whatsapp\.com)\//i', $whats ) === 1 ) {
					$whats = 'https://' . $whats;
				}
				// Only accept https URLs.
				if ( stripos( $whats, 'https://' ) !== 0 ) {
					continue;
				}
				$href = esc_url_raw( $whats );
				if ( $href === '' ) {
					continue;
				}
				$channels[] = array(
					'type'  => $type,
					'value' => $whats,
					'href'  => $href,
					'icon'  => puffergo_footer_channel_icon_slug( $type ),
				);
				continue;
			}

			// Other channels: use the existing unified href builder.
			$value = esc_url_raw( $raw_value );
			if ( $value === '' ) {
				$value = sanitize_text_field( $raw_value );
			}
			$channels[] = array(
				'type'  => $type,
				'value' => $value,
				'href'  => puffergo_footer_channel_href( $value, $home ),
				'icon'  => puffergo_footer_channel_icon_slug( $type ),
			);
		}
	}

	$context = array(
		'sections'          => $sections,
		'copyright_text'    => $copyright,
		'home_url'          => $home,
		'year'              => $year,
		'brand_name'       => $brand_name,
		'logo_id'          => $brand['logo_id'],
		'logo_url'         => $logo_url,
		'logo_alt'         => $logo_alt,
		'contact_email'    => $email,
		'contact_phone'     => $phone,
		'contact_address'   => $address,
		'contact_channels'  => $channels,
		'wechat_value'       => $wechat_value,
	);

	return apply_filters( 'puffergo_footer_context', $context );
}

/**
 * Parse the footer classic nav menu location into { sections: [{title, links: [{name,url}]}] }.
 *
 * @return array
 */
function puffergo_get_footer_sections_from_menu() {
	// 复用 nav-menu-helper 的统一解析逻辑（位置 → 按名 fallback → 自修复）
	$tree = puffergo_get_menu_tree( 'puffergo_footer', 'PufferGo Footer' );
	if ( empty( $tree ) ) {
		return array();
	}

	$sections = array();
	foreach ( $tree as $section ) {
		$title = isset( $section->title ) ? sanitize_text_field( $section->title ) : '';
		if ( $title === '' ) {
			continue;
		}
		$children = isset( $section->children ) && is_array( $section->children ) ? $section->children : array();
		if ( empty( $children ) ) {
			continue;
		}

		$links = array();
		foreach ( $children as $child ) {
			$name = isset( $child->title ) ? sanitize_text_field( $child->title ) : '';
			$url  = isset( $child->url ) ? esc_url_raw( $child->url ) : '';
			if ( $name === '' ) {
				continue;
			}
			$links[] = array(
				'name' => $name,
				'url'  => $url,
			);
		}
		if ( empty( $links ) ) {
			continue;
		}
		$sections[] = array(
			'title' => $title,
			'links' => $links,
		);
	}
	return $sections;
}

