<?php

use Magento\Eav\Api\AttributeOptionManagementInterface;
use Magento\Eav\Model\Entity\Attribute\Option;
use Magento\Framework\App\Bootstrap;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\File\Csv;
use Magento\Eav\Api\AttributeRepositoryInterface;
use Magento\Eav\Model\Config as EavConfig;

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

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

// Inject dependencies
$csv = $objectManager::getInstance()->get(Csv::class);
$attributeRepository = $objectManager::getInstance()->get(AttributeRepositoryInterface::class);
$eavConfig = $objectManager::getInstance()->get(EavConfig::class);

// Replace with your actual CSV file path
$csvFilePath = __DIR__ . '/vetture.csv';

// Define parent-child attribute relationships
$attributeRelationships = [
    'auto_brand_bare' => ['auto_model_bare'],
    'auto_model_bare' => ['auto_body_bare', 'auto_roof_type_bare', 'auto_from_to_bare'],
    'auto_body_bare'  => ['auto_from_to_bare']
];

// Define attribute mapping
$attributeMapping = [
    'Brand' => 'auto_brand_bare',
    'Model' => 'auto_model_bare',
    'Doors' => 'auto_body_bare',
    'Year 1' => 'auto_from_to_bare', // Will be concatenated with Year 2
    'Year 2' => 'auto_from_to_bare',
    'Roof kind' => 'auto_roof_type_bare',
    'Metal roof' => 'auto_metal_roof_bare',
    'Glass roof' => 'auto_glass_roof_bare'
];

// Load CSV data
$csvData = $csv->getData($csvFilePath);
//$handle = fopen($csvFilePath, "r");
//$csvData = fgetcsv($handle, 1000, ",");


// Store the header row
$headerRow = array_shift($csvData);

// Prepare data for the attribute_dependency table
$dependencies = [];
$processedDependencies = []; // Keep track of processed dependencies

foreach ($csvData as $row) {
    $parentValues = [];
    $childValues = [];

    // Skip the first column (SKU)
    array_shift($row);

    foreach ($attributeMapping as $csvHeader => $attributeCode) {
        if ($csvHeader === 'Year 1' || $csvHeader === 'Year 2') {
            // Concatenate Year 1 and Year 2
            $year1 = $row[array_search('Year 1', $headerRow) - 1];
            $year2 = $row[array_search('Year 2', $headerRow) - 1];
            $value = $year1 . ($year2 ? '-' . $year2 : '-');
            $parentValues[$attributeCode] = $value;
        } else {
            $parentValues[$attributeCode] = ucwords(strtolower($row[array_search($csvHeader, $headerRow) - 1]));
        }
    }

    // Generate dependency entries based on relationships
    $currentParentValue = null;
    foreach ($attributeRelationships as $parentAttributeCode => $childAttributeCodes) {
        $parentValue = $currentParentValue ?: $parentValues[$parentAttributeCode];

        foreach ($childAttributeCodes as $childAttributeCode) { // Iterate over child attributes
            $childValue = $parentValues[$childAttributeCode];
            $currentParentValue = $childValue;

            $dependencyKey = $parentAttributeCode . '-' . $parentValue . '-' . $childAttributeCode;

            if (isset($processedDependencies[$dependencyKey])) {
                $dependencies[$processedDependencies[$dependencyKey]]['child_allowed_values'][] = $childValue;
            } else {
                $dependencyIndex = count($dependencies);
                $dependencies[] = [
                    'parent_attribute_id'   => getAttributeIdByCode($parentAttributeCode),
                    'parent_selected_value' => $parentValue,
                    'child_attribute_id'    => getAttributeIdByCode($childAttributeCode),
                    'child_allowed_values'  => [$childValue],
                ];
                $processedDependencies[$dependencyKey] = $dependencyIndex;
            }
        }
    }
}

// Insert data into the attribute_dependency table
$connection = $objectManager->get(\Magento\Framework\App\ResourceConnection::class)->getConnection();
$tableName = $connection->getTableName('attribute_dependency');
foreach ($dependencies as $dependency) {
    // Check if the parent and child values exist as options
    $parentOptionId = getOptionId($dependency['parent_attribute_id'], $dependency['parent_selected_value']);
    $childOptionIds = array_unique($dependency['child_allowed_values']);
    $childOptionIds = array_map(function ($childValue) use ($dependency) {
        return getOptionId($dependency['child_attribute_id'], (string)$childValue);
    }, $childOptionIds);

    // If any option is not found, add it
    if (!$parentOptionId || in_array(null, $childOptionIds, true)) {
        continue; // Skip this dependency if options are not found
    }

    // Update the dependency with the option IDs
    $dependency['parent_selected_value'] = $parentOptionId;
    // Implode the child_allowed_values array after getting option IDs
    $dependency['child_allowed_values'] = implode(',', $childOptionIds);

    $connection->insertOnDuplicate($tableName, $dependency);
}

/**
 * Helper function to get attribute ID by code
 *
 * @param string $attributeCode
 *
 * @return int|null
 */
function getAttributeIdByCode(string $attributeCode): ?int
{
    global $attributeRepository;
    try {
        return $attributeRepository->get(\Magento\Catalog\Model\Product::ENTITY, $attributeCode)->getAttributeId();
    } catch (NoSuchEntityException $e) {
        return null;
    }
}

/**
 * Helper function to get option ID by attribute ID and value
 *
 * @param int $attributeId
 * @param string $value
 *
 * @return int|null
 * @throws LocalizedException
 */
function getOptionId(int $attributeId, string $value): ?int
{
    global $eavConfig;
    $attribute = $eavConfig->getAttribute(\Magento\Catalog\Model\Product::ENTITY, $attributeId);
    $optionId = $attribute->getSource()->getOptionId($value);

    $objectManager = ObjectManager::getInstance();
    if (!$optionId) {
        $option = $objectManager::getInstance()->create(Option::class);
        $attributeOptionManagement = $objectManager::getInstance()->create(AttributeOptionManagementInterface::class);
        $option->setValue($value);
        $option->setLabel($value);
        //$option->setSortOrder(0);
        $option->setIsDefault(false);
        $optionId = $attributeOptionManagement->add('catalog_product', $attributeId, $option);
    }

    return $optionId;
}