<?php
/**
 * Gutenberg Blocks handler for BW AI Schema Pro
 *
 * @package BW_AI_Schema_Pro
 */

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

class BW_Schema_Blocks {
	
	/**
	 * Initialize blocks
	 */
	public static function init() {
		add_action( 'init', array( __CLASS__, 'register_blocks' ) );
		add_action( 'enqueue_block_editor_assets', array( __CLASS__, 'enqueue_block_editor_assets' ) );
		add_action( 'enqueue_block_assets', array( __CLASS__, 'enqueue_block_assets' ) );
	}
	
	/**
	 * Register all blocks
	 */
	public static function register_blocks() {
		// Register author schema block
		register_block_type( 'bw-schema/author-schema', array(
			'editor_script' => 'bw-schema-author-block-editor',
			'editor_style'  => 'bw-schema-author-block-editor',
			'style'         => 'bw-schema-author-block',
			'render_callback' => array( __CLASS__, 'render_author_schema_block' ),
			'attributes' => array(
				'authorType' => array(
					'type' => 'string',
					'default' => 'custom'
				),
				'authorId' => array(
					'type' => 'string',
					'default' => ''
				),
				'authorName' => array(
					'type' => 'string',
					'default' => ''
				),
				'authorJobTitle' => array(
					'type' => 'string',
					'default' => ''
				),
				'authorBio' => array(
					'type' => 'string',
					'default' => ''
				),
				'authorImage' => array(
					'type' => 'string',
					'default' => ''
				),
				'authorUrl' => array(
					'type' => 'string',
					'default' => ''
				),
				'teamPageId' => array(
					'type' => 'number',
					'default' => 0
				),
				'teamPageUrl' => array(
					'type' => 'string',
					'default' => ''
				),
				'showFrontend' => array(
					'type' => 'boolean',
					'default' => false
				),
				'frontendStyle' => array(
					'type' => 'string',
					'default' => 'card'
				),
				'knowsAbout' => array(
					'type' => 'array',
					'default' => []
				),
				'sameAs' => array(
					'type' => 'array',
					'default' => []
				),
				'alumniOf' => array(
					'type' => 'string',
					'default' => ''
				),
				'credentials' => array(
					'type' => 'array',
					'default' => []
				)
			)
		) );
	}
	
	/**
	 * Enqueue block editor assets
	 */
	public static function enqueue_block_editor_assets() {
		// Get custom authors for the dropdown
		$custom_authors = get_option( 'bw_schema_custom_authors', array() );
		$authors_for_select = array();
		
		foreach ( $custom_authors as $author ) {
			$authors_for_select[] = array(
				'value' => $author['id'],
				'label' => $author['name'] . ' - ' . $author['jobTitle'],
				'data' => $author
			);
		}
		
		// Get all public post types for team page selection
		$custom_post_types = get_post_types( array( 'public' => true, '_builtin' => false ), 'objects' );
		$builtin_post_types = get_post_types( array( 'public' => true, '_builtin' => true ), 'objects' );
		$all_post_types = array_merge( $builtin_post_types, $custom_post_types );
		
		$pages_for_select = array();
		
		foreach ( $all_post_types as $post_type ) {
			if ( $post_type->name === 'attachment' ) continue;
			
			$posts = get_posts( array(
				'post_type' => $post_type->name,
				'posts_per_page' => 50, // Limit for performance
				'orderby' => 'title',
				'order' => 'ASC',
				'post_status' => 'publish',
				'suppress_filters' => false
			) );
			
			if ( ! empty( $posts ) ) {
				foreach ( $posts as $post ) {
					$pages_for_select[] = array(
						'value' => $post->ID,
						'label' => $post_type->labels->singular_name . ': ' . $post->post_title,
						'url' => get_permalink( $post->ID ),
						'postType' => $post_type->name
					);
				}
			}
		}
		
		// Enqueue block editor script
		wp_enqueue_script(
			'bw-schema-author-block-editor',
			BW_SCHEMA_PLUGIN_URL . 'blocks/author-schema/editor.js',
			array( 'wp-blocks', 'wp-element', 'wp-editor', 'wp-components', 'wp-data' ),
			BW_SCHEMA_VERSION,
			true
		);
		
		// Pass data to JavaScript
		wp_localize_script( 'bw-schema-author-block-editor', 'bwSchemaData', array(
			'customAuthors' => $authors_for_select,
			'pages' => $pages_for_select,
			'pluginUrl' => BW_SCHEMA_PLUGIN_URL
		) );
		
		// Enqueue editor styles
		wp_enqueue_style(
			'bw-schema-author-block-editor',
			BW_SCHEMA_PLUGIN_URL . 'blocks/author-schema/editor.css',
			array( 'wp-edit-blocks' ),
			BW_SCHEMA_VERSION
		);
	}
	
