<?php



use Idearia\Logger;



class WooProduct extends BaseObject {



	public function __construct() {

		parent::__construct("WooModel");

	}





	/* MAIN LOGIC */



	public function load($productId) {



		Logger::debug( "Loading WooProduct({$productId})" );



		if ($productData = $this->model()->getProduct($productId)) {

			$this->props($productData);

			$this->prop( "_attributes", array_column($this->prop("attributes"), null, 'slug') );

			$this->prop( "_tags", array_column($this->prop("tags"), 'name', 'slug') );

			$this->isLoaded(true);



			Logger::info( "WooProduct loaded" );



			return true;

		} else {

			Logger::error( "WooProduct({$productId}) failed to load" );



			return false;

		}

	}



	public function loadBySKU($sku) {



		Logger::debug( "Loading WooProduct({$sku})" );



		if ($products = $this->model()->getProducts(["sku" => $sku])) {

			$this->load($products[0]["id"]);



			Logger::info( "WooProduct loaded" );



			return true;

		} else {

			Logger::warning( "WooProduct({$sku}) not found" );



			return false;

		}

	}



	public function update($data) {

		if ($this->isLoaded()) {

			$this->model()->putProduct($this->prop("id"), $data);

			return true;

		}

		return false;

	}



	public function create($data) {

		Logger::debug( "Creating WooProduct()" );



		$this->loadSystemAttributes();



		if (!isset($data["attributes"])) {

			$data["attributes"] = [];

		}



		if ($data["_attributes"]) {

			foreach ($data["_attributes"] as $attributeItem) {

				if ($attributeItem["slug"]) {

					$attributeData = $this->getSysAttribute($attributeItem["slug"], "slug");

				} else {

					$attributeData = $this->getSysAttribute($attributeItem["name"]);

				}

				if ($attributeData) {

					Logger::debug( "Found attribute ({$attributeItem['name']})" );

					$data["attributes"][] = [

						'id' => $attributeData["id"],

						'position' => 0,

						'variation' => false,

						'options' => [$attributeItem["value"]],

					];

				} else {

					$attributeCreate = [

					    'name' => $attributeItem["name"],

					    'type' => 'select',

					    'order_by' => 'menu_order',

					    'has_archives' => false,

					];

					if ($attributeData = $this->model()->addAttribute($attributeCreate)) {

						Logger::info( "Created attribute ({$attributeItem['name']}) ID={$attributeData['id']}" );

						$data["attributes"][] = [

							'id' => $attributeData["id"],

							'position' => 0,

							'variation' => false,

							'options' => [$attributeItem["value"]],

						];

					} else {

						Logger::error( "Failed attribute creation ({$attributeItem['name']})" );						

					}

				}

			}

		}



		if ($productData = $this->model()->addProduct($data)) {

			if ($brand = $data["_brand"] ?? false) {

				$this->model()->updateProductBrand($data["sku"], $brand);

			}

			$this->props($productData);

			$this->prop( "_attributes", array_column($this->prop("attributes"), null, 'slug') );

			$this->prop( "_tags", array_column($this->prop("tags"), 'name', 'slug') );

			$this->isLoaded(true);



			Logger::info( "WooProduct created" );



			return true;

		} else {

			Logger::warning( "WooProduct() error" );



			return false;

		}

	}







	private function loadSystemAttributes() {

		if ($attributesData = $this->model()->getAttributes()) {

			$this->prop( "_sysattributes", array_column($attributesData, null, 'slug') );

		}

		return false;

	}

	private function getSysAttribute($value, $by = "name") {

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

			foreach ($this->prop( "_sysattributes") as $slug => $attributeData) {

				if ($attributeData[$by] == $value) {

					return $attributeData;

				}

			}

		}

	}









	/* DATA LOGIC */





	/* PUBLIC SETTERS */





	/* PUBLIC GETTERS */



	public function isOnBackorder() {

		return $this->prop("stock_status") == "onbackorder";

	}

	public function getBrand() {

		return $this->getAttribute("pa_brand", true);

	}





	/* PRIVATE LOGIC */



	private function getAttribute($attributeKey, $firstValue = false) {

		if ($options = $this->prop(["_attributes", $attributeKey])["options"] ?? false) {

			return count($options) == 1 || $firstValue ? current($options) : $options;

		}

		return false;

	}







}