<?php

/**
 * @package     Joomla.Administrator
 * @subpackage  com_formea
 *
 * @copyright   Copyright (C) 2010-2025 Feseur Sdn Bhd. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 * @version     1.3.0
 */

namespace Joomla\Component\Formea\Site\Controller;

defined('_JEXEC') or die;

use Exception;
use Feseur\Library\FsrResponse;
use Joomla\CMS\Access\Access;
use Joomla\CMS\Factory;
use Joomla\Filesystem\File;
use Joomla\CMS\Helper\UserGroupsHelper;
use Joomla\CMS\Language\Associations;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Controller\BaseController;
use Joomla\Component\Formea\Administrator\Helper\FormeaHelper;
use Joomla\Component\Formea\Site\Helper\FormeaGeneralHelper;
use Joomla\Component\Formea\Site\Libraries\FormeaElement;

use Joomla\Component\Formea\Site\Libraries\FormeaValidations;
use Joomla\Component\Formea\Site\Model\ElementModel;
use Joomla\Filesystem\Path;
use stdClass;

class ElementController extends BaseController
{
	public function getValidationLists()
	{

		$element_id         = $this->input->getInt('element_id', 0);
		$response           = new FsrResponse();
		$validations        = new FormeaValidations();
		$lists              = $validations->getLists();
		$selectedValidation = [];
		if (!empty($lists)) {
			//$configs       = $validations->getConfigs($lists);
			$totalLists    = count($lists);
			$elValidations = [];
			if ($element_id > 0) {
				$fe                 = new FormeaElement(['element_id' => $element_id]);
				$elValidationsArray = $fe->getValidations();
				$elValidations      = FormeaGeneralHelper::formatKeyArray($elValidationsArray, 'validation_type');
			}
			for ($i = 0; $i < $totalLists; $i++) {
				//$lists[$i]->configs = $configs[$lists[$i]->name];
				if (isset($elValidations[$lists[$i]->name])) {
					$tgt = $elValidations[$lists[$i]->name];
					$t   = $lists[$i];
					if (isset($t->configs) && !empty($t->configs)) {
						$totalC = count($t->configs);
						for ($j = 0; $j < $totalC; $j++) {
							$name = $t->configs[$j]->name;
							if (isset($tgt[$name])) {
								$val = $tgt[$name];
								if ($t->configs[$j]->translatable) {
									$totalLangVal = count($t->configs[$j]->language_val);
									for ($l = 0; $l < $totalLangVal; $l++) {
										$lang_code = $t->configs[$j]->language_val[$l]->lang_code;

										if (isset($val[$lang_code])) {
											$t->configs[$j]->language_val[$l]->value = $val[$lang_code];
										}
									}
								} else {
									$t->configs[$j]->value = $val;
								}
							}
						}
					}
					$selectedValidation[] = $t;
				}
			}
		}


		$ret = [
			'lists'              => $lists,
			'selectedValidation' => $selectedValidation,
			'label'              => Text::_('COM_FORMEA_VALIDATION_TYPE')
		];
		//var_dump($ret);die;
		$response->setSuccess(true);
		$response->setResult($ret);
		echo json_encode($response);
		$this->app->close();
	}

