<?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 Exception;
use Feseur\Library\FsrFieldQuery;
use Joomla\CMS\Factory;
use Joomla\Filesystem\File;
use Joomla\Filesystem\Folder;
use Joomla\CMS\Language\Text;
use Joomla\Database\DatabaseDriver;
use Joomla\Filesystem\Path;
use stdClass;

class FormeaEltypes
{


  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, $db_limit = [], $ordering = ['a.id' => 'DESC'], $whereClause = [])
  {
    if ($isCount) {
      $ret = $this->_totalItems($whereClause);
    } else {
      $ret = $this->_getEltypes($db_limit, $ordering, $whereClause);
    }

    return $ret;
  }

  /**
   * @param                    $db_limit
   * @param                    $ordering
   * @param   FsrFieldQuery[]  $whereClause
   *
   * @return array
   *
   * @throws Exception
   * @since version
   */
  protected function _getEltypes($db_limit = [], $ordering = ['a.id' => 'DESC'], array $whereClause = [])
  {
    $ret    = [];
    $limit  = 15;
    $offset = 0;
    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('*');
    $query->from($db->quoteName('#__formea_eltypes', 'a'));
    if (!empty($whereClause)) {
      foreach ($whereClause as $clause) {
        $query->where(
          $db->quoteName($clause->field) . ' ' .
            $clause->operator . ' ' .
            $db->quote($clause->value)
        );
      }
    } else {
      $query->where($db->quoteName('a.state') . ' = 1');
    }
    if ($limit > 0) {
      $query->setLimit($limit, $offset);
    }
    if (empty($ordering)) {
      $ordering = ['a.id' => 'DESC'];
    }
    foreach ($ordering as $column => $direction) {
      $query->order($db->quoteName($column) . ' ' . $direction);
    }
    $db->setQuery($query);
    $results = $db->loadObjectList();
    if (!empty($results)) {
      $app          = Factory::getApplication();
      $lang         = $app->getLanguage();
      $langTag      = $lang->getTag();
      $totalResults = count($results);
      for ($i = 0; $i < $totalResults; $i++) {
        $langPath = JPATH_ROOT . '/components/com_formea/plugins/element/' . $results[$i]->name;
        if (is_dir(Path::clean($langPath . '/language/' . $langTag))) {
          $lang->load($results[$i]->name, $langPath, $langTag);
        }
        $elementJson = null;
        if (is_file(Path::clean($langPath . '/element.json'))) {
          $elementJson = json_decode(file_get_contents($langPath . '/element.json'));
        }
        $results[$i]->imageDetails = (array) $this->_getImageDetails($elementJson);
        $results[$i]->title        = Text::_($results[$i]->title);
        $results[$i]->description  = Text::_($results[$i]->description);
        $ret[]                     = $results[$i];
      }
    }

    return $ret;
  }

  protected function _totalItems($whereClause = [])
  {
    return 0;
  }

  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',
    ];
  }

  protected function _getImageDetails($elementConfig)
  {
    $ret            = new stdClass();
    $ret->image     = '';
    $ret->imageSafe = '';
    $ret->imageType = '';
    if (!empty($elementConfig)) {
      if (isset($elementConfig->imageDetails)) {
        $ret = $elementConfig->imageDetails;
      }
    }

    return $ret;
  }
}
