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

namespace WriteTextAI\WriteTextAI\Model\Config\Source\CategoryAttributes;

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

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

    /**
     * Get text type product attributes
     *
     * @return array
     */
    public function toOptionArray()
    {
        $attributes = $this->attributeCollectionFactory->create()
            ->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;
            }

            $label = $attribute->getFrontendLabel();
            if ($attribute->getAttributeCode() === 'meta_title') {
                $label = __('Meta Title');
            }

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

        return $options;
    }
}