	public function getOptionListsVal()
	{
		$element_id        = $this->input->getInt('element_id', 0);
		$element_type_name = $this->input->getString('type');

		$response = new FsrResponse();
		if (empty($element_type_name)) {
			$response->setSuccess(false);
			$response->setMsg('Empty type', 'danger', true);
		} else {
			$optionLists = [];

			/** @var ElementModel $model */
			$model             = $this->getModel('Element');
			$element_type      = $model->getElementType($element_type_name);
			$langTag           = $this->app->getLanguage()->getTag();
			$langTagUnderscore = str_replace('-', '_', $langTag);
			$langTitle         = $langTag;
			$languages         = FormeaGeneralHelper::getLanguages();
			$elementValues     = [];
			if ($element_id > 0) {
				$formeaElement = new FormeaElement(['element_id' => $element_id]);
				$elementValues = $formeaElement->getValues();
			}

			$totalLanguages = count($languages);
			for ($i = 0; $i < $totalLanguages; $i++) {
				if ($langTag == $languages[$i]->lang_code) {
					$langTitle = $languages[$i]->title;
					break;
				}
			}
			$isMulti = false;
			if (isset($element_type->config->values->isMulti)) {
				$isMulti = filter_var($element_type->config->values->isMulti, FILTER_VALIDATE_BOOLEAN);
			}
			$items = [];
			if (isset($elementValues[$langTagUnderscore])) {
				if (isset($elementValues[$langTagUnderscore]['option_lists'])) {
					if (!empty($elementValues[$langTagUnderscore]['option_lists'])) {
						$items = $elementValues[$langTagUnderscore]['option_lists'];
					}
				}
			}

			$optionLists[] = [
				'lang_code'  => $langTagUnderscore,
				'lang_title' => $langTitle,
				'items'      => $items,
				'isMulti'    => $isMulti
			];
			$optionLabel   = [
				'label'          => Text::_('COM_FORMEA_DEFAULT_VALUE'),
				'label_value'    => Text::_('COM_FORMEA_VALUE'),
				'label_text'     => Text::_('COM_FORMEA_TEXT'),
				'label_selected' => Text::_('COM_FORMEA_SELECTED'),
				'label_yes'      => Text::_('JYES'),
				'label_no'       => Text::_('JNO'),
				'label_desc'     => Text::_('COM_FORMEA_DEFAULT_VALUE_DESC'),
			];
			if (Associations::isEnabled()) {
				for ($i = 0; $i < $totalLanguages; $i++) {
					if ($langTag != $languages[$i]->lang_code) {
						$items             = [];
						$langTagUnderscore = str_replace('-', '_', $languages[$i]->lang_code);
						if (isset($elementValues[$langTagUnderscore])) {
							if (isset($elementValues[$langTagUnderscore]['option_lists'])) {
								if (!empty($elementValues[$langTagUnderscore]['option_lists'])) {
									$items = $elementValues[$langTagUnderscore]['option_lists'];
								}
							}
						}
						$optionLists[] = [
							'lang_code'  => $langTagUnderscore,
							'lang_title' => $languages[$i]->title,
							'items'      => $items,
							'isMulti'    => $isMulti
						];
					}
				}
			}


			$ret = [
				'optionLists' => $optionLists,
				'optionLabel' => $optionLabel
			];
			$response->setSuccess(true);
			$response->setResult($ret);
		}

		echo json_encode($response);
		$this->app->close();
	}

