<?php

namespace HulkPlugins\Woo\ProductConditionManager\Models;

use HulkPlugins\Woo\ProductConditionManager\Traits\SingletonTrait;
use WC_Product;

defined( 'ABSPATH' ) || exit;

class ProductModel {
	use SingletonTrait;

	private array $cache = [];

	private array $defaultMeta = [
		'hulk_woo_pcm_productCondition'            => '',
		'hulk_woo_pcm_productConditionCustomGroup' => '',
		'hulk_woo_pcm_productConditionCustom'      => '',
		'hulk_woo_pcm_productConditionLabel'       => '',
		'hulk_woo_pcm_productConditionShopLabel'   => '',
	];

	/**
	 * @param $post_id
	 *
	 * @return false|mixed|WC_Product|null
	 */
	public function getProduct( $post_id ) {
		if ( isset( $this->cache['product'][ $post_id ] ) ) {
			return $this->cache['product'][ $post_id ];
		}
		$product = wc_get_product( $post_id );
		$this->cache['product'][ $post_id ] = $product;
		return $product;
	}

	/**
	 * Retrieves a post meta field for the given post ID.
	 *
	 * @param $post_id
	 * @param string $key
	 * @param bool $single
	 *
	 * @return array|mixed|string|null
	 */
	public function getMeta( $post_id, string $key = '', bool $single = true ) {
		$product = $this->getProduct( $post_id );
		if ( ! $product ) {
			return null;
		}
		return $product->get_meta( $key, $single );
	}

	/**
	 * Get all metadata
	 * @param $post_id
	 *
	 * @return array
	 */
	public function getAllMeta( $post_id ): array {
		$data = [];
		$product = $this->getProduct( $post_id );
		if ( ! $product ) {
			return $data;
		}
		foreach ( $this->defaultMeta as $key => $value ) {
            $data[ $key ] = $product->get_meta( $key );
		}
		return $data;
	}

	/**
	 * Update all metadata
	 *
	 * @param $post_id
	 * @param array $data
	 *
	 * @return int
	 */
	public function updateAllMeta( $post_id, array $data ): int {
		$product = $this->getProduct( $post_id );
		foreach ( $this->defaultMeta as $key => $value ) {
			if ( isset( $data[ $key ] ) ) {
				$product->update_meta_data( $key, wc_clean( $data[ $key ] ) );
			}
		}
		return $product->save();
	}

	/**
	 * Delete the all metadata
	 *
	 * @return void
	 */
	public function deleteAllMeta(): void {
		foreach ( $this->defaultMeta as $key => $value ) {
			delete_post_meta_by_key( $key );
		}
	}
}
