<?php



// error_reporting(E_ALL);



use Idearia\Logger;



class AccProductController {



	private $branch = false;

	private $wooProducts = false;



	private function queueApiCall($url) {

		Logger::debug( "AccProductController::queueApiCall() URL={$url}" );

		file_get_contents("https://sync.lazyhouse.lt/api/{$url}");

	}



	public function prepareImportBranches() {

		foreach (SyncData::ACC_BRANCHES as $branchData) {

			$this->queueApiCall("acc/branch/{$branchData['branchId']}/import");

		}

	}

	public function loadBranch($branchId) {

		$this->branch = new AccProducts();

		return $this->branch->load($branchId);

	}

	public function loadWooProducts() {

		$this->wooProducts = new WooProducts();

		if ($this->wooProducts->loadCache()) {

			return true;

		} else {

			if ($this->wooProducts->load()){

				$this->wooProducts->saveCache();

				return true;

			}

		}

		return false;

	}

	public function prepareImportProducts() {

		$skuList = [];

		foreach ($this->branch->getProducts() as $product) {

			$sku = $product["MPN"];

			$skuList[] = $sku;

			if (!$this->wooProducts->hasProducts([ "sku" => $sku ])) {

				$this->queueApiCall("acc/product/{$product['PID']}/import");

			} else {

				$this->queueApiCall("acc/product/{$product['PID']}/sync");

				// $accProduct = new AccProduct();

				// $accProduct->loadByData($product);

				// $currentStockStatus = $accProduct->isInStock() ? "instock" : "outofstock";

				// if ($wooProducts = $this->wooProducts->getProducts([ "sku" => $sku ])) {

				// 	foreach ($wooProducts as $wooProduct) {

				// 		if ($wooProduct["stock_status"] != $currentStockStatus) {

				// 			break;

				// 		}

				// 	}

				// }

			}

		}

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

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

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

				$product["_tag_ids"] = array_column($product["tags"], "id");

				//SyncData::ACC_TAG

				if (!in_array($product["sku"], $skuList) && in_array(SyncData::ACC_TAG, $product["_tag_ids"])) {

					if ($product["stock_status"] == "instock" && $product["status"] == "publish") {

						$this->queueApiCall("woo/product/{$sku}/unpublish");

					}

				}

			}

		}

	}



	public function prepareSyncBranches() {

		foreach (SyncData::ACC_BRANCHES as $branchData) {

			$this->queueApiCall("acc/branch/{$branchData['branchId']}/sync");

		}

	}

	public function syncBranch() {

		foreach ($this->branch->getProducts() as $product) {

			if ($this->wooProducts->hasProducts([ "sku" => $product["MPN"] ])) {

				// sync product

			}

		}		

	}



	public function processImportProduct($accProductId) {

        Logger::debug( "processImportProduct {$accProductId}..." );

		$accProduct = new AccProduct();

		$accProduct->load($accProductId);



		$categories = [];

		foreach ($accProduct->prop("Branches") as $branchInfo) {

			foreach (SyncData::ACC_BRANCHES as $branchData) {

				if ("{$branchInfo['OId']}" == "{$branchData['branchId']}") {

					$categories[] = [ 'id' => $branchData["categoryId"] ];

				}

			}

		}

		if (count($categories) == 0) {

	        Logger::debug( "No appropriate categories. BRANCHES=" . json_encode($accProduct->prop("Branches")) );

			return false;

		}



		$productData = [

		    'name' => $accProduct->prop("Name"),

		    "sku" => $accProduct->prop("MPN"),

		    'type' => 'simple',

		    "status" => "draft",

		    "featured" => false,

		    "purchasable" => true,

		    "manage_stock" => false,

		    "stock_status" => $accProduct->isInStock() ? "instock" : "outofstock",

		    "catalog_visibility" => "visible",

		    'price' => "" . $accProduct->getPrice(0),

		    'regular_price' => "" . $accProduct->getRegularPrice(0),

		    'description' => '',

		    'short_description' => '',

		    'images' => $accProduct->getMediaSrc(true),

		    'categories' => $categories,

		    "tags" => [

		    	["id" => SyncData::ACC_TAG],

		    ],

			"dimensions" => [

				"length" => $accProduct->getParameter("Gross depth (mm)") ?: "",

				"width" => $accProduct->getParameter("Gross width (mm)") ?: "",

				"height" => $accProduct->getParameter("Gross height (mm)") ?: "",

			],

			"weight" => $accProduct->getParameter("Gross weight") ?: "",

		    "attributes" => [],

		    "meta_data" => [

		    	["key" => "_alg_wc_pq_min", "value" => (intval($accProduct->getParameter("Packing quantity")) ?: "1")],

		    	["key" => "_alg_wc_pq_step", "value" => (intval($accProduct->getParameter("Packing quantity")) ?: "1")],

		    	["key" => "_accId", "value" => "{$accProductId}"],

		    ],

		    "_brand" => $accProduct->prop(["Producer", "Name"]),

		    "_attributes" => [],

		];



		foreach ($accProduct->prop("Parameters") as $p) {

			if (!in_array($p["ParameterName"], SyncData::ACC_ATTRIBUTES_EXCLUDE)) {

				$attributeData = [

					"name" => $p['ParameterName'],

					"slug" => $this->getAccAttributeSlug($p['ParameterName']),

					"value" => $p['Value'] . ($p['MeasureAbbr'] ? " {$p['MeasureAbbr']}" : ""),

				];

				$productData["_attributes"][] = $attributeData;

        		Logger::debug( "processImportProduct PARAMDATA FOUND=" . json_encode($p, JSON_UNESCAPED_UNICODE) );

        		Logger::debug( "processImportProduct PARAMDATA=" . json_encode($attributeData, JSON_UNESCAPED_UNICODE) );

			} else {

        		Logger::debug( "processImportProduct PARAMDATA SKIPPED=" . json_encode($p, JSON_UNESCAPED_UNICODE) );



			}

		}



		$wooProduct = new WooProduct();

		if ($wooProduct->loadBySKU($accProduct->prop("MPN"))) {

        	Logger::debug( "processImportProduct ALREADY EXIST " . $accProduct->prop("MPN") );

			return true;

		} else {

			if ($wooProduct->create($productData)) {

	        	// $this->queueApiCall("acc/product/{$accProductId}/pictures");

	        	// $this->queueApiCall("acc/product/{$accProductId}/gpt");

				return true;

			}

		}



		return false;

	}



	public function processSyncProduct($accProductId) {

        Logger::debug( "processSyncProduct {$accProductId}..." );



		$accProduct = new AccProduct();

		$accProduct->load($accProductId);



		$wooProduct = new WooProduct();

		if ($wooProduct->loadBySKU($accProduct->prop("MPN"))) {

			$wooProduct->update([

			    "stock_status" => $accProduct->isInStock() ? "instock" : "outofstock",

			]);

			return true;

		}



		return false;

	}



	public function processUnpublishProduct($wooProductId) {

        Logger::debug( "processUnpublishProduct {$wooProductId}..." );



		$wooProduct = new WooProduct();

		if ($wooProduct->load($wooProductId)) {

			$wooProduct->update(["status" => "draft"]);

			return true;

		}



		return false;

	}









	private function getAccAttributeSlug($attributeName) {

		foreach (SyncData::ACC_ATTRIBUTES_REWRITE as $slug => $name) {

			if ($name == $attributeName) {

				return $slug;

			}

		}

		return false;

	}



}