<?php

use Amasty\ShopbyBase\Api\Data\FilterSettingRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend;
use Magento\Framework\App\Bootstrap;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Eav\Model\Entity\Attribute\GroupFactory as AttributeGroupFactory;
use Magento\Eav\Model\Entity\AttributeFactory as AttributeFactory;
use Magento\Catalog\Model\Product\Attribute\Management as AttributeManagement;
use Magento\Eav\Api\AttributeSetRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Eav\Model\Entity\Attribute\Source\Table as TableSource;
use Magento\Eav\Model\Entity\Type;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;

require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

/** @var AttributeSetFactory $attributeSetFactory */
$attributeSetFactory = $objectManager->get(AttributeSetFactory::class);

/** @var AttributeGroupFactory $attributeGroupFactory */
$attributeGroupFactory = $objectManager->get(AttributeGroupFactory::class);

/** @var AttributeFactory $attributeFactory */
$attributeFactory = $objectManager->get(AttributeFactory::class);

/** @var AttributeManagement $attributeManagement */
$attributeManagement = $objectManager->get(AttributeManagement::class);

/** @var AttributeSetRepositoryInterface $attributeSetRepository */
$attributeSetRepository = $objectManager->get(AttributeSetRepositoryInterface::class);

/** @var Type $entityType */
$entityType = $objectManager->get(Type::class);

/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $objectManager->get(SearchCriteriaBuilder::class);

$eavSetupFactory = $objectManager->get(EavSetupFactory::class);
$setup = $objectManager->get(ModuleDataSetupInterface::class);

$amastyLayeredSettings = $objectManager->get(FilterSettingRepositoryInterface::class);

$entityTypeId = $entityType->loadByCode('catalog_product')->getEntityTypeId();

$attributeSets = [
    'Bare Transversale Simple' => 'Attributes',
    'Bare Transversale Bundle' => 'Attributes',
];

$attributes = [
    'Marca' => 'auto_brand',
    'Model' => 'auto_model',
    'Caroserie' => 'auto_body_bare',
    'Fabricatie' => 'auto_from_to_bare',
    'Tip plafon' => 'auto_roof_type_bare',
    //'Titlu' => 'name',
    'Producator' => 'manufacturer',
    "Compatibil cu plafon metalic" => 'auto_metal_roof_bare',
    "Compatibil cu plafon sticla" => 'auto_glass_roof_bare',

    "Tip produs (nu se afiseaza in AGD - pt marketplace)" => 'auto_product_type_bare',
    "Tip (nu se afiseaza)" => 'auto_type_bare',
    "Tip bare (nu se afiseaza)" => 'auto_bar_type_bare',
    "Tip montare (nu se afiseaza - pt marketplace)" => 'auto_mount_type_bare',

    "Greutate suportata (kg)" => 'auto_supported_weight_bare',
    "Latime bare (cm)" => 'auto_width_bare',
    "Lungime bara (cm)" => 'auto_length_bare',
    "Inaltime (cm)" => 'auto_height_bare',
    "Culoare" => 'auto_color_bare',
    "Material" => 'auto_material_bare',
    "Greutate produs" => 'weight',
    "Antifurt" => 'auto_anti_theft_bare',
    "Garantie (ani)" => 'auto_warranty_bare',
    "T-slot" => 'auto_t_slot_bare',
    "Certificare TUV" => 'auto_tuv_certification_bare',
    "City Crush test" => 'auto_city_crush_test_bare',
    "Termen_livrare" => 'termen_livrare',
    'SKU Bundles Intern' => 'sku_intern',
    'Cod Produs' => 'sku_fz'
];

$attributeDependency = [
    'auto_model' => ['auto_body_bare'],
    'auto_body_bare' => ['auto_from_to_bare'],
    'auto_from_to_bare' => ['auto_roof_type_bare'],
    'auto_roof_type_bare' => ['auto_metal_roof_bare', 'auto_glass_roof_bare'],
];

