<?php

namespace ViartasThemes\Florial\Seeders;

use Illuminate\Database\Eloquent\Model;
use ViartasCore\Core\Models\Theme;
use ViartasCore\Core\Models\ThemeConfig;
use ViartasCore\ThemesManager\Models\ThemeSection;

class FlorialThemeSeeder
{
    /**
     * Seed Florial theme sections and configs.
     */
    public static function seed(?Theme $theme = null): void
    {
        $theme = $theme ?? Theme::where('tag', 'florial')->first();

        if (!$theme) {
            throw new \RuntimeException('Florial theme not found in database.');
        }

        $wasUnguarded = Model::isUnguarded();
        Model::unguard();

        try {
            $locales = self::getLocales();

            foreach (self::getSections() as $sectionData) {
                if (ThemeSection::where('theme_id', $theme->id)->where('key', $sectionData['key'])->exists()) {
                    continue;
                }

                $title = [];
                foreach ($locales as $locale) {
                    $title[$locale] = $sectionData['title'][$locale] ?? $sectionData['title']['en'] ?? $sectionData['key'];
                }

                $section = ThemeSection::create([
                    'theme_id' => $theme->id,
                    'key' => $sectionData['key'],
                    'type' => $sectionData['type'],
                    'title' => $title,
                    'position' => $sectionData['position'],
                    'is_active' => $sectionData['is_active'] ?? true,
                    'settings' => array_merge(
                        ThemeSection::defaultSettings($sectionData['type']),
                        $sectionData['settings'] ?? []
                    ),
                ]);

                // Seed config keys from model defaults first
                $configKeys = ThemeSection::defaultConfigKeys($sectionData['type'], $sectionData['key']);
                $position = 0;

                foreach ($configKeys as $key => $keyConfig) {
                    $value = $keyConfig['value'];
                    if (is_array($value)) {
                        $value = !empty($value) ? json_encode($value) : null;
                    } elseif ($value === '' || $value === null) {
                        $value = null;
                    } else {
                        $value = json_encode($value);
                    }

                    ThemeConfig::updateOrCreate(
                        ['theme_id' => $theme->id, 'key' => $key, 'section' => $section->key],
                        [
                            'section' => $section->key,
                            'type' => $keyConfig['type'],
                            'value' => $value,
                            'position' => $position++,
                            'is_active' => true,
                        ]
                    );
                }

                // Override with real content values
                if (isset($sectionData['configs'])) {
                    foreach ($sectionData['configs'] as $key => $configData) {
                        $value = $configData['value'];
                        $type = $configData['type'] ?? 'text';

                        if (is_array($value)) {
                            $value = json_encode($value);
                        } elseif ($value === '' || $value === null) {
                            $value = null;
                        } else {
                            $value = json_encode($value);
                        }

                        ThemeConfig::updateOrCreate(
                            ['theme_id' => $theme->id, 'key' => $key, 'section' => $section->key],
                            [
                                'section' => $section->key,
                                'type' => $type,
                                'value' => $value,
                                'position' => $position++,
                                'is_active' => true,
                            ]
                        );
                    }
                }
            }
        } finally {
            if (!$wasUnguarded) {
                Model::reguard();
            }
        }
    }

    /**
     * Delete everything and reseed
     */
    public static function reseed(?Theme $theme = null): array
    {
        $theme = $theme ?? Theme::where('tag', 'florial')->first();

        if (!$theme) {
            throw new \RuntimeException('Florial theme not found in database.');
        }

        $deletedConfigs = ThemeConfig::where('theme_id', $theme->id)->delete();
        $deletedSections = ThemeSection::where('theme_id', $theme->id)->delete();

        self::seed($theme);

        return [
            'deleted_sections' => $deletedSections,
            'deleted_configs' => $deletedConfigs,
            'new_sections' => ThemeSection::where('theme_id', $theme->id)->count(),
            'new_configs' => ThemeConfig::where('theme_id', $theme->id)->count(),
        ];
    }

    protected static function getLocales(): array
    {
        try {
            $locales = \ViartasCore\Core\Models\Locale::where('is_active', 1)
                ->orderByDesc('is_default')
                ->pluck('tag')
                ->toArray();
            return !empty($locales) ? $locales : ['lt', 'en', 'ru'];
        } catch (\Exception $e) {
            return ['lt', 'en', 'ru'];
        }
    }

