<?php
/**
 * Product Schema Class for BW AI Schema Pro
 *
 * @package BW_AI_Schema_Pro
 */

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

class BW_Schema_Product extends BW_Schema_Base {
	
	/**
	 * Generate product schema
	 */
	public function generate( $post, $type = 'Product' ) {
		// Base schema
		$schema = array(
			'@context' => 'https://schema.org',
			'@type' => $type,
		);
		
		// Add common properties
		$schema = array_merge( $schema, $this->get_common_properties( $post ) );
		
		// Add SKU
		$sku = get_post_meta( $post->ID, '_bw_schema_sku', true );
		if ( ! empty( $sku ) ) {
			$schema['sku'] = $sku;
		}
		
		// Add brand
		$brand = $this->get_brand_properties( $post );
		if ( ! empty( $brand ) ) {
			$schema['brand'] = $brand;
		}
		
		// Add manufacturer
		$manufacturer = get_post_meta( $post->ID, '_bw_schema_manufacturer', true );
		if ( ! empty( $manufacturer ) ) {
			$schema['manufacturer'] = array(
				'@type' => 'Organization',
				'name' => $manufacturer,
			);
		}
		
		// Add offers
		$offers = $this->get_product_offers( $post );
		if ( ! empty( $offers ) ) {
			$schema['offers'] = $offers;
		}
		
		// Add aggregate rating
		$rating = $this->get_aggregate_rating( $post );
		if ( ! empty( $rating ) ) {
			$schema['aggregateRating'] = $rating;
		}
		
		// Add reviews
		$reviews = $this->get_product_reviews( $post );
		if ( ! empty( $reviews ) ) {
			$schema['review'] = $reviews;
		}
		
		// Add product ID (GTIN, MPN, ISBN)
		$gtin = get_post_meta( $post->ID, '_bw_schema_gtin', true );
		if ( ! empty( $gtin ) ) {
			$schema['gtin'] = $gtin;
		}
		
		$mpn = get_post_meta( $post->ID, '_bw_schema_mpn', true );
		if ( ! empty( $mpn ) ) {
			$schema['mpn'] = $mpn;
		}
		
		// Add dimensions
		$dimensions = $this->get_product_dimensions( $post );
		if ( ! empty( $dimensions ) ) {
			foreach ( $dimensions as $key => $value ) {
				$schema[$key] = $value;
			}
		}
		
		// Add material
		$material = get_post_meta( $post->ID, '_bw_schema_material', true );
		if ( ! empty( $material ) ) {
			$schema['material'] = $material;
		}
		
		// Add color
		$color = get_post_meta( $post->ID, '_bw_schema_color', true );
		if ( ! empty( $color ) ) {
			$schema['color'] = $color;
		}
		
		// Add category
		$category = get_post_meta( $post->ID, '_bw_schema_product_category', true );
		if ( ! empty( $category ) ) {
			$schema['category'] = $category;
		}
		
		// Add in language
		$schema['inLanguage'] = get_locale();
		
		// Add AI-optimized properties
		$schema = $this->add_ai_properties( $schema, $post );
		
		// Add specific properties based on product type
		switch ( $type ) {
			case 'Book':
				$schema = $this->add_book_properties( $schema, $post );
				break;
				
			case 'Movie':
				$schema = $this->add_movie_properties( $schema, $post );
				break;
				
			case 'SoftwareApplication':
				$schema = $this->add_software_properties( $schema, $post );
				break;
				
			case 'Vehicle':
				$schema = $this->add_vehicle_properties( $schema, $post );
				break;
		}
		
		return apply_filters( 'bw_schema_product', $schema, $post, $type );
	}
	
