<?php
namespace WPLens\Schema\Generators;

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

final class OrganizationGenerator implements \WPLens\Schema\Generator {

	public function get_slug(): string  { return 'organization'; }
	public function get_label(): string { return __( 'Organization (publisher / brand)', 'lens-ai-visibility-monitor' ); }

	public function applies( ?\WP_Post $post = null ): bool {
		return true;
	}

	public function generate( ?\WP_Post $post = null ): ?array {
		$settings = \WPLens\Utils\Options::all();
		$org      = (array) ( $settings['schema']['organization'] ?? array() );

		$name = ! empty( $org['name'] ) ? (string) $org['name'] : get_bloginfo( 'name' );
		$logo = ! empty( $org['logo'] ) ? (string) $org['logo'] : $this->resolve_logo();
		$same = array_values( array_filter( (array) ( $org['same_as'] ?? array() ) ) );

		$payload = array(
			'@type' => 'Organization',
			'@id'   => home_url( '/' ) . '#organization',
			'name'  => $name,
			'url'   => home_url( '/' ),
		);

		if ( $logo ) {
			$payload['logo'] = array(
				'@type' => 'ImageObject',
				'url'   => $logo,
			);
		}

		if ( ! empty( $same ) ) {
			$payload['sameAs'] = $same;
		}

		if ( ! empty( $org['contact_email'] ) ) {
			$payload['contactPoint'] = array(
				'@type'       => 'ContactPoint',
				'contactType' => 'customer support',
				'email'       => (string) $org['contact_email'],
			);
		}

		return $payload;
	}

	private function resolve_logo(): string {
		$custom_logo_id = (int) get_theme_mod( 'custom_logo' );
		if ( $custom_logo_id > 0 ) {
			$src = wp_get_attachment_image_url( $custom_logo_id, 'full' );
			if ( $src ) {
				return $src;
			}
		}
		$site_icon = (int) get_option( 'site_icon' );
		if ( $site_icon > 0 ) {
			$src = wp_get_attachment_image_url( $site_icon, 'full' );
			if ( $src ) {
				return $src;
			}
		}
		return '';
	}
}
