<?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\View\Dashboard;

defined('_JEXEC') or die;

use Exception;
use Feseur\Library\FsrDate;
use Joomla\CMS\Application\CMSApplicationInterface;
use Joomla\CMS\Factory;
use Joomla\CMS\Form\Form;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\View\GenericDataException;
use Joomla\CMS\Object\CMSObject;
use Joomla\CMS\Pagination\Pagination;
use Joomla\CMS\Toolbar\Toolbar;
use Joomla\CMS\Toolbar\ToolbarHelper;
use Joomla\CMS\WebAsset\WebAssetManager;
use Joomla\Component\Formea\Administrator\Helper\FormeaHelper;
use Joomla\Component\Formea\Administrator\Model\FormeaModel;
use Joomla\Component\Formea\Administrator\View\FormeaView;
use Joomla\Component\Formea\Site\Helper\FormeaGeneralHelper;
use Joomla\Component\Formea\Site\Libraries\FormeaForms;
use Joomla\Component\Formea\Site\Libraries\FormeaSubmissions;
use stdClass;



/**
 * View class for a list of formeas.
 *
 * @since  1.0.0
 */
class HtmlView extends FormeaView
{
  /**
   * An array of items
   *
   * @var    array
   * @since  1.0.0
   */
  protected $items = [];

  /**
   * The pagination object
   *
   * @var    Pagination
   * @since  1.0.0
   */
  protected $pagination;

  /**
   * The model state
   *
   * @var    CMSObject
   * @since  1.0.0
   */
  protected $state;

  /**
   * Form object for search filters
   *
   * @var    Form
   * @since  1.0.0
   */
  public $filterForm;

  /**
   * The active search filters
   *
   * @var    array
   * @since  1.0.0
   */
  public $activeFilters = [];

  /**
   * The sidebar markup
   *
   * @var    string
   * @since  1.0.0
   */
  protected $sidebar;

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

  /**
   * Object of list installed Formea extensions
   * @var stdClass
   * @since 1.0.0
   */
  public $installedExtensions;

  /**
   * Array of formea submission objects, limit to 5 latest & totalItems
   * @var array
   * @since 1.0.0
   */
  public $submissions;

  /**
   * Lists of formea Form Id's
   * @var int[]
   * @since 1.0.0
   */
  public $formIds;

  /**
   * @var WebAssetManager
   * @since 1.0.0
   */
  public $wa;

  /**
   * Method to display the view.
   *
   * @param   string  $tpl  A template file to load. [optional]
   *
   * @return  void
   *
   * @throws  Exception
   * @since   1.0.0
   */
  public function display($tpl = null): void
  {
    $this->app = Factory::getApplication();
    /** @var FormeaModel $model */
    $model       = $this->getModel();
    //  $this->items = $model->getItems();
    $this->state = $model->getState();
    $errors      = $this->getErrors();

    if (count($errors)) {
      throw new GenericDataException(implode("\n", $errors), 500);
    }
    $elTypes = FormeaHelper::getInstalledElTypes();
    $this->_loadLanguages('element', $elTypes);
    $installedValidations = FormeaHelper::getInstalledValidations();
    $this->_loadLanguages('validation', $installedValidations);
    $coreExtensions = FormeaGeneralHelper::getCoreExtensions();
    $themes         = FormeaHelper::getInstalledThemes();

    $this->installedExtensions = (object) [
      'eltypes'     => $elTypes,
      'validations' => $installedValidations,
      'themes'      => $themes,
      'core'        => $coreExtensions
    ];


    $doc = $this->getDocument();
    /** @var WebAssetManager $wa */
    $this->wa = $doc->getWebAssetManager();
    $this->wa->useScript('com_formea.admin-dashboard');
    $this->wa->useScript('field.modal-fields');
    $this->_getSubmissions();
    $this->_getStats();
    $this->addToolbar();
    parent::display($tpl);
  }

  /**
   * Add the page title and toolbar.
   *
   * @return  void
   *
   * @throws  Exception
   * @since   1.0.0
   */
  protected function addToolbar()
  {
    $app = Factory::getApplication();
    // Get the toolbar object instance
    $toolbar = Toolbar::getInstance('toolbar');
    //Below initialization fails in Joomla 4
    // $toolbar = Factory::getContainer()->get(ToolbarFactoryInterface::class)->createToolbar('toolbar');
    $user = $app->getIdentity();
    ToolbarHelper::title(
      Text::_('COM_FORMEA_FORM_BUILDER'),
      'icon-formea-block'
    );
    if (
      $user->authorise('core.admin', 'com_formea')
      || $user->authorise(
        'core.options',
        'com_formea'
      )
    ) {
      $toolbar->preferences('com_formea');
    }
    ToolbarHelper::divider();
    ToolbarHelper::help('', false, FormeaHelper::getHelpLink('Dashboard'));

    HTMLHelper::_('sidebar.setAction', 'index.php?option=com_formea');
  }