	/**
	 * Get brand properties
	 */
	private function get_brand_properties( $post ) {
		$brand_name = get_post_meta( $post->ID, '_bw_schema_brand', true );
		
		if ( empty( $brand_name ) ) {
			return null;
		}
		
		$brand = array(
			'@type' => 'Brand',
			'name' => $brand_name,
		);
		
		$brand_url = get_post_meta( $post->ID, '_bw_schema_brand_url', true );
		if ( ! empty( $brand_url ) ) {
			$brand['url'] = $brand_url;
		}
		
		return $brand;
	}
	
	/**
	 * Get product offers
	 */
	private function get_product_offers( $post ) {
		$offer = array(
			'@type' => 'Offer',
		);
		
		// Price
		$price = get_post_meta( $post->ID, '_bw_schema_price', true );
		if ( ! empty( $price ) ) {
			$offer['price'] = $price;
		}
		
		// Currency
		$currency = get_post_meta( $post->ID, '_bw_schema_price_currency', true );
		if ( ! empty( $currency ) ) {
			$offer['priceCurrency'] = $currency;
		}
		
		// Availability
		$availability = get_post_meta( $post->ID, '_bw_schema_availability', true );
		if ( ! empty( $availability ) ) {
			$offer['availability'] = $availability;
		} else {
			$offer['availability'] = 'https://schema.org/InStock';
		}
		
		// Item condition
		$condition = get_post_meta( $post->ID, '_bw_schema_item_condition', true );
		if ( ! empty( $condition ) ) {
			$offer['itemCondition'] = $condition;
		} else {
			$offer['itemCondition'] = 'https://schema.org/NewCondition';
		}
		
		// Seller
		$offer['seller'] = $this->get_organization_properties();
		
		// Price valid until
		$price_valid_until = get_post_meta( $post->ID, '_bw_schema_price_valid_until', true );
		if ( ! empty( $price_valid_until ) ) {
			$offer['priceValidUntil'] = $price_valid_until;
		}
		
		// Shipping details
		$shipping = $this->get_shipping_details( $post );
		if ( ! empty( $shipping ) ) {
			$offer['shippingDetails'] = $shipping;
		}
		
		// Return policy
		$return_policy = get_post_meta( $post->ID, '_bw_schema_return_policy', true );
		if ( ! empty( $return_policy ) ) {
			$offer['hasMerchantReturnPolicy'] = array(
				'@type' => 'MerchantReturnPolicy',
				'returnPolicyCategory' => $return_policy,
			);
		}
		
		// URL
		$offer['url'] = get_permalink( $post );
		
		return $offer;
	}
	
	/**
	 * Get aggregate rating
	 */
	private function get_aggregate_rating( $post ) {
		$rating_value = get_post_meta( $post->ID, '_bw_schema_rating_value', true );
		$rating_count = get_post_meta( $post->ID, '_bw_schema_rating_count', true );
		
		if ( empty( $rating_value ) || empty( $rating_count ) ) {
			return null;
		}
		
		return array(
			'@type' => 'AggregateRating',
			'ratingValue' => floatval( $rating_value ),
			'reviewCount' => intval( $rating_count ),
			'bestRating' => 5,
			'worstRating' => 1,
		);
	}
	
	/**
	 * Get product reviews
	 */
	private function get_product_reviews( $post ) {
		$reviews = get_post_meta( $post->ID, '_bw_schema_reviews', true );
		
		if ( empty( $reviews ) || ! is_array( $reviews ) ) {
			return null;
		}
		
		$review_list = array();
		foreach ( $reviews as $review ) {
			$review_schema = array(
				'@type' => 'Review',
			);
			
			if ( ! empty( $review['author'] ) ) {
				$review_schema['author'] = array(
					'@type' => 'Person',
					'name' => $review['author'],
				);
			}
			
			if ( ! empty( $review['rating'] ) ) {
				$review_schema['reviewRating'] = array(
					'@type' => 'Rating',
					'ratingValue' => $review['rating'],
					'bestRating' => 5,
					'worstRating' => 1,
				);
			}
			
			if ( ! empty( $review['text'] ) ) {
				$review_schema['reviewBody'] = $review['text'];
			}
			
			if ( ! empty( $review['date'] ) ) {
				$review_schema['datePublished'] = $review['date'];
			}
			
			$review_list[] = $review_schema;
		}
		
		return $review_list;
	}
	
