<?php

namespace ViartasThemes\Florial\Commands;

use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Http;
use ViartasCore\Core\Models\Item;
use ViartasCore\Core\Models\Locale;
use ViartasCore\Core\Models\Menu;
use ViartasCore\Core\Models\MenuItem;
use ViartasCore\Core\Models\Theme;
use ViartasModules\Pages\Models\Accounting\Page;
use ViartasModules\PostCategories\Models\Accounting\PostCategory;
use ViartasModules\Posts\Models\Accounting\Post;
use ViartasShop\Attributes\Models\Accounting\Attribute;
use ViartasShop\Attributes\Models\Accounting\AttributeGroup;
use ViartasShop\Brands\Models\Accounting\Brand;
use ViartasShop\Brands\Models\Accounting\Model;
use ViartasShop\Cart\Models\Accounting\SellerBank;
use ViartasShop\Cart\Models\Accounting\Warehouse;
use ViartasShop\Orders\Models\InvoiceSeries;
use ViartasShop\Orders\Models\Seller;
use ViartasShop\ProductCategories\Models\Accounting\ProductCategory;
use ViartasShop\Products\Models\Accounting\Product;
use ViartasThemes\Florial\Models\Import;

class FillShop extends Command
{
    /**
     * @var string
     */
    protected $signature = 'florial:shop';

    /**
     * @var array
     */
    private array $import = [];

    /**
     * @var array
     */
    private array $sameData = [];

    /**
     * @return void
     */
    public function handle(): void
    {
        $this->config();
        $this->emptyData();
        $this->importData();

        $this->generatePages();
        $this->generatePostCategories();
        $this->generatePosts();
        $this->generateProductCategories();
        $this->generateProducts();

        //$this->generateAttributes();
        //$this->generateCategories();
        //$this->generateBrands();

        $this->generateFromMenu();
        $this->generateWarehouses();
        $this->generateSellers();
    }

    /**
     * @return void
     */
    private function generateSellers(): void
    {
        Seller::query()->delete();
        SellerBank::query()->delete();
        InvoiceSeries::query()->delete();

        $seller = Seller::create([
            'user_id'    => 1,
            'title'      => [
                'en' => 'UAB Florial',
                'lt' => 'UAB Florial',
                'ru' => 'UAB Florial',
            ],
            'name'       => 'UAB Florial',
            'code'       => '307475999',
            'vat'        => 'LT100019115516',
            'address'    => 'V. Nagevičiaus g. 3, LT-08237 Vilnius',
            'phone'      => '+370 601 11 560',
            'email'      => 'info@florial.lt',
            'country_id' => 135,
            'vat_type'   => Seller::VAT_TYPE_SELLER_COUNTRY,
            'series'     => 'FLP',
            'number'     => 1,
            'note'       => null,
            'is_default' => true,
        ]);

        SellerBank::create([
            'seller_id' => $seller->id,
            'title'     => [
                'en' => 'Swedbank',
                'lt' => 'Swedbank',
                'ru' => 'Swedbank',
            ],
            'name'      => 'Swedbank AB',
            'code'      => 'LT29 7300 0101 9783 4623',
            'swift'     => 'HABALT22',
            'address'   => null,
            'note'      => null,
        ]);

        // Išankstinės sąskaitos (Proforma)
        InvoiceSeries::create([
            'seller_id'    => $seller->id,
            'series'       => 'FLP',
            'title'        => [
                'en' => 'Proforma invoices',
                'lt' => 'Išankstinės sąskaitos',
                'ru' => 'Счета-проформы',
            ],
            'type'         => InvoiceSeries::TYPE_PROFORMA,
            'start_number' => 1,
            'is_default'   => true,
            'is_active'    => true,
        ]);

        // PVM sąskaitos faktūros
        InvoiceSeries::create([
            'seller_id'    => $seller->id,
            'series'       => 'FLV',
            'title'        => [
                'en' => 'VAT invoices',
                'lt' => 'PVM sąskaitos faktūros',
                'ru' => 'Счета-фактуры НДС',
            ],
            'type'         => InvoiceSeries::TYPE_VAT,
            'start_number' => 1,
            'is_default'   => true,
            'is_active'    => true,
        ]);

        // Kreditinės sąskaitos
        InvoiceSeries::create([
            'seller_id'    => $seller->id,
            'series'       => 'FLK',
            'title'        => [
                'en' => 'Credit notes',
                'lt' => 'Kreditinės sąskaitos',
                'ru' => 'Кредитные счета',
            ],
            'type'         => InvoiceSeries::TYPE_CREDIT,
            'start_number' => 1,
            'is_default'   => true,
            'is_active'    => true,
        ]);
    }

