<?php

namespace ViartasThemes\Florial\Seeders;

use Illuminate\Database\Eloquent\Model;
use ViartasCore\BannersManager\Models\Banner;
use ViartasCore\BannersManager\Models\BannerItem;
use ViartasCore\Core\Models\Theme;
use ViartasCore\ThemesManager\Models\ThemeSection;
use ViartasShop\ProductCategories\Models\Accounting\ProductCategory;

class FlorialBannerSeeder
{
    /**
     * Seed Florial banners with items and images.
     * Links banners to theme sections automatically.
     *
     * Usage:
     *   FlorialBannerSeeder::seed();
     *   FlorialBannerSeeder::reseed();  // deletes old and recreates
     */
    public static function seed(?Theme $theme = null): array
    {
        $theme = $theme ?? Theme::where('tag', 'florial')->first();

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

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

        $result = ['banners' => 0, 'items' => 0, 'images' => 0];

        try {
            $applicationId = $theme->application_id ?? 1;
            $imagesPath = self::getImagesPath();

            // 1. Hero Banner (hero_sidebar layout: 1 big left + 2 small right)
            $heroBanner = self::createBanner($applicationId, 'florial_hero', [
                'lt' => 'Pagrindinis baneris',
                'en' => 'Hero Banner',
                'ru' => 'Главный баннер',
            ], 'slider');
            $result['banners']++;

            $heroItems = self::getHeroItems();
            $heroImages = [
                'hero-tulips-envelope.png',
                'hero-red-roses.png',
                'hero-pink-tulips.png',
            ];

            foreach ($heroItems as $i => $itemData) {
                $item = self::createBannerItem($heroBanner, $itemData, $i);
                $result['items']++;

                // Attach image if exists
                if (isset($heroImages[$i])) {
                    $imagePath = $imagesPath . '/' . $heroImages[$i];
                    if (file_exists($imagePath)) {
                        $item->addMedia($imagePath)
                            ->preservingOriginal()
                            ->toMediaCollection('images');
                        $result['images']++;
                    }
                }
            }

            // Assign linkable IDs to hero items via lookup
            $heroLinkables = [
                0 => 'geliu-puokstes',     // Slide 1 → Gėlių puokštės
                1 => 'mamu-diena',         // Slide 2 → Mamų diena
                2 => 'meiles-puokstes',    // Slide 3 → Meilės puokštės (Valentino diena)
            ];
            self::assignLinkables($heroBanner, $heroLinkables);

            // Link hero banner to theme section
            self::linkBannerToSection($theme, 'homepage_hero', $heroBanner->id);

            // 2. Promo Cards Banner (cards_row layout: 4 promo cards)
            $promoBanner = self::createBanner($applicationId, 'florial_promo', [
                'lt' => 'Promo kortelės',
                'en' => 'Promo Cards',
                'ru' => 'Промо карточки',
            ], 'static');
            $result['banners']++;

            $promoItems = self::getPromoItems();
            $promoImages = [
                'promo-pink-roses-box.png',
                'promo-pink-roses-light.png',
                'promo-mixed-bouquet.png',
                'promo-red-roses-heart.png',
            ];

            foreach ($promoItems as $i => $itemData) {
                $item = self::createBannerItem($promoBanner, $itemData, $i);
                $result['items']++;

                if (isset($promoImages[$i])) {
                    $imagePath = $imagesPath . '/' . $promoImages[$i];
                    if (file_exists($imagePath)) {
                        $item->addMedia($imagePath)
                            ->preservingOriginal()
                            ->toMediaCollection('images');
                        $result['images']++;
                    }
                }
            }

            // Link promo banner to theme section
            self::linkBannerToSection($theme, 'homepage_promo_cards', $promoBanner->id);

            // Assign linkable IDs to promo items via lookup
            $promoLinkables = [
                0 => 'rozes',              // Promo 1 → Rožės
                1 => 'sezono-puokstes',    // Promo 2 → Sezono puokštės
                2 => 'vip-pasiulymai',     // Promo 3 → VIP pasiūlymai
                3 => 'meiles-puokstes',    // Promo 4 → Meilės puokštės
            ];
            self::assignLinkables($promoBanner, $promoLinkables);

        } finally {
            if (!$wasUnguarded) {
                Model::reguard();
            }
        }

        return $result;
    }

