<?php
/**
 * Handles article meta stock data storage.
 *
 * @package flo-sync
 */

namespace NMFS\Sync\Items\Articles\Stock;

use NMFS\Sync\Items\Articles\Stock\Models\Stock_Data_Collection_Model;

/**
 * Class Stock_Data_Storage
 */
class Stock_Data_Storage {

	private const META_KEY_STOCK_DATA = '_northmill_stock_data';

	/**
	 * Get stock data for a product.
	 *
	 * @param int $product_id The product ID.
	 *
	 * @return Stock_Data_Collection_Model|null
	 */
	public static function get( int $product_id ): ?Stock_Data_Collection_Model {
		$stock_data_json = get_post_meta( $product_id, self::META_KEY_STOCK_DATA, true );
		if ( empty( $stock_data_json ) ) {
			return null;
		}
		return Stock_Data_Collection_Model::jsonUnserialize( $stock_data_json );
	}

	/**
	 * Set stock data for a product.
	 *
	 * @param int                         $product_id            The product ID.
	 * @param Stock_Data_Collection_Model $stock_data_collection The stock data.
	 *
	 * @return bool True if successful, false otherwise.
	 */
	public static function set( int $product_id, Stock_Data_Collection_Model $stock_data_collection ): bool {
		$stock_data_json = wp_json_encode( $stock_data_collection );

		if ( empty( $stock_data_json ) ) {
			return false;
		}

		return self::update_db(
			$product_id,
			$stock_data_json
		);
	}

	/**
	 * Clear stock data for a product.
	 *
	 * @param int $product_id The product ID.
	 *
	 * @return bool True if successful, false otherwise.
	 */
	public static function clear( int $product_id ): bool {
		return self::update_db(
			$product_id,
			null
		);
	}

	/**
	 * Update stock data for a product.
	 *
	 * @param int         $product_id The product ID.
	 * @param null|string $stock_data JSON encoded stock data, or null to clear.
	 *
	 * @return bool True if successful, false otherwise.
	 */
	private static function update_db( int $product_id, ?string $stock_data ): bool {
		$curr_val = get_post_meta( $product_id, self::META_KEY_STOCK_DATA, true );

		if ( $curr_val === $stock_data ) {
			return true;
		}

		return update_post_meta(
			$product_id,
			self::META_KEY_STOCK_DATA,
			$stock_data
		);
	}
}
