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

defined('_JEXEC') or die;

use Exception;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Model\AdminModel;
use Joomla\CMS\Object\CMSObject;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\Component\Formea\Site\Libraries\FormeaAttachment;
use Joomla\Component\Formea\Site\Libraries\FormeaElement;
use Joomla\Component\Formea\Site\Libraries\FormeaSubmission;
use Joomla\Registry\Registry;
use Joomla\Utilities\ArrayHelper;

/**
 * Item Model for a Formea.
 *
 * @since  1.0.0
 */
class SubmissionModel extends AdminModel
{
  /**
   * Method to get a single record.
   *
   * @param   integer  $pk  The id of the primary key.
   *
   * @return  mixed  Object on success, false on failure.
   *
   * @throws  Exception
   * @since   1.0.0
   */
  public function getItem($pk = null)

  {
    $pk    = (!empty($pk)) ? $pk : (int) $this->getState($this->getName() . '.id');
    $table = $this->getTable();

    if ($pk > 0) {
      // Attempt to load the row.
      $return = $table->load($pk);

      // Check for a table object error.
      if ($return === false) {
        // If there was no underlying error, then the false means there simply was not a row in the db for this $pk.
        if (!$table->getError()) {
          $this->setError(Text::_('JLIB_APPLICATION_ERROR_NOT_EXIST'));
        } else {
          $this->setError($table->getError());
        }

        return false;
      }
    }

    // Convert to the CMSObject before adding other data.
    $properties = $table->getProperties(1);
    $details    = [];
    $files = [];
    if (isset($properties['id'])) {
      if ($properties['id'] > 0) {
        $formeaAttachment = new FormeaAttachment();


        $db    = $this->getDatabase();
        $query = $db->getQuery(true);
        $query->select('*');
        $query->from($db->quoteName('#__formea_submission_data'));
        $query->where($db->quoteName('submission_id') . ' = ' . $properties['id']);
        $db->setQuery($query);
        $_details = $db->loadObjectList();
        $totalDetails = count($_details);
        for ($i = 0; $i < $totalDetails; $i++) {
          $tempFiles = [];
          if (empty($_details[$i]->link_path) || strlen($_details[$i]->link_path) < 4) {
            $_details[$i]->link_path = "[]";
          }
          if (empty($_details[$i]->dir_path) || strlen($_details[$i]->dir_path) < 4) {
            $_details[$i]->dir_path = "[]";
          }
          $_details[$i]->link_path = json_decode($_details[$i]->link_path);
          $_details[$i]->dir_path = json_decode($_details[$i]->dir_path);
          if ((int)$_details[$i]->is_link == 1) {
            $tempFiles   = $formeaAttachment->getRelativeFiles($_details[$i]->dir_path);
            $files =  array_merge($files, $tempFiles);
          }
          $_details[$i]->files = $tempFiles;
          $details[] = $_details[$i];
        }

        $query->clear();
        $query->select('title');
        $query->from($db->quoteName('#__formea_forms'));
        $query->where($db->quoteName('id') . ' = ' . $properties['form_id']);
        $db->setQuery($query);
        $properties['form_title'] = $db->loadResult();
      }
    }

    $item          = ArrayHelper::toObject($properties, CMSObject::class);
    $item->details = $details;
    $item->files = $files;
    if (property_exists($item, 'params')) {
      $registry     = new Registry($item->params);
      $item->params = $registry->toArray();
    }

    return $item;
  }


  public function delete(&$pks)
  {

    if (is_array($pks)) {
      $pks = ArrayHelper::toInteger((array) $pks);
      // Include the plugins for the delete events.
      PluginHelper::importPlugin($this->events_map['delete']);
      $table = $this->getTable();

      $totalIds = count($pks);
      for ($i = 0; $i < $totalIds; $i++) {
        if ($table->load($pks[$i])) {
          if ($this->canDelete($table)) {
            $context = $this->option . '.' . $this->name;

            // Trigger the before delete event.
            $result = Factory::getApplication()->triggerEvent($this->event_before_delete, [$context, $table]);

            if (in_array(false, $result, true)) {
              $this->setError($table->getError());

              return false;
            }
            $formeaSubmission = new FormeaSubmission($pks[$i]);
            $delete        = $formeaSubmission->deleteSubmission();
            if (!$delete->success) {
              if (isset($delete->msg[0])) {
                $this->setError($delete->msg[0]->text);
              } else {
                $this->setError(Text::_('COM_FORMEA_FAILED_TO_DELETE_ELEMENT'));
              }

              return false;
            }
            Factory::getApplication()->triggerEvent($this->event_after_delete, [$context, $table]);
          }
        }
      }

      // Clear the component's cache
      $this->cleanCache();
    }

    return true;
  }

  public function getForm($data = [], $loadData = true) {}
}