    /**
     * @return void
     */
    private function generateWarehouses(): void
    {
        Warehouse::query()->delete();

        $warehouses = [
            [
                'user_id'    => 1,
                'title'      => [
                    'en' => 'Store in Vilnius, Rinktinės 42',
                    'lt' => 'Parduotuvėje Vilniuje, Rinktinės 42',
                    'ru' => 'Магазин в Вильнюсе, Rinktinės 42',
                ],
                'content'    => null,
                'country_id' => 135,
                'state'      => 'Vilniaus m. sav.',
                'city'       => 'Vilnius',
                'address'    => 'Rinktinės g. 42',
                'zip'        => '09316',
                'phone'      => '+370 601 11 560',
                'email'      => 'info@florial.lt',
                'is_own'     => 1,
            ],
            [
                'user_id'    => 1,
                'title'      => [
                    'en' => 'Supplier 1',
                    'lt' => 'Tiekėjas 1',
                    'ru' => 'Поставщик 1',
                ],
                'content'    => null,
                'country_id' => 169,
                'state'      => 'Amsterdam',
                'city'       => 'Amsterdam',
                'address'    => 'Amsterdam',
                'zip'        => '06327',
                'phone'      => '+37067849854',
                'email'      => 'srklt89@gmail.com',
                'is_own'     => 0,
            ],
        ];

        foreach ($warehouses as $warehouse) {
            Warehouse::create($warehouse);
        }
    }

    /**
     * @return void
     */
    private function config(): void
    {
        Locale::query()->update(['is_default' => false]);
        Locale::query()->where('tag', 'lt')->update(['is_default' => true]);

        Theme::query()->update(['is_default' => false]);
        Theme::query()->where('tag', 'florial')->update(['is_default' => true]);
        Theme::query()->where('tag', 'viartas-theme')->update(['is_default' => true]);
    }

    /**
     * @return void
     */
    private function sameData(): void
    {
        $this->sameData = [
            'content' => [
                'en' => "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
                'lt' => "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
                'ru' => "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
            ],
            'is_visible' => true,
            'user_id' => 1,
        ];
    }

    /**
     * @return void
     */
    private function importData(): void
    {
        $this->import = Http::timeout(30)
            ->get('https://www.topgeles.lt/cart?action=export')
            ->json();
    }

    /**
     * @return void
     */
    private function emptyData(): void
    {
        Import::query()
            ->whereIn('model', [
                Page::class,
                PostCategory::class,
                Post::class,
                ProductCategory::class,
                Product::class,
            ])
            ->delete();

        Page::query()->delete();

        PostCategory::query()->delete();
        Post::query()->delete();

        $menus = MenuItem::query()
            ->whereHas('menus', function ($query) {
                $query->where('tag', 'top_menu');
            })
            ->get();

        foreach ($menus as $item) {
            $item->delete();
        }

        Menu::query()->where('tag', 'main_menu')->delete();

        Item::query()->delete();

        Attribute::query()->delete();
        AttributeGroup::query()->delete();
        //ProductCategory::query()->delete();
        //Product::query()->delete();
        Brand::query()->delete();
        Model::query()->delete();
    }

