<?php
/**
 * Helper Functions for BW AI Schema Pro
 *
 * @package BW_AI_Schema_Pro
 */

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

class BW_Schema_Helpers {
	
	/**
	 * Create a tooltip
	 */
	public static function tooltip( $text, $icon = 'dashicons-editor-help' ) {
		return sprintf(
			'<span class="bw-tooltip">
				<span class="dashicons %s"></span>
				<span class="bw-tooltip-content">%s</span>
			</span>',
			esc_attr( $icon ),
			esc_html( $text )
		);
	}
	
	/**
	 * Create help text
	 */
	public static function help_text( $text ) {
		return sprintf(
			'<p class="bw-help-text">%s</p>',
			wp_kses_post( $text )
		);
	}
	
	/**
	 * Get schema type label
	 */
	public static function get_schema_type_label( $type ) {
		$types = BW_Schema_Core::get_schema_types();
		list( $main_type, $sub_type ) = explode( ':', $type );
		
		if ( isset( $types[$main_type]['subtypes'][$sub_type] ) ) {
			return $types[$main_type]['subtypes'][$sub_type];
		}
		
		return ucfirst( $sub_type );
	}
	
	/**
	 * Get schema type icon
	 */
	public static function get_schema_type_icon( $type ) {
		$types = BW_Schema_Core::get_schema_types();
		$main_type = explode( ':', $type )[0];
		
		if ( isset( $types[$main_type]['icon'] ) ) {
			return $types[$main_type]['icon'];
		}
		
		return 'dashicons-media-default';
	}
	
