<?php

/**
 * @package         Tassos Code Snippets
 * @version         1.0.1-RC2 Free
 *
 * @author          Tassos Marinos <info@tassos.gr>
 * @link            https://www.tassos.gr
 * @copyright       Copyright © 2026 Tassos Marinos All Rights Reserved
 * @license         GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> or later
 */

namespace Tassos\CodeSnippets\Administrator\Field;

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Form\Field\ListField;
use Joomla\CMS\HTML\HTMLHelper;

/**
 * Snippets list field — used by the Mirror Snippet feature to let the user
 * select another published snippet whose display conditions will be mirrored.
 */
class SnippetsField extends ListField
{
    /**
     * The form field type.
     *
     * @var string
     */
    protected $type = 'Snippets';

    /**
     * Method to get a list of options for the field.
     *
     * @return array
     */
    protected function getOptions()
    {
        $app       = Factory::getApplication();
        $factory   = $app->bootComponent('com_tassoscodesnippets')->getMVCFactory();
        $model     = $factory->createModel('Snippets', 'Administrator', ['ignore_request' => true]);
        $currentId = (int) $app->input->getInt('id', 0);

        $model->setState('filter.state', 1);
        $model->setState('list.ordering', 'a.title');
        $model->setState('list.direction', 'ASC');

        $snippets = $model->getItems();
        $options  = [];

        foreach ($snippets as $snippet)
        {
            // Exclude the snippet currently being edited
            if ($currentId > 0 && (int) $snippet->id === $currentId)
            {
                continue;
            }

            $options[] = HTMLHelper::_('select.option', $snippet->id, $snippet->title . ' (' . $snippet->id . ')');
        }

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