<?php



use Idearia\Logger;



class WooProducts extends BaseObject {



	public function __construct() {

		parent::__construct("WooModel");

	}





	/* MAIN LOGIC */



	public function load() {



		Logger::debug( "Loading WooProducts()" );



		$result = [];

		$page = 1;



		while ($products = $this->model()->getProducts(["per_page" => 100, "page" => $page])) {

			$result = [...$result, ...$products];

			$page++;

		}



		$this->prop("products", $result);

		$this->isLoaded(true);



		return true;



	}



	public function loadCache() {



		Logger::debug( "Loading cached WooProducts()" );



		if (file_exists(DATA_DIR . "/cache-woo-products.json")) {

			$data = file_get_contents(DATA_DIR . "/cache-woo-products.json");

			if ($products = json_decode($data, 1)) {

				$this->prop("products", $products);

				$this->isLoaded(true);

				return true;

			}

		}



		return false;

	}



	public function saveCache() {



		Logger::debug( "Caching WooProducts()" );



		file_put_contents(DATA_DIR . "/cache-woo-products.json", json_encode($this->prop("products")));



		return true;



	}



	/* DATA LOGIC */









	/* PUBLIC SETTERS */

	

	public function hasProducts($filter) {

		return count($this->getProducts($filter)) > 0;

	}





	public function getProducts($filter) {

		$result = [];

		if ($this->prop("products")) {

			foreach ($this->prop("products") as $product) {

				$product["_tag_slugs"] = array_column($product["tags"], "slug");

				foreach ($filter as $key => $value) {

					if ($currentValue = $product[$key] ?? false) {

						if (is_array($currentValue)) {

							if (!in_array($value, $currentValue)) {

								continue 2;

							}

						} else {

							if ($value != $currentValue) {

								continue 2;

							}

						}



					}

				}

				$result[] = $product;

			}

		}

		return $result;

	}





	/* PUBLIC GETTERS */







	/* PRIVATE LOGIC */







}