<?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 Joomla\CMS\Factory;
use Joomla\Database\DatabaseDriver;
use stdClass;

class FormeaElementAttribute
{
	/** @var int */
	protected $element_id;

	/** @var string $size */
	public $class;

	/** @var int */
	public $size;

	/** @var int */
	public $max_size;

	/** @var string */
	public $additional_attr;

	public function __construct($config = [])
	{
		if (isset($config['element_id'])) {
			$this->element_id = $config['element_id'];
		} else {
			$this->element_id = 0;
		}
	}

	/**
	 * Get element attribute values
	 *
	 * @param   bool  $formatted
	 *
	 * @return FormeaElementAttribute|null|stdClass
	 *
	 * @since 1.0.0
	 */
	public function getAttributes(bool $formatted = true)
	{
		$ret = null;
		if ($this->element_id > 0) {
			$container = Factory::getContainer();
			/** @var DatabaseDriver $db */
			$db = $container->get('DatabaseDriver');
			$columns = [
				'class',
				'size',
				'max_size',
				'additional_attr',
			];
			if (!$formatted) {
				$columns = '*';
			}
			$query = $db->getQuery(true);
			$query->select($columns);
			$query->from($db->quoteName('#__formea_element_attributes'));
			$query->where($db->quoteName('element_id') . ' = ' . $this->element_id);
			$db->setQuery($query);
			$ret = $db->loadAssoc();
			if (!empty($ret)) {
				if ($formatted) {
					foreach ($ret as $key => $value) {
						$this->{$key} = $value;
					}
					$ret = $this;
				} else {
					$ret = (object) $ret;
				}
			} else {
				//TODO:split the additional attr
				$ret = [
					'class'           => '',
					'size'            => -1,
					'max_size'        => -1,
					'additional_attr' => '',
				];
				if ($formatted) {
					foreach ($ret as $key => $value) {
						$this->{$key} = $value;
					}
					$ret = $this;
				}
			}
		} else {
			$ret = [
				'class'           => '',
				'size'            => -1,
				'max_size'        => -1,
				'additional_attr' => '',
			];
			if ($formatted) {
				foreach ($ret as $key => $value) {
					$this->{$key} = $value;
				}
				$ret = $this;
			}
		}

		return $ret;
	}

	public function setClass($class)
	{
		$this->class = $class;
	}
}
