<?php

/**
 * @package         MailChimp Auto-Subscribe
 * @version         5.0.3 Pro
 *
 * @author          Tassos Marinos <info@tassos.gr>
 * @link            http://www.tassos.gr
 * @copyright       Copyright © 2021 Tassos Marinos All Rights Reserved
 * @license         GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> or later
 */

// No direct access to this file
defined('_JEXEC') or die;
JFormHelper::loadFieldClass('groupedlist');

class JFormFieldAutoSubscribeTags extends JFormFieldGroupedList
{
    /**
     *  Field Groups and Options
     *
     *  @var  array
     */
    private $groups = array(
        'User' => array(
            '{user.id}'           => 'ID',
            '{user.name}'         => 'Full Name',
            '{user.firstname}'    => 'First Name',
            '{user.lastname}'     => 'Last Name',
            '{user.login}'        => 'Username',
            '{user.email}'        => 'Email',
            '{user.groups}'       => 'Group IDs',
            '{user.groups.names}' => 'Group Names'
        ),
        'Client' => array(
            '{client.device}'     => 'Device',
            '{client.os}'         => 'Operating System',
            '{client.browser}'    => 'Browser',
            '{client.useragent}'  => 'User Agent'
        ),
        'Other' => array(
            '{date}'              => 'JDATE',
            '{ip}'                => 'NR_IPADDRESS'
        )
    );

    /**
     * Method to get the time zone field option groups.
     *
     * @return  array  The field option objects as a nested array in groups.
     *
     * @since   11.1
     */
    protected function getGroups()
    {
        $this->addCustomFields();

        $groups = array();

        foreach ($this->groups as $groupKey => $group)
        {
            foreach ($group as $tagKey => $tag)
            {
                $groups[JText::_($groupKey)][] = JHTML::_('select.option', $tagKey, JText::_($tag));
            }
        }

        return array_merge(parent::getGroups(), $groups);
    }

    /**
     *  If com_users has Custom Fields, add them to the collection.
     */
    private function addCustomFields()
    {
        // Add Custom Fields to Groups
        JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');

        if (!class_exists('FieldsHelper'))
        {
            return;
        }

        $fields = FieldsHelper::getFields('com_users.user');

        if (!is_array($fields))
        {
            return;
        }

        foreach ($fields as $key => $field)
        {
            $this->groups[JText::_('MAS_USER_CUSTOM_FIELDS')]['{cf.' . $field->name . '}'] = $field->title;
        }
    }
}