<?php

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

defined('_JEXEC') or die;

use Feseur\Library\FsrHelper;
use Feseur\Library\FsrResponse;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Controller\AdminController;
use Joomla\CMS\Router\Route;
use Joomla\Component\Formea\Administrator\Model\FormeaModel;
use Joomla\Component\Formea\Administrator\Model\FormeasModel;
use Joomla\Component\Formea\Site\Helper\FormeaGeneralHelper;
use Joomla\Filesystem\Path;
use function count;

/**
 * Formea list controller class.
 *
 * @since  1.0.0
 */
class FormeasController extends AdminController
{
  /**
   * The prefix to use with controller messages.
   *
   * @var    string
   * @since  1.0.0
   */
  protected $text_prefix = 'COM_FORMEA';


  /**
   * Proxy for getModel.
   *
   * @param   string  $name    The name of the model.
   * @param   string  $prefix  The prefix for the PHP class name.
   * @param   array   $config  Array of configuration parameters.
   *
   * @return  FormeaModel
   *
   * @since   1.0.0
   */
  public function getModel($name = 'Formea', $prefix = 'Administrator', $config = ['ignore_request' => true])
  {
    return parent::getModel($name, $prefix, $config);
  }

  public function clearSubmission()
  {
    $this->checkToken() or die;
    $cids             = $this->app->getInput()->getInt('cid', []);
    $model            = $this->getModel();
    $deleteSubmission = $model->deleteFormSubmissions($cids);
    if ($deleteSubmission) {
      $this->setMessage(Text::plural($this->text_prefix . '_N_FORMS_SUBMISSIONS_DELETED', count($cids)));
    } else {
      $this->setMessage($model->getError(), 'error');
    }
    $this->setRedirect(
      Route::_(
        'index.php?option=' . $this->option . '&view=' . $this->view_list
          . $this->getRedirectToListAppend(),
        false
      )
    );
  }

  public function initFormUploadComponent()
  {

    $this->checkToken('GET') or die;;

    $response = new FsrResponse();
    try {
      $format = $this->input->get('format');

      $defaultLangTag = $this->app->getLanguage()->getTag();
      $formeaLangPath = JPATH_ROOT . '/administrator/components/com_formea/language/' . $defaultLangTag . '/com_formea.ini';
      if (!is_file(Path::clean($formeaLangPath))) {
        $defaultLangTag = 'en-GB';
      }
      $formeaLangPath = JPATH_ROOT . '/administrator/components/com_formea/language/' . $defaultLangTag . '/com_formea.ini';
      $languageString = FsrHelper::getCommonLanguage(true, [
        $formeaLangPath
      ], $defaultLangTag);

      $exampleLink   = FORMEA_DOC_LINK . '/examples/forms';
      $maxSizeString = ini_get('upload_max_filesize');
      $maxSize       = FsrHelper::convertToBytes($maxSizeString);

      $iconSets = [
        'check'   => [
          'svg'     => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960"><path d="M382-240 154-468l57-57 171 171 367-367 57 57-424 424Z"/></svg>',
          'svgSafe' => ''
        ],
        'warning' => [
          'svg'     => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960"><path d="m40-120 440-760 440 760H40Zm138-80h604L480-720 178-200Zm302-40q17 0 28.5-11.5T520-280q0-17-11.5-28.5T480-320q-17 0-28.5 11.5T440-280q0 17 11.5 28.5T480-240Zm-40-120h80v-200h-80v200Zm40-100Z"/></svg>',
          'svgSafe' => ''
        ],
        'error'   => [
          'svg'     => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960"><path d="M480-280q17 0 28.5-11.5T520-320q0-17-11.5-28.5T480-360q-17 0-28.5 11.5T440-320q0 17 11.5 28.5T480-280Zm-40-160h80v-240h-80v240Zm40 360q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q134 0 227-93t93-227q0-134-93-227t-227-93q-134 0-227 93t-93 227q0 134 93 227t227 93Zm0-320Z"/></svg>',
          'svgSafe' => ''
        ],
        'tips'    => [
          'svg'     => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960"><path d="M480-80q-26 0-47-12.5T400-126q-33 0-56.5-23.5T320-206v-142q-59-39-94.5-103T190-590q0-121 84.5-205.5T480-880q121 0 205.5 84.5T770-590q0 77-35.5 140T640-348v142q0 33-23.5 56.5T560-126q-12 21-33 33.5T480-80Zm-80-126h160v-36H400v36Zm0-76h160v-38H400v38Zm-8-118h58v-108l-88-88 42-42 76 76 76-76 42 42-88 88v108h58q54-26 88-76.5T690-590q0-88-61-149t-149-61q-88 0-149 61t-61 149q0 63 34 113.5t88 76.5Zm88-162Zm0-38Z"/></svg>',
          'svgSafe' => ''
        ],
      ];

      $formLists = FormeaGeneralHelper::getFormeaFormLists();
      $response->setSuccess(true);
      $response->setResult([
        'formLists'      => $formLists,
        //'formeaExtensions'  => $formeaExtensions,
        'languageString' => $languageString,
        'iconSets'       => $iconSets,
        'exampleLink'    => $exampleLink,
        'maxSize'        => $maxSize,
        'maxSizeString'  => $maxSizeString,
      ]);
    } catch (\Exception $e) {
      $response->setMsg($e->getMessage());
    }

    $view            = $this->getView('Formea', 'json');
    $view->retObject = $response;
    $view->display();

    return true;
  }

