<?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\Application\CMSApplicationInterface;
use Joomla\CMS\Factory;
use Joomla\Filesystem\File;
use Joomla\Filesystem\Folder;
use Joomla\CMS\Language\Associations;
use Joomla\CMS\Language\Text;
use Joomla\Component\Formea\Site\Helper\FormeaGeneralHelper;
use Joomla\Database\DatabaseDriver;
use Joomla\Filesystem\Path;

class FormeaValidations
{

  /**
   * Directory to the validation plugin ends with slash
   * @var string
   * @since 1.0.0
   */
  public $dirPath;

  /**
   * @var CMSApplicationInterface|null
   * @since 1.0.0
   */
  protected $app;

  public function __construct()
  {
    $this->app     = Factory::getApplication();
    $this->dirPath = JPATH_ROOT . '/components/com_formea/plugins/validation/';
  }

  public function getLists()
  {
    $container = Factory::getContainer();
    /** @var DatabaseDriver $db */
    $db    = $container->get('DatabaseDriver');
    $query = $db->getQuery(true);
    $query->select('*');
    $query->from($db->quoteName('#__formea_validations'));
    $query->where($db->quoteName('state') . ' = 1');
    $query->order('id DESC');
    $db->setQuery($query);
    $results = $db->loadObjectList();
    if (!empty($results)) {

      $this->_loadLanguages($results);
      //params
      $configs = $this->getConfigs($results);

      $totalResults = count($results);
      for ($i = 0; $i < $totalResults; $i++) {
        $results[$i]->configs = $configs[$results[$i]->name];
        if (!empty($results[$i]->params)) {
          $results[$i]->params = json_decode($results[$i]->params);
        } else {
          $results[$i]->params = (object) [];
        }
        $results[$i]->description = Text::_($results[$i]->description);
      }
    }

    return $results;
  }

  public function getConfigs($lists)
  {
    $ret = [];
    if (!empty($lists)) {
      $totalLists = count($lists);
      for ($i = 0; $i < $totalLists; $i++) {
        $c = [];

        if (is_file(Path::clean($this->dirPath . $lists[$i]->name . '/validation.json'))) {
          $json = file_get_contents($this->dirPath . $lists[$i]->name . '/validation.json');
          if (!empty($json)) {
            $c = json_decode($json);
            if (is_array($c)) {
              $totalC = count($c);
              for ($j = 0; $j < $totalC; $j++) {
                if (isset($c[$j]->options)) {
                  $totalOptions = count($c[$j]->options);
                  for ($k = 0; $k < $totalOptions; $k++) {
                    if (isset($c[$j]->options[$k]->description)) {
                      $c[$j]->options[$k]->description = Text::_($c[$j]->options[$k]->description);
                    }
                    if (isset($c[$j]->options[$k]->text)) {
                      $c[$j]->options[$k]->text = Text::_($c[$j]->options[$k]->text);
                    }
                  }
                }
                if (isset($c[$j]->label)) {
                  $c[$j]->label = Text::_($c[$j]->label);
                }
                if (!isset($c[$j]->translatable)) {
                  $c[$j]->translatable = false;
                }
                if (!isset($c[$j]->language_val)) {
                  $c[$j]->language_val = [];
                }
                if (!isset($c[$j]->isConditions)) {
                  $c[$j]->isConditions = false;
                }
                if (!isset($c[$j]->conditions)) {
                  $c[$j]->conditions = [];
                } else {
                  $totalConditions = count($c[$j]->conditions);
                  for ($l = 0; $l < $totalConditions; $l++) {
                    if (isset($c[$j]->conditions[$l]->text)) {
                      $c[$j]->conditions[$l]->text = Text::_($c[$j]->conditions[$l]->text);
                    }
                    if (isset($c[$j]->conditions[$l]->operators)) {
                      $totalOperators = count($c[$j]->conditions[$l]->operators);
                      for ($m = 0; $m < $totalOperators; $m++) {
                        $c[$j]->conditions[$l]->operators[$m]->text = Text::_($c[$j]->conditions[$l]->operators[$m]->text);
                      }
                    }
                  }
                }
                if (!isset($c[$j]->showOn)) {
                  $c[$j]->showOn = '';
                }
                if (!isset($c[$j]->selectedConditions)) {
                  $c[$j]->selectedConditions = [];
                }
              }
            }
          }
        }
        $default_value = '';
        if (isset($lists[$i]->params->default_invalid_value)) {
          $default_value = $lists[$i]->params->default_invalid_value;
        }
        $c[]                   = $this->getDefaultValueField($default_value);
        $ret[$lists[$i]->name] = $c;
      }
    }

    return $ret;
  }

  /**
   * Get field for the default value of the validation invalid msg
   *
   * @param   string  $value
   *
   * @return object
   *
   * @since 1.0.0
   */
  public function getDefaultValueField(string $value = '')
  {
    $ret            = [
      'label'        => Text::_('COM_FORMEA_INVALID_MESSAGE'),
      'description'  => Text::_('COM_FORMEA_INVALID_MESSAGE_DESC'),
      'name'         => 'invalid_msg',
      'value'        => $value,
      'required'     => false,
      'options'      => [],
      'isMulti'      => false,
      'selectable'   => false,
      'translatable' => true,
      'isConditions'   => false,
      'showOn'       => "",
      'language_val' => []
    ];
    // $language       = $this->app->getLanguage();
    $languages      = FormeaGeneralHelper::getLanguages();
    $langTag        = $this->app->getLanguage()->getTag();
    $langTitle      = $langTag;
    $totalLanguages = count($languages);
    for ($i = 0; $i < $totalLanguages; $i++) {
      if ($languages[$i]->lang_code === $langTag) {
        $langTitle = $languages[$i]->title;
        break;
      }
    }

    $ret['language_val'][] = (object) [
      'lang_code'  => str_replace('-', '_', $langTag), // replace dash to underscore for uniformity
      'value'      => $value,
      'lang_title' => $langTitle,
    ];
    if (Associations::isEnabled()) {
      for ($i = 0; $i < $totalLanguages; $i++) {
        if ($languages[$i]->lang_code !== $langTag) {
          $ret['language_val'][] = (object) [
            'lang_code'  => str_replace('-', '_', $languages[$i]->lang_code), // replace dash to underscore for uniformity
            'value'      => $value,
            'lang_title' => $languages[$i]->title,
          ];
        }
      }
    }

    return (object) $ret;
  }

  protected function _loadLanguages($items)
  {
    if (!empty($items)) {
      $totalItems = count($items);
      $lang       = $this->app->getLanguage();
      $langTag    = $lang->getTag();
      for ($i = 0; $i < $totalItems; $i++) {
        FormeaGeneralHelper::loadExtensionLanguage($items[$i]->name, 'validation', $lang, $langTag);
      }
    }
  }
}
