<?php
/**
 * @psalm-suppress InvalidArgument
 */
$setup = Mage::getResourceModel("catalog/setup", "catalog_setup");
$entityTypeId = $setup->getEntityTypeId("catalog_product");

$configAttributeGroupName = "Configurables";

$attributeTemplate = [

    // eav_attribute
    "backend_model"     => null,
    "backend_type"      => "varchar",
    "backend_table"     => null,
    "frontend_model"    => null,
    "frontend_input"    => "text",
    "frontend_class"    => null,
    "source_model"      => null,
    "is_required"       => false,
    "is_user_defined"   => true,
    "default_value"     => null,
    "is_unique"         => false,
    "note"              => null,

//  catalog_eav_attribute
    "frontend_input_renderer"       => null,
    "is_global"                     => true,
    "is_visible"                    => true,
    "is_searchable"                 => true,
    "is_filterable"                 => true,
    "is_comparable"                 => true,
    "is_visible_on_front"           => true,
    "is_html_allowed_on_front"      => false,
    "is_used_for_price_rules"       => false,
    "is_filterable_in_search"       => false,
    "used_in_product_listing"       => true,
    "used_for_sort_by"              => true,
    "is_configurable"               => true,
    "apply_to"                      => "simple,virtual",
    "is_visible_in_advanced_search" => true,
    "is_wysiwyg_enabled"            => false,
    "is_used_for_promo_rules"       => false,
];

$attributeTypes = [
    "select-list" => [
        "backend_type"      => "int",
        "frontend_input"    => "select",
        "source_model"      => "eav/entity_attribute_source_table",
    ],
];

$configAttributes = [
    "color" => [
        "attribute_type" => "select-list",
        "attribute_data" => [
            "frontend_label"    => "Color",
        ],
        "sort_order"            => 0,
    ],
    "difficulty" => [
        "attribute_type" => "select-list",
        "attribute_data" => [
            "frontend_label"    => "Difficulty",
        ],
        "sort_order"            => 0,
    ],
    "model" => [
        "attribute_type" => "select-list",
        "attribute_data" => [
            "frontend_label"    => "Model",
        ],
        "sort_order"            => 0,
    ],
    "resistance" => [
        "attribute_type" => "select-list",
        "attribute_data" => [
            "frontend_label"    => "Resistance",
        ],
        "sort_order"            => 0,
    ],
    "size" => [
        "attribute_type" => "select-list",
        "attribute_data" => [
            "frontend_label"    => "Size",
        ],
        "sort_order"            => 0,
    ],
    "value" => [
        "attribute_type" => "select-list",
        "attribute_data" => [
            "frontend_label"    => "Value",
        ],
        "sort_order"            => 0,
    ],
];

foreach ($configAttributes as $newAttributeCode => $newAttributeData) {

    Mage::log(
        sprintf(
            "Checking status of attribute '%s'",
            $newAttributeCode
        ),
        Zend_Log::DEBUG
    );

    // Check if attribute already exists
    $newAttribute = Mage::getModel("catalog/resource_eav_attribute")->loadByCode($entityTypeId, $newAttributeCode);
    $attributeId = intval($newAttribute->getId());
    if ($attributeId > 0) {
        Mage::log(
            sprintf(
                "Updating attribute '%s'",
                $newAttributeCode
            ),
            Zend_Log::DEBUG
        );
    } else {
        Mage::log(
            sprintf(
                "Adding attribute '%s'",
                $newAttributeCode
            ),
            Zend_Log::DEBUG
        );
        $newAttribute
            ->setEntityTypeId($entityTypeId)
            ->setAttributeCode($newAttributeCode);
    }

    foreach ($attributeTemplate as $key => $val) {
        $newAttribute->setData($key, $val);
    }
    foreach ($attributeTypes[ $newAttributeData["attribute_type"] ] as $key => $val) {
        $newAttribute->setData($key, $val);
    }
    foreach ($newAttributeData["attribute_data"] as $key => $val) {
        $newAttribute->setData($key, $val);
    }
    $newAttribute->save();

    if ($attributeId === 0) {
        $attributeId = intval($newAttribute->getId());
    }

    // Add new attributes to new group in all attribute sets
    $sets = Mage::getModel("eav/entity_attribute_set")->getResourceCollection()->addFilter("entity_type_id", strval($entityTypeId))->load();
    foreach ($sets as $set){

        // Create/update attribute group
        $attributeSetId = intval($set->getId());
        $attributeGroupId = intval(
            Mage::getModel("eav/entity_attribute_group")
                ->getCollection()
                ->addFieldToFilter("attribute_group_name", $configAttributeGroupName)
                ->addFieldToFilter("attribute_set_id", $attributeSetId)
                ->getFirstItem()
                ->getId()
        );
        if ($attributeGroupId === 0) {
            Mage::log(
                sprintf(
                    "Adding attribute group '%s' to attribute set '%s'",
                    $configAttributeGroupName,
                    $set->getAttributeSetName()
                ),
                Zend_Log::DEBUG
            );
            $attributeGroup = Mage::getModel("eav/entity_attribute_group")
                ->setAttributeGroupName($configAttributeGroupName)
                ->setAttributeSetId($attributeSetId)
                ->setSortOrder(2)
                ->save();

            $attributeGroupId = intval($attributeGroup->getId());
        }
        
        // Add attributes to attribute set and attribute group.
        Mage::log(
            sprintf(
                "Adding attribute '%s' to attribute group '%s' in attribute set '%s'",
                $newAttributeCode,
                $configAttributeGroupName,
                $set->getAttributeSetName()
            ),
            Zend_Log::DEBUG
        );
        $setup->addAttributeToSet($entityTypeId, $attributeSetId, $attributeGroupId, $attributeId, $newAttributeData["sort_order"]);
    }
}