	/**
	 * Format schema JSON for display
	 */
	public static function format_schema_json( $schema ) {
		return wp_json_encode( $schema, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
	}
	
	/**
	 * Check if post type supports schema
	 */
	public static function post_type_supports_schema( $post_type ) {
		$supported = get_option( 'bw_schema_supported_post_types', array( 'post', 'page' ) );
		return in_array( $post_type, $supported );
	}
	
	/**
	 * Get Schema.org types mapped to business type categories.
	 *
	 * Each category maps to an array of specific Schema.org types.
	 * Every category includes Organization and LocalBusiness as fallback options.
	 */
	public static function get_schema_org_types() {
		$common = array(
			'Organization' => 'Organization (General)',
			'LocalBusiness' => 'Local Business (General)',
		);

		return array(
			'professional' => array_merge( array(
				'ProfessionalService' => 'Professional Service',
				'Corporation' => 'Corporation',
			), $common ),
			'medical' => array_merge( array(
				'MedicalBusiness' => 'Medical Business',
				'Physician' => 'Physician',
				'Dentist' => 'Dentist',
				'Optician' => 'Optician',
				'Pharmacy' => 'Pharmacy',
			), $common ),
			'hospitality' => array_merge( array(
				'LodgingBusiness' => 'Lodging Business',
				'Hotel' => 'Hotel',
				'Motel' => 'Motel',
				'Resort' => 'Resort',
				'BedAndBreakfast' => 'Bed and Breakfast',
				'Restaurant' => 'Restaurant',
				'FoodEstablishment' => 'Food Establishment',
				'BarOrPub' => 'Bar or Pub',
				'CafeOrCoffeeShop' => 'Cafe or Coffee Shop',
				'TouristInformationCenter' => 'Tourist Information Center',
			), $common ),
			'education' => array_merge( array(
				'EducationalOrganization' => 'Educational Organization',
				'School' => 'School',
				'HighSchool' => 'High School',
				'CollegeOrUniversity' => 'College or University',
				'Preschool' => 'Preschool',
			), $common ),
			'ecommerce' => array_merge( array(
				'Store' => 'Store',
				'OnlineStore' => 'Online Store',
				'ShoppingCenter' => 'Shopping Center',
				'ClothingStore' => 'Clothing Store',
				'ElectronicsStore' => 'Electronics Store',
				'HardwareStore' => 'Hardware Store',
				'HomeGoodsStore' => 'Home Goods Store',
				'GroceryStore' => 'Grocery Store',
			), $common ),
			'technology' => array_merge( array(
				'Corporation' => 'Corporation',
				'ProfessionalService' => 'Professional Service',
			), $common ),
			'realestate' => array_merge( array(
				'RealEstateAgent' => 'Real Estate Agent',
				'ProfessionalService' => 'Professional Service',
			), $common ),
			'financial' => array_merge( array(
				'FinancialService' => 'Financial Service',
				'BankOrCreditUnion' => 'Bank or Credit Union',
				'InsuranceAgency' => 'Insurance Agency',
				'AccountingService' => 'Accounting Service',
			), $common ),
			'media' => array_merge( array(
				'NewsMediaOrganization' => 'News Media Organization',
				'Corporation' => 'Corporation',
			), $common ),
			'nonprofit' => array_merge( array(
				'NGO' => 'Non-Governmental Organization',
				'GovernmentOrganization' => 'Government Organization',
			), $common ),
			'government' => array_merge( array(
				'GovernmentOrganization' => 'Government Organization',
				'GovernmentOffice' => 'Government Office',
			), $common ),
			'personal' => array_merge( array(
				'ProfessionalService' => 'Professional Service',
			), $common ),
		);
	}

	/**
	 * Get business types
	 */
	public static function get_business_types() {
		return array(
			'general' => __( 'General Business', 'bw-ai-schema-pro' ),
			'consulting' => __( 'Consulting / Professional Services', 'bw-ai-schema-pro' ),
			'technology' => __( 'Technology / Software', 'bw-ai-schema-pro' ),
			'retail' => __( 'Retail / E-commerce', 'bw-ai-schema-pro' ),
			'hospitality' => __( 'Hospitality / Tourism', 'bw-ai-schema-pro' ),
			'medical' => __( 'Medical / Healthcare', 'bw-ai-schema-pro' ),
			'legal' => __( 'Legal Services', 'bw-ai-schema-pro' ),
			'financial' => __( 'Financial Services', 'bw-ai-schema-pro' ),
			'realestate' => __( 'Real Estate', 'bw-ai-schema-pro' ),
			'education' => __( 'Education / Training', 'bw-ai-schema-pro' ),
			'nonprofit' => __( 'Non-Profit Organization', 'bw-ai-schema-pro' ),
			'entertainment' => __( 'Entertainment / Media', 'bw-ai-schema-pro' )
		);
	}
	
	/**
	 * Sanitize schema data
	 */
	public static function sanitize_schema_data( $data ) {
		if ( is_array( $data ) ) {
			foreach ( $data as $key => $value ) {
				$data[$key] = self::sanitize_schema_data( $value );
			}
		} else {
			$data = sanitize_text_field( $data );
		}
		
		return $data;
	}
	
	/**
	 * Get schema validation URL
	 */
	public static function get_validation_url( $url = '' ) {
		if ( empty( $url ) ) {
			$url = home_url();
		}
		
		return 'https://validator.schema.org/#url=' . urlencode( $url );
	}
	
	/**
	 * Get Rich Results Test URL
	 */
	public static function get_rich_results_url( $url = '' ) {
		if ( empty( $url ) ) {
			$url = home_url();
		}
		
		return 'https://search.google.com/test/rich-results?url=' . urlencode( $url );
	}
	
	/**
	 * Get all posts organized by post type for select dropdowns
	 */
	public static function get_posts_for_select() {
		$results = array();
		
		// Get all public post types
		$args = array(
			'public' => true,
			'show_ui' => true // Ensure it has a UI
		);
		
		$post_types = get_post_types( $args, 'objects' );
		
		// Sort post types alphabetically
		uasort( $post_types, function( $a, $b ) {
			return strcmp( $a->labels->name, $b->labels->name );
		} );
		
		foreach ( $post_types as $post_type ) {
			// Skip attachments
			if ( $post_type->name === 'attachment' ) {
				continue;
			}
			
			// Use direct database query for better performance with custom post types
			global $wpdb;
			
			$posts = $wpdb->get_results( $wpdb->prepare(
				"SELECT ID, post_title 
				FROM {$wpdb->posts} 
				WHERE post_type = %s 
				AND post_status = 'publish' 
				ORDER BY post_title ASC 
				LIMIT 100",
				$post_type->name
			) );
			
			if ( ! empty( $posts ) ) {
				$results[$post_type->name] = array(
					'label' => $post_type->labels->name,
					'singular' => $post_type->labels->singular_name,
					'posts' => $posts
				);
			}
		}
		
		return $results;
	}
	
	/**
	 * Render post select options grouped by post type
	 */
	public static function render_post_select_options( $selected = '', $show_post_type = true ) {
		$posts_by_type = self::get_posts_for_select();
		
		foreach ( $posts_by_type as $post_type => $data ) {
			$label = $show_post_type ? $data['label'] . ' (' . $post_type . ')' : $data['label'];
			echo '<optgroup label="' . esc_attr( $label ) . '">';
			
			foreach ( $data['posts'] as $post ) {
				echo '<option value="' . esc_attr( $post->ID ) . '" ' . selected( $selected, $post->ID, false ) . '>';
				echo esc_html( $post->post_title );
				echo '</option>';
			}
			
			echo '</optgroup>';
		}
	}
}