<?php

namespace Database\Seeders;

use App\Models\CarouselSlide;
use App\Models\Category;
use App\Models\Collection;
use App\Models\CollectionItem;
use App\Models\Product;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class DemoSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Ensure storage directories exist
        Storage::disk('public')->makeDirectory('slides');
        Storage::disk('public')->makeDirectory('products');
        Storage::disk('public')->makeDirectory('collections');

        $this->command->info('Seeding Carousel Slides...');
        for ($i = 1; $i <= 3; $i++) {
            $imagePath = 'slides/slide-'.$i.'.jpg';
            $this->generateDummyImage($imagePath, 1200, 600, 'Slide '.$i);

            CarouselSlide::create([
                'title' => 'Täze harytlar '.$i,
                'subtitle' => 'Iň oňat bahalar bilen öýüňizi bezäň',
                'order' => $i,
                'is_active' => true,
                'image' => $imagePath,
            ]);
        }

        $this->command->info('Seeding Categories & Products...');
        $categories = ['Diwanlar', 'Krowatlar', 'Stollar', 'Oturgyçlar', 'Şkaflar'];

        foreach ($categories as $index => $categoryName) {
            $category = Category::create([
                'name' => $categoryName,
                'icon' => 'heroicon-o-archive-box', // dummy icon
                'order' => $index + 1,
            ]);

            for ($p = 1; $p <= 4; $p++) {
                $imagePath = 'products/product-'.$category->id.'-'.$p.'.jpg';
                $this->generateDummyImage($imagePath, 800, 800, $categoryName.' '.$p);

                Product::create([
                    'category_id' => $category->id,
                    'name' => 'Owadan '.Str::lower($categoryName).' modeli '.$p,
                    'description' => 'Bu '.Str::lower($categoryName).' örän ýokary hilli we berk materialdan öndürilen. Öýüňize bezeg gatar.',
                    'price' => rand(1000, 15000),
                    'is_active' => true,
                    'image' => $imagePath,
                ]);
            }
        }

        $this->command->info('Seeding Collections & Items...');
        $collections = ['Tomus Kolleksiýasy', 'Täze Ýyl', 'Otag Bezegi'];

        foreach ($collections as $index => $collectionName) {
            $collection = Collection::create([
                'title' => $collectionName,
                'subtitle' => 'Aýratyn dizaýnlar',
                'order' => $index + 1,
                'is_active' => true,
            ]);

            for ($i = 1; $i <= 3; $i++) {
                $imagePath = 'collections/item-'.$collection->id.'-'.$i.'.jpg';
                $this->generateDummyImage($imagePath, 600, 800, 'Item '.$i);

                CollectionItem::create([
                    'collection_id' => $collection->id,
                    'title' => $collectionName.' elementi '.$i,
                    'subtitle' => 'Gözel dizaýn '.$i,
                    'order' => $i,
                    'is_active' => true,
                    'image' => $imagePath,
                ]);
            }
        }
    }

    private function generateDummyImage(string $path, int $width, int $height, string $text): void
    {
        // Try to download a random image from picsum, if it fails, generate a basic image using GD
        try {
            // Using UI Avatars for reliable and fast text-based placeholders
            $url = 'https://ui-avatars.com/api/?name='.urlencode($text).'&size=512&background=random&color=fff&font-size=0.33';
            $contents = file_get_contents($url);
            if ($contents) {
                Storage::disk('public')->put($path, $contents);

                return;
            }
        } catch (\Exception $e) {
            // fallback
        }

        // GD fallback if network fails
        if (extension_loaded('gd')) {
            $image = imagecreatetruecolor($width, $height);
            $bg = imagecolorallocate($image, rand(100, 200), rand(100, 200), rand(100, 200));
            $textColor = imagecolorallocate($image, 255, 255, 255);
            imagefill($image, 0, 0, $bg);
            imagestring($image, 5, $width / 2 - strlen($text) * 4, $height / 2 - 8, $text, $textColor);

            ob_start();
            imagejpeg($image);
            $contents = ob_get_clean();
            imagedestroy($image);

            Storage::disk('public')->put($path, $contents);
        } else {
            // If GD is not available and download failed, just put an empty file or dummy svg
            $svg = '<svg xmlns="http://www.w3.org/2000/svg" width="'.$width.'" height="'.$height.'"><rect width="100%" height="100%" fill="#ccc"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-family="sans-serif" font-size="20px" fill="#333">'.$text.'</text></svg>';
            Storage::disk('public')->put($path, $svg);
        }
    }
}
