<?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\Model;

defined('_JEXEC') or die;

use Exception;
use Feseur\Library\FsrResponse;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Factory\MVCFactoryInterface;
use Joomla\CMS\MVC\Model\BaseDatabaseModel;
use Joomla\CMS\Uri\Uri;
use Joomla\Component\Formea\Site\Libraries\FormeaForm;
use Joomla\Database\DatabaseDriver;
use Joomla\Registry\Registry;
use Joomla\Session\SessionInterface;

/**
 * Formea model for the Joomla Formea component.
 *
 * @since  1.0.0
 */
class FormeaModel extends BaseDatabaseModel
{
  /**
   * @var string item
   */
  protected $_item = null;


  public function __construct($config = [], MVCFactoryInterface $factory = null)
  {
    parent::__construct($config, $factory);
  }

  /**
   * Gets a formea
   *
   * @param   integer  $pk  Id for the formea
   *
   * @return  mixed Object or null
   *
   * @since   1.0
   */
  public function getItem($pk = null)
  {
    $app = Factory::getApplication();
    if (empty($pk)) {
      $pk = $app->input->getInt('id');
    } else {
      $pk = (int) $pk;
    }

    if ($this->_item === null) {
      $this->_item = array();
    }

    if (!isset($this->_item[$pk])) {
      try {
        $db    = $this->getDatabase();
        $query = $db->getQuery(true);

        $query->select('*')
          ->from($db->quoteName('#__formea_forms', 'a'))
          ->where($db->quoteName('a.id') . ' = ' . $db->quote($pk))->where(
            $db->quoteName('a.state') . ' = ' . $db->quote(1)
          );

        $db->setQuery($query);
        $data = $db->loadObject();


        if (empty($data)) {
          throw new Exception(Text::_('COM_FORMEA_ERROR_FORMEA_NOT_FOUND'), 404);
        }
        $data->params     = new Registry($data->params);
        $this->_item[$pk] = $data;
      } catch (Exception $e) {
        $this->setError($e);
        $this->_item[$pk] = false;
      }
    }

    return $this->_item[$pk];
  }

  /**
   * Method to auto-populate the model state.
   *
   * Note. Calling getState in this method will result in recursion.
   *
   * @return  void
   *
   * @since   1.0
   */
  protected function populateState()
  {
    $app = Factory::getApplication();
    $this->setState('formea.id', $app->input->getInt('id'));
    $this->setState('params', $app->getParams());
  }

  public function submit()
  {
    $app       = Factory::getApplication();
    $input     = $app->getInput();
    $form_id   = $input->getInt('fom', 0);
    $return_url = $input->getString('return_url');
    if (!empty($return_url)) {
      $return_url = base64_decode($return_url);
    } else {
      $return_url = Uri::root();
    }
    $retObject = new FsrResponse();
    try {
      if ($form_id < 1) {
        throw new Exception(Text::_('COM_FORMEA_INVALID_FORM'));
      }
      $formeaToken = $input->get('fomToken', null);
      if (empty($formeaToken)) {
        throw new Exception(Text::_('COM_FORMEA_FORM_NOT_FOUND'));
      }
      $honeyPot = $input->get('formea_name');
      if (!empty($honeyPot)) {
        throw new Exception(Text::_('COM_FORMEA_INVALID_SUBMISSION'));
      }

      $container = Factory::getContainer();
      /** @var DatabaseDriver $db */
      $db    = $container->get('DatabaseDriver');
      $query = $db->getQuery(true);
      $query->select('*');
      $query->from($db->quoteName('#__formea_forms'));
      $query->where($db->quoteName('id') . ' = ' . $db->quote($form_id));
      $query->where($db->quoteName('state') . ' = ' . $db->quote(1));
      $db->setQuery($query);
      $form = $db->loadObject();
      if (empty($form)) {
        throw new Exception(Text::_('COM_FORMEA_FORM_NOT_FOUND'));
      }
      $formeaToken = base64_decode($formeaToken);
      $formea      = $input->get('formea', [], 'array');

      $formeaFiles = $input->files->get('formea');

      if (!empty($formeaFiles)) {
        $formea = array_merge($formea, $formeaFiles);
      }

      $formeaForm = new FormeaForm(['id' => $form_id]);
      $retObject  = $formeaForm->processSubmission($formea, $form_id, $formeaToken, $return_url);
      /** @var SessionInterface $session */
      $session = $app->getSession();

      if ($retObject->success) {
        $retObject->result->elements = [];
      }

      $session->set('FORMEA_FORM_SUBMISSION_' . $form_id, $retObject->result);
    } catch (Exception $e) {
      $retObject->setMsg($e->getMessage(), 'danger', true);
    }

    return $retObject;
  }
}