    /**
     * @return void
     */
    private function generatePages(): void
    {
        $pages = [
            [
                'title' => ['en' => 'About us', 'lt' => 'Apie mus', 'ru' => 'О нас'],
            ],
            [
                'title' => ['en' => 'Information', 'lt' => 'Informacija', 'ru' => 'Информация'],
            ],
            [
                'title' => ['en' => 'For customers', 'lt' => 'Pirkėjams', 'ru' => 'Покупателям'],
                'children' => [
                    [
                        'title' => ['en' => 'Payment Methods', 'lt' => 'Mokėjimo būdai', 'ru' => 'Способы оплаты'],
                    ],
                    [
                        'title' => ['en' => 'Delivery Terms', 'lt' => 'Pristatymo sąlygos', 'ru' => 'Условия доставки'],
                    ],
                    [
                        'title' => ['en' => 'Return Policy', 'lt' => 'Grąžinimo garantijos', 'ru' => 'Гарантия возврата'],
                    ],
                    [
                        'title' => ['en' => 'Warranties', 'lt' => 'Garantijos', 'ru' => 'Гарантии'],
                    ],
                    [
                        'title' => ['en' => 'Terms and Conditions', 'lt' => 'Taisyklės ir sąlygos', 'ru' => 'Правила и условия'],
                    ]
                ]
            ],
            [
                'title' => ['en' => 'Cookie Policy', 'lt' => 'Slapukų politika', 'ru' => 'Политика использования файлов cookie'],
                'children' => [
                    [
                        'title' => ['en' => 'Personal Data Protection', 'lt' => 'Asmens duomenų apsauga', 'ru' => 'Защита персональных данных'],
                    ],
                    [
                        'title' => ['en' => 'Cookie Usage Rules', 'lt' => 'Slapukų naudojimo taisyklės', 'ru' => 'Правила использования файлов cookie'],
                    ],
                    [
                        'title' => ['en' => 'Cookie Policy', 'lt' => 'Slapukų politika', 'ru' => 'Политика использования файлов cookie'],
                    ],
                ],
            ],
            [
                'title' => ['en' => 'Contact us', 'lt' => 'Kontaktai', 'ru' => 'Контакты'],
            ],

        ];

        foreach ($pages as $page) {
            $created = Page::query()->create(
                array_merge($page, $this->sameData)
            );

            if (isset($page['children'])) {
                foreach ($page['children'] as $child) {
                    $child['page_id'] = $created->id;
                    Page::query()->create(
                        array_merge($child, $this->sameData)
                    );
                }
            }
        }
    }

    /**
     * @return void
     */
    private function generatePostCategories(): void
    {
        foreach ($this->import['post_categories'] as $page) {
            $created = PostCategory::query()->create(
                array_merge($page, [])
            );

            Import::query()->create(array_merge($page, [
                'inner_id' => $created->id,
                'model' => PostCategory::class,
                'external_id' => $page['external_id'],
                'external_parent_id' => $page['external_parent_id'],
            ]));

            /*if (isset($page['children'])) {
                foreach ($page['children'] as $child) {
                    $child['page_id'] = $created->id;
                    Page::query()->create(
                        array_merge($child, $this->sameData)
                    );
                }
            }*/
        }
    }

    /**
     * @return void
     */
    private function generatePosts(): void
    {
        foreach ($this->import['posts'] as $page) {

            $external = Import::query()
                ->where('external_id', $page['external_parent_id'])
                ->where('model', PostCategory::class)
                ->first();

            $created = Post::query()->create(
                array_merge($page, [
                    'post_category_id' => $external->inner_id,
                ])
            );

            Import::query()->create(array_merge($page, [
                'inner_id' => $created->id,
                'model' => Post::class,
                'external_id' => $page['external_id'],
                'external_parent_id' => $page['external_parent_id'],
            ]));

            /*if (isset($page['children'])) {
                foreach ($page['children'] as $child) {
                    $child['page_id'] = $created->id;
                    Page::query()->create(
                        array_merge($child, $this->sameData)
                    );
                }
            }*/
        }
    }

    /**
     * @return void
     */
    private function generateProductCategories(): void
    {
        $categories = $this->buildTree($this->import['categories']);

        foreach ($categories as $page) {
            $this->createProductCategory($page);
        }
    }

    /**
     * @param array $page
     * @return void
     */
    private function createProductCategory(array $page): void
    {
        $external = Import::query()
            ->where('external_id', $page['external_parent_id'])
            ->where('model', ProductCategory::class)
            ->first();

        $created = ProductCategory::query()->create(
            array_merge($page, [
                'product_category_id' => $external->inner_id ?? null,
            ])
        );

        Import::query()->create(array_merge($page, [
            'inner_id' => $created->id,
            'model' => ProductCategory::class,
            'external_id' => $page['external_id'],
            'external_parent_id' => $page['external_parent_id'],
        ]));

        if (isset($page['children'])) {
            foreach ($page['children'] as $child) {
                $this->createProductCategory($child);
            }
        }

    }