	/**
	 * Enqueue frontend block assets
	 */
	public static function enqueue_block_assets() {
		if ( ! is_admin() ) {
			wp_enqueue_style(
				'bw-schema-author-block',
				BW_SCHEMA_PLUGIN_URL . 'blocks/author-schema/style.css',
				array(),
				BW_SCHEMA_VERSION
			);
		}
	}
	
	/**
	 * Render author schema block
	 */
	public static function render_author_schema_block( $attributes ) {
		$author_data = array();
		
		// Get author data based on type
		if ( $attributes['authorType'] === 'custom' && ! empty( $attributes['authorId'] ) ) {
			// Get custom author data
			$custom_authors = get_option( 'bw_schema_custom_authors', array() );
			foreach ( $custom_authors as $author ) {
				if ( $author['id'] === $attributes['authorId'] ) {
					$author_data = $author;
					break;
				}
			}
		} elseif ( $attributes['authorType'] === 'manual' ) {
			// Use manually entered data
			$author_data = array(
				'name' => $attributes['authorName'],
				'jobTitle' => $attributes['authorJobTitle'],
				'description' => $attributes['authorBio'],
				'image' => $attributes['authorImage'],
				'url' => $attributes['authorUrl'],
				'knowsAbout' => $attributes['knowsAbout'],
				'sameAs' => $attributes['sameAs'],
				'alumniOf' => $attributes['alumniOf'],
				'hasCredential' => $attributes['credentials']
			);
		}
		
		// Add team page link if specified
		if ( ! empty( $attributes['teamPageId'] ) ) {
			$author_data['url'] = get_permalink( $attributes['teamPageId'] );
		} elseif ( ! empty( $attributes['teamPageUrl'] ) ) {
			$author_data['url'] = $attributes['teamPageUrl'];
		}
		
		// Generate schema markup
		$schema = self::generate_author_schema( $author_data );
		
		$output = '';
		
		// Add schema markup (always, even if not showing frontend)
		if ( ! empty( $schema ) ) {
			$output .= '<script type="application/ld+json">' . wp_json_encode( $schema ) . '</script>';
		}
		
		// Add frontend display if enabled
		if ( $attributes['showFrontend'] && ! empty( $author_data ) ) {
			$output .= self::render_author_frontend( $author_data, $attributes['frontendStyle'] );
		}
		
		return $output;
	}
	
	/**
	 * Generate author schema
	 */
	private static function generate_author_schema( $author_data ) {
		if ( empty( $author_data['name'] ) ) {
			return null;
		}
		
		$schema = array(
			'@context' => 'https://schema.org',
			'@type' => 'Person',
			'name' => $author_data['name']
		);
		
		// Add optional fields
		if ( ! empty( $author_data['jobTitle'] ) ) {
			$schema['jobTitle'] = $author_data['jobTitle'];
		}
		
		if ( ! empty( $author_data['description'] ) ) {
			$schema['description'] = $author_data['description'];
		}
		
		if ( ! empty( $author_data['image'] ) ) {
			$schema['image'] = $author_data['image'];
		}
		
		if ( ! empty( $author_data['url'] ) ) {
			$schema['url'] = $author_data['url'];
		}
		
		if ( ! empty( $author_data['email'] ) ) {
			$schema['email'] = $author_data['email'];
		}
		
		if ( ! empty( $author_data['knowsAbout'] ) && is_array( $author_data['knowsAbout'] ) ) {
			$schema['knowsAbout'] = $author_data['knowsAbout'];
		}
		
		if ( ! empty( $author_data['sameAs'] ) && is_array( $author_data['sameAs'] ) ) {
			$schema['sameAs'] = array_filter( $author_data['sameAs'] );
		}
		
		if ( ! empty( $author_data['alumniOf'] ) ) {
			$schema['alumniOf'] = array(
				'@type' => 'EducationalOrganization',
				'name' => $author_data['alumniOf']
			);
		}
		
		if ( ! empty( $author_data['hasCredential'] ) && is_array( $author_data['hasCredential'] ) ) {
			$credentials = array();
			foreach ( $author_data['hasCredential'] as $credential ) {
				if ( ! empty( $credential ) ) {
					$credentials[] = array(
						'@type' => 'EducationalOccupationalCredential',
						'name' => $credential
					);
				}
			}
			if ( ! empty( $credentials ) ) {
				$schema['hasCredential'] = $credentials;
			}
		}
		
		// Add organization affiliation
		$org_schema = BW_Schema_Core::get_organization_schema();
		if ( ! empty( $org_schema ) ) {
			$schema['worksFor'] = array(
				'@type' => 'Organization',
				'name' => $org_schema['name'],
				'url' => $org_schema['url']
			);
		}
		
		return $schema;
	}
	
