<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Model\Config\Source\ProductAttributes;

use WriteTextAI\WriteTextAI\Model\Config\Source\ProductAttributes\Excluded;

class Text extends \WriteTextAI\WriteTextAI\Model\Config\Source\ProductAttributes
{
    /**
     * Set the order of data mapping options,
     * with the last item first.
     *
     * @var array
     */
    public const ORDER = [
        "'short_description'",
        "'description'",
        "'meta_description'",
        "'meta_title'",
    ];

    /**
     * Get text type product attributes
     *
     * @return array
     */
    public function toOptionArray()
    {
        $attributes = $this->attributeCollectionFactory->create()
            ->addVisibleFilter()
            ->addFieldToFilter('frontend_input', ['in' => ['text', 'textarea']]);

        $order = implode(',', self::ORDER);
        $attributes->getSelect()->order(new \Zend_Db_Expr("FIELD(main_table.attribute_code, $order) DESC"));
        
        $options = [[
            'value' => '',
            'label' => '',
        ]];
        foreach ($attributes as $attribute) {
            if (in_array(
                $attribute->getAttributeCode(),
                Excluded::DATA_MAPPING_EXCLUDE_ATTRIBUTES
            )) {
                continue;
            }

            $options[] = [
                'value' => $attribute->getAttributeCode(),
                'label' => $attribute->getFrontendLabel(),
            ];
        }
        usort($options, function ($a, $b) {
            return strcmp($a['label'], $b['label']);
        });
        
        return $options;
    }
}
