<?php

/**
 * @package         Smile Pack
 * @version         2.1.5-RC4 Free
 * 
 * @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 Joomla\CMS\Factory;
use Joomla\Filesystem\Path;
use Joomla\CMS\Form\Field\TextField;
use Joomla\Registry\Registry;
use Tassos\Framework\FileUpload;

class JFormFieldSPGalleryEditor extends TextField
{
    /**
	 * Generates the Gallery Field
	 *
	 * @return  string  The field input markup.
	 */
	protected function getInput()
	{
        require_once __DIR__ . '/helper.php';

        
        $limit_files = (int) $this->form->getData()->get('params.limit_files');
        if ($limit_files < 1 || $limit_files > 8)
        {
            $limit_files = 8;
        }
        
        
        
        $data = [
            'value' => $this->prepareValue(),
            'name' => $this->name . '[items][ITEM_ID]',
            'limit_files' => $limit_files,
            
            'max_file_size' => 5,
            'original_image_resize' => false,
            
            
            'disabled' => $this->disabled,
            'context' => 'module',
            'item_id' => $this->getItemID(),
            'id' => $this->id
        ];

        return \NRFramework\Widgets\Helper::render('GalleryManager2', $data);
    }

    private function getItemID()
    {
        $item_id = (int) Factory::getApplication()->input->get('id');

        switch (Factory::getApplication()->input->get('option'))
        {
            case 'com_users':
                $item_id = Factory::getUser()->id;
                break;
        }
        
        return $item_id;
    }

    /**
     * The list of uploaded Gallery Items.
     * 
     * @return  mixed
     */
    private function prepareValue()
    {
        if (empty($this->value))
        {
            return;
        }

        $this->value = is_string($this->value) ? json_decode($this->value, true) : (array) $this->value;

        if (!isset($this->value['items']))
        {
            return;
        }

        $value = [];

        // SP modules don't have a field_id; normalize to '0' so the token's
        // context matches the server-side $input->getInt('field_id') value
        // baked into GalleryManager2::ajax_delete's expected_context.
        $tokenContext = [
            'field_id' => '0',
            'item_id'  => (string) (int) $this->getItemID(),
            'context'  => 'module',
        ];

        foreach ($this->value['items'] as $key => $file)
        {
            $file = new Registry($file);

            $tags = $file->get('tags', []);
            $tags = is_array($tags) ? $tags : [];

            // `source`/`original`/`thumbnail`/`slideshow` are used by the front-end
            $entry = [
                'source' => $file->get('source'),
                'original' => $file->get('image'),
                'exists' => file_exists(Path::clean(implode(DIRECTORY_SEPARATOR, [JPATH_ROOT, $file->get('thumbnail')]))),
                'caption' => $file->get('caption', ''),
                'thumbnail' => $file->get('thumbnail', ''),
                'slideshow' => $file->get('slideshow', ''),
                'alt' => $file->get('alt', ''),
                'tags' => json_encode($tags)
            ];

            // Issue tokens for each file path (used by JS for secure delete)
            foreach (['source', 'original', 'thumbnail', 'slideshow'] as $pathKey)
            {
                $tokenKey = $pathKey . '_token';
                $entry[$tokenKey] = '';
                $pathValue = $entry[$pathKey] ?? '';

                if ($pathValue)
                {
                    $fullPath = Path::clean(implode(DIRECTORY_SEPARATOR, [JPATH_ROOT, $pathValue]));
                    if (is_file($fullPath))
                    {
                        try
                        {
                            $entry[$tokenKey] = FileUpload::issueToken($fullPath, dirname($fullPath), $tokenContext);
                        }
                        catch (\Throwable $e) {}
                    }
                }
            }

            $value[] = $entry;
        }

        return $value;
    }
}