    /**
     * Delete Florial banners 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.');
        }

        $applicationId = $theme->application_id ?? 1;

        // Delete existing Florial banners
        $deleted = 0;
        foreach (['florial_hero', 'florial_promo'] as $tag) {
            $banner = Banner::where('application_id', $applicationId)->where('tag', $tag)->first();
            if ($banner) {
                // Delete items and their media
                foreach ($banner->items as $item) {
                    $item->clearMediaCollection('images');
                    $item->delete();
                }
                $banner->delete();
                $deleted++;
            }
        }

        $result = self::seed($theme);
        $result['deleted_banners'] = $deleted;

        return $result;
    }

    /**
     * Get path to banner images in the florial package
     */
    protected static function getImagesPath(): string
    {
        // Try multiple locations
        $paths = [
            base_path('packages/viartas-themes/florial/resources/images/banners'),
            dirname(__DIR__, 2) . '/resources/images/banners',
        ];

        foreach ($paths as $path) {
            if (is_dir($path)) {
                return $path;
            }
        }

        return $paths[0]; // fallback
    }

    /**
     * Create or find a banner
     */
    protected static function createBanner(int $applicationId, string $tag, array $title, string $type): Banner
    {
        return Banner::updateOrCreate(
            ['application_id' => $applicationId, 'tag' => $tag],
            [
                'title' => $title,
                'type' => $type,
                'is_active' => true,
                'position' => 0,
                'settings' => Banner::defaultSettings($type),
            ]
        );
    }

    /**
     * Create a banner item
     */
    protected static function createBannerItem(Banner $banner, array $data, int $position): BannerItem
    {
        return BannerItem::create(array_merge($data, [
            'banner_id' => $banner->id,
            'position' => $position,
            'is_active' => true,
            'settings' => BannerItem::defaultSettings(),
        ]));
    }

    /**
     * Link a banner to a theme section via settings
     */
    protected static function linkBannerToSection(Theme $theme, string $sectionKey, int $bannerId): void
    {
        $section = ThemeSection::where('theme_id', $theme->id)
            ->where('key', $sectionKey)
            ->first();

        if ($section) {
            $settings = $section->settings ?? [];
            $settings['banner_id'] = $bannerId;
            $section->update(['settings' => $settings]);
        }
    }

    /**
     * Hero banner items (3 slides)
     */
    protected static function getHeroItems(): array
    {
        return [
            // Slide 1 - Main hero (big left)
            [
                'title' => [
                    'lt' => 'Būkite namuose ir mes pristatysime šviežias gėles',
                    'en' => 'Stay home & we will deliver fresh flowers',
                    'ru' => 'Оставайтесь дома, а мы доставим свежие цветы',
                ],
                'subtitle' => [
                    'lt' => 'Išskirtiniai pasiūlymai',
                    'en' => 'Exclusive offers',
                    'ru' => 'Эксклюзивные предложения',
                ],
                'description' => [
                    'lt' => 'Pristatome gėles tiesiai iš Nyderlandų. Siūlome geriausias kainas ir šviežiausias gėles.',
                    'en' => 'We deliver flowers directly from the Netherlands. We offer probably the best prices and the freshest flowers.',
                    'ru' => 'Мы доставляем цветы напрямую из Нидерландов. Мы предлагаем лучшие цены и самые свежие цветы.',
                ],
                'button_text' => [
                    'lt' => 'Pirkti dabar',
                    'en' => 'Shop Now',
                    'ru' => 'Купить сейчас',
                ],
                'button_url' => [
                    'lt' => '/katalogas',
                    'en' => '/catalog',
                    'ru' => '/katalog',
                ],
                'badge_text' => [
                    'lt' => '30% nuolaida',
                    'en' => '30% Off',
                    'ru' => 'Скидка 30%',
                ],
            ],
            // Slide 2 - Right top (Mothers day)
            [
                'title' => [
                    'lt' => 'Mamų diena',
                    'en' => 'Mothers day',
                    'ru' => 'День матери',
                ],
                'subtitle' => [
                    'lt' => 'Sveikiname',
                    'en' => 'Happy',
                    'ru' => 'С праздником',
                ],
                'description' => [
                    'lt' => 'Tik geriausios kokybės puokštės mamoms',
                    'en' => 'Only the best quality bouquets for Moms',
                    'ru' => 'Только лучшие букеты для мам',
                ],
                'button_text' => [
                    'lt' => 'Pirkti dabar',
                    'en' => 'Shop Now',
                    'ru' => 'Купить сейчас',
                ],
                'button_url' => [
                    'lt' => '/katalogas/mamu-diena',
                    'en' => '/catalog/mothers-day',
                    'ru' => '/katalog/den-materi',
                ],
                'badge_text' => null,
            ],
            // Slide 3 - Right bottom (Valentines day)
            [
                'title' => [
                    'lt' => 'Šv. Valentino diena',
                    'en' => 'St. Valentines day',
                    'ru' => 'День Св. Валентина',
                ],
                'subtitle' => [
                    'lt' => 'Sveikiname',
                    'en' => 'Happy',
                    'ru' => 'С праздником',
                ],
                'description' => [
                    'lt' => 'Tik geriausios kokybės puokštės jūsų mylimiesiems',
                    'en' => 'Only the best quality bouquets for your loved ones',
                    'ru' => 'Только лучшие букеты для ваших любимых',
                ],
                'button_text' => [
                    'lt' => 'Pirkti dabar',
                    'en' => 'Shop Now',
                    'ru' => 'Купить сейчас',
                ],
                'button_url' => [
                    'lt' => '/katalogas/valentino-diena',
                    'en' => '/catalog/valentines-day',
                    'ru' => '/katalog/den-valentina',
                ],
                'badge_text' => null,
            ],
        ];
    }

