<?php

namespace Database\Seeders;

use App\Models\User;
use App\Models\Brand;
use App\Models\Category;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\Coupon;
use App\Models\ShippingMethod;
use App\Models\Setting;
use App\Models\Page;
use App\Models\PageSection;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class DemoDataSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // 1. Seed Default and Alias Users
        $usersToSeed = [
            // Admin users with password123
            ['email' => 'admin@sawdabazar.com', 'name' => 'Sawdabazar Admin', 'password' => 'password123', 'role' => 'admin'],
            ['email' => 'admin@sawdabazar.test', 'name' => 'Sawdabazar Admin Test', 'password' => 'password123', 'role' => 'admin'],
            ['email' => 'admin@example.com', 'name' => 'Sawdabazar Admin Example', 'password' => 'password123', 'role' => 'admin'],
            
            // Admin users with password
            ['email' => 'admin2@sawdabazar.com', 'name' => 'Sawdabazar Admin 2', 'password' => 'password', 'role' => 'admin'],
            ['email' => 'admin2@sawdabazar.test', 'name' => 'Sawdabazar Admin 2 Test', 'password' => 'password', 'role' => 'admin'],
            ['email' => 'admin2@example.com', 'name' => 'Sawdabazar Admin 2 Example', 'password' => 'password', 'role' => 'admin'],
            
            // Customer users with password123
            ['email' => 'customer@sawdabazar.com', 'name' => 'Sawdabazar Customer', 'password' => 'password123', 'role' => 'customer'],
            ['email' => 'customer@sawdabazar.test', 'name' => 'Sawdabazar Customer Test', 'password' => 'password123', 'role' => 'customer'],
            ['email' => 'customer@example.com', 'name' => 'John Doe', 'password' => 'password123', 'role' => 'customer'],
            
            // Customer users with password
            ['email' => 'customer2@sawdabazar.com', 'name' => 'Sawdabazar Customer 2', 'password' => 'password', 'role' => 'customer'],
            ['email' => 'customer2@sawdabazar.test', 'name' => 'Sawdabazar Customer 2 Test', 'password' => 'password', 'role' => 'customer'],
            ['email' => 'customer2@example.com', 'name' => 'John Doe 2', 'password' => 'password', 'role' => 'customer'],
        ];

        foreach ($usersToSeed as $u) {
            User::updateOrCreate(
                ['email' => $u['email']],
                [
                    'name' => $u['name'],
                    'password' => Hash::make($u['password']),
                    'role' => $u['role'],
                ]
            );
        }

        // 2. Seed 2 Brands
        $brands = [
            ['name' => 'Xiaomi', 'slug' => 'xiaomi', 'description' => 'Global technology leader', 'is_visible' => true],
            ['name' => 'Apex', 'slug' => 'apex', 'description' => 'Premium footwear brand in Bangladesh', 'is_visible' => true],
        ];

        $brandModels = [];
        foreach ($brands as $b) {
            $brandModels[$b['slug']] = Brand::updateOrCreate(['slug' => $b['slug']], $b);
        }

        // 3. Seed Grocery/Natural Food Categories
        $categories = [
            ['name' => 'Honey', 'slug' => 'honey', 'description' => '১০০% প্রাকৃতিক ও বিশুদ্ধ সরাসরি মৌয়ালদের থেকে সংগৃহীত মধু', 'is_visible' => true, 'parent_id' => null],
            ['name' => 'Dates', 'slug' => 'dates', 'description' => 'সরাসরি আমদানিকৃত প্রিমিয়াম মানের খেজুর', 'is_visible' => true, 'parent_id' => null],
            ['name' => 'Spices', 'slug' => 'spices', 'description' => 'কেমিক্যালমুক্ত খাঁটি ও সুগন্ধি গুড়ো মসলা', 'is_visible' => true, 'parent_id' => null],
            ['name' => 'Nuts & Seeds', 'slug' => 'nuts-seeds', 'description' => 'পুষ্টিকর ও সুস্বাদু বিভিন্ন রকমের বাদাম ও বীজ', 'is_visible' => true, 'parent_id' => null],
            ['name' => 'Beverage', 'slug' => 'beverage', 'description' => 'প্রাকৃতিক ও সুস্বাদু বিভিন্ন পানীয় এবং চা', 'is_visible' => true, 'parent_id' => null],
            ['name' => 'Rice', 'slug' => 'rice', 'description' => 'প্রাকৃতিক উপায়ে চাষকৃত প্রিমিয়াম কোয়ালিটি চাল', 'is_visible' => true, 'parent_id' => null],
            ['name' => 'Flours & Lentils', 'slug' => 'flours-lentils', 'description' => 'উচ্চমানের আটা, ময়দা ও দেশি-বিদেশি ডাল', 'is_visible' => true, 'parent_id' => null],
            ['name' => 'Functional Food', 'slug' => 'functional-food', 'description' => 'বিশেষ পুষ্টিগুণ সম্পন্ন অর্গানিক ও ফাংশনাল ফুড', 'is_visible' => true, 'parent_id' => null],
            ['name' => 'Ghee', 'slug' => 'ghee', 'description' => 'হাতে তৈরি প্রিমিয়াম সুগন্ধি গাওয়া ঘি', 'is_visible' => true, 'parent_id' => null],
            ['name' => 'Mustard Oil', 'slug' => 'oil', 'description' => 'কাঠের ঘানিতে ভাঙা খাঁটি সরিষার তেল', 'is_visible' => true, 'parent_id' => null],
        ];

        $categoryModels = [];
        foreach ($categories as $cat) {
            $categoryModels[$cat['slug']] = Category::updateOrCreate(['slug' => $cat['slug']], $cat);
        }

        // 4. Seed 10 Food Products with variants
        $products = [
            [
                'category_id' => $categoryModels['dates']->id,
                'brand_id' => null,
                'name' => 'Premium Mariom Dates (খেজুর)',
                'slug' => 'premium-mariom-dates',
                'description' => 'সরাসরি আমদানিকৃত প্রিমিয়াম মানের মারিয়ম খেজুর। অত্যন্ত সুস্বাদু এবং পুষ্টিগুণে ভরপুর।',
                'short_description' => 'সরাসরি আমদানিকৃত প্রিমিয়াম মারিয়ম খেজুর।',
                'sku' => 'DAT-MRM-001',
                'price' => 950.00,
                'sale_price' => 850.00,
                'quantity' => 100,
                'is_visible' => true,
                'is_featured' => true,
                'variants' => []
            ],
            [
                'category_id' => $categoryModels['honey']->id,
                'brand_id' => null,
                'name' => 'Sundarban Natural Honey (মধু)',
                'slug' => 'sundarban-natural-honey',
                'description' => 'সুন্দরবনের ১০০% প্রাকৃতিক ও বিশুদ্ধ মধু, সরাসরি মৌয়ালদের থেকে সংগৃহীত। কোনো ভেজাল বা কৃত্রিম ফ্লেভার নেই।',
                'short_description' => 'সুন্দরবনের খাঁটি প্রাকৃতিক মধু।',
                'sku' => 'HON-SND-002',
                'price' => 650.00,
                'sale_price' => 600.00,
                'quantity' => 150,
                'is_visible' => true,
                'is_featured' => true,
                'variants' => []
            ],
            [
                'category_id' => $categoryModels['ghee']->id,
                'brand_id' => null,
                'name' => 'Premium Handmade Ghee (ঘি)',
                'slug' => 'premium-handmade-ghee',
                'description' => 'হাতে তৈরি খাঁটি প্রিমিয়াম গাওয়া ঘি। অতুলনীয় সুগন্ধি ও পুষ্টিগুণে ভরপুর ঐতিহ্যবাহী ঘি।',
                'short_description' => 'হাতে তৈরি খাঁটি প্রিমিয়াম গাওয়া ঘি।',
                'sku' => 'GHE-PRM-003',
                'price' => 1600.00,
                'sale_price' => 1500.00,
                'quantity' => 80,
                'is_visible' => true,
                'is_featured' => true,
                'variants' => []
            ],
            [
                'category_id' => $categoryModels['oil']->id,
                'brand_id' => null,
                'name' => 'Wood Pressed Mustard Oil (সরিষার তেল)',
                'slug' => 'wood-pressed-mustard-oil',
                'description' => 'কাঠের ঘানিতে ভাঙা ১০০% খাঁটি সরিষার তেল। ঝাঁঝালো সুবাস ও খাঁটি পুষ্টির নিশ্চয়তা।',
                'short_description' => 'ঘানি ভাঙা খাঁটি সরিষার তেল।',
                'sku' => 'OIL-MST-004',
                'price' => 380.00,
                'sale_price' => null,
                'quantity' => 120,
                'is_visible' => true,
                'is_featured' => true,
                'variants' => []
            ],
            [
                'category_id' => $categoryModels['spices']->id,
                'brand_id' => null,
                'name' => 'Organic Turmeric Powder (হলুদ গুঁড়ো)',
                'slug' => 'organic-turmeric-powder',
                'description' => 'সম্পূর্ণ ভেজালমুক্ত ও কেমিক্যালমুক্ত খাঁটি হলুদ গুঁড়ো। সরাসরি কুষ্টিয়া থেকে সংগৃহীত।',
                'short_description' => 'ভেজালমুক্ত খাঁটি হলুদ গুঁড়ো।',
                'sku' => 'SPC-TUR-005',
                'price' => 180.00,
                'sale_price' => null,
                'quantity' => 200,
                'is_visible' => true,
                'is_featured' => false,
                'variants' => []
            ],
            [
                'category_id' => $categoryModels['nuts-seeds']->id,
                'brand_id' => null,
                'name' => 'Premium Cashew Nuts (কাজু বাদাম)',
                'slug' => 'premium-cashew-nuts',
                'description' => 'উচ্চমানের বড় সাইজের কাঁচা কাজুবাদাম। স্বাস্থ্যকর ফ্যাট ও ফাইবার সমৃদ্ধ।',
                'short_description' => 'প্রিমিয়াম কোয়ালিটি কাজু বাদাম।',
                'sku' => 'NUT-CSW-006',
                'price' => 750.00,
                'sale_price' => 700.00,
                'quantity' => 60,
                'is_visible' => true,
                'is_featured' => true,
                'variants' => []
            ],
            [
                'category_id' => $categoryModels['beverage']->id,
                'brand_id' => null,
                'name' => 'Organic Green Tea (গ্রিন টি)',
                'slug' => 'organic-green-tea',
                'description' => 'সিলেটের চা বাগান থেকে সরাসরি উৎপাদিত ১০০% অর্গানিক গ্রিন টি। অ্যান্টি-অক্সিডেন্ট সমৃদ্ধ।',
                'short_description' => '১০০% অর্গানিক প্রিমিয়াম গ্রিন টি।',
                'sku' => 'BEV-TEA-007',
                'price' => 250.00,
                'sale_price' => 220.00,
                'quantity' => 90,
                'is_visible' => true,
                'is_featured' => false,
                'variants' => []
            ],
            [
                'category_id' => $categoryModels['rice']->id,
                'brand_id' => null,
                'name' => 'Premium Miniket Rice (মিনিকেট চাল)',
                'slug' => 'premium-miniket-rice',
                'description' => 'ঝরঝরে এবং সুস্বাদু প্রিমিয়াম কোয়ালিটি মিনিকেট চাল। কেমিক্যাল ও ইউরিয়ামুক্ত পলিশ।',
                'short_description' => 'ঝরঝরে সুস্বাদু মিনিকেট চাল।',
                'sku' => 'RCE-MNK-008',
                'price' => 375.00,
                'sale_price' => null,
                'quantity' => 100,
                'is_visible' => true,
                'is_featured' => false,
                'variants' => []
            ],
            [
                'category_id' => $categoryModels['flours-lentils']->id,
                'brand_id' => null,
                'name' => 'Deshi Masoor Dal (দেশি মসুর ডাল)',
                'slug' => 'deshi-masoor-dal',
                'description' => 'খাঁটি দেশি ছোট দানার মসুর ডাল। অতি দ্রুত সিদ্ধ হয় এবং স্বাদে অনন্য।',
                'short_description' => 'ছোট দানার খাঁটি দেশি মসুর ডাল।',
                'sku' => 'FLR-MSD-009',
                'price' => 150.00,
                'sale_price' => 140.00,
                'quantity' => 300,
                'is_visible' => true,
                'is_featured' => false,
                'variants' => []
            ],
            [
                'category_id' => $categoryModels['functional-food']->id,
                'brand_id' => null,
                'name' => 'Cold Pressed Black Seed Oil (কালোজিরা তেল)',
                'slug' => 'cold-pressed-black-seed-oil',
                'description' => 'কালোজিরা থেকে বিশেষ কোল্ড-প্রেস প্রযুক্তিতে তৈরি ১০০% খাঁটি তেল, যা সর্বরোগের মহৌষধ হিসেবে খ্যাত।',
                'short_description' => '১০০% খাঁটি কোল্ড-প্রেসড কালোজিরা তেল।',
                'sku' => 'FND-BKS-010',
                'price' => 320.00,
                'sale_price' => 290.00,
                'quantity' => 50,
                'is_visible' => true,
                'is_featured' => true,
                'variants' => []
            ]
        ];

        foreach ($products as $prod) {
            $variants = $prod['variants'] ?? [];
            unset($prod['variants']);

            $product = Product::updateOrCreate(['slug' => $prod['slug']], $prod);

            foreach ($variants as $v) {
                ProductVariant::updateOrCreate(['sku' => $v['sku']], [
                    'product_id' => $product->id,
                    'price' => $v['price'],
                    'quantity' => $v['quantity'],
                    'options' => $v['options'],
                ]);
            }
        }

        // 5. Seed 3 Coupons
        $coupons = [
            [
                'code' => 'SAVE100',
                'type' => 'fixed',
                'value' => 100.00,
                'min_amount' => 1000.00,
                'starts_at' => now(),
                'expires_at' => now()->addMonths(6),
                'is_active' => true,
            ],
            [
                'code' => 'EID20',
                'type' => 'percentage',
                'value' => 20.00,
                'min_amount' => 500.00,
                'starts_at' => now(),
                'expires_at' => now()->addMonths(6),
                'is_active' => true,
            ],
            [
                'code' => 'FREE50',
                'type' => 'fixed',
                'value' => 50.00,
                'min_amount' => 0.00,
                'starts_at' => now(),
                'expires_at' => now()->subDays(5), // Expired coupon
                'is_active' => true,
            ]
        ];

        foreach ($coupons as $coup) {
            Coupon::updateOrCreate(['code' => $coup['code']], $coup);
        }

        // 6. Seed 2 Shipping Methods
        $shippingMethods = [
            [
                'name' => 'Inside Dhaka',
                'cost' => 80.00,
                'zone' => 'inside_dhaka',
                'is_active' => true,
            ],
            [
                'name' => 'Outside Dhaka',
                'cost' => 120.00,
                'zone' => 'outside_dhaka',
                'is_active' => true,
            ]
        ];

        foreach ($shippingMethods as $sm) {
            ShippingMethod::updateOrCreate(['name' => $sm['name']], $sm);
        }

        // 7. Seed Settings Defaults
        $settings = [
            // General Group
            ['key' => 'site_name', 'value' => 'Sawdabazar', 'group' => 'general'],
            ['key' => 'store_email', 'value' => 'info@sawdabazar.com', 'group' => 'general'],
            ['key' => 'store_phone', 'value' => '+8801700000000', 'group' => 'general'],
            ['key' => 'store_address', 'value' => "House 12, Road 5, Sector 3\nUttara, Dhaka - 1230\nBangladesh", 'group' => 'general'],
            ['key' => 'logo', 'value' => null, 'group' => 'general'],
            ['key' => 'favicon', 'value' => null, 'group' => 'general'],
            ['key' => 'facebook_url', 'value' => 'https://facebook.com/sawdabazar', 'group' => 'general'],
            ['key' => 'instagram_url', 'value' => 'https://instagram.com/sawdabazar', 'group' => 'general'],
            ['key' => 'whatsapp_number', 'value' => '+8801700000000', 'group' => 'general'],

            // SMS Gateway Config Group
            ['key' => 'sms_gateway', 'value' => 'bulksmsbd', 'group' => 'sms'],
            ['key' => 'bulksmsbd_username', 'value' => 'demo_user', 'group' => 'sms'],
            ['key' => 'bulksmsbd_password', 'value' => 'demo_pass', 'group' => 'sms'],
            ['key' => 'bulksmsbd_senderid', 'value' => '8801844000000', 'group' => 'sms'],
            ['key' => 'greenweb_token', 'value' => 'demo_greenweb_token', 'group' => 'sms'],
            ['key' => 'greenweb_senderid', 'value' => 'Sawdabazar', 'group' => 'sms'],
            ['key' => 'sslwireless_token', 'value' => 'demo_ssl_token', 'group' => 'sms'],
            ['key' => 'sslwireless_sid', 'value' => 'Sawdabazar_SID', 'group' => 'sms'],

            // Dynamic Courier Credentials Group
            ['key' => 'steadfast_api_key', 'value' => 'demo_steadfast_key', 'group' => 'courier'],
            ['key' => 'steadfast_secret_key', 'value' => 'demo_steadfast_secret', 'group' => 'courier'],
            ['key' => 'pathao_client_id', 'value' => 'demo_pathao_id', 'group' => 'courier'],
            ['key' => 'pathao_client_secret', 'value' => 'demo_pathao_secret', 'group' => 'courier'],
            ['key' => 'pathao_username', 'value' => 'demo_pathao_user', 'group' => 'courier'],
            ['key' => 'pathao_password', 'value' => 'demo_pathao_pass', 'group' => 'courier'],
            ['key' => 'pathao_store_id', 'value' => 'demo_pathao_store', 'group' => 'courier'],

            // Dynamic SMTP Credentials Group
            ['key' => 'smtp_host', 'value' => 'sandbox.smtp.mailtrap.io', 'group' => 'email'],
            ['key' => 'smtp_port', 'value' => '2525', 'group' => 'email'],
            ['key' => 'smtp_username', 'value' => 'demo_username', 'group' => 'email'],
            ['key' => 'smtp_password', 'value' => 'demo_password', 'group' => 'email'],
            ['key' => 'smtp_encryption', 'value' => 'tls', 'group' => 'email'],
            ['key' => 'smtp_from_address', 'value' => 'noreply@sawdabazar.com', 'group' => 'email'],
            ['key' => 'smtp_from_name', 'value' => 'Sawdabazar', 'group' => 'email'],

            // Header & Footer Scripts Group
            ['key' => 'header_scripts', 'value' => '', 'group' => 'scripts'],
            ['key' => 'footer_scripts', 'value' => '', 'group' => 'scripts'],
            ['key' => 'meta_pixel_id', 'value' => 'demo_pixel_id', 'group' => 'scripts'],
            ['key' => 'gtm_container_id', 'value' => 'GTM-DEMO', 'group' => 'scripts'],
        ];

        foreach ($settings as $set) {
            Setting::updateOrCreate(['key' => $set['key']], [
                'value' => $set['value'],
                'group' => $set['group'],
            ]);
        }

        // 8. Seed Home Page & Builder Blocks
        $homePage = Page::updateOrCreate(
            ['slug' => 'home'],
            [
                'title' => 'Welcome to Sawdabazar',
                'meta_title' => 'Sawdabazar - High Quality E-Commerce Store',
                'meta_description' => 'Browse our catalog of premium products, fast shipping and easy online payments.',
                'is_active' => true,
            ]
        );

        // Seed home page sections
        $categoryIds = [
            $categoryModels['honey']->id,
            $categoryModels['dates']->id,
            $categoryModels['spices']->id,
            $categoryModels['nuts-seeds']->id,
        ];

        $sections = [
            [
                'block_type' => 'hero',
                'sort_order' => 1,
                'content' => [
                    'slides' => [
                        [
                            'title' => 'প্রতিটি ফোঁটা খাঁটি, স্বাস্থ্যকর খেজুর',
                            'subtitle' => 'সরাসরি আমদানিকৃত প্রিমিয়াম মানের খেজুরের সংগ্রহ',
                            'button_text' => 'অর্ডার করুন',
                            'button_url' => '/shop?categorySlug=dates',
                            'image_path' => 'page-builder/hero-demo.jpg',
                        ]
                    ]
                ]
            ],
            [
                'block_type' => 'category_grid',
                'sort_order' => 2,
                'content' => [
                    'title' => 'Featured Categories',
                    'category_ids' => $categoryIds,
                ]
            ],
            [
                'block_type' => 'product_collection',
                'sort_order' => 3,
                'content' => [
                    'title' => 'Featured Collection',
                    'collection_type' => 'featured',
                    'limit' => 4,
                ]
            ],
            [
                'block_type' => 'faq',
                'sort_order' => 4,
                'content' => [
                    'title' => 'Frequently Asked Questions',
                    'faqs' => [
                        ['question' => 'How long does delivery take?', 'answer' => 'Inside Dhaka within 24-48 hours. Outside Dhaka takes 3-5 working days.'],
                        ['question' => 'What payment methods do you support?', 'answer' => 'We accept Cash on Delivery (COD), bKash checkout, and major local debit/credit cards.'],
                    ]
                ]
            ]
        ];


        // Delete existing home page sections first
        PageSection::where('page_id', $homePage->id)->delete();

        foreach ($sections as $sec) {
            PageSection::create([
                'page_id' => $homePage->id,
                'block_type' => $sec['block_type'],
                'content' => $sec['content'],
                'sort_order' => $sec['sort_order'],
            ]);
        }
    }
}