    /**
     * @return void
     */
    private function generateProducts(): void
    {
        $count = 0;

        foreach ($this->import['products'] as $page) {
            $count++;

            if (! $page['external_parent_id']) {
                continue;
            }

            $external = Import::query()
                ->where('external_id', $page['external_parent_id'])
                ->where('model', ProductCategory::class)
                ->first();

            $created = Product::query()->create(
                array_merge($page, [
                    'product_category_id' => $external->inner_id,
                    'layout' => 'default',
                ])
            );

            if (! empty($page['images'])) {

                if ($count > 10) {
                    continue;
                }

                foreach ($page['images'] as $image) {
                    $media = $created->addMediaFromUrl(sprintf(
                        'https://topgeles.lt/files/img/products/%s.%s',
                        $image['image_name'],
                        $image['image_ext']
                    ))->toMediaCollection('products', 'public');

                    $media->order_column = $image['image_nr'];
                    $media->save();
                }
            }

            Import::query()->create(array_merge($page, [
                'inner_id' => $created->id,
                'model' => Product::class,
                'external_id' => $page['external_id'],
                'external_parent_id' => $page['external_parent_id'],
            ]));

            /*if (isset($page['children'])) {
                foreach ($page['children'] as $child) {
                    $child['page_id'] = $created->id;
                    Page::query()->create(
                        array_merge($child, $this->sameData)
                    );
                }
            }*/
        }
    }

    /**
     * @return void
     */
    private function generateFromMenu(): void
    {
        $menu = Menu::query()->where('tag', 'top_menu')->first();
        $menu->items()->create([
            'element' => 0,
            'class' => 'ViartasModules\Pages\Models\Accounting\Page',
            'sort' => 1,
            'layout' => 'sidebar',
            'has_children' => 1,
        ]);

        $menu->items()->create([
            'element' => PostCategory::query()->where('title->lt','Straipsniai ir patarimai')->first()->id,
            'class' => 'ViartasModules\PostCategories\Models\Accounting\PostCategory',
            'sort' => 2,
            'layout' => 'sidebar',
            'has_children' => 1,
        ]);

        $menu = Menu::create([
            'title' => ['en' => 'Main menu', 'lt' => 'Pagrindinis meniu', 'ru' => 'Главное меню',],
            'tag' => 'main_menu',
            'guard' => 'web',
            'layout' => 'main',
            'depth' => 3,
        ]);

        $menu->items()->create([
            'element' => 0,
            'class' => 'ViartasShop\ProductCategories\Models\Accounting\ProductCategory',
            'sort' => 1,
            'layout' => 'sidebar',
            'has_children' => 1,
        ]);
    }

    /**
     * @return void
     */
    private function generateAttributes(): void
    {
        $attributes = [
            [
                'title' => ['en' => 'Electronics', 'lt' => 'Elektronika', 'ru' => 'Электроника'],
                'tag' => 'electronics',
                'children' => [
                    [
                        'title' => ['en' => 'Type', 'lt' => 'Tipas', 'ru' => 'Тип'],
                        'tag' => 'type',
                        'is_visible' => true,
                    ],
                ],
            ],

            [
                'title' => ['en' => 'Phones', 'lt' => 'Telefonai', 'ru' => 'Телефоны'],
                'tag' => 'phones',
                'children' => [
                    [
                        'title' => ['en' => 'Screen size', 'lt' => 'Ekrano dydis', 'ru' => 'Размер экрана'],
                        'tag' => 'screen_size',
                        'is_visible' => true,
                    ],
                ],
            ],

            [
                'title' => ['en' => 'Clothes', 'lt' => 'Drabužiai', 'ru' => 'Одежда'],
                'tag' => 'clothes',
                'children' => [
                    [
                        'title' => ['en' => 'Size', 'lt' => 'Dydis', 'ru' => 'Размер'],
                        'tag' => 'size',
                        'is_visible' => true,
                    ],
                    [
                        'title' => ['en' => 'Color', 'lt' => 'Spalva', 'ru' => 'Цвет'],
                        'tag' => 'color',
                        'is_visible' => true,
                    ],
                ],
            ],
        ];

        foreach ($attributes as $attribute) {
            $created = AttributeGroup::query()->create(
                array_merge($attribute, $this->sameData)
            );

            if (isset($attribute['children'])) {
                foreach ($attribute['children'] as $child) {
                    $child['attribute_group_id'] = $created->id;
                    Attribute::query()->create(
                        array_merge($child, $this->sameData)
                    );
                }
            }
        }
    }

