<?php
 if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**
 * Vserpb_Category
 */
class Vserpb_Category {

	private $product_id;
	private $categories = array();
	private $tags       = array();
	private $schema     = array();

	public function __construct( $product_id ) {
		$this->product_id = $product_id;
		$this->vserpb_setCategories();
		$this->vserpb_buildSchema();
	}

	/**
	 * vserpb_setCategories
	 *
	 * @return void
	 */
	private function vserpb_setCategories() {
		$categories = wp_get_post_terms( $this->product_id, 'product_cat' );
		if ( ! empty( $categories ) && ! is_wp_error( $categories ) ) {
			foreach ( $categories as $category ) {
				if ( $category->name !== 'Uncategorized' ) {
					$this->categories[] = array(
						'id'          => $category->term_id,
						'name'        => $category->name,
						'description' => ! empty( $category->description ) ? $category->description : 'No description available.',
					);
				}
			}
		}
	}

	/**
	 * vserpb_buildSchema
	 *
	 * @return void
	 */
	private function vserpb_buildSchema() {
		$this->schema = array();
		foreach ( $this->categories as $category ) {
		$term_link = get_term_link( (int) $category['id'], 'product_cat' );

			$this->schema[] = array(
				'@type'       => 'CategoryCode',
				'name'        => $category['name'],
				'description' => $category['description'],
				'codeValue'   => $category['id'],
				'url'         => ! is_wp_error( $term_link ) ? esc_url( $term_link ) : '',
			);

		}


	}

	/**
	 * Vserpb_getSchema
	 *
	 * @return void
	 */
	public function vserpb_getSchema() {
		return ! empty( $this->schema ) ? $this->schema : array(
			array(
				'@type' => 'Text',
				'value' => 'Uncategorized Product',
			),
		);
	}
}
