<?php
defined("DS") OR define("DS", DIRECTORY_SEPARATOR);

interface iTransQR {
	public function set_data(array $trans = []);
	public function get_content(array $trans = []);
	public function __toString();
}
//Outputbooks
class TransQR
{
	private $file_path = FCPATH . 'temp' . DS . "qrtrans";

	private $file_name = "";

	private $trans = null;

	function __construct(array &$trans = [])
	{
		if (!empty($trans))
		{
			$this->trans = &$trans;
		}
	}

	private function get_file_name()
	{
		if (!file_exists($this->file_path))
		{
			mkdir($this->file_path, 0777, true);
		}

		$this->file_path = $this->file_path . DS;

		$this->file_name = $this->trans["id"] . "_" . preg_replace("/[^a-zA-Z0-9]+/", "_", $this->trans['tNo']) . ".png";

		$file = $this->file_path . $this->file_name;

		@unlink($file);

		return $file;
	}

	private function _get_content(array &$trans = [])
	{
		$qrContent = "";

		if (!empty($trans["company"]))
		{
			$obj = null;

			$qrlib = "GeneralShort";

			if (!empty($trans["transQr"]))
			{
				$qrlib = $trans["transQr"];
			}
			else if ($trans["company"]["countryCode"] == "SA") // Saudi Arabia
			{
				$qrlib = "ZATCA";
			}

			$file = APPPATH . "third_party/TransQR/" . $qrlib . "/" . $qrlib . ".php";
			if (file_exists($file))
			{
				require_once($file);

				$obj = new $qrlib($trans);

				if ($obj)
				{
					$qrContent = $obj->get_content();
				}
			}
		}

		return $qrContent;
	}

	public static function GetModuleList()
	{
		$path = APPPATH . DS . "third_party" . DS . "TransQR" . DS . "*";
		$list = [];
		foreach(glob($path, GLOB_ONLYDIR) as $dir)
		{
			$list[] = basename($dir);
		}
		return $list;
	}

	public function get_content(array &$trans = [])
	{
		if (!empty($trans))
		{
			$this->trans = &$trans;
		}

		return $this->_get_content($this->trans);
	}

	public function __toString()
	{
		return $this->get_content();
	}

	public function render(array $qrOptions = [])
	{
		$levels = array('L','M','Q','H');
		$errorCorrectionLevel = $levels[0];

		$matrixPointSize = 5; // 1 - 10

		$qrContent = $this->get_content();

		$qrContent = substr($qrContent, 0, 2500);

		$file_path = $this->get_file_name();

		require_once(APPPATH . "third_party/phpqrcode/phpqrcode.php");

		QRcode::png($qrContent, $file_path, $errorCorrectionLevel, $matrixPointSize, 2);

		// $file_path = str_replace(FCPATH, base_url(), $file_path);

		return $file_path;
	}
}

