<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class Vserpb_Product {

	private $product_id;
	private $product;
	private $name;
	private $description;
	private $url;
	private $image;
	private $sku;
	private $additional_type;

	public function __construct( $product_id ) {

		$this->product_id = $product_id;
		$this->product    = wc_get_product( $this->product_id );

		if ( ! $this->product ) {
			throw new Exception( 'Invalid product ID: ' . esc_html( $product_id ) );
		}

		$this->name        = $this->product->get_name();
		$this->url         = get_permalink( $this->product_id );
		$this->image       = wp_get_attachment_url( $this->product->get_image_id() ) ?: '';
		$this->description = wp_strip_all_tags( $this->product->get_short_description() );
		$this->sku         = $this->product->get_sku();

	
		$this->additional_type = $this->get_product_category_url();
	}

	/**
	 * Get product category URL for additionalType
	 */
	private function get_product_category_url() {

		$terms = get_the_terms( $this->product_id, 'product_cat' );

		if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
			return get_term_link( $terms[0] ); // Primary / first category
		}

		return '';
	}

	/**
	 * Product Schema
	 */
	public function vserpb_getSchema( $with_offer = false ) {

		$schema = array(
			'@type'       => 'Product',
			'name'        => $this->name,
			'description' => $this->description,
			'url'         => $this->url,
			'image'       => $this->image,
			'identifier'  => $this->sku,
			'mainEntityOfPage' => array(
				'@type' => 'WebPage',
				'@id'   => $this->url,
			),
			
		);

		if ( ! empty( $this->additional_type ) ) {
			$schema['additionalType'] = esc_url( $this->additional_type );
		}

		// Attach offers only if explicitly requested
		if ( $with_offer ) {
			try {
				$offer       = new Vserpb_Offer( $this->product_id );
				$offerSchema = $offer->vserpb_getSchema();

				if ( ! empty( $offerSchema ) && is_array( $offerSchema ) ) {
					$schema['offers'] = $offerSchema;
				}

			} catch ( Exception $e ) {
				
			}
		}

		return $schema;
	}
}
