<?php

/**
 * @package         Smile Pack
 * @version         1.2.3 Pro
 * 
 * @author          Tassos Marinos <info@tassos.gr>
 * @link            http://www.tassos.gr
 * @copyright       Copyright © 2019 Tassos Marinos All Rights Reserved
 * @license         GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> or later
*/

defined('_JEXEC') or die('Restricted access');

use NRFramework\Helpers\Widgets\GalleryManager2 as GalleryManagerHelper;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Utility\Utility;
use Joomla\CMS\Language\Text;
use Joomla\Registry\Registry;
use Joomla\CMS\Form\Form;
use Joomla\CMS\Factory;

class ModSPGalleryInstance
{
	public function onContentPrepareForm(Form &$form, $data)
    {
        if ($data->module !== 'mod_spgallery')
        {
            return $form;
        }
        
		// Display the server's maximum upload size in the field's description
		$max_upload_size_str = HTMLHelper::_('number.bytes', Utility::getMaxUploadSize());
        
		$field_desc = $form->getFieldAttribute('max_file_size', 'description', null, 'params');
		$form->setFieldAttribute('max_file_size', 'description', Text::sprintf($field_desc, $max_upload_size_str), 'params');
        
        
    }

    /**
     * Runs when the module is saved.
     * 
     * @param   object  $context
     * @param   object  $table
     * @param   bool    $isNew
     * 
     * @return  bool
     */
	public function onExtensionBeforeSave($context, $table, $isNew)
	{
        $params = $table->params;

        if (!$params = json_decode($params, true))
        {
            return true;
        }

        
        return true;
        

        
    }

    /**
     * Runs when the module is saved.
     * 
     * @param   object  $context
     * @param   object  $table
     * @param   bool    $isNew
     * 
     * @return  void
     */
    public function onExtensionAfterSave($context, $table, $isNew, $oldParams)
	{
        $params = $table->params;

        if (!$params = json_decode($params, true))
        {
            return;
        }

        if (!isset($params['value']['items']))
        {
            return;
        }
        
        if (!is_array($params['value']['items']))
        {
            return;
        }
        
        if (!count($params['value']['items']))
        {
            return;
        }

        // Increase memory size and execution time to prevent PHP errors on datasets > 20K
        set_time_limit(300); // 5 Minutes
        ini_set('memory_limit', '-1');
		
        $fieldParams = (object) [
            'fieldparams' => $params
        ];

        

        $items = GalleryManagerHelper::moveTempItemsToDestination($params['value']['items'], $fieldParams, $this->getDestinationFolder($table, $params));

        // Regenerate images
        $regenerated_items = GalleryManagerHelper::maybeRegenerateImages('module', $items, null, $table->id, $oldParams);
        if ($regenerated_items)
        {
            $items = $regenerated_items;
        }

		// Save item tags
		$items = GalleryManagerHelper::saveItemTags($items);
        $params['value']['items'] = $items;
        $table->bind(['params' => json_encode($params)]);
        $table->check();
        $table->store();

    }

    
    /**
     * Runs when a tag is deleted.
     * 
     * @param   string  $context
     * @param   object  $item
     * 
     * @return  void
     */
	public function onContentAfterDelete($context, $item)
	{
        if ($context !== 'com_tags.tag')
        {
            return;
        }

		$this->deleteTagsFromModules($item->id);
	}

	/**
	 * Deletes a specific tag from every Smile Pack Gallery module.
	 * 
	 * @param   int  $tag_id
	 * 
	 * @return  void
	 */
	private static function deleteTagsFromModules($tag_id = null)
	{
		if (!$tag_id)
		{
			return;
		}

		$db = Factory::getDbo();
        $query = $db->getQuery(true)
            ->select('id, params')
            ->from('#__modules')
            ->where('module = ' . $db->quote('mod_spgallery'));

        $db->setQuery($query);

        $modules = $db->loadAssocList();

		if (!$modules)
		{
			return;
		}

        foreach ($modules as $module)
        {
            if (!$decoded_params = json_decode($module['params'], true))
            {
                continue;
            }

            if (!isset($decoded_params['value']['items']))
            {
                continue;
            }

            $update = false;

            foreach ($decoded_params['value']['items'] as &$item)
            {
                if (!isset($item['tags']))
                {
                    continue;
                }

                if (!is_array($item['tags']))
                {
                    continue;
                }

                if (!count($item['tags']))
                {
                    continue;
                }

                $item['tags'] = array_values($item['tags']);

                if (($key = array_search($tag_id, $item['tags'])) !== false)
                {
                    $update = true;
                    unset($item['tags'][$key]);
                }

                $item['tags'] = array_values($item['tags']);
            }

            if (!$update)
            {
				continue;
			}
		
			$module['params'] = json_encode($decoded_params);

			// Update module params
			$query->clear()
				->update('#__modules')
				->set($db->quoteName('params') . ' = ' . $db->quote($module['params']))
				->where($db->quoteName('id') . ' = ' . $db->quote($module['id']));
			$db->setQuery($query);
			$db->execute();
        }
	}
    
    
	/**
	 * Returns the destination folder.
	 * 
	 * @param   array  $module
	 * @param   array  $params
	 * 
	 * @return  string
	 */
	private function getDestinationFolder($module, $params)
	{
		$ds = DIRECTORY_SEPARATOR;
        $destination_folder = ['media', 'spgallery', $module->id];

        
		// Make params use Registry
		if (!$params instanceof Registry)
		{
			$params = new Registry($params);
		}
        
		switch ($params->get('upload_folder_type', 'auto'))
		{
			case 'custom':
				$upload_folder = trim(ltrim($params->get('upload_folder'), $ds), $ds);

				// Smart Tags Instance
				$st = \SmilePack\SmartTags::getInstance();

				// Add custom Smart Tags
				$custom_tags = [
					'id' => $module->id
				];
				$st->add($custom_tags, 'module.');

				// Replace Smart Tags
				$upload_folder = $st->replace($upload_folder);

				$destination_folder = [$upload_folder];
				break;
		}
        

		return implode($ds, array_merge([JPATH_ROOT], $destination_folder)) . $ds;
	}
}