	/**
	 * Render author frontend display
	 */
	private static function render_author_frontend( $author_data, $style = 'card' ) {
		$output = '<div class="bw-schema-author-display bw-schema-author-' . esc_attr( $style ) . '">';
		
		switch ( $style ) {
			case 'card':
				$output .= '<div class="bw-author-card">';
				
				if ( ! empty( $author_data['image'] ) ) {
					$output .= '<div class="bw-author-image">';
					$output .= '<img src="' . esc_url( $author_data['image'] ) . '" alt="' . esc_attr( $author_data['name'] ) . '">';
					$output .= '</div>';
				}
				
				$output .= '<div class="bw-author-content">';
				$output .= '<h3 class="bw-author-name">';
				
				if ( ! empty( $author_data['url'] ) ) {
					$output .= '<a href="' . esc_url( $author_data['url'] ) . '">' . esc_html( $author_data['name'] ) . '</a>';
				} else {
					$output .= esc_html( $author_data['name'] );
				}
				
				$output .= '</h3>';
				
				if ( ! empty( $author_data['jobTitle'] ) ) {
					$output .= '<p class="bw-author-title">' . esc_html( $author_data['jobTitle'] ) . '</p>';
				}
				
				if ( ! empty( $author_data['description'] ) ) {
					$output .= '<div class="bw-author-bio">' . wp_kses_post( $author_data['description'] ) . '</div>';
				}
				
				// Social links
				if ( ! empty( $author_data['sameAs'] ) && is_array( $author_data['sameAs'] ) ) {
					$output .= '<div class="bw-author-social">';
					foreach ( $author_data['sameAs'] as $url ) {
						if ( ! empty( $url ) ) {
							$domain = parse_url( $url, PHP_URL_HOST );
							$icon_class = 'bw-social-link';
							
							if ( strpos( $domain, 'linkedin' ) !== false ) {
								$icon_class .= ' bw-linkedin';
							} elseif ( strpos( $domain, 'twitter' ) !== false || strpos( $domain, 'x.com' ) !== false ) {
								$icon_class .= ' bw-twitter';
							} elseif ( strpos( $domain, 'facebook' ) !== false ) {
								$icon_class .= ' bw-facebook';
							}
							
							$output .= '<a href="' . esc_url( $url ) . '" class="' . esc_attr( $icon_class ) . '" target="_blank" rel="noopener noreferrer"></a>';
						}
					}
					$output .= '</div>';
				}
				
				$output .= '</div>'; // .bw-author-content
				$output .= '</div>'; // .bw-author-card
				break;
				
			case 'inline':
				$output .= '<span class="bw-author-inline">';
				$output .= __( 'By ', 'bw-ai-schema-pro' );
				
				if ( ! empty( $author_data['url'] ) ) {
					$output .= '<a href="' . esc_url( $author_data['url'] ) . '">' . esc_html( $author_data['name'] ) . '</a>';
				} else {
					$output .= '<strong>' . esc_html( $author_data['name'] ) . '</strong>';
				}
				
				if ( ! empty( $author_data['jobTitle'] ) ) {
					$output .= ', ' . esc_html( $author_data['jobTitle'] );
				}
				
				$output .= '</span>';
				break;
				
			case 'minimal':
				$output .= '<div class="bw-author-minimal">';
				$output .= '<strong>' . __( 'Author: ', 'bw-ai-schema-pro' ) . '</strong>';
				
				if ( ! empty( $author_data['url'] ) ) {
					$output .= '<a href="' . esc_url( $author_data['url'] ) . '">' . esc_html( $author_data['name'] ) . '</a>';
				} else {
					$output .= esc_html( $author_data['name'] );
				}
				
				$output .= '</div>';
				break;
		}
		
		$output .= '</div>';
		
		return $output;
	}
}