<?php
declare(strict_types=1);
if ( ! defined( 'ABSPATH' ) ) { exit; }
/**
 * JSON-LD Schema Builders.
 * @package WTE_Business_Card
 */

function wte_build_organization_schema(): array {
	$name = get_theme_mod( 'wte_business_name', '' ) ?: get_theme_mod( 'wte_owner_name', '' ) ?: get_bloginfo( 'name' );
	$type = get_theme_mod( 'wte_schema_business_type', 'ProfessionalService' );
	$schema = [
		'@type' => [ $type, 'LocalBusiness' ],
		'@id' => home_url( '/#organization' ),
		'name' => $name,
		'url' => home_url( '/' ),
	];
	$logo = get_theme_mod( 'wte_site_logo', '' );
	if ( $logo ) { $schema['logo'] = [ '@type' => 'ImageObject', 'url' => $logo ]; }
	$desc = get_theme_mod( 'wte_meta_description', '' );
	if ( $desc ) { $schema['description'] = $desc; }
	$tel = get_theme_mod( 'wte_business_tel', '' );
	if ( $tel ) { $schema['telephone'] = $tel; }
	$address = get_theme_mod( 'wte_business_address', '' );
	if ( $address ) { $schema['address'] = [ '@type' => 'PostalAddress', 'streetAddress' => $address, 'addressCountry' => 'JP' ]; }
	$owner = get_theme_mod( 'wte_owner_name', '' );
	if ( $owner ) {
		$founder = [ '@type' => 'Person', 'name' => $owner ];
		$title = get_theme_mod( 'wte_owner_title', '' );
		if ( $title ) { $founder['jobTitle'] = $title; }
		$photo = get_theme_mod( 'wte_owner_photo', '' );
		if ( $photo ) { $founder['image'] = $photo; }
		$schema['founder'] = $founder;
	}
	$founded = get_theme_mod( 'wte_business_founded', '' );
	if ( $founded ) { $schema['foundingDate'] = $founded; }
	$price = get_theme_mod( 'wte_schema_price_range', '¥¥' );
	$schema['priceRange'] = $price;
	$same_as = wte_get_schema_same_as();
	if ( ! empty( $same_as ) ) { $schema['sameAs'] = $same_as; }
	return $schema;
}

function wte_build_faqpage_schema(): array {
	$items = wte_get_faq_items();
	if ( empty( $items ) ) return [];
	$entities = [];
	foreach ( $items as $item ) {
		$entities[] = [
			'@type' => 'Question',
			'name' => $item['question'],
			'acceptedAnswer' => [ '@type' => 'Answer', 'text' => $item['answer'] ],
		];
	}
	return [ '@context' => 'https://schema.org', '@type' => 'FAQPage', 'mainEntity' => $entities ];
}

function wte_build_person_schema(): array {
	$name = get_theme_mod( 'wte_owner_name', '' );
	if ( ! $name ) return [];
	$schema = [ '@type' => 'Person', 'name' => $name, 'url' => home_url( '/' ) ];
	$title = get_theme_mod( 'wte_owner_title', '' );
	if ( $title ) { $schema['jobTitle'] = $title; }
	$photo = get_theme_mod( 'wte_owner_photo', '' );
	if ( $photo ) { $schema['image'] = $photo; }
	$schema['worksFor'] = [ '@id' => home_url( '/#organization' ) ];
	return $schema;
}

function wte_get_schema_same_as(): array {
	$keys = [ 'wte_sns_x', 'wte_sns_instagram', 'wte_sns_facebook', 'wte_sns_linkedin', 'wte_sns_youtube', 'wte_sns_note', 'wte_sns_github' ];
	$urls = [];
	foreach ( $keys as $key ) {
		$url = get_theme_mod( $key, '' );
		if ( ! empty( $url ) ) { $urls[] = $url; }
	}
	return $urls;
}