foreach ($attributeSets as $attributeSetName => $attributeGroupName) {
    $searchCriteria = $searchCriteriaBuilder
        ->addFilter('attribute_set_name', $attributeSetName, 'eq')
        ->create();
    $attributeSetList = $attributeSetRepository->getList($searchCriteria);

    if ($attributeSetList->getTotalCount() > 0) {
        $attributeSet = current($attributeSetList->getItems());
    } else {
        $attributeSet = $attributeSetFactory->create();
        $attributeSet->setEntityTypeId($entityTypeId);
        $attributeSet->setAttributeSetName($attributeSetName);
        $attributeSet->save();

        echo "Attribute set '$attributeSetName' created.\n";
    }

    $attributeGroupList = $attributeGroupFactory->create()->getCollection()
        ->addFieldToFilter('attribute_set_id', $attributeSet->getAttributeSetId()) // Filter by attribute set ID
        ->addFieldToFilter('attribute_group_name', $attributeGroupName);

    if ($attributeGroupList->getSize() > 0) {
        $attributeGroup = current($attributeGroupList->getItems());
        $attributeGroupId = $attributeGroup->getAttributeGroupId();
    } else {
        $attributeGroup = $attributeGroupFactory->create();
        $attributeGroup->setAttributeSetId($attributeSet->getAttributeSetId());
        $attributeGroup->setAttributeGroupName($attributeGroupName);
        $attributeGroup->setDefaultId($attributeSet->getDefaultGroupId()); // Use default group ID if available
        $attributeGroup->save();
        $attributeGroupId = $attributeGroup->getAttributeGroupId();

        echo "Attribute group '$attributeGroupName' created for attribute set '$attributeSetName'.\n";
    }

    $sortOrder = 0;
    foreach ($attributes as $frontendLabel => $attributeCode) {
        try {
            $attribute = $attributeFactory->create()->loadByCode('catalog_product', $attributeCode);

            $allowVisible = (!in_array($attributeCode, ['sku_intern', 'weight', 'termen_livrare']) && stripos($frontendLabel, 'nu se afiseaza') === false);
            $allowSearchAble = in_array($attributeCode, ['auto_model', 'auto_brand', 'auto_brand_bare', 'auto_model_bare', 'auto_body_bare',
                    'auto_from_to_bare', 'auto_roof_type_bare']);
            $allowForBundles = in_array($attributeCode, ['auto_model', 'auto_brand', 'sku_fz']);
            $isNotRequired = in_array($attributeCode, ['auto_model', 'auto_brand']);

            if (!$attribute->getId()) {
                /** @var $attribute \Magento\Catalog\Model\ResourceModel\Eav\Attribute */
                $attribute = $attributeFactory->create();

                // Determine frontend_input type based on attribute code
                $frontendInput = 'text'; // Default for varchar
                if (in_array($attributeCode, ['auto_brand_bare', 'auto_model_bare', 'auto_body_bare',
                    'auto_from_to_bare', 'auto_roof_type_bare', 'auto_metal_roof_bare',
                    'auto_glass_roof_bare'])) {
                    $frontendInput = 'multiselect'; // Set to multiselect for specific attributes
                }

                $attribute->setData([
                    'attribute_code' => $attributeCode,
                    'frontend_label' => $frontendLabel,
                    'frontend_input' => $frontendInput, // Use the determined input type
                    'source_model' => null, // Set source model only for multiselect
                    'backend_type' => $frontendInput === 'multiselect' ? 'text' : 'varchar',
                    'backend_model' => $frontendInput === 'multiselect' ? ArrayBackend::class : null,
                    'is_required' => 0,
                    'is_user_defined' => 1,
                    'is_global' => 1,
                    'is_unique' => 0,
                    'entity_type_id' => $entityTypeId,
                    'is_searchable' => $allowSearchAble ? 1 : 0,
                    'is_filterable' => $allowSearchAble ? 1 : 0,
                    'is_visible_on_front' => $allowVisible ? 1 : 0,
                    'is_html_allowed_on_front' => $allowVisible ? 1 : 0,
                    'is_filterable_on_front' => $allowSearchAble ? 1 : 0,
                    'is_filterable_in_search' => $allowSearchAble ? 1 : 0
                ]);
                $attribute->save();

                echo "Attribute '$attributeCode' created.\n";
            } else {

                /** @var EavSetup $eavSetup */
                $eavSetup = $eavSetupFactory->create(['setup' => $setup]);

                $eavSetup->updateAttribute(
                    $entityTypeId,
                    $attributeCode,
                    [
                        'is_searchable' => $allowSearchAble ? 1 : 0,
                        'is_filterable' => $allowSearchAble ? 1 : 0,
                        'is_visible_on_front' => $allowVisible ? 1 : 0,
                        'is_html_allowed_on_front' => $allowVisible ? 1 : 0,
                        'is_filterable_on_front' => $allowSearchAble ? 1 : 0,
                        'is_filterable_in_search' => $allowSearchAble ? 1 : 0,
                        'is_required' => $isNotRequired && $attribute->getIsRequired() ? 0 : $attribute->getIsRequired(),
                        'apply_to' => $allowForBundles ? null : $attribute->getApplyTo(),
                    ]
                );
                echo "Attribute '$attributeCode' updated.\n";

            }
            $attributeManagement->assign(
                $attributeSet->getAttributeSetId(),
                $attributeGroupId,
                $attributeCode,
                $sortOrder++
            );

            echo "Attribute '$attributeCode' added to attribute set '$attributeSetName' and group '$attributeGroupName'.\n";
        } catch (\Exception $e) {
            echo "Error adding attribute '$attributeCode': " . $e->getMessage() . "\n";
        }
    }

    foreach ($attributeDependency as $parentAttributeCode => $childrenAttributeCodes) {
        $parentAttribute = $attributeFactory->create()->loadByCode('catalog_product', $parentAttributeCode);
        foreach ($childrenAttributeCodes as $childAttributeCode) {
            $childAttribute = $attributeFactory->create()->loadByCode('catalog_product', $childAttributeCode);

            try {
                $filterSetting = $amastyLayeredSettings->getFilterSetting($childAttributeCode);
            } catch (\Exception $e) {
                $filterSetting = $amastyLayeredSettings->getByAttributeCode($childAttributeCode);
            }

            $filterSetting->setAttributesFilter($parentAttribute->getId());
            $filterSetting->setAttributeId($childAttribute->getId());
            $filterSetting->setAttributeCode($childAttribute->getAttributeCode());


            try {
                if ($filterSetting->getId()) {
                    $amastyLayeredSettings->update($filterSetting);
                    echo 'Updated Amasty Layered settings for ' . $childAttributeCode . '\n';
                } else {
                    $amastyLayeredSettings->save($filterSetting);
                    echo 'Saved Amasty Layered settings for ' . $childAttributeCode . '\n';
                }

            } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
            } catch (\Exception $e) {
            }
        }
    }
}