    /**
     * @return void
     */
    private function generateCategories(): void
    {
        $categories = [
            [
                'title' => [
                    'en' => "Women's clothes",
                    'lt' => 'Moteriški drabužiai',
                    'ru' => 'Женская одежда',
                ],
                'children' => [
                    ['title' => ['en' => 'Dresses',           'lt' => 'Suknelės',                  'ru' => 'Платья']],
                    ['title' => ['en' => 'Tops & T-shirts',   'lt' => 'Topai ir marškinėliai',     'ru' => 'Топы и футболки']],
                    ['title' => ['en' => 'Skirts',            'lt' => 'Sijonai',                    'ru' => 'Юбки']],
                    ['title' => ['en' => 'Pants',             'lt' => 'Kelnės',                     'ru' => 'Брюки']],
                ],
                'attributes' => [
                    'size', 'color',
                ],
            ],
            [
                'title' => [
                    'en' => 'Electronics',
                    'lt' => 'Elektronika',
                    'ru' => 'Электроника',
                ],
                'children' => [
                    [
                        'title' => ['en' => 'Phones', 'lt' => 'Telefonai',    'ru' => 'Телефоны'],
                        'attributes' => [
                            'screen_size',
                        ],
                    ],
                    ['title' => ['en' => 'PC',     'lt' => 'Kompiuteriai', 'ru' => 'ПК']],
                ],
                'attributes' => [
                    'type',
                ],
            ],
        ];

        foreach ($categories as $category) {
            $created = ProductCategory::query()->create(
                array_merge($category, $this->sameData)
            );

            if (isset($category['attributes'])) {
                $attributes = Attribute::query()->whereIn('tag', $category['attributes'])->get();
                $created->attrs()->sync($attributes);
            }

            if (isset($category['children'])) {
                foreach ($category['children'] as $child) {
                    $child['product_category_id'] = $created->id;
                    $child_created = ProductCategory::query()->create(
                        array_merge($child, $this->sameData)
                    );

                    if (isset($child['attributes'])) {
                        $attributes = Attribute::query()->whereIn('tag', $child['attributes'])->get();
                        $child_created->attrs()->sync($attributes);
                    }
                }
            }
        }
    }