  public function formUploadFile()
  {

    $this->checkToken() or die;;

    $response = new FsrResponse();
    try {
      $formeaFormFile = $this->input->files->get('formeaFormFile', [], 'RAW');
      $hasError       = false;
      $errorMsg       = '';
      if (empty($formeaFormFile)) {
        $hasError = true;
        $errorMsg = Text::_('COM_FORMEA_PLEASE_UPLOAD_YOUR_FORM_FILE');
      }

      /** @var FormeasModel $formeasModel */
      $formeasModel     = $this->getModel('Formeas');
      $formLists        = FormeaGeneralHelper::getFormeaFormLists();
      $fileInfoResponse = $formeasModel->uploadFormeaForm($formeaFormFile, $formLists);
      $fileInfo         = [];
      if ($fileInfoResponse->success) {
        $fileInfo = $fileInfoResponse->result;
      } else {
        $hasError = true;
        $msgs     = [];
        foreach ($fileInfoResponse->msg as $msg) {
          if ($msg->show) {
            $msgs[] = $msg->text;
          }
        }
        $errorMsg = implode("\n", $msgs);
      }
      $response->setSuccess(true);
      $response->setResult([
        'formLists' => $formLists,
        'fileInfo'  => $fileInfo,
        'hasError'  => $hasError,
        'errorMsg'  => $errorMsg,
      ]);
    } catch (\Exception $e) {
      $response->setMsg($e->getMessage());
    }

    $view            = $this->getView('Formea', 'json');
    $view->retObject = $response;
    $view->display();

    return true;
  }

  public function formUploadInstall()
  {

    $this->checkToken() or die;;

    $response = new FsrResponse();
    try {
      $tmpDir = $this->input->getString('tmp_dir');
      $filename = $this->input->getString('filename');
      $form_detail = $this->input->get('form_detail', [], 'ARRAY');
      if (empty($tmpDir)) {
        throw new \Exception('Please set tmpDir');
      }
      if (empty($filename)) {
        throw new \Exception('Please set filename');
      }
      if (empty($form_detail)) {
        throw new \Exception('Please set filename');
      }

      /** @var FormeasModel $formeasModel */
      $formeasModel     = $this->getModel('Formeas');
      $response = $formeasModel->formUploadInstall($tmpDir, $filename, $form_detail);
    } catch (\Exception $e) {
      $response->setMsg($e->getMessage());
    }

    $view            = $this->getView('Formea', 'json');
    $view->retObject = $response;
    $view->display();

    return true;
  }
  public function formUploadRemovePkg()
  {

    $this->checkToken() or die;;

    $response = new FsrResponse();
    try {
      $tmpDir = $this->input->getString('tmp_dir');
      $filename = $this->input->getString('filename');
      if (empty($tmpDir)) {
        throw new \Exception('Please set tmpDir');
      }
      if (empty($filename)) {
        throw new \Exception('Please set filename');
      }

      $formeasModel = new \Joomla\Component\Formea\Administrator\Model\FormeasModel();
      $remove = $formeasModel->removeUploadedFormPkg($tmpDir, $filename);
      $response->setSuccess(true);
      $response->setResult([]);
    } catch (\Exception $e) {
      $response->setMsg($e->getMessage());
    }

    $view            = $this->getView('Formea', 'json');
    $view->retObject = $response;
    $view->display();

    return true;
  }
}
