<?php

/**
 * @package     VP Prime Framework
 *
 * @author      Abhishek Das <info@virtueplanet.com>
 * @link        https://www.virtueplanet.com
 * @copyright   Copyright (C) 2012-2025 Virtueplanet Services LLP. All Rights Reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

namespace Virtueplanet\Plugin\System\Prime\Field;

use Joomla\CMS\Factory;
use Joomla\CMS\Form\Field\ListField;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Session\Session;
use Joomla\Registry\Registry;
use Virtueplanet\Plugin\System\Prime\Helper\GoogleFontHelper;

// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects

class GfontvariantsField extends ListField
{
    /**
     * The form field type.
     *
     * @var    string
     */
    public $type = 'gfontvariants';

    protected function getOptions()
    {
        if (empty($this->element['file']) || empty($this->element['parent'])) {
            return parent::getOptions();
        }

        /** @var \Joomla\CMS\Application\AdministratorApplication $app */
        $app      = Factory::getApplication();
        $document = $app->getDocument();
        $wa       = $document->getWebAssetManager();
        $file     = $this->element['file'];
        $parent   = $this->element['parent'];
        $token    = Session::getFormToken();
        $formData = new Registry($this->form->getValue('params'));

        $wa->useScript('core');
        $wa->useScript('jquery');
        $wa->addInlineScript("
        jQuery(document).ready(function($) {
            var systemPaths = Joomla.getOptions('system.paths', '');
            var baseUrl = systemPaths ? systemPaths.base : systemPaths;
            $('.{$parent}').on('change', function() {
                var form = $(this).parents('form');
                var font_name = $(this).val();
                $('#{$this->id}').html('');
                $.ajax({
                    type: 'GET',
                    dataType: 'JSON',
                    url: baseUrl + '/index.php?option=com_ajax&format=json&plugin=vpprime&method=getGoogleFontDetails',
                    data: {
                        'file': encodeURIComponent('{$file}'),
                        'name': encodeURIComponent(font_name),
                        '{$token}': 1
                    },
                    success: function(e) {
                        if (e.error) {
                            alert(e.message);
                            return false;
                        }
                        if (!e.data || !e.data.variants) {
                            $('#{$this->id}').trigger('liszt:updated');
                            return false;
                        }
                        function ucwords (str) {
                            return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
                                return $1.toUpperCase();
                            });
                        }
                        var options = '';
                        $.each(e.data.variants, function(index, value) {
                            options += '<option value=\"' + value + '\">' + $.trim(ucwords(value.replace(/([a-z])/, \" $1\"))) + '</option>';
                        });
                        $('#{$this->id}').html(options);
                        $('#{$this->id}').trigger('liszt:updated');
                    },
                    error: function(e, f, g) {
                        console.log(e);
                        console.log(f);
                        console.log(g);
                        $('#{$this->id}').trigger('liszt:updated');
                    }
                });
                
            });
        })
        ");

        $selectedFont = $formData->get($parent, '');
        $options      = [];

        if ($selectedFont) {
            $font = GoogleFontHelper::getItem($file, $selectedFont);

            if ($font) {
                $items = !empty($font['variants']) ? $font['variants'] : [];

                foreach ($items as $item) {
                    $ints = preg_match_all('/[0-9]/', $item, $imatch);
                    $name = $ints > 0 ? preg_replace('/([a-z])/', ' $0', $item, 1) : $item;

                    $options[] = HTMLHelper::_('select.option', $item, ucwords($name));
                }
            }
        }

        return array_merge(parent::getOptions(), $options);
    }
}
