<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use App\Models\Category;
use App\Models\Product;
use App\Models\Banner;
use App\Models\User;
use App\Models\Seller;

class DummyContentSeeder extends Seeder
{
    public function run()
    {
        $this->command->info('Starting Dummy Content Generation...');

        // Ensure directories exist
        Storage::disk('public')->makeDirectory('banners');
        Storage::disk('public')->makeDirectory('products');
        Storage::disk('public')->makeDirectory('categories');

        // 1. Categories
        $this->command->info('Seeding Categories...');
        $categories = [
            'Electronics' => 'https://images.unsplash.com/photo-1498049860654-af1a5c5668ba?w=500&q=80',
            'Fashion' => 'https://images.unsplash.com/photo-1445205170230-053b83016050?w=500&q=80',
            'Home & Garden' => 'https://images.unsplash.com/photo-1484101403633-562f891dc89a?w=500&q=80',
            'Industrial' => 'https://images.unsplash.com/photo-1581091226825-a6a2a5aee158?w=500&q=80',
            'Beauty & Health' => 'https://images.unsplash.com/photo-1596462502278-27bfdd403348?w=500&q=80',
            'Automotive' => 'https://images.unsplash.com/photo-1568605117036-5fe5e7bab0b7?w=500&q=80',
            'Sports' => 'https://images.unsplash.com/photo-1461896836934-ffe607ba8211?w=500&q=80',
            'Toys & Hobbies' => 'https://images.unsplash.com/photo-1566576912902-4b61e8781543?w=500&q=80',
        ];

        foreach ($categories as $name => $url) {
            $slug = Str::slug($name);
            $imageName = "categories/{$slug}.jpg";
            
            if (!Storage::disk('public')->exists($imageName)) {
                $this->downloadImage($url, $imageName);
            }

            Category::updateOrCreate(
                ['slug' => $slug],
                [
                    'name' => $name,
                    'image' => $imageName,
                    'is_active' => true,
                    'is_featured' => true,
                ]
            );
        }

        // 2. Banners (Home Top)
        $this->command->info('Seeding Banners...');
        $banners = [
            [
                'title' => 'Global Trade Made Easy',
                'description' => 'Connect with verified suppliers from around the world.',
                'image_url' => 'https://images.unsplash.com/photo-1454165804606-c3d57bc86b40?w=1200&q=80',
                'position' => 'home_top',
            ],
            [
                'title' => 'Quality Products, Best Prices',
                'description' => 'Source high-quality products directly from manufacturers.',
                'image_url' => 'https://images.unsplash.com/photo-1586528116311-ad8dd3c8310d?w=1200&q=80',
                'position' => 'home_top',
            ],
            [
                'title' => 'Secure Payments & Logistics',
                'description' => 'We ensure smooth transactions and timely delivery.',
                'image_url' => 'https://images.unsplash.com/photo-1566576912902-4b61e8781543?w=1200&q=80',
                'position' => 'home_top',
            ],
        ];

        foreach ($banners as $index => $data) {
            $imageName = "banners/home_banner_{$index}.jpg";
            if (!Storage::disk('public')->exists($imageName)) {
                $this->downloadImage($data['image_url'], $imageName);
            }

            Banner::updateOrCreate(
                ['title' => $data['title']],
                [
                    'description' => $data['description'],
                    'image' => $imageName,
                    'position' => $data['position'],
                    'active' => true,
                    'link' => '#',
                ]
            );
        }

        // 3. Products
        $this->command->info('Seeding Products...');
        
        // Ensure a seller exists
        $sellerUser = User::firstOrCreate(
            ['email' => 'seller@example.com'],
            [
                'name' => 'Demo Seller',
                'password' => bcrypt('password'),
                'role' => 'seller',
            ]
        );
        
        $seller = Seller::firstOrCreate(
            ['user_id' => $sellerUser->id],
            [
                'company_name' => 'Demo Global Traders',
                'business_type' => 'Manufacturer',
                'is_verified' => true,
            ]
        );

        $products = [
            ['name' => 'Wireless Noise Cancelling Headphones', 'price' => 2500, 'cat' => 'Electronics', 'img' => 'https://images.unsplash.com/photo-1505740420928-5e560c06d30e?w=500&q=80'],
            ['name' => 'Smart Watch Series 7', 'price' => 4500, 'cat' => 'Electronics', 'img' => 'https://images.unsplash.com/photo-1523275335684-37898b6baf30?w=500&q=80'],
            ['name' => 'Modern Sofa Set', 'price' => 25000, 'cat' => 'Home & Garden', 'img' => 'https://images.unsplash.com/photo-1555041469-a586c61ea9bc?w=500&q=80'],
            ['name' => 'Industrial Drilling Machine', 'price' => 15000, 'cat' => 'Industrial', 'img' => 'https://images.unsplash.com/photo-1581091226825-a6a2a5aee158?w=500&q=80'],
            ['name' => 'Organic Face Serum', 'price' => 800, 'cat' => 'Beauty & Health', 'img' => 'https://images.unsplash.com/photo-1620916566398-39f1143ab7be?w=500&q=80'],
            ['name' => 'Running Shoes Pro', 'price' => 3200, 'cat' => 'Fashion', 'img' => 'https://images.unsplash.com/photo-1542291026-7eec264c27ff?w=500&q=80'],
            ['name' => 'Yoga Mat Premium', 'price' => 1200, 'cat' => 'Sports', 'img' => 'https://images.unsplash.com/photo-1592432678016-e910b452f9a2?w=500&q=80'],
            ['name' => 'RC Drone with Camera', 'price' => 8500, 'cat' => 'Toys & Hobbies', 'img' => 'https://images.unsplash.com/photo-1507582020474-9a35b7d455d9?w=500&q=80'],
        ];

        foreach ($products as $index => $p) {
            $category = Category::where('name', $p['cat'])->first();
            $imageName = "products/product_{$index}.jpg";
            
            if (!Storage::disk('public')->exists($imageName)) {
                $this->downloadImage($p['img'], $imageName);
            }

            Product::updateOrCreate(
                ['name' => $p['name']],
                [
                    'slug' => Str::slug($p['name']),
                    'category_id' => $category->id ?? 1,
                    'seller_id' => $seller->id,
                    'description' => 'High quality ' . $p['name'] . ' available for bulk order. Contact for best prices.',
                    'price' => $p['price'],
                    'moq' => 10,
                    'is_highlighted' => $index < 4, 
                    'images_json' => json_encode([['thumbnail' => $imageName, 'original' => $imageName]]),
                ]
            );
        }

        $this->command->info('Dummy Content Generated Successfully!');
    }

    private function downloadImage($url, $path)
    {
        try {
            $contents = file_get_contents($url);
            if ($contents) {
                Storage::disk('public')->put($path, $contents);
            }
        } catch (\Exception $e) {
            $this->command->warn("Failed to download image: {$url}");
        }
    }
}
