<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-category.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-brand.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-review.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-size.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-aggregaterating.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-color.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-offer.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-imageobject.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-country.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-organization.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-keyword.php';

class Vserpb_Product_Schema {

	/**
	 * Generate structured schema for a WooCommerce product.
	 *
	 * @param int $product_id WooCommerce Product ID.
	 * @return array|void JSON-LD Schema Markup or void if not a product page.
	 */
	public static function vserpb_generate_schema( $product_id ) {
		// if ( ! is_product() ) {
		// 	return;
		// }
			  $product = wc_get_product( $product_id );
			if ( ! $product || ! $product instanceof WC_Product ) {
				return '';
			}
		$vserpb_settings = get_option( 'vserpb_product_schema', array() );
		// Fetching Basic Product details


		// Fetching Basic Product details
		$product_id      = (int) $product->get_id();
		$product_name    = sanitize_text_field( $product->get_name() );
		$description = wp_strip_all_tags( do_shortcode( $product->get_description() ) );
		$sku             = $product->get_sku() ? sanitize_text_field( $product->get_sku() ) : 'N/A';
		$published_date  = get_post_field( 'post_date', $product_id );
		$production_date = gmdate( 'Y-m-d', strtotime( $published_date ) );

			$product  = wc_get_product( $product_id );
			$attributes = $product->get_attributes();

				$additional_properties = array(
					array(
						'@type' => 'PropertyValue',
						'name'  => 'text',
						'value' => $sku,
					),
					array(
						'@type' => 'PropertyValue',
						'name'  => 'alternateTextOfSku',
						'value' => $product_name,
					),
				);

				// Loop WooCommerce Product Attributes
				foreach ( $attributes as $attribute ) {

    $name        = wc_attribute_label( $attribute->get_name() );
    $property_id = $attribute->get_id();
    $value       = implode( ', ', $attribute->get_options() );

    $unit_code = '';
    $unit_text = '';
    $max_value = '';
    $min_value = '';

    $property_value = array(
        '@type'      => 'PropertyValue',
        'propertyID' => $property_id,
        'name'       => $name,
        'value'      => $value,
        'unitCode'   => $unit_code,
        'unitText'   => $unit_text,
        'maxValue'   => $max_value,
        'minValue'   => $min_value,
    );

    // Remove null, empty string, empty array, false
    $property_value = array_filter( $property_value, function( $v ) {
        return ! ( $v === null || $v === '' || $v === false || ( is_array($v) && empty($v) ) );
    });

    $additional_properties[] = $property_value;
}

			$type = $product->is_type('variable') ? 'ProductGroup' : 'Product';

				$schema = array(
					'@context'           => 'https://schema.org/',
					'@type'              => $type,
					'name'               => $product_name,
					'description'        => $description,
					'productID'          => $product_id,
					'sku'                => $sku,
					'additionalProperty' => $additional_properties,
					'productionDate'     => $production_date,
				);


				if ( $product->is_type('variable') ) {
				$schema['hasVariant'] = [];

				foreach ( $product->get_children() as $variation_id ) {
					$variation = wc_get_product( $variation_id );

					// Get variation image OR fallback to parent image
					$image_id = $variation->get_image_id();
					if ( ! $image_id ) {
						$image_id = $product->get_image_id(); // fallback
					}
					$variation_image = $image_id ? wp_get_attachment_url( $image_id ) : '';

					// Variation description (optional)
					$variation_description = wp_strip_all_tags(
						do_shortcode( $variation->get_description() )
					);

					$schema['hasVariant'][] = [
						"@type" => "Product",
						"@id"   => get_permalink( $variation_id ),
						"sku"   => $variation->get_sku(),
						"name"  => $variation->get_name(),
						"image" => $variation_image,              // REQUIRED
						"description" => $variation_description,  // optional but recommended

						"offers" => [
							"@type" => "Offer",
							"price" => $variation->get_price(),
							"priceCurrency" => get_woocommerce_currency(),
							"availability" => "https://schema.org/InStock",
							"url" => get_permalink( $variation_id )
						]
					];
				}
			}

				if ( $product->is_type('variation') ) {
					$parent_id = $product->get_parent_id();
					$parent    = wc_get_product( $parent_id );

					$schema['isVariantOf'] = [
						'@type' => 'ProductModel',
						'@id'   => get_permalink( $parent_id ) . '#product',
						'name'  => $parent->get_name(),
					];
				}
				// GTIN Property Start
			$gtin = '';

				if ( is_object( $product ) ) {

					// WooCommerce newer versions.
					if ( method_exists( $product, 'get_global_unique_id' ) ) {
						$gtin = $product->get_global_unique_id();
					}

					// Fallback meta keys.
					if ( empty( $gtin ) ) {
						$gtin = get_post_meta( $product->get_id(), '_global_unique_id', true );
					}

					if ( empty( $gtin ) ) {
						$gtin = get_post_meta( $product->get_id(), '_gtin', true );
					}
				}

				$gtin = ! empty( $gtin ) ? sanitize_text_field( $gtin ) : '';


					if ( ! empty( $gtin ) ) {
						$schema['gtin'] = $gtin;
					}
				// GTIN Property End
		// Category Property Start
				$categoryObject     = new Vserpb_Category( $product_id );
			$categorySchema =  $categoryObject->vserpb_getSchema();
				if(!empty($categorySchema)){
						$schema['category'] = $categorySchema;
				}
		// Category Property End
				//brand property start 

				$brand = new Vserpb_Brand($product_id);
				$brandSchema = $brand->getSchema();

				if (!empty($brandSchema)) {
					$schema['brand'] = $brandSchema;
				}

				//brand property end
		// Review Property Start
			$reviewObj     = new Vserpb_Review( $product_id );
			$reviewsSchema = $reviewObj->vserpb_getSchema();
			if ( ! empty( $reviewsSchema ) ) {
				$schema['review'] = $reviewsSchema;
			}
		// Review Property End

		// Size Property Start
			$sizeobj     = new Vserpb_Size( $product );
			$size_output = $sizeobj->vserpb_getSchema();
				if ( ! empty( $size_output ) ) {
					$schema['size'] = $size_output;
				}
		// Size Property End
		// AggregateRating Property Star
				$rating = new Vserpb_AggregateRating( $product_id );
				$rating_schema = $rating->vserpb_getSchema();

				if ( ! empty( $rating_schema ) ) {
					$schema['aggregateRating'] = $rating_schema;
				}
		// AggregateRating Property End
		// Color Property Start
				$colorobject     = new Vserpb_Color( $product_id );
				$colorSchema = $colorobject->vserpb_get_schema();
				if( ! empty( $colorSchema ) ) {
					$schema['color'] = $colorSchema;
				}
		// Color Property End

//image filed start
				$images = $product->get_gallery_image_ids();
				$image_urls = array();

				// Get the main product image
				$main_image_id = $product->get_image_id();
				if ( $main_image_id ) {
					$main_image_url = wp_get_attachment_url( $main_image_id );
					if ( $main_image_url ) {
						$image_urls[] = esc_url( $main_image_url );
					}
				}

				// Get gallery images
				if ( ! empty( $images ) ) {
					foreach ( $images as $image_id ) {
						$image_url = wp_get_attachment_url( $image_id );
						if ( $image_url ) {
							$image_urls[] = esc_url( $image_url );
						}
					}
				}

				if ( ! empty( $image_urls ) ) {
					$schema['image'] = array_values( array_unique( $image_urls ) );
				}

//image field end

		// Logo Property Start
	
				$logo   = new Vserpb_ImageObject( $product_id );
				$Logoschema = $logo->vserpb_getSchema();
				if ( ! empty( $Logoschema ) ) {
					$schema['logo'] = $Logoschema;
				}
		
		// Logo Property End

		// Keywords Property Start
				$keyword = new Vserpb_Keyword( $product_id, 'product_tag' );
				$keywordSchema = $keyword->vserpb_getSchema();
				if ( ! empty( $keywordSchema ) ) {
					$schema['keywords'] = $keywordSchema;
				}
	
		// Keywords Property End


		// CountryOforigin Property Start
	
				$countryoforigin           = new Vserpb_Country( $product_id );
				$countryoforiginSchema = $countryoforigin->vserpb_getSchema();
				if ( ! empty( $countryoforiginSchema ) ) {
					$schema['countryOfOrigin'] = $countryoforiginSchema;
				}
		// CountryOforigin Property End

		// Offer Property Start
				$offer            = new Vserpb_Offer( $product_id );
				$offerSchema = $offer->vserpb_getSchema();
				if ( ! empty( $offerSchema ) ) {
					$schema['offers'] = $offerSchema;
				}
		// Offer Property End


		// Keywords Property Start
				$keywords           = new Vserpb_Keyword( $product_id );
				$keywordSchema = $keywords->vserpb_getSchema();
				if ( ! empty( $keywordSchema ) ) {
					$schema['keywords'] = $keywordSchema;
				}
		// Keywords Property End

		$schema = apply_filters( 'vserpb_extend_product_schema', $schema, $product_id );
		return $schema;
	}
}
