<?php

/**
 * @package     Joomla.Site
 * @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\Libraries;

defined('_JEXEC') or die;

use Feseur\Library\FsrFieldQuery;
use Joomla\CMS\Factory;
use Joomla\Database\DatabaseDriver;
use Joomla\Registry\Registry;

class FormeaElements
{
	/**
	 * @var FormeaElement[]
	 * @since 1.0.0
	 */
	public $elements = [];

	public function __construct() {}

	/**
	 * @param   boolean          $isCount
	 * @param   array            $db_limit
	 * @param   array            $ordering
	 * @param   FsrFieldQuery[]  $whereClause
	 *
	 *
	 * @since 1.0.0
	 */
	public function get($isCount = false, $fieldType = ['*'], $db_limit = [], $ordering = ['a.id' => 'DESC'], $whereClause = [])
	{
		if ($isCount) {
			$ret = $this->_totalItems($whereClause);
		} else {
			$ret = $this->_getElements($fieldType, $db_limit, $ordering, $whereClause);
		}

		return $ret;
	}

	/**
	 * @param   string[]         $fieldType
	 * @param                    $db_limit
	 * @param                    $ordering
	 * @param   FsrFieldQuery[]  $whereClause
	 *
	 *
	 * @since version
	 */
	protected function _getElements($fieldType = ['*'], $db_limit = [], $ordering = ['a.id' => 'DESC'], array $whereClause = [])
	{
		$ret    = [];
		$limit  = 5;
		$offset = 0;
		if (!empty($db_limit)) {
			if (isset($db_limit['limit'])) {
				$limit = (int) $db_limit['limit'];
			}
			if (isset($db_limit['offset'])) {
				$offset = (int) $db_limit['offset'];
			}
		}
		$container = Factory::getContainer();
		/** @var DatabaseDriver $db */
		$db    = $container->get('DatabaseDriver');
		$query = $db->getQuery(true);
		$query->select(['a.*', 'b.id AS eltype_id']);
		$query->from($db->quoteName('#__formea_elements', 'a'))->innerJoin(
			$db->quoteName('#__formea_eltypes', 'b') . ' ON ' . $db->quoteName('a.type') . ' = ' .
				$db->quoteName('b.name')
		);
		if (!empty($whereClause)) {
			foreach ($whereClause as $clause) {
				$v = $db->quote($clause->value);
				if ($clause->value[0] == '(' && $clause->value[strlen($clause->value) - 1] == ')') {
					$v = $clause->value;
				}
				$query->where(
					$db->quoteName($clause->field) . ' ' .
						$clause->operator . ' ' .
						$v
				);
			}
		}
		/*else
			{
			  $query->where($db->quoteName('a.state') . ' = 1');
			}*/
		if ($limit > 0) {
			$query->setLimit($limit, $offset);
		}
		foreach ($ordering as $column => $direction) {
			$query->order($db->quoteName($column) . ' ' . $direction);
		}
		$db->setQuery($query);
		$results = $db->loadObjectList();

		if (!empty($results)) {
			$defaultFields = $this->getDefaultfFields();
			$totalResults  = count($results);
			for ($i = 0; $i < $totalResults; $i++) {
				$element = new FormeaElement(['element_id' => $results[$i]->id]);
				foreach ($defaultFields as $field) {
					if ($field === 'params') {
						$p = new Registry($results[$i]->{$field});
						$element->set($field, $p);
					} else {
						$element->set($field, $results[$i]->{$field});
					}
				}

				if (!empty($fieldType)) {
					$t = [];
					foreach ($fieldType as $ty) {
						$t[] = strtoupper($ty);
					}
					$fieldType = $t;
					if (in_array('*', $fieldType)) {
						//all
						$element->getAttributes();
						$element->getValues();
						$element->getValues();
						$element->getDetails();
						$element->getValidations();
						$element->getPreview();
						$element->getPreviewBare();
						$element->getElementTypeImage();
						$element->getElementTypeTitle();
						$element->getElementTypeValueType();
						$element->getElementTypeId();
						$element->getElementPreviewSettings();
					} else {
						if (in_array('VALUES', $fieldType)) {
							$element->getValues();
						}
						if (in_array('ATTRIBUTES', $fieldType)) {
							$element->getAttributes();
						}
						if (in_array('DETAILS', $fieldType)) {
							$element->getDetails();
						}
						if (in_array('VALIDATIONS', $fieldType)) {
							$element->getValidations();
						}
						if (in_array('PREVIEW', $fieldType)) {
							$element->getPreview();
						}
						if (in_array('PREVIEWBARE', $fieldType)) {
							$element->getPreviewBare();
						}
						if (in_array('LABELSETTINGS', $fieldType)) {
							$element->getLabelSettings();
						}
						if (in_array('IMAGEDETAILS', $fieldType)) {
							$element->getElementTypeImage();
						}
						if (in_array('ELEMENTTYPETITLE', $fieldType)) {
							$element->getElementTypeTitle();
						}
						if (in_array('ELEMENTTYPEVALUETYPE', $fieldType)) {
							$element->getElementTypeValueType();
						}
						if (in_array('ELEMENTTYPEID', $fieldType)) {
							$element->getElementTypeId();
						}
						if (in_array('PREVIEWSETTINGS', $fieldType)) {
							$element->getElementPreviewSettings();
						}
					}
				}
				$ret[] = $element;
			}
		}

		return $ret;
	}


	public function getItemCountData($db_limit = [], $whereClause = [])
	{
		$limit  = 5;
		$offset = 0;
		if (!empty($db_limit)) {
			if (isset($db_limit['limit'])) {
				$limit = (int) $db_limit['limit'];
			}
			if (isset($db_limit['offset'])) {
				$offset = (int) $db_limit['offset'];
			}
		}
		$total = $this->_totalItems($whereClause);
		$page  = 1;
		if ($offset > 0) {
			$page = ceil(($offset + 1) / $limit);
		}
		$fromResult = $offset + 1;
		$toResult   = 0;
		if ($offset + $limit < $total) {
			$toResult = $offset + $limit;
		} else {
			$toResult = $total;
		}

		return [
			'total'      => $total,
			'limit'      => $limit,
			'offset'     => $offset,
			'page'       => (int) $page,
			'fromResult' => $fromResult,
			'toResult'   => $toResult
		];
	}

	protected function _totalItems($whereClause = [])
	{
		$container = Factory::getContainer();
		/** @var DatabaseDriver $db */
		$db    = $container->get('DatabaseDriver');
		$query = $db->getQuery(true);
		$query->select('COUNT(*)');
		$query->from($db->quoteName('#__formea_elements', 'a'))->innerJoin(
			$db->quoteName('#__formea_eltypes', 'b') . ' ON ' . $db->quoteName('a.type') . ' = ' .
				$db->quoteName('b.name')
		);
		if (!empty($whereClause)) {
			foreach ($whereClause as $clause) {
				$v = $db->quote($clause->value);
				if ($clause->value[0] == '(' && $clause->value[strlen($clause->value) - 1] == ')') {
					$v = $clause->value;
				}
				$query->where(
					$db->quoteName($clause->field) . ' ' .
						$clause->operator . ' ' .
						$v
				);
			}
		}
		$db->setQuery($query);

		return $db->loadResult();
	}

	public function getDefaultfFields()
	{
		return [
			'id',
			'title',
			'alias',
			'type',
			'state',
			'params',
			'checked_out',
			'checked_out_time',
			'created_date',
			'modified_date',
			'modified_by',
			'created_by',
			'access_level',
			'publish_up',
			'publish_down',
		];
	}
}