	public function getElementDetails()
	{

		$element_id        = $this->input->getInt('element_id', 0);
		$element_type_name = $this->input->getString('type');

		$response = new FsrResponse();
		if (empty($element_type_name)) {
			$response->setSuccess(false);
			$response->setMsg('Empty type', 'danger', true);
		} else {
			// /** @var ElementModel $model */
			/*$model = $this->getModel('Element','',['eltype_name'=>$element_type_name]);
				$elementType = $model->getElementType($element_type_name);*/
			/*$model = $this->getModel('Element','',['eltype_name'=>$element_type_name]);
				$element = $model->getItem($element_id);
				var_dump($element);die;*/
			/*$elType = new FormeaEltype(['name'=>$element_type_name]);
				$element = $elType->getElementType();*/
			$config = [];
			if ($element_id > 0) {
				$config['element_id'] = $element_id;
			}
			$langData = FormeaGeneralHelper::prepareLangDataVerbose(true);

			$fmElement = new FormeaElement($config);
			$fmElement->set('type', $element_type_name);
			$element = $fmElement->getElement();

			$element->getDetails();
			$details = $element->details;

			$details_rearranged = [];
			foreach ($details as $lang_code => $detail) {
				if (isset($langData[$lang_code])) {
					$details_rearranged[] = (object) [
						'lang_code'  => $langData[$lang_code]['lang_code'],
						'lang_title' => $langData[$lang_code]['lang_title'],
						'detail'     => $detail
					];
				}
			}
			$element->set('details', $details_rearranged);
			$element->details = $details_rearranged;
			$element->getValues();
			$values            = $element->elementvalues;
			$values_rearranged = [];
			foreach ($values as $lang_code => $detail) {
				if (isset($langData[$lang_code])) {
					$values_rearranged[] = (object) [
						'lang_code'  => $langData[$lang_code]['lang_code'],
						'lang_title' => $langData[$lang_code]['lang_title'],
						'detail'     => $detail
					];
				}
			}
			$element->elementvalues = $values_rearranged;

			$element->getValidations();
			$element->getElementTypeConfig();
			$element->getAttributes();

			//validations
			$validations         = new FormeaValidations();
			$validationLists     = $validations->getLists();
			$selectedValidations = FormeaHelper::mapSelectedValidations($validationLists, $element->validations);


			$obj                      = new stdClass();
			$obj->id                  = $element->id;
			$obj->title               = $element->title;
			$obj->alias               = $element->alias;
			$obj->type                = $element->type;
			$obj->state               = $element->state;
			$obj->params              = $element->params;
			$obj->checked_out         = $element->checked_out;
			$obj->checked_out_time    = $element->checked_out_time;
			$obj->created_date        = $element->created_date;
			$obj->modified_date       = $element->modified_date;
			$obj->modified_by         = $element->modified_by;
			$obj->created_by          = $element->created_by;
			$obj->access_level        = $element->access_level;
			$obj->publish_up          = $element->publish_up;
			$obj->publish_down        = $element->publish_down;
			$obj->attributes          = $element->attributes;
			$obj->details             = $details_rearranged;
			$obj->elementvalues       = $values_rearranged;
			$obj->elementTypeConfig   = $element->elementTypeConfig;
			$obj->validations         = $element->validations;
			$obj->selectedValidations = $selectedValidations;

			//Access levels
			$ug = \Joomla\CMS\HTML\Helpers\Access::assetgroups();


			$ret = [
				'element'          => $obj,
				'accessLevelLists' => $ug,
				'validationLists'  => $validations->getLists()
			];
			// var_dump($ret);die;

			$response->setSuccess(true);
			$response->setResult($ret);
		}

		echo json_encode($response);
		$this->app->close();
	}

	/**
	 *
	 * @return false|string|void
	 *
	 * @since 1.0.6
	 */
	public function apiCall()
	{

		$retObject = new FsrResponse();
		$app = Factory::getApplication();
		try {
			$mode = $this->input->get('formeaMode');
			if ($mode !== 'debug') {
				if (!$this->checkToken('GET')) {
					throw new Exception('Invalid token');
				}
			} else {
				if (!defined('FORMEA_PLG_PATH')) {
					define('FORMEA_PLG_PATH', JPATH_ROOT . '/components/com_formea/plugins');
					define('FORMEA_CORE_PATH', FORMEA_PLG_PATH . '/core');
					define('FORMEA_THEME_PATH', FORMEA_PLG_PATH . '/theme');
					define('FORMEA_ELEMENT_PATH', FORMEA_PLG_PATH . '/element');
					define('FORMEA_VALIDATION_PATH', FORMEA_PLG_PATH . '/validation');
				}
			}
			$methodName    = $app->getInput()->getString('methodName');
			$extensionName = $app->getInput()->getString('extensionName');
			$config        = $app->getInput()->getString('config', [], 'ARRAY');
			$args          = $app->getInput()->get('args', [], 'RAW');

			$clsName       = 'Formea' . $extensionName;
			$targetFile    = $clsName . '.php';
			if (!is_file(Path::clean(FORMEA_ELEMENT_PATH . '/' . $extensionName . '/' . $targetFile))) {
				throw new Exception('Invalid Element type');
			}
			require_once FORMEA_ELEMENT_PATH . '/' . $extensionName . '/' . $targetFile;
			if (!class_exists($clsName) || !method_exists($clsName, $methodName)) {
				throw new Exception('Invalid method');
			}
			$class  = new $clsName($config);
			$result = $class->{$methodName}($args);

			$retObject->setResult($result);
			$retObject->setSuccess(true);
		} catch (Exception $e) {
			$retObject->setSuccess(false);
			$retObject->setMsg($e->getMessage());
		}

		if ($mode !== 'debug') {
			echo json_encode($retObject);
			$this->app->close();
		} else {
			return json_encode($retObject);
		}
	}
}
