<?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\FsrResponse;
use Joomla\CMS\Application\CMSApplicationInterface;
use Joomla\CMS\Factory;
use Joomla\Filesystem\Folder;
use Joomla\CMS\Language\Text;
use Joomla\Database\DatabaseDriver;
use Joomla\Filesystem\Path;
use Joomla\Registry\Registry;

class FormeaValidation
{
  public $submitted_value;

  /**
   * @var Registry
   * @since 1.0.0
   */
  public $params;
  public $validation;

  /**
   * @var int
   * @since 1.0.0
   */
  public $id;

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

  /**
   * @var string
   * @since 1.0.0
   */
  public $langTag;

  /**
   * @var int
   * @since 1.0.0
   */
  public $value_type = 0;

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

  /**
   * @var string
   * @since 1.0.0
   */
  public $langTagUnderScore;

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

    if (isset($config['submitted_value'])) {
      $this->submitted_value = $config['submitted_value'];
    }
    if (isset($config['validation'])) {
      $this->validation = $config['validation'];
    }
    if (isset($config['params'])) {
      if (is_string($config['params'])) {
        $this->params = new Registry($config['params']);
      } else {
        $this->params = $config['params'];
      }
    }

    $this->app               = Factory::getApplication();
    $this->langTag           = $this->app->getLanguage()->getTag();
    $this->langTagUnderScore = str_replace('-', '_', $this->langTag);
    $this->dirPath           = JPATH_ROOT . '/components/com_formea/plugins/validation/';
  }

  public function validate()
  {
    $retObject = new FsrResponse(true, true);
    $retObject->setResult((object) ['hasError' => false, 'msg' => '']);
    $retObject->setMsg(Text::_('COM_FORMEA_BYPASS_DEFAULT_VALIDATION'), 'info', false);

    return $retObject;
  }

  public function getValidationObject()
  {
    if (empty($this->id)) {
      return null;
    }
    $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('id') . ' = ' . $db->quote($this->id));
    $db->setQuery($query);

    return $db->loadObject();
  }

  /**
   * Method to delete Element type plugin (eltype)
   * @return FsrResponse
   *
   * @since 1.0.0
   */
  public function deleteValidationPlugin()
  {
    $retObject = new FsrResponse();
    try {
      if ((int) $this->id < 1) {
        throw new Exception(Text::_('COM_FORMEA_NO_VALIDATION_SELECTED'));
      }

      $container = Factory::getContainer();
      /** @var DatabaseDriver $db */
      $db    = $container->get('DatabaseDriver');
      $query = $db->getQuery(true);

      //check if element is in used
      $query->select(['a.title', 'b.element_id', 'c.title AS element_title']);
      $query->from($db->quoteName('#__formea_validations', 'a'))->innerJoin(
        $db->quoteName('#__formea_element_validations', 'b') . ' ON ' . $db->quoteName('a.name') . ' = ' .
          $db->quoteName('b.validation_type')
      )->innerJoin(
        $db->quoteName('#__formea_elements', 'c') . ' ON ' .
          $db->quoteName('b.element_id') . ' = ' . $db->quoteName('c.id')
      );
      $query->where($db->quoteName('a.id') . ' = ' . $db->quote($this->id));
      $db->setQuery($query);
      $usedInFormLists  = $db->loadObjectList();
      $validationObject = $this->getValidationObject();
      if (empty($validationObject)) {
        throw new Exception(Text::_('COM_FORMEA_NO_VALIDATION_FOUND'));
      }
      //$this->dirPath

      if (!empty($usedInFormLists)) {
        $eltype_title    = '';
        $elementLists    = [];
        $totalUsedInForm = count($usedInFormLists);
        for ($i = 0; $i < $totalUsedInForm; $i++) {
          $eltype_title   = $usedInFormLists[$i]->title;
          $elementLists[] = $usedInFormLists[$i]->element_title;
        }
        $msg = Text::sprintf('COM_FORMEA_FAILED_TO_DELETE_VALIDATION_S', $eltype_title, implode(', ', $elementLists));
        throw new Exception($msg);
      }

      // delete all custom keys for user 1001.
      $conditions = array(
        $db->quoteName('id') . ' = ' . $this->id
      );

      $query->clear();
      $query->delete($db->quoteName('#__formea_validations'));
      $query->where($conditions);
      $db->setQuery($query);
      $db->execute();
      if (is_dir(Path::clean($this->dirPath . $validationObject->name))) {
        Folder::delete($this->dirPath . $validationObject->name);
      }
      if (is_dir(Path::clean(JPATH_ROOT . '/media/com_formea/css/validation/' . $validationObject->name))) {
        Folder::delete(JPATH_ROOT . '/media/com_formea/css/validation/' . $validationObject->name);
      }
      if (is_dir(Path::clean(JPATH_ROOT . '/media/com_formea/js/validation/' . $validationObject->name))) {
        Folder::delete(JPATH_ROOT . '/media/com_formea/js/validation/' . $validationObject->name);
      }

      $retObject->setSuccess(true);
      $retObject->setResult((object) [
        'deleted_validation' => $validationObject
      ]);
    } catch (Exception $e) {
      $retObject->setSuccess(false);
      $retObject->setMsg($e->getMessage());
    }

    return $retObject;
  }

  public function beforeGeneratingLabel($htmlStructure)
  {
    return $htmlStructure;
  }
}
