<?php
/**
 * Manage Color Swatches
 *
 * PHP version 5.6
 *
 * @category  Settings
 * @package   Eloquent
 * @author    Sanjeeb <steve@imprintnext.com>
 * @copyright 2019-2023 Riaxe Systems
 * @license   http://www.php.net/license/3_0.txt  PHP License 3.0
 * @link      http://inkxe-v10.inkxe.io/xetool/admin
 */
namespace App\Modules\Settings\Controllers;

use App\Components\Controllers\Component as ParentController;

/**
 * DesignerScript Controller
 *
 * @category Class
 * @package  Setting
 * @author   Sanjeeb <steve@imprintnext.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://inkxe-v10.inkxe.io/xetool/admin
 */
class DesignerScriptController extends ParentController {

	/**
	 * GET: Add new custom script
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author Sanjeeb <steve@imprintnext.com>
	 * @date   18 Jan 2023
	 * @return Status
	 */
	public function addDesignerScript($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Settings', 'error')
		];
		$allPostPutVars = $request->getParsedBody();
		$title = $allPostPutVars['title'];
		$script = $allPostPutVars['script'];

		// Check the script valid or not
		$status = $this->validateScript($script);
		if ($status == 0) {
			$oldJsonContent = [];
			$jsonDir = ASSETS_PATH_W . DESIGNER_SCRIPT . "/";
			$jsonPath = $jsonDir . "/" . "custom_script.json";
			$defaultScriptPath = $jsonDir . "/" . "designer_script.json";
			$indexPath = ASSETS_PATH_W . "../index.html";
			$indexContent = file_get_contents($indexPath);
			$designerScript = "";
			$defaultScript = $this->getStringBetween($indexContent, '<head>', '</head>');
			$designerScript = $defaultScript;
			$newIndexContent = "";
			$write = 0;

			//Check default script file avaliable or not , if not create defaut script once only.
			if (!file_exists($defaultScriptPath)) {
				if (!is_dir($jsonDir)) {
					mkdir($jsonDir);
				}
				file_put_contents($defaultScriptPath, $defaultScript);
			}

			//Check custom script availbe or not if not create add script into it as json format.
			if (file_exists($jsonPath)) {
				$oldJsonContent = file_get_contents($jsonPath);
				$oldJsonArray = json_clean_decode($oldJsonContent, true);
				if (array_search($script, array_column($oldJsonArray, 'script')) !== false) {
					$jsonResponse['message'] = "Script Already Available";
				} else {
					$oldJsonArray[] = ["title" => $title, "script" => $script, "type" => "custom"];
					$newJsonContent = json_encode($oldJsonArray);
					file_put_contents($jsonPath, $newJsonContent);
					$write = 1;
					$jsonResponse = [
						'status' => 1,
						'message' => "Script Added Successfully"
					];
				}
			} else {
				$oldJsonArray[] = ["title" => "Default Script", "script" => $defaultScript, "type" => "default_script"];
				$oldJsonArray[] = ["title" => $title, "script" => $script, "type" => "custom"];
				$newJsonContent = json_encode($oldJsonArray);

				file_put_contents($jsonPath, $newJsonContent);
				$designerScript .= "<!-- Designer-Custom-Script-START -->";
				$write = 1;
				$jsonResponse = [
					'status' => 1,
					'message' => "Script Added Successfully",
				];
			}
			if ($write == 1) {
				$designerScript .=  "<!-- START " . $title . " -->" . $script . "<!-- END " . $title . " -->";
				$newIndexContent = str_replace($defaultScript, $designerScript, $indexContent);
				file_put_contents($indexPath, $newIndexContent);
			}
		} else {
			$jsonResponse['message'] = "Invalid Script";
		}

		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}

	/**
	 * GET: List All Custom script
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author Sanjeeb <steve@imprintnext.com>
	 * @date   18 Jan 2023
	 * @return Status
	 */
	public function getDesignerScriptList($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 1,
			'data' => []
		];
		$oldJsonContent = [];
		$jsonDir = ASSETS_PATH_W . DESIGNER_SCRIPT . "/";
		create_directory($jsonDir);
		$jsonPath = $jsonDir . "/" . "custom_script.json";
		if (file_exists($jsonPath)) {
			$oldJsonContent = file_get_contents($jsonPath);
			$oldJsonContent = json_clean_decode($oldJsonContent, true);
			foreach ($oldJsonContent as $key => $value) {
				if ($value['type'] == "custom") {
					$scriptArray[] = ["id" => $key, "title" => $value['title'], "type" => $value['type'], "script" => $value['script']];
				}
			}
			$jsonResponse = [
				'status' => 1,
				'data' => $scriptArray
			];
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}

	/**
	 * GET: Delete Custom Script
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author Sanjeeb <steve@imprintnext.com>
	 * @date   18 Jan 2023
	 * @return Status
	 */
	public function deleteDesignerScript($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => "Script not available"
		];
		$allPostPutVars = $request->getParsedBody();
		$id = $allPostPutVars['id'];

		$oldJsonContent = [];
		$jsonDir = ASSETS_PATH_W . DESIGNER_SCRIPT . "/";
		$jsonPath = $jsonDir . "/" . "custom_script.json";

		$oldJsonContent = file_get_contents($jsonPath);
		$oldJsonArray = json_clean_decode($oldJsonContent, true);

		if (isset($oldJsonArray[$id]) && $oldJsonArray[$id]['type'] == 'custom') {
			unset($oldJsonArray[$id]);
			$designerScript = "";
			$key = 0;
			foreach ($oldJsonArray as  $value) {
				if ($key == 0) {
					$designerScript .=  $value['script'];
					$designerScript .= "<!-- Designer-Custom-Script-START -->";
					$key++;
				} else {
					$designerScript .=  "<!-- START " . $value['title'] . " -->" . $value['script'] . "<!-- END " . $value['title'] . " -->";
				}
			}
			$newJson = json_encode($oldJsonArray);
			file_put_contents($jsonPath, $newJson);

			$indexPath = ASSETS_PATH_W . "../index.html";
			$indexContent = file_get_contents($indexPath);

			$defaultScript = $this->getStringBetween($indexContent, '<head>', '</head>');
			$newIndexContent = str_replace($defaultScript, $designerScript, $indexContent);
			file_put_contents($indexPath, $newIndexContent);

			$jsonResponse = [
				'status' => 1,
				'message' => "Removed Successfully",
			];
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}

	/**
	 * GET: Update Custom Script
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author Sanjeeb <steve@imprintnext.com>
	 * @date   18 Jan 2023
	 * @return Status
	 */
	public function updateDesignerScript($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => "Unable to update script"
		];
		$allPostPutVars = $request->getParsedBody();

		$id = $allPostPutVars['id'];
		$title = $allPostPutVars['title'];
		$script = $allPostPutVars['script'];
		$status = $this->validateScript($script);
		if ($status == 0) {
			$oldJsonContent = [];
			$jsonDir = ASSETS_PATH_W . DESIGNER_SCRIPT . "/";
			$jsonPath = $jsonDir . "/" . "custom_script.json";

			$oldJsonContent = file_get_contents($jsonPath);
			$oldJsonArray = json_clean_decode($oldJsonContent, true);

			if (isset($oldJsonArray[$id]) && $oldJsonArray[$id]['type'] == 'custom') {
				$oldJsonArray[$id] = ["title" => $title, "script" => $script, "type" => "custom"];
				$designerScript = "";
				$key = 0;
				foreach ($oldJsonArray as  $value) {
					if ($key == 0) {
						$designerScript .=  $value['script'];
						$designerScript .= "<!-- Designer-Custom-Script-START -->";
					} else {
						$designerScript .=  "<!-- START " . $value['title'] . " -->" . $value['script'] . "<!-- END " . $value['title'] . " -->";
					}
					$key++;
				}
				$newJson = json_encode($oldJsonArray);
				file_put_contents($jsonPath, $newJson);

				$indexPath = ASSETS_PATH_W . "../index.html";
				$indexContent = file_get_contents($indexPath);

				$defaultScript = $this->getStringBetween($indexContent, '<head>', '</head>');
				$newIndexContent = str_replace($defaultScript, $designerScript, $indexContent);
				file_put_contents($indexPath, $newIndexContent);

				$jsonResponse = [
					'status' => 1,
					'message' => "Script Updated Successfully"
				];
			}
		} else {
			$jsonResponse = [
				'status' => 0,
				'message' => "Invalid Script"
			];
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}

	/**
	 * GET: Reset Custom Script
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author Sanjeeb <steve@imprintnext.com>
	 * @date   18 Jan 2023
	 * @return Status
	 */
	public function resetDesignerScript($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonDir = ASSETS_PATH_W . DESIGNER_SCRIPT . "/";
		$defaultScriptPath = $jsonDir . "/" . "designer_script.json";
		$defaultScript = file_get_contents($defaultScriptPath);
		$customScriptPath = $jsonDir . "/" . "custom_script.json";
		if (file_exists($defaultScriptPath)) {
			$indexPath = ASSETS_PATH_W . "../index.html";
			$indexContent = file_get_contents($indexPath);
			$currentScript = $this->getStringBetween($indexContent, '<head>', '</head>');
			$newIndexContent = str_replace($currentScript, $defaultScript, $indexContent);
			file_put_contents($indexPath, $newIndexContent);
			unlink($customScriptPath);
			unlink($defaultScriptPath);
			$jsonResponse = [
				'status' => 1,
				'message' => "Script Updated Successfully"
			];
		} else {
			$jsonResponse = [
				'status' => 0,
				'message' => "Failed to reset"
			];
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}
	
	private function getStringBetween($string, $start, $end)
    {
		$string = ' ' . $string;
		$ini = strpos($string, $start);
		if ($ini == 0) {
			return '';
		}
		$ini += strlen($start);
		$len = strpos($string, $end, $ini) - $ini;
		return substr($string, $ini, $len);
    }

	private function validateScript($string)
	{
		$start = strpos($string, '<');
		$end  = strrpos($string, '>', $start);

		$len = strlen($string);

		if ($end !== false) {
			$string = substr($string, $start);
		} else {
			$string = substr($string, $start, $len - $start);
		}
		libxml_use_internal_errors(true);
		libxml_clear_errors();
		simplexml_load_string($string);
		return count(libxml_get_errors());
	}
}