  /**
   * Returns an array of fields the table can be sorted by
   *
   * @return  array  Array containing the field name to sort by as the key and display text as value
   *
   * @since   1.0.0
   */
  protected function getSortFields()
  {
    return [
      'a.ordering'     => Text::_('JGRID_HEADING_ORDERING'),
      'a.published'    => Text::_('JSTATUS'),
      'a.name'         => Text::_('JGLOBAL_TITLE'),
      'category_title' => Text::_('JCATEGORY'),
      'a.access'       => Text::_('JGRID_HEADING_ACCESS'),
      'a.language'     => Text::_('JGRID_HEADING_LANGUAGE'),
      'a.id'           => Text::_('JGRID_HEADING_ID'),
    ];
  }

  protected function _loadLanguages($extensionType, $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, $extensionType, $lang, $langTag);
      }
    }
  }

  protected function _getSubmissions()
  {
    $formeaSubmissions = new FormeaSubmissions();
    $result            = [
      'submissionLists' => $formeaSubmissions->get(),
      'totalItems'      => $formeaSubmissions->get(true)
    ];
    $this->submissions = $result;
  }

  protected function _getStats()
  {
    $formeaForms    = new FormeaForms();
    $formLists      = $formeaForms->get(
      false,
      ['a.id'],
      ['limit' => -1, 'offset' => 0]
    );
    $formIds        = [];
    $totalFormLists = count($formLists);
    for ($i = 0; $i < $totalFormLists; $i++) {
      $formIds[] = $formLists[$i]->id;
    }
    $this->formIds = $formIds;
    if (!empty($this->formIds)) {
      $formeaSubmissions = new FormeaSubmissions();
      $toDate            = new FsrDate();
      $fromDate          = new FsrDate('- 12 months');
      $stats             = $formeaSubmissions->getStatsByMonths($fromDate->toSql(), $toDate->toSql(), $this->formIds);
      $series            = [];
      $options           = [];
      $xAxisCategories   = [];
      if (!empty($stats)) {
        $totalDatum = count($stats['datum']);
        for ($j = 0; $j < $totalDatum; $j++) {
          $data           = [];
          $statsData      = array_values($stats['datum'][$j]['data']);
          $totalStatsData = count($statsData);
          for ($k = 0; $k < $totalStatsData; $k++) {
            $data[] = $statsData[$k];
          }
          $series[] = (object) [
            'name' => $stats['datum'][$j]['form_title'],
            'data' => $data
          ];
        }

        $monthArray  = array_keys($stats['months']);
        $totalMonths = count($monthArray);
        for ($l = 0; $l < $totalMonths; $l++) {
          $xAxisCategories[] = $monthArray[$l] . '-01';
        }
      }
      $charts = [
        "height"     => 300,
        "type"       => "line",
        "dropShadow" => [
          "enabled" => true,
          "color"   => "#000",
          "top"     => 18,
          "left"    => 7,
          "blur"    => 10,
          "opacity" => 0.2,
        ],
        "toolbar"    => ["show" => false],
      ];


      $xAxis                 = [
        "type"       => "datetime",
        "categories" => $xAxisCategories,
        "title"      => ["text" => Text::_('COM_FORMEA_MONTH')],
        "labels"     => ["format" => "MMM"]
      ];
      $yaxis                 = ["title" => ["text" => Text::_('COM_FORMEA_SUBMISSIONS')]];
      $legend                = [
        "position"        => "top",
        "horizontalAlign" => "right",
        "floating"        => true,
        "offsetY"         => -25,
        "offsetX"         => -5,
      ];
      $options['series']     = $series;
      $options['chart']      = $charts;
      $options['dataLabels'] = ['enabled' => false, 'background' => ['borderRadius' => 30]];
      $options['stroke']     = ['curve' => 'smooth', 'width' => 2];
      $options['xaxis']      = $xAxis;
      $options['yaxis']      = $yaxis;
      $options['legend']     = $legend;
      $options['tooltip']    = ['enabled' => true, 'x' => ['format' => 'MMM \'yy']];
      //$options['title'] = ['text'=>Text::_('COM_FORMEA_FORM_SUBMISSIONS'),'align'=>'left'];
      $js = 'var formeaSubmissionChartOption = ' . json_encode($options) . ';';
      $js .= 'window.addEventListener(\'DOMContentLoaded\',function(){';
      $js .= 'var formeaSubmissionChart = new ApexCharts(document.querySelector("#formeaSubmissionChart"), formeaSubmissionChartOption);formeaSubmissionChart.render();';
      $js .= '})';
      //var chart = new ApexCharts(document.querySelector("#chart"), options);chart.render();
      $this->wa->addInlineScript($js);
    }
  }
}