	/**
	 * Get product dimensions
	 */
	private function get_product_dimensions( $post ) {
		$dimensions = array();
		
		// Weight
		$weight = get_post_meta( $post->ID, '_bw_schema_weight', true );
		if ( ! empty( $weight ) ) {
			$dimensions['weight'] = array(
				'@type' => 'QuantitativeValue',
				'value' => $weight,
				'unitCode' => get_post_meta( $post->ID, '_bw_schema_weight_unit', true ) ?: 'KGM',
			);
		}
		
		// Height
		$height = get_post_meta( $post->ID, '_bw_schema_height', true );
		if ( ! empty( $height ) ) {
			$dimensions['height'] = array(
				'@type' => 'QuantitativeValue',
				'value' => $height,
				'unitCode' => get_post_meta( $post->ID, '_bw_schema_dimension_unit', true ) ?: 'CMT',
			);
		}
		
		// Width
		$width = get_post_meta( $post->ID, '_bw_schema_width', true );
		if ( ! empty( $width ) ) {
			$dimensions['width'] = array(
				'@type' => 'QuantitativeValue',
				'value' => $width,
				'unitCode' => get_post_meta( $post->ID, '_bw_schema_dimension_unit', true ) ?: 'CMT',
			);
		}
		
		// Depth
		$depth = get_post_meta( $post->ID, '_bw_schema_depth', true );
		if ( ! empty( $depth ) ) {
			$dimensions['depth'] = array(
				'@type' => 'QuantitativeValue',
				'value' => $depth,
				'unitCode' => get_post_meta( $post->ID, '_bw_schema_dimension_unit', true ) ?: 'CMT',
			);
		}
		
		return $dimensions;
	}
	
	/**
	 * Get shipping details
	 */
	private function get_shipping_details( $post ) {
		$shipping_rate = get_post_meta( $post->ID, '_bw_schema_shipping_rate', true );
		$shipping_destination = get_post_meta( $post->ID, '_bw_schema_shipping_destination', true );
		
		if ( empty( $shipping_rate ) ) {
			return null;
		}
		
		return array(
			'@type' => 'OfferShippingDetails',
			'shippingRate' => array(
				'@type' => 'MonetaryAmount',
				'value' => $shipping_rate,
				'currency' => get_post_meta( $post->ID, '_bw_schema_price_currency', true ) ?: 'USD',
			),
			'shippingDestination' => array(
				'@type' => 'DefinedRegion',
				'addressCountry' => $shipping_destination ?: 'US',
			),
		);
	}
	
	/**
	 * Add book specific properties
	 */
	private function add_book_properties( $schema, $post ) {
		// ISBN
		$isbn = get_post_meta( $post->ID, '_bw_schema_isbn', true );
		if ( ! empty( $isbn ) ) {
			$schema['isbn'] = $isbn;
		}
		
		// Author
		$author = get_post_meta( $post->ID, '_bw_schema_book_author', true );
		if ( ! empty( $author ) ) {
			$schema['author'] = array(
				'@type' => 'Person',
				'name' => $author,
			);
		}
		
		// Number of pages
		$pages = get_post_meta( $post->ID, '_bw_schema_number_of_pages', true );
		if ( ! empty( $pages ) ) {
			$schema['numberOfPages'] = intval( $pages );
		}
		
		// Book format
		$format = get_post_meta( $post->ID, '_bw_schema_book_format', true );
		if ( ! empty( $format ) ) {
			$schema['bookFormat'] = $format;
		}
		
		return $schema;
	}
	