    /**
     * @return void
     */
    private function generateBrands(): void
    {
        $brands = [
            [
                'title' => ['en' => 'Samsung', 'lt' => 'Samsung', 'ru' => 'Samsung'],
                'tag'   => 'samsung',
                'children' => [
                    [
                        'title'  => ['en' => 'Galaxy S20', 'lt' => 'Galaxy S20', 'ru' => 'Galaxy S20'],
                        'tag'    => 'galaxy_s20',
                        'series' => 'Galaxy', // added
                    ],
                    [
                        'title'  => ['en' => 'Galaxy S21', 'lt' => 'Galaxy S21', 'ru' => 'Galaxy S21'],
                        'tag'    => 'galaxy_s21',
                        'series' => 'Galaxy', // added
                    ],
                    [
                        'title'  => ['en' => 'Galaxy S22', 'lt' => 'Galaxy S22', 'ru' => 'Galaxy S22'],
                        'tag'    => 'galaxy_s22',
                        'series' => 'Galaxy', // added
                    ],
                ],
            ],
            [
                'title' => ['en' => 'Apple', 'lt' => 'Apple', 'ru' => 'Apple'],
                'tag'   => 'apple',
                'children' => [
                    ['title' => ['en' => 'iPhone 12', 'lt' => 'iPhone 12', 'ru' => 'iPhone 12'], 'tag' => 'iphone_12'],
                    ['title' => ['en' => 'iPhone 13', 'lt' => 'iPhone 13', 'ru' => 'iPhone 13'], 'tag' => 'iphone_13'],
                    ['title' => ['en' => 'iPhone 14', 'lt' => 'iPhone 14', 'ru' => 'iPhone 14'], 'tag' => 'iphone_14'],
                    ['title' => ['en' => 'iPhone 15', 'lt' => 'iPhone 15', 'ru' => 'iPhone 15'], 'tag' => 'iphone_15'],
                    ['title' => ['en' => 'iPhone 16', 'lt' => 'iPhone 16', 'ru' => 'iPhone 16'], 'tag' => 'iphone_16'],
                ],
            ],

            // Clothes brands
            [
                'title' => ['en' => 'Nike', 'lt' => 'Nike', 'ru' => 'Nike'],
                'tag'   => 'nike',
                'children' => [
                    ['title' => ['en' => 'Air Max',     'lt' => 'Air Max',     'ru' => 'Air Max'],     'tag' => 'air_max'],
                    ['title' => ['en' => 'Air Force 1', 'lt' => 'Air Force 1', 'ru' => 'Air Force 1'], 'tag' => 'air_force_1'],
                    ['title' => ['en' => 'Dri-FIT',     'lt' => 'Dri-FIT',     'ru' => 'Dri-FIT'],     'tag' => 'dri_fit'],
                ],
            ],
            [
                'title' => ['en' => 'Adidas', 'lt' => 'Adidas', 'ru' => 'Adidas'],
                'tag'   => 'adidas',
                'children' => [
                    ['title' => ['en' => 'Ultraboost', 'lt' => 'Ultraboost', 'ru' => 'Ultraboost'], 'tag' => 'ultraboost'],
                    ['title' => ['en' => 'Superstar',  'lt' => 'Superstar',  'ru' => 'Superstar'],  'tag' => 'superstar'],
                    ['title' => ['en' => 'Terrex',     'lt' => 'Terrex',     'ru' => 'Terrex'],     'tag' => 'terrex'],
                ],
            ],
            [
                'title' => ['en' => 'Zara', 'lt' => 'Zara', 'ru' => 'Zara'],
                'tag'   => 'zara',
                'children' => [
                    ['title' => ['en' => 'Basic',     'lt' => 'Basic',     'ru' => 'Basic'],     'tag' => 'basic'],
                    ['title' => ['en' => 'Join Life', 'lt' => 'Join Life', 'ru' => 'Join Life'], 'tag' => 'join_life'],
                    ['title' => ['en' => 'TRF',       'lt' => 'TRF',       'ru' => 'TRF'],       'tag' => 'trf'],
                ],
            ],
            [
                'title' => ['en' => 'H&M', 'lt' => 'H&M', 'ru' => 'H&M'],
                'tag'   => 'h_m',
                'children' => [
                    ['title' => ['en' => 'Conscious', 'lt' => 'Conscious', 'ru' => 'Conscious'], 'tag' => 'conscious'],
                    ['title' => ['en' => 'Divided',   'lt' => 'Divided',   'ru' => 'Divided'],   'tag' => 'divided'],
                ],
            ],
            [
                'title' => ['en' => "Levi's", 'lt' => "Levi's", 'ru' => "Levi's"],
                'tag'   => 'levis',
                'children' => [
                    ['title' => ['en' => '501', 'lt' => '501', 'ru' => '501'], 'tag' => '501'],
                    ['title' => ['en' => '511', 'lt' => '511', 'ru' => '511'], 'tag' => '511'],
                    ['title' => ['en' => 'Wedgie', 'lt' => 'Wedgie', 'ru' => 'Wedgie'], 'tag' => 'wedgie'],
                ],
            ],
        ];

        foreach ($brands as $brand) {
            $created = Brand::query()->create(
                array_merge($brand, $this->sameData)
            );

            if (isset($brand['children'])) {
                foreach ($brand['children'] as $child) {
                    $child['brand_id'] = $created->id;

                    if ($brand['tag'] == 'apple' || $brand['tag'] == 'samsung') {
                        $category = ProductCategory::query()->where('title->en', 'Phones')->first();
                    } else {
                        $category = ProductCategory::query()->where('title->en', "Women's clothes")->first();
                    }

                    $child['product_category_id'] = $category->id;

                    Model::query()->create(
                        array_merge($child, $this->sameData)
                    );
                }
            }
        }
    }

    /**
     * Build a nested tree from flat rows using external_id / external_parent_id.
     *
     * @param array $rows  Each row must have: 'external_id', 'external_parent_id' (nullable), and 'title'.
     * @param string $idKey
     * @param string $parentKey
     * @return array       Tree where each node is ['title' => string, 'children' => array]
     */
    private function buildTree(array $rows, string $idKey = 'external_id', string $parentKey = 'external_parent_id'): array
    {
        // 1) Create a node for each item and remember its parent
        $nodes = [];
        foreach ($rows as $row) {
            $id = $row[$idKey];

            $nodes[$id] = [
                'title'    => $row['title'] ?? '',
                'slug'    => $row['slug'] ?? '',
                'content'    => $row['content'] ?? '',
                'external_id'    => $row['external_id'] ?? '',
                'external_parent_id'    => $row['external_parent_id'] ?? '',
                'children' => [],
                '__parent' => $row[$parentKey] ?? null, // temp field used for linking
            ];
        }

        // 2) Link children to parents
        $tree = [];
        foreach ($nodes as $id => &$node) {
            $parentId = $node['__parent'];
            unset($node['__parent']); // cleanup once read

            // guard against self-parenting and missing parent
            if ($parentId && $parentId !== $id && isset($nodes[$parentId])) {
                $nodes[$parentId]['children'][] = &$node; // by reference keeps structure consistent
            } else {
                $tree[] = &$node; // no parent -> root node
            }
        }
        unset($node); // break reference

        return $tree;
    }
}