    /**
     * Promo card items (4 cards)
     */
    protected static function getPromoItems(): array
    {
        return [
            [
                'title' => [
                    'lt' => 'Nuostabios<br>rožių puokštės',
                    'en' => 'Amazing<br>rose bouquets',
                    'ru' => 'Потрясающие<br>букеты роз',
                ],
                'subtitle' => null,
                'description' => null,
                'button_text' => [
                    'lt' => 'Pirkti dabar',
                    'en' => 'Shop Now',
                    'ru' => 'Купить сейчас',
                ],
                'button_url' => [
                    'lt' => '/katalogas/rozes',
                    'en' => '/catalog/roses',
                    'ru' => '/katalog/rozy',
                ],
                'badge_text' => [
                    'lt' => '25% OFF',
                    'en' => '25% OFF',
                    'ru' => '25% OFF',
                ],
            ],
            [
                'title' => [
                    'lt' => 'Pavasariškos<br>gėlių puokštės',
                    'en' => 'Spring<br>flower bouquets',
                    'ru' => 'Весенние<br>букеты цветов',
                ],
                'subtitle' => null,
                'description' => null,
                'button_text' => [
                    'lt' => 'Pirkti dabar',
                    'en' => 'Shop Now',
                    'ru' => 'Купить сейчас',
                ],
                'button_url' => [
                    'lt' => '/katalogas/pavasaris',
                    'en' => '/catalog/spring',
                    'ru' => '/katalog/vesna',
                ],
                'badge_text' => [
                    'lt' => '30% OFF',
                    'en' => '30% OFF',
                    'ru' => '30% OFF',
                ],
            ],
            [
                'title' => [
                    'lt' => 'Prabangūs<br>gėlių rinkiniai',
                    'en' => 'Luxury<br>flower sets',
                    'ru' => 'Роскошные<br>цветочные наборы',
                ],
                'subtitle' => null,
                'description' => null,
                'button_text' => [
                    'lt' => 'Pirkti dabar',
                    'en' => 'Shop Now',
                    'ru' => 'Купить сейчас',
                ],
                'button_url' => [
                    'lt' => '/katalogas/prabangus',
                    'en' => '/catalog/luxury',
                    'ru' => '/katalog/roskosh',
                ],
                'badge_text' => [
                    'lt' => '30% OFF',
                    'en' => '30% OFF',
                    'ru' => '30% OFF',
                ],
            ],
            [
                'title' => [
                    'lt' => 'Romantiškos<br>kompozicijos',
                    'en' => 'Romantic<br>arrangements',
                    'ru' => 'Романтические<br>композиции',
                ],
                'subtitle' => null,
                'description' => null,
                'button_text' => [
                    'lt' => 'Pirkti dabar',
                    'en' => 'Shop Now',
                    'ru' => 'Купить сейчас',
                ],
                'button_url' => [
                    'lt' => '/katalogas/romantiskas',
                    'en' => '/catalog/romantic',
                    'ru' => '/katalog/romantika',
                ],
                'badge_text' => [
                    'lt' => '40% OFF',
                    'en' => '40% OFF',
                    'ru' => '40% OFF',
                ],
            ],
        ];
    }

    /**
     * Assign linkable (product_category) to banner items by position via slug lookup.
     * This replaces hardcoded button_url with dynamic linkable references.
     */
    protected static function assignLinkables(Banner $banner, array $positionToSlug): void
    {
        $items = $banner->items()->orderBy('position')->get();

        foreach ($positionToSlug as $position => $slug) {
            $item = $items->get($position);
            if (!$item) continue;

            $category = ProductCategory::whereRaw("JSON_EXTRACT(slug, '$.lt') = ?", [$slug])->first();
            if ($category) {
                $item->update([
                    'linkable_type' => 'product_category',
                    'linkable_id' => $category->id,
                ]);
            }
        }
    }
}