	/**
	 * Add movie specific properties
	 */
	private function add_movie_properties( $schema, $post ) {
		// Director
		$director = get_post_meta( $post->ID, '_bw_schema_director', true );
		if ( ! empty( $director ) ) {
			$schema['director'] = array(
				'@type' => 'Person',
				'name' => $director,
			);
		}
		
		// Actors
		$actors = get_post_meta( $post->ID, '_bw_schema_actors', true );
		if ( ! empty( $actors ) && is_array( $actors ) ) {
			$actor_list = array();
			foreach ( $actors as $actor ) {
				$actor_list[] = array(
					'@type' => 'Person',
					'name' => $actor,
				);
			}
			$schema['actor'] = $actor_list;
		}
		
		// Duration
		$duration = get_post_meta( $post->ID, '_bw_schema_duration', true );
		if ( ! empty( $duration ) ) {
			$schema['duration'] = $duration;
		}
		
		// Date created
		$date_created = get_post_meta( $post->ID, '_bw_schema_date_created', true );
		if ( ! empty( $date_created ) ) {
			$schema['dateCreated'] = $date_created;
		}
		
		return $schema;
	}
	
	/**
	 * Add software specific properties
	 */
	private function add_software_properties( $schema, $post ) {
		// Operating system
		$os = get_post_meta( $post->ID, '_bw_schema_operating_system', true );
		if ( ! empty( $os ) ) {
			$schema['operatingSystem'] = $os;
		}
		
		// Application category
		$app_category = get_post_meta( $post->ID, '_bw_schema_application_category', true );
		if ( ! empty( $app_category ) ) {
			$schema['applicationCategory'] = $app_category;
		}
		
		// Software version
		$version = get_post_meta( $post->ID, '_bw_schema_software_version', true );
		if ( ! empty( $version ) ) {
			$schema['softwareVersion'] = $version;
		}
		
		// File size
		$file_size = get_post_meta( $post->ID, '_bw_schema_file_size', true );
		if ( ! empty( $file_size ) ) {
			$schema['fileSize'] = $file_size;
		}
		
		// Requirements
		$requirements = get_post_meta( $post->ID, '_bw_schema_software_requirements', true );
		if ( ! empty( $requirements ) ) {
			$schema['softwareRequirements'] = $requirements;
		}
		
		return $schema;
	}
	
	/**
	 * Add vehicle specific properties
	 */
	private function add_vehicle_properties( $schema, $post ) {
		// Vehicle identification number
		$vin = get_post_meta( $post->ID, '_bw_schema_vehicle_vin', true );
		if ( ! empty( $vin ) ) {
			$schema['vehicleIdentificationNumber'] = $vin;
		}
		
		// Model
		$model = get_post_meta( $post->ID, '_bw_schema_vehicle_model', true );
		if ( ! empty( $model ) ) {
			$schema['model'] = $model;
		}
		
		// Mileage
		$mileage = get_post_meta( $post->ID, '_bw_schema_mileage_from_odometer', true );
		if ( ! empty( $mileage ) ) {
			$schema['mileageFromOdometer'] = array(
				'@type' => 'QuantitativeValue',
				'value' => $mileage,
				'unitCode' => 'KMT',
			);
		}
		
		// Fuel type
		$fuel_type = get_post_meta( $post->ID, '_bw_schema_fuel_type', true );
		if ( ! empty( $fuel_type ) ) {
			$schema['fuelType'] = $fuel_type;
		}
		
		// Number of doors
		$doors = get_post_meta( $post->ID, '_bw_schema_number_of_doors', true );
		if ( ! empty( $doors ) ) {
			$schema['numberOfDoors'] = intval( $doors );
		}
		
		// Vehicle engine
		$engine = get_post_meta( $post->ID, '_bw_schema_vehicle_engine', true );
		if ( ! empty( $engine ) ) {
			$schema['vehicleEngine'] = array(
				'@type' => 'EngineSpecification',
				'description' => $engine,
			);
		}
		
		return $schema;
	}
}