<?php

namespace Database\Seeders;

use App\Models\User;
use App\Models\Category;
use App\Models\Product;
use App\Models\Coupon;
use App\Models\BlogPost;
use App\Models\Testimonial;
use App\Models\Order;
use App\Models\OrderItem;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        // 1. Admin User
        $admin = User::updateOrCreate(
            ['email' => 'admin@divne.com'],
            [
                'name' => 'Divne Admin',
                'password' => Hash::make('password123'),
                'is_admin' => true,
                'phone' => '+91 98765 43210',
                'address' => '12 Luxury Wellness Way',
                'city' => 'Bengaluru',
                'state' => 'Karnataka',
                'pincode' => '560001',
            ]
        );

        // 2. Customer User
        $customer = User::updateOrCreate(
            ['email' => 'user@divne.com'],
            [
                'name' => 'Ananya Sharma',
                'password' => Hash::make('password123'),
                'is_admin' => false,
                'phone' => '+91 98123 45678',
                'address' => '45 Green Park, Jubilee Hills',
                'city' => 'Hyderabad',
                'state' => 'Telangana',
                'pincode' => '500033',
            ]
        );

        // 3. Categories (Using real Divine Drops Collections)
        $categoriesData = [
            ['name' => 'Face Cleansers', 'slug' => 'face-wash', 'image' => 'divine-assets/Our Collections/Cleanser.png', 'description' => 'Gentle botanical face washes & dewy cleansers.'],
            ['name' => 'Moisturisers', 'slug' => 'moisturisers', 'image' => 'divine-assets/Our Collections/Moisturizer.png', 'description' => 'Saffron & Goat Milk deep hydration formulations.'],
            ['name' => 'Lip Care', 'slug' => 'lip-care', 'image' => 'divine-assets/Our Collections/Lip Balm.png', 'description' => 'Ultra-nourishing lip balms, masks & sugar scrubs.'],
            ['name' => 'Shampoos', 'slug' => 'shampoos', 'image' => 'divine-assets/Our Collections/Shampoos.png', 'description' => 'Cold-pressed herbal shampoos for hairfall control.'],
            ['name' => 'Toners & Mists', 'slug' => 'toners', 'image' => 'divine-assets/Our Collections/Toner.png', 'description' => 'Refreshing botanical face mists and skin toners.'],
            ['name' => 'Luxury Perfumes', 'slug' => 'perfumes', 'image' => 'divine-assets/Our Collections/Perfume.png', 'description' => 'Artisanal haute perfumes inspired by iconic scents.'],
        ];

        $categoryMap = [];
        foreach ($categoriesData as $cat) {
            $created = Category::updateOrCreate(
                ['slug' => $cat['slug']],
                [
                    'name' => $cat['name'],
                    'image' => $cat['image'],
                    'description' => $cat['description'],
                    'is_active' => true,
                ]
            );
            $categoryMap[$cat['slug']] = $created->id;
        }

        // 4. Products (Using real Divine Drops Bestsellers with display & hover images)
        $productsData = [
            [
                'name' => 'Saffron Face Moisturizer',
                'slug' => 'saffron-face-moisturizer',
                'tag' => '24hr Saffron Glow & Deep Moisturization',
                'category_slug' => 'moisturisers',
                'price' => 495,
                'compare_at' => 595,
                'rating' => 4.9,
                'reviews_count' => 1420,
                'badge' => 'Best Seller',
                'image' => 'divine-assets/BEST SELLERS/Saffron Face Moisturizer/Display Image.png',
                'image_alt' => 'divine-assets/BEST SELLERS/Saffron Face Moisturizer/Hover Image.png',
                'sizes' => ['50 g', '100 g'],
                'description' => 'Enriched with pure Kashmiri Saffron extracts, goat milk, and cold-pressed almond oil. Restores radiant glow, fades dark spots, and provides round-the-clock hydration without grease.',
                'stock' => 85,
                'is_featured' => true,
            ],
            [
                'name' => 'Rosy Facial Cleanser',
                'slug' => 'rosy-facial-cleanser',
                'tag' => 'Soap-Free Damask Rose Dewy Cleanser',
                'category_slug' => 'face-wash',
                'price' => 349,
                'compare_at' => 449,
                'rating' => 4.8,
                'reviews_count' => 1160,
                'badge' => 'Best Seller',
                'image' => 'divine-assets/BEST SELLERS/Rosy Facial Cleanser/Display Image.png',
                'image_alt' => 'divine-assets/BEST SELLERS/Rosy Facial Cleanser/Hover Image.png',
                'sizes' => ['100 ml', '200 ml'],
                'description' => 'Gentle, sulphate-free cleanser infused with real Damask Rose water and oat proteins. Gently purifies pores while locking in natural skin dewiness.',
                'stock' => 110,
                'is_featured' => true,
            ],
            [
                'name' => 'Herbal Hairfall Shampoo',
                'slug' => 'herbal-hairfall-shampoo',
                'tag' => '9 Botanical Cold-Pressed Hairfall Control',
                'category_slug' => 'shampoos',
                'price' => 425,
                'compare_at' => 499,
                'rating' => 4.7,
                'reviews_count' => 980,
                'badge' => 'Most Popular',
                'image' => 'divine-assets/BEST SELLERS/Herbal Shampoo/Display Image.png',
                'image_alt' => 'divine-assets/BEST SELLERS/Herbal Shampoo/Hover Image.png',
                'sizes' => ['200 ml', '400 ml'],
                'description' => 'Powered by Amla, Bhringraj, Hibiscus, and cold-pressed Neem oils. Strengthens hair roots from week 2 and reduces breakages visibly.',
                'stock' => 60,
                'is_featured' => true,
            ],
            [
                'name' => 'Luxury Lip Mask',
                'slug' => 'luxury-lip-mask',
                'tag' => 'Overnight Repair Lip Butter Mask',
                'category_slug' => 'lip-care',
                'price' => 295,
                'compare_at' => 349,
                'rating' => 4.9,
                'reviews_count' => 860,
                'badge' => 'Trending',
                'image' => 'divine-assets/BEST SELLERS/Lip Mask/Display Image.png',
                'image_alt' => 'divine-assets/BEST SELLERS/Lip Mask/Hover Image.png',
                'sizes' => ['15 g'],
                'description' => 'Rich leave-on lip mask packed with Shea Butter, Berry extracts, and Hyaluronic Acid. Heals cracked, dry lips overnight for velvety soft lips.',
                'stock' => 45,
                'is_featured' => true,
            ],
            [
                'name' => 'Nourishing Lip Balm',
                'slug' => 'nourishing-lip-balm',
                'tag' => 'Nourishing Beetroot & Honey Lip Tint',
                'category_slug' => 'lip-care',
                'price' => 245,
                'compare_at' => 299,
                'rating' => 4.8,
                'reviews_count' => 740,
                'badge' => 'Daily Essential',
                'image' => 'divine-assets/BEST SELLERS/Lip Balm/Display Image.png',
                'image_alt' => 'divine-assets/BEST SELLERS/Lip Balm/Hover Image.png',
                'sizes' => ['10 g'],
                'description' => 'Natural lip tint formulated with organic beeswax, cold-pressed coconut oil, and natural beet pigment.',
                'stock' => 90,
                'is_featured' => true,
            ],
            [
                'name' => 'Gentle Sugar Scrub',
                'slug' => 'gentle-sugar-scrub',
                'tag' => 'Brown Sugar & Raw Honey Exfoliating Scrub',
                'category_slug' => 'moisturisers',
                'price' => 395,
                'compare_at' => 450,
                'rating' => 4.7,
                'reviews_count' => 520,
                'badge' => 'New Launch',
                'image' => 'divine-assets/BEST SELLERS/Sugar Scrub/Display Image.png',
                'image_alt' => 'divine-assets/BEST SELLERS/Sugar Scrub/Hover Image.png',
                'sizes' => ['100 g'],
                'description' => 'Fine brown sugar crystals infused with raw wild honey and jojoba oil to gently buff away dead skin cells for baby-soft texture.',
                'stock' => 35,
                'is_featured' => true,
            ],
            [
                'name' => 'Artisanal Perfume — Dior Inspired',
                'slug' => 'dior-inspired-perfume',
                'tag' => 'Luxury Artisanal Eau De Parfum (Dior Edition)',
                'category_slug' => 'perfumes',
                'price' => 895,
                'compare_at' => 1199,
                'rating' => 4.9,
                'reviews_count' => 1540,
                'badge' => 'Luxury Edition',
                'image' => 'divine-assets/BEST SELLERS/Our Version of Dior/Display Image.png',
                'image_alt' => 'divine-assets/BEST SELLERS/Our Version of Dior/Hover Image.png',
                'sizes' => ['50 ml', '100 ml'],
                'description' => 'A captivating blend of French Jasmine, White Musk, and Citrus notes. Long-lasting 18-hour Eau de Parfum crafted for timeless elegance.',
                'stock' => 25,
                'is_featured' => true,
            ],
            [
                'name' => 'Berry Sugar Lip Scrub',
                'slug' => 'berry-sugar-lip-scrub',
                'tag' => 'Gentle Buffing Sugar & Berry Lip Scrub',
                'category_slug' => 'lip-care',
                'price' => 225,
                'compare_at' => 275,
                'rating' => 4.8,
                'reviews_count' => 610,
                'badge' => null,
                'image' => 'divine-assets/BEST SELLERS/Lip Scrub/Display Image.png',
                'image_alt' => 'divine-assets/BEST SELLERS/Lip Scrub/Hover Image.png',
                'sizes' => ['15 g'],
                'description' => 'Exfoliates dead skin from lips and reveals natural pink softness. Flavored with wild strawberry and cane sugar.',
                'stock' => 70,
                'is_featured' => false,
            ],
        ];

        $createdProducts = [];
        foreach ($productsData as $prod) {
            $catId = $categoryMap[$prod['category_slug']] ?? null;

            $metaTitle = $prod['name'] . ' — Buy Online | Divine Drops Luxury Skincare';
            $metaDesc = $prod['description'] . ' 100% natural, farm-fresh Indian botanicals with free delivery across India.';
            $metaKeywords = implode(', ', explode(' ', strtolower($prod['name']))) . ', natural skincare, divine drops, organic beauty';

            $p = Product::updateOrCreate(
                ['slug' => $prod['slug']],
                [
                    'category_id' => $catId,
                    'name' => $prod['name'],
                    'tag' => $prod['tag'],
                    'price' => $prod['price'],
                    'compare_at' => $prod['compare_at'],
                    'rating' => $prod['rating'],
                    'reviews_count' => $prod['reviews_count'],
                    'badge' => $prod['badge'],
                    'image' => $prod['image'],
                    'image_alt' => $prod['image_alt'],
                    'gallery' => [$prod['image'], $prod['image_alt']],
                    'sizes' => $prod['sizes'],
                    'description' => $prod['description'],
                    'meta_title' => $metaTitle,
                    'meta_description' => $metaDesc,
                    'meta_keywords' => $metaKeywords,
                    'og_title' => $prod['name'] . ' — Divine Drops',
                    'og_description' => $metaDesc,
                    'stock' => $prod['stock'],
                    'is_featured' => $prod['is_featured'],
                    'is_active' => true,
                ]
            );

            // Seed Product Variants
            if (!empty($prod['sizes'])) {
                foreach ($prod['sizes'] as $idx => $sizeName) {
                    $multiplier = 1 + ($idx * 0.7);
                    $varPrice = round($prod['price'] * $multiplier);
                    $varCompare = $prod['compare_at'] ? round($prod['compare_at'] * $multiplier) : null;
                    
                    \App\Models\ProductVariant::updateOrCreate(
                        [
                            'product_id' => $p->id,
                            'name' => $sizeName,
                        ],
                        [
                            'sku' => strtoupper(substr(Str::slug($p->name), 0, 4)) . '-' . Str::slug($sizeName),
                            'price' => $varPrice,
                            'compare_at' => $varCompare,
                            'stock' => max(10, $prod['stock'] - ($idx * 15)),
                            'is_default' => ($idx === 0),
                        ]
                    );
                }
            }

            $createdProducts[] = $p;
        }

        // 5. Advanced Coupons
        Coupon::updateOrCreate(
            ['code' => 'WELCOME15'],
            [
                'type' => 'percent',
                'value' => 15,
                'max_discount_amount' => 300,
                'min_order_amount' => 499,
                'usage_limit' => 100,
                'usage_count' => 12,
                'is_active' => true,
                'expires_at' => now()->addMonths(3),
            ]
        );

        Coupon::updateOrCreate(
            ['code' => 'DIVINE200'],
            [
                'type' => 'fixed',
                'value' => 200,
                'min_order_amount' => 799,
                'usage_limit' => 50,
                'usage_count' => 8,
                'is_active' => true,
                'expires_at' => now()->addMonths(3),
            ]
        );

        Coupon::updateOrCreate(
            ['code' => 'GLOW20'],
            [
                'type' => 'percent',
                'value' => 20,
                'max_discount_amount' => 500,
                'min_order_amount' => 999,
                'usage_limit' => 200,
                'usage_count' => 35,
                'is_active' => true,
                'expires_at' => now()->addMonths(6),
            ]
        );

        // 6. Blog Posts
        $postsConfig = config('shop.posts', []);
        foreach ($postsConfig as $post) {
            BlogPost::updateOrCreate(
                ['slug' => $post['slug']],
                [
                    'title' => $post['title'],
                    'excerpt' => $post['excerpt'],
                    'content' => "<p>" . $post['excerpt'] . "</p><p>Natural ingredients like Kashmiri Saffron, Goat Milk, and Amla have been celebrated for generations. At Divine Drops, we bottle these pure botanical treasures without synthetic fillers or harmful chemicals.</p>",
                    'category' => $post['category'] ?? 'Botanical Secrets',
                    'read_time' => $post['read'] ?? '5 min read',
                    'image' => 'divine-assets/SHOP BY KEY INGREDIENTS/Saffron.png',
                    'is_published' => true,
                ]
            );
        }

        // 7. Testimonials (Using Real People Real Stories photos)
        $testimonialsData = [
            [
                'name' => 'Ananya R.',
                'location' => 'Bengaluru',
                'rating' => 5,
                'text' => 'The Saffron Moisturizer is hands down the best cream I have ever used. My skin looks visibly brighter and super dewy without feeling heavy!',
            ],
            [
                'name' => 'Priyanka M.',
                'location' => 'Hyderabad',
                'rating' => 5,
                'text' => 'Herbal Shampoo dramatically reduced my hairfall within 3 weeks. Loving the natural botanical scent and shine!',
            ],
            [
                'name' => 'Divya S.',
                'location' => 'Chennai',
                'rating' => 5,
                'text' => 'The Rosy Facial Cleanser feels so luxurious and gentle. Doesn’t strip my skin barrier at all. Highly recommend!',
            ],
        ];

        foreach ($testimonialsData as $t) {
            Testimonial::updateOrCreate(
                ['name' => $t['name']],
                [
                    'location' => $t['location'],
                    'rating' => $t['rating'],
                    'text' => $t['text'],
                    'is_approved' => true,
                ]
            );
        }

        // 8. Sample Orders for Admin Analytics
        if (!empty($createdProducts)) {
            $statuses = ['delivered', 'shipped', 'processing', 'pending'];
            for ($i = 1; $i <= 5; $i++) {
                $status = $statuses[($i - 1) % count($statuses)];
                $prod1 = $createdProducts[array_rand($createdProducts)];
                $prod2 = $createdProducts[array_rand($createdProducts)];

                $item1Sub = $prod1->price * 1;
                $item2Sub = $prod2->price * 2;
                $total = $item1Sub + $item2Sub;

                $order = Order::create([
                    'order_number' => 'DIV-' . rand(10000, 99999),
                    'user_id' => $customer->id,
                    'customer_name' => $customer->name,
                    'customer_email' => $customer->email,
                    'customer_phone' => $customer->phone,
                    'shipping_address' => $customer->address,
                    'city' => $customer->city,
                    'state' => $customer->state,
                    'pincode' => $customer->pincode,
                    'total_amount' => $total,
                    'discount_amount' => 0,
                    'payment_method' => 'cod',
                    'payment_status' => $status === 'delivered' ? 'paid' : 'pending',
                    'order_status' => $status,
                    'created_at' => now()->subDays(rand(1, 15)),
                ]);

                OrderItem::create([
                    'order_id' => $order->id,
                    'product_id' => $prod1->id,
                    'product_name' => $prod1->name,
                    'price' => $prod1->price,
                    'quantity' => 1,
                    'size' => $prod1->sizes[0] ?? 'Standard',
                    'subtotal' => $item1Sub,
                ]);

                OrderItem::create([
                    'order_id' => $order->id,
                    'product_id' => $prod2->id,
                    'product_name' => $prod2->name,
                    'price' => $prod2->price,
                    'quantity' => 2,
                    'size' => $prod2->sizes[0] ?? 'Standard',
                    'subtotal' => $item2Sub,
                ]);
            }
        }
    }
}
