<?php



use Idearia\Logger;



class AccProduct extends BaseObject {



	public function __construct() {

		parent::__construct("AccModel");

	}



	/* MAIN LOGIC */



	public function load($productId) {



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



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

			$this->props($productData);

			$this->isLoaded(true);



			Logger::info( "AccProduct loaded" );



			return true;

		} else {

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



			return false;

		}

	}

	public function loadByData($productData) {

		$this->props($productData);

		$this->isLoaded(true);



		Logger::info( "AccProduct loaded" );



		return true;

	}





	/* DATA LOGIC */





	/* PUBLIC SETTERS */





	/* PUBLIC GETTERS */



	public function getImageSrc() {

		return $this->getAccImageUri($this->prop("Picture"));

	}



	private function transformPrice($price, $rrp, $external) {

		$finalCost = $price * SyncData::PRICE_FC;



		if (0 < $rrp && $rrp < $external) {

			return $rrp;

		}



		$p = max(SyncData::PRICE_PV_MIN, $finalCost * SyncData::PRICE_PV);

		if ($price + $p < $external) {

			return $price + $p;

		}



		$p = $finalCost * SyncData::PRICE_MPV;

		$e = min(SyncData::PRICE_SV_MAX, max(SyncData::PRICE_SV_MIN, $external * SyncData::PRICE_SV));

		if ($price + $p < $external - $e) {

			return $external - $e;

		}



		$p = $finalCost * SyncData::PRICE_MPV;

		$e = min(SyncData::PRICE_SV_MAX, max(SyncData::PRICE_SV_MIN, $external * SyncData::PRICE_SV));

		if ($price + $p > $external - $e && $external - $e > 0) {

			return $price + $p;

		}



		if ($rrp > 0) {

			return $rrp;

		} else {

			$p = max(SyncData::PRICE_PV_MIN, $finalCost * SyncData::PRICE_PV);

			return $price + $p;

		}

	}

	private function roundPrice($price) {

		if ($price < 20) {

			return ceil($price * 2) / 2 - .01;

		} else {

			return ceil($price) - .01;

		}

	}

	private function getRRP($CountryId = "lt") {

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

			foreach ($this->prop("RRP") as $rrp) {

				if ($rrp["CountryId"] == $CountryId) {

					return $rrp;

				}

			}

		}

		return false;

	}



	public function getPrice($external = 0) {

		return $this->roundPrice($this->transformPrice(

			$this->prop(["Price", "Value"]),

			$this->getRRP()["Price"] ?? 0,

			$external

		));

	}

	public function getRegularPrice($external = 0) {

		return $this->roundPrice($this->transformPrice(

			$this->prop(["OldPrice", "Value"]) ?: $this->prop(["Price", "Value"]),

			$this->getRRP()["OldPrice"] ?? $this->getRRP()["Price"] ?? 0,

			$external

		));

	}

	public function isInStock() {

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

			foreach ($this->prop("Stocks") as $stockData) {

				if ($stockData["Amount"] > 0) {

					return true;

				}

			}

		}

		return false;		

	}

	public function getParameter($name) {

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

			foreach ($this->prop("Parameters") as $parameter) {

				if ($parameter['ParameterName'] == $name) {

					return $parameter["Value"];

				}

			}

		}

		return false;		

	}



	public function getMediaSrc($first = true) {

		$list = [];

		if ($src = $this->getImageSrc()) {

			$list = [['src' => $this->transformImageURI($src)]];

		}

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

			foreach ($this->prop("Medias") as $mediaData) {

				if ($mediaData["Type"] == 0 && $src = $this->getAccImageUri($mediaData["Uri"], $mediaData["OriginalUri"])) {

					$list[] = ['src' => $this->transformImageURI($src)];

				}

			}

		}

		if ($first && $list) {

			return [array_shift($list)];

		}

		array_shift($list);

		return $list;

	}



	private function transformImageURI($uri) {

		$uri = str_replace("https://www.blobs.lt/", "https://dev.namurobotai.lt/getimage/", $uri);

		$uri = str_replace("https://blobs.lt/", "https://dev.namurobotai.lt/getimage/", $uri);

		$uri = str_replace("http://www.blobs.lt/", "https://dev.namurobotai.lt/getimage/", $uri);

		$uri = str_replace("http://blobs.lt/", "https://dev.namurobotai.lt/getimage/", $uri);

		return $uri;

	}





	/* PRIVATE LOGIC */



    private function uriExists($uri) {

        $handle = curl_init($uri);

        curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

        $response = curl_exec($handle);

        $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);

        curl_close($handle);

		Logger::debug( "Checking URI({$uri}) CODE={$httpCode}" );

        if ($httpCode == 200) {

            return true;

        }

        return false;

    }

    private function getAccImageUri($uri, $originalUri = false) {

    	$uri = str_replace("http://", "https://", $uri);

    	$originalUri = str_replace("http://", "https://", $originalUri);



        $files = [

        	"{$originalUri}", 

        	"{$uri}",

        ];

        foreach (["original", "1920x1920", "440x440", "220x220", "50x50"] as $fPart) {

        	foreach (["png", "jpg"] as $fExt) {

        		$files[] = "{$uri}/{$fPart}.{$fExt}";

        	}

        }

        foreach ($files as $fileName) {

        	$imageUri = "{$fileName}";

            if ($this->uriExists($imageUri)) {

            	if ($mime = $this->getMime($imageUri)) {

            		if (explode("/", $mime)[0] == "image") {

		                return $imageUri;

            		}

            	}

            }

        }

        return "";

    }

    private function getMime($uri) {

    	try {

			$buffer = file_get_contents($uri);

			$finfo = new finfo(FILEINFO_MIME_TYPE);

			return $finfo->buffer($buffer);

    	} catch (Extension $e) {

    		return false;

    	}

    }









}