    /**
     * ═══════════════════════════════════════════════════════════════
     * FLORIAL HOMEPAGE — REAL CONTENT DATA
     * ═══════════════════════════════════════════════════════════════
     */
    protected static function getSections(): array
    {
        return [

            // ─── 0. MENU LOCATIONS ──────────────────────────────────
            [
                'key' => 'menus',
                'type' => 'menus',
                'title' => ['en' => 'Menu Locations', 'lt' => 'Meniu vietos', 'ru' => 'Расположение меню'],
                'position' => 0,
                'settings' => [
                    'slots' => [
                        'top'        => ['menu_id' => null, 'label' => 'themes.menu_top'],
                        'main'       => ['menu_id' => null, 'label' => 'themes.menu_main'],
                        'categories' => ['menu_id' => null, 'label' => 'themes.menu_categories'],
                        'sidebar'    => ['menu_id' => null, 'label' => 'themes.menu_sidebar'],
                        'footer_1'   => ['menu_id' => null, 'label' => 'themes.menu_footer_1'],
                        'footer_2'   => ['menu_id' => null, 'label' => 'themes.menu_footer_2'],
                        'footer_3'   => ['menu_id' => null, 'label' => 'themes.menu_footer_3'],
                    ],
                ],
            ],

            // ─── 1. HEADER ──────────────────────────────────────────
            [
                'key' => 'header',
                'type' => 'header',
                'title' => ['en' => 'Header', 'lt' => 'Antraštė', 'ru' => 'Шапка'],
                'position' => 1,
                'settings' => [
                    'show_top_bar' => true,
                    'show_search' => true,
                    'show_cart' => true,
                    'show_account' => true,
                    'show_wishlist' => true,
                    'show_phone_icon' => true,
                    'show_language_switcher' => true,
                    'show_store_locator' => true,
                    'logo_position' => 'left',
                ],
                'configs' => [
                    'header_address' => [
                        'type' => 'translatable',
                        'value' => [
                            'lt' => 'Rinktinės g. 42, Vilnius',
                            'en' => 'Rinktinės g. 42, Vilnius',
                            'ru' => 'Rinktinės g. 42, Вильнюс',
                        ],
                    ],
                    'header_phone' => [
                        'type' => 'text',
                        'value' => '+370 601 11 560',
                    ],
                    'header_email' => [
                        'type' => 'text',
                        'value' => 'info@florial.lt',
                    ],
                    'header_promo_text' => [
                        'type' => 'translatable_html',
                        'value' => [
                            'lt' => '<strong class="me-1">Sveiki atvykę į Florial!</strong> Nuolaidos kodas atidarymo proga: <strong class="ms-1">FLORIAL2025</strong>',
                            'en' => '<strong class="me-1">Welcome to Florial!</strong> Discount code for the opening event: <strong class="ms-1">FLORIAL2025</strong>',
                            'ru' => '<strong class="me-1">Добро пожаловать в Florial!</strong> Код скидки по случаю открытия: <strong class="ms-1">FLORIAL2025</strong>',
                        ],
                    ],
                    'header_promo_text_2' => [
                        'type' => 'translatable_html',
                        'value' => [
                            'lt' => 'Tai, ką mėgstate, dabar išpardavime! <a href="#" class="text-white">Pirkti dabar</a>',
                            'en' => 'Something you love is now on sale! <a href="#" class="text-white">Shop now</a>',
                            'ru' => 'То, что вам нравится, теперь на распродаже! <a href="#" class="text-white">Купить сейчас</a>',
                        ],
                    ],
                    'header_store_text' => [
                        'type' => 'translatable',
                        'value' => [
                            'lt' => 'Mūsų parduotuvė',
                            'en' => 'Our shop',
                            'ru' => 'Наш магазин',
                        ],
                    ],
                ],
            ],

            // ─── 2. HERO BANNER ─────────────────────────────────────
            [
                'key' => 'homepage_hero',
                'type' => 'banner',
                'title' => ['en' => 'Hero Banner', 'lt' => 'Pagrindinis baneris', 'ru' => 'Главный баннер'],
                'position' => 2,
                'settings' => [
                    'banner_id' => null,
                    'layout' => 'hero_sidebar',
                    'position_label' => 'homepage_hero',
                ],
            ],

            // ─── 3. PROMO CARDS ─────────────────────────────────────
            [
                'key' => 'homepage_promo_cards',
                'type' => 'banner',
                'title' => ['en' => 'Promo Cards', 'lt' => 'Promo kortelės', 'ru' => 'Промо карточки'],
                'position' => 3,
                'settings' => [
                    'banner_id' => null,
                    'layout' => 'cards_row',
                    'columns' => 4,
                    'position_label' => 'homepage_promo',
                ],
            ],

            // ─── 4. CATEGORY SHOWCASE ───────────────────────────────
            [
                'key' => 'homepage_categories',
                'type' => 'category_showcase',
                'title' => ['en' => 'Product Catalog', 'lt' => 'Prekių Katalogas', 'ru' => 'Каталог товаров'],
                'position' => 4,
                'settings' => [
                    'category_id' => null,
                    'display_mode' => 'grid',
                    'items_count' => 6,
                    'columns' => 6,
                    'show_icons' => true,
                ],
                'configs' => [
                    'section_title' => [
                        'type' => 'translatable',
                        'value' => [
                            'lt' => 'Prekių Katalogas',
                            'en' => 'Product Catalog',
                            'ru' => 'Каталог товаров',
                        ],
                    ],
                    'view_all_text' => [
                        'type' => 'translatable',
                        'value' => [
                            'lt' => 'Visos kategorijos',
                            'en' => 'All categories',
                            'ru' => 'Все категории',
                        ],
                    ],
                ],
            ],

            // ─── 5. PRODUCTS ROW 1 ─────────────────────────────────
            [
                'key' => 'homepage_products_1',
                'type' => 'products',
                'title' => ['en' => 'Featured Products', 'lt' => 'Rekomenduojamos prekės', 'ru' => 'Рекомендуемые товары'],
                'position' => 5,
                'settings' => [
                    'source' => 'latest',
                    'items_count' => 6,
                    'columns' => 6,
                    'show_price' => true,
                    'show_add_to_cart' => true,
                ],
                'configs' => [
                    'section_title' => [
                        'type' => 'translatable',
                        'value' => [
                            'lt' => 'Rekomenduojamos prekės',
                            'en' => 'Featured Products',
                            'ru' => 'Рекомендуемые товары',
                        ],
                    ],
                ],
            ],

            // ─── 6. CONTENT WITH SIDEBAR ────────────────────────────
            [
                'key' => 'homepage_content_sidebar',
                'type' => 'content_block',
                'title' => ['en' => 'Content with Sidebar', 'lt' => 'Turinys su šoniniu meniu', 'ru' => 'Контент с боковым меню'],
                'position' => 6,
                'settings' => [
                    'layout' => 'with_sidebar',
                    'menu_id' => null,
                    'padding' => 'normal',
                ],
                'configs' => [
                    'heading' => [
                        'type' => 'translatable',
                        'value' => [
                            'lt' => 'Gėlės Kiekvienai Progai',
                            'en' => 'Flowers for Every Occasion',
                            'ru' => 'Цветы на каждый случай',
                        ],
                    ],
                    'body' => [
                        'type' => 'translatable_html',
                        'value' => [
                            'lt' => 'Kiekviena puokštė – tai kruopščiai atrinktos gėlės, subtilios spalvos ir floristo rankų darbas. Nesvarbu, ar ieškote dovanos mylimam žmogui, ar norite pradžiuginti save – čia rasite gėles, kurios kalba be žodžių.',
                            'en' => 'Every bouquet is carefully selected flowers, subtle colors and the work of a florist\'s hands. Whether you are looking for a gift for a loved one or want to treat yourself – here you will find flowers that speak without words.',
                            'ru' => 'Каждый букет – это тщательно подобранные цветы, тонкие цвета и ручная работа флориста. Неважно, ищете ли вы подарок для любимого человека или хотите порадовать себя – здесь вы найдёте цветы, которые говорят без слов.',
                        ],
                    ],
                ],
            ],

            // ─── 7. PRODUCTS ROW 2 ─────────────────────────────────
            [
                'key' => 'homepage_products_2',
                'type' => 'products',
                'title' => ['en' => 'More Products', 'lt' => 'Daugiau prekių', 'ru' => 'Больше товаров'],
                'position' => 7,
                'settings' => [
                    'source' => 'category',
                    'category_id' => null,
                    'items_count' => 6,
                    'columns' => 3,
                    'show_price' => true,
                    'show_add_to_cart' => true,
                ],
                'configs' => [
                    'section_title' => [
                        'type' => 'translatable',
                        'value' => [
                            'lt' => 'Daugiau prekių',
                            'en' => 'More Products',
                            'ru' => 'Больше товаров',
                        ],
                    ],
                ],
            ],

            // ─── 8. BENEFITS BAR ────────────────────────────────────
            [
                'key' => 'benefits',
                'type' => 'custom',
                'title' => ['en' => 'Benefits Bar', 'lt' => 'Privalumų juosta', 'ru' => 'Преимущества'],
                'position' => 8,
                'settings' => [
                    'component' => 'benefits_bar',
                    'items_count' => 4,
                ],
                'configs' => [
                    'benefit_1_icon' => ['type' => 'text', 'value' => 'fas fa-leaf'],
                    'benefit_1_text' => [
                        'type' => 'translatable',
                        'value' => [
                            'lt' => 'Visada šviežios gėlės',
                            'en' => 'Every Fresh Products',
                            'ru' => 'Всегда свежие цветы',
                        ],
                    ],
                    'benefit_2_icon' => ['type' => 'text', 'value' => 'fas fa-truck'],
                    'benefit_2_text' => [
                        'type' => 'translatable',
                        'value' => [
                            'lt' => 'Nemokamas pristatymas nuo 50€',
                            'en' => 'Free Delivery For Order Over €50',
                            'ru' => 'Бесплатная доставка от 50€',
                        ],
                    ],
                    'benefit_3_icon' => ['type' => 'text', 'value' => 'fas fa-percent'],
                    'benefit_3_text' => [
                        'type' => 'translatable',
                        'value' => [
                            'lt' => 'Kasdienės nuolaidos',
                            'en' => 'Daily Mega Discounts',
                            'ru' => 'Ежедневные скидки',
                        ],
                    ],
                    'benefit_4_icon' => ['type' => 'text', 'value' => 'fas fa-tags'],
                    'benefit_4_text' => [
                        'type' => 'translatable',
                        'value' => [
                            'lt' => 'Geriausia kaina rinkoje',
                            'en' => 'Best Price On The Market',
                            'ru' => 'Лучшая цена на рынке',
                        ],
                    ],
                ],
            ],

            // ─── 99. FOOTER ─────────────────────────────────────────
            [
                'key' => 'footer',
                'type' => 'footer',
                'title' => ['en' => 'Footer', 'lt' => 'Poraštė', 'ru' => 'Подвал'],
                'position' => 99,
                'settings' => [
                    'columns' => 5,
                    'show_social' => true,
                    'show_newsletter' => false,
                    'show_payment_icons' => true,
                ],
                'configs' => [
                    'footer_description' => [
                        'type' => 'translatable_html',
                        'value' => [
                            'lt' => 'Mes esame gėlių studija, siūlanti plačiausią šviežių gėlių, puokščių ir kompozicijų pasirinkimą. Mūsų parduotuvė – tobula vieta rasti dovaną kiekvienai progai.',
                            'en' => 'We are a flower studio offering the widest selection of fresh flowers, bouquets and arrangements. Our shop is a perfect place to find a gift for every occasion.',
                            'ru' => 'Мы – цветочная студия, предлагающая широчайший выбор свежих цветов, букетов и композиций. Наш магазин – идеальное место для подарка на любой случай.',
                        ],
                    ],
                    'copyright_text' => [
                        'type' => 'translatable',
                        'value' => [
                            'lt' => '©2026 Florial. Visos teisės saugomos',
                            'en' => '©2026 Florial. All rights reserved',
                            'ru' => '©2026 Florial. Все права защищены',
                        ],
                    ],
                    'footer_contact_title' => [
                        'type' => 'translatable',
                        'value' => [
                            'lt' => 'Susisiekite',
                            'en' => 'Contact Us',
                            'ru' => 'Контакты',
                        ],
                    ],
                    'footer_hotline_label' => [
                        'type' => 'translatable',
                        'value' => [
                            'lt' => 'Skambinkite 24/7',
                            'en' => 'Hotline 24/7',
                            'ru' => 'Горячая линия 24/7',
                        ],
                    ],
                    'footer_email_label' => [
                        'type' => 'translatable',
                        'value' => [
                            'lt' => 'El. paštas',
                            'en' => 'Email Address',
                            'ru' => 'Эл. почта',
                        ],
                    ],
                    'footer_address' => ['type' => 'text', 'value' => 'Rinktinės g. 42, Vilnius'],
                    'footer_email' => ['type' => 'text', 'value' => 'info@florial.lt'],
                    'footer_phone' => ['type' => 'text', 'value' => '+370 601 11 560'],
                    'footer_hotline' => ['type' => 'text', 'value' => '+370 601 11 560'],
                    'social_facebook' => ['type' => 'text', 'value' => 'https://www.facebook.com/florial'],
                    'social_instagram' => ['type' => 'text', 'value' => 'https://www.instagram.com/florial'],
                ],
            ],
        ];
    }
}
