<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use App\Models\User;
use App\Models\Seller;
use App\Models\Buyer;
use App\Models\Product;
use App\Models\Category;
use App\Models\Plan;
use App\Models\Subscription;
use App\Models\Inquiry;
use App\Models\Unit;
use Spatie\Permission\Models\Role;

class CustomCleanupSeeder extends Seeder
{
    public function run()
    {
        // 1. CLEAR DATA
        $this->command->info('Cleaning up database...');
        
        if (DB::getDriverName() === 'sqlite') {
            DB::statement('PRAGMA foreign_keys = OFF;');
        } else {
            DB::statement('SET FOREIGN_KEY_CHECKS=0;');
        }
        
        // Truncate tables
        $tables = [
            'inquiries', 'product_promotions', 'products', 'subscriptions', 
            'sellers', 'buyers', 'users', 'model_has_roles', 'rfqs', 
            'quotes', 'favorites', 'saved_searches', 'banners', 
            'help_faqs', 'reviews', 'transactions', 'kyc_documents'
        ];

        foreach ($tables as $table) {
            if (\Schema::hasTable($table)) {
                DB::table($table)->truncate();
            }
        }
        
        if (DB::getDriverName() === 'sqlite') {
            DB::statement('PRAGMA foreign_keys = ON;');
        } else {
            DB::statement('SET FOREIGN_KEY_CHECKS=1;');
        }
        
        $this->command->info('Database cleaned.');

        // 2. ENSURE ESSENTIALS EXIST (Roles, Plans)
        $this->command->info('Setting up roles and plans...');
        
        $adminRole = Role::firstOrCreate(['name' => 'admin']);
        $sellerRole = Role::firstOrCreate(['name' => 'seller']);
        $buyerRole = Role::firstOrCreate(['name' => 'buyer']);

        // Plans
        $freePlan = Plan::firstOrCreate(
            ['slug' => 'free-plan'],
            [
                'name' => 'Free Plan', 
                'price_inr' => 0, 
                'price_usd' => 0,
                'duration_days' => 365, 
                'product_limit' => 3,
                'product_image_limit' => 3,
                'inquiry_limit' => 10,
                'banner_limit' => 0,
                'custom_page_limit' => 0,
                'show_contact_details' => false,
                'view_buyer_contact' => false,
                'has_verified_badge' => false,
                'allow_microsite' => false,
                'is_active' => true,
                'commission_rate' => 0,
            ]
        );
        
        $paidPlan = Plan::firstOrCreate(
            ['slug' => 'gold-plan'],
            [
                'name' => 'Gold Plan', 
                'price_inr' => 4999, 
                'price_usd' => 60,
                'duration_days' => 365, 
                'product_limit' => 50,
                'product_image_limit' => 10,
                'inquiry_limit' => 100,
                'banner_limit' => 5,
                'custom_page_limit' => 5,
                'show_contact_details' => true,
                'view_buyer_contact' => true,
                'has_verified_badge' => true,
                'allow_microsite' => true,
                'is_active' => true,
                'commission_rate' => 0,
            ]
        );
        
        // Generic Unit
        $unit = Unit::firstOrCreate(['code' => 'PCS'], ['name' => 'Pieces']);

        // 3. CREATE ADMIN
        $this->command->info('Creating Admin...');
        $admin = User::create([
            'name' => 'Super Admin',
            'email' => 'admin@theminiport.com',
            'password' => Hash::make('password'),
            'role' => 'admin',
            'phone' => '1234567890',
            'is_active' => true,
        ]);
        $admin->assignRole($adminRole);

        // --- ADMIN MODULE DATA ---
        $this->seedAdminModules();

        // 4. CREATE PAID SELLER (Verified, Gold Plan)
        $this->command->info('Creating Paid Seller...');
        $paidUser = User::create([
            'name' => 'Paid Seller',
            'email' => 'paid@seller.com',
            'password' => Hash::make('password'),
            'role' => 'seller',
            'phone' => '9876543210',
            'is_active' => true,
        ]);
        $paidUser->assignRole($sellerRole);

        $paidSeller = Seller::create([
            'user_id' => $paidUser->id,
            'company_name' => 'Premium Global Exports',
            'slug' => 'premium-global',
            'mobile' => '9876543210',
            'city' => 'Mumbai', 
            'is_verified' => true,
            'category_id' => Category::first()->id ?? 1,
            'about' => 'We are a premium export company dealing in high-quality furniture and home decor. Established in 2010.',
            'logo' => 'sellers/logos/default_logo.png', // Simulated
        ]);

        Subscription::create([
            'seller_id' => $paidSeller->id,
            'plan_id' => $paidPlan->id,
            'start_date' => now(),
            'end_date' => now()->addYear(),
            'status' => 'active',
        ]);

        // Paid Seller Transactions
        // \App\Models\Transaction::create([
        //     'user_id' => $paidUser->id,
        //     'seller_id' => $paidSeller->id,
        //     'transaction_type' => 'subscription',
        //     'amount' => 4999,
        //     'total_amount' => 4999,
        //     'currency' => 'INR',
        //     'status' => 'success',
        //     'payment_method' => 'online',
        //     'transaction_id' => 'TXN_' . Str::random(10),
        //     'reference_id' => 1, // Dummy reference
        //     'payment_started_at' => now()->subMonths(1),
        //     'payment_completed_at' => now()->subMonths(1),
        //     'created_at' => now()->subMonths(1),
        // ]);

        // Products for Paid Seller (High Quality Dataset)
        $premiumProducts = [
            [
                'name' => 'Ergonomic Mesh Office Chair',
                'category' => 'Furniture',
                'price' => 12500,
                'image' => 'https://images.unsplash.com/photo-1505843490538-5133c6c7d0e1?w=500&q=80',
                'description' => 'High-performance ergonomic chair designed for all-day comfort. Features breathable mesh back, adjustable lumbar support, and synchronized tilt mechanism.',
                'specs' => ['Material' => 'Nylon Mesh', 'Weight Capacity' => '150 kg', 'Warranty' => '3 Years', 'Color' => 'Black']
            ],
            [
                'name' => 'Executive L-Shaped Desk',
                'category' => 'Furniture',
                'price' => 45000,
                'image' => 'https://images.unsplash.com/photo-1518455027359-f3f8164ba6bd?w=500&q=80',
                'description' => 'Premium mahogany finish L-shaped executive desk with integrated cable management and lockable drawers. Perfect for modern offices.',
                'specs' => ['Material' => 'Solid Wood & MDF', 'Dimensions' => '180x160x75 cm', 'Finish' => 'Mahogany', 'Assembly' => 'Required']
            ],
            [
                'name' => 'Industrial Steel Storage Shelf', 
                'category' => 'Furniture',
                'price' => 8900,
                'image' => 'https://images.unsplash.com/photo-1595428774223-ef52624120d2?w=500&q=80',
                'description' => 'Heavy-duty steel shelving unit for warehouses and industrial use. Corrosion-resistant coating and adjustable shelf heights.',
                'specs' => ['Material' => 'Galvanized Steel', 'Load Capacity' => '200 kg/shelf', 'Shelves' => '5 Layers', 'Color' => 'Silver']
            ],
            [
                'name' => 'Smart Conference Speaker 360',
                'category' => 'Electronics',
                'price' => 22000,
                'image' => 'https://images.unsplash.com/photo-1558507300-4b2665e7178c?w=500&q=80',
                'description' => '360-degree audio and video conference camera with AI-powered face tracking. Compatible with Zoom, Teams, and Meet.',
                'specs' => ['Resolution' => '4K', 'Microphone' => 'Omnidirectional Array', 'Connectivity' => 'USB-C & Bluetooth', 'Range' => '5 Meters']
            ],
            [
                'name' => 'Ultra-Wide Curved Monitor 34"',
                'category' => 'Electronics',
                'price' => 65000,
                'image' => 'https://images.unsplash.com/photo-1527443224154-c4a3942d3acf?w=500&q=80',
                'description' => 'Immersive 34-inch curved display with WQHD resolution. ideal for multitasking professionals and creative designers.',
                'specs' => ['Resolution' => '3440 x 1440', 'Refresh Rate' => '144Hz', 'Panel' => 'IPS', 'Ports' => 'HDMI, DP, USB-C']
            ],
            [
                'name' => 'Cotton 40s Combed Yarn',
                'category' => 'Textiles',
                'price' => 450,
                'image' => 'https://images.unsplash.com/photo-1620799140408-ed5341cd2431?w=500&q=80',
                'description' => 'Premium quality 40s combed cotton yarn suitable for high-end knitting and weaving. Soft texture and high strength.',
                'specs' => ['Count' => '40s', 'Material' => '100% Cotton', 'Usage' => 'Knitting/Weaving', 'Color' => 'Raw White']
            ],
             [
                'name' => 'Denim Fabric Roll (12oz)',
                'category' => 'Textiles',
                'price' => 1200, // per meter
                'image' => 'https://images.unsplash.com/photo-1584382296156-f6c125d74291?w=500&q=80',
                'description' => 'Classic indigo blue denim fabric, 12oz weight. Durable and perfect for jeans, jackets, and heavy-duty apparel.',
                'specs' => ['Weight' => '12oz', 'Width' => '60 inches', 'Weave' => 'Twill', 'Dye' => 'Indigo Blue']
            ]
        ];

        $product1 = null;
        foreach ($premiumProducts as $index => $prod) {
            $p = $this->createProduct($paidSeller, $prod['name'], $prod['category'], $prod['image'], $prod['price'], $prod['description'], $prod['specs']);
            if ($index === 0) $product1 = $p; // Keep ref for associations
        }

        // 5. CREATE FREE SELLER (Unverified, Free Plan)
        $this->command->info('Creating Free Seller...');
        $freeUser = User::create([
            'name' => 'Free Seller',
            'email' => 'free@seller.com',
            'password' => Hash::make('password'),
            'role' => 'seller',
            'phone' => '9876543211',
            'is_active' => true,
        ]);
        $freeUser->assignRole($sellerRole);

        $freeSeller = Seller::create([
            'user_id' => $freeUser->id,
            'company_name' => 'Budget Traders',
            'slug' => 'budget-traders',
            'mobile' => '9876543211',
            'city' => 'Delhi',
            'is_verified' => false,
            'category_id' => Category::first()->id ?? 1,
        ]);

        Subscription::create([
            'seller_id' => $freeSeller->id,
            'plan_id' => $freePlan->id,
            'start_date' => now(),
            'end_date' => now()->addYear(),
            'status' => 'active',
        ]);

        // KYC for Free Seller (Pending)
        // if (class_exists(\App\Models\KycDocument::class)) {
        //     \App\Models\KycDocument::create([
        //         'seller_id' => $freeSeller->id,
        //         'document_type' => 'gst',
        //         'document_path' => 'kyc/dummy_gst.pdf',
        //         'status' => 'pending',
        //     ]);
        // }

        // Products for Free Seller
        $budgetProducts = [
            [
                'name' => 'Basic Office Desk (MDF)',
                'category' => 'Furniture',
                'price' => 3500,
                'image' => 'https://images.unsplash.com/photo-1518455027359-f3f8164ba6bd?w=500&q=80',
                'description' => 'Simple and functional office desk made from durable MDF. Ideal for small offices and home setups.',
                'specs' => ['Material' => 'MDF', 'Dimensions' => '120x60 cm', 'Color' => 'Beech', 'Assembly' => 'Easy DIY']
            ],
             [
                'name' => 'Plastic Stacking Chair',
                'category' => 'Furniture',
                'price' => 850,
                'image' => 'https://images.unsplash.com/photo-1503602642458-232111445657?w=500&q=80',
                'description' => 'Lightweight and stackable plastic chair. Weather-resistant and easy to clean, suitable for events and cafeterias.',
                'specs' => ['Material' => 'Polypropylene', 'Load Capacity' => '100 kg', 'Stackable' => 'Yes', 'Color' => 'Red/Blue']
            ],
        ];

        $product2 = null;
        foreach ($budgetProducts as $index => $prod) {
             $p = $this->createProduct($freeSeller, $prod['name'], $prod['category'], $prod['image'], $prod['price'], $prod['description'], $prod['specs']);
             if ($index === 0) $product2 = $p;
        }

        // 6. CREATE BUYER 1 (Inquiry Process)
        $this->command->info('Creating Buyer 1...');
        $buyer1User = User::create([
            'name' => 'Buyer Process',
            'email' => 'buyer.process@demo.com',
            'password' => Hash::make('password'),
            'role' => 'buyer',
            'phone' => '9876543212',
            'is_active' => true,
        ]);
        $buyer1User->assignRole($buyerRole);
        $buyer1 = Buyer::create(['user_id' => $buyer1User->id]);

        // RFQ (Open)
        $rfqOpen = \App\Models\Rfq::create([
            'buyer_id' => $buyer1->id,
            'category_id' => Category::first()->id ?? 1,
            'title' => 'Need Bulk Cotton Fabric',
            'description' => 'Looking for 100% Cotton Fabric in bulk for manufacturing shirts. White and Blue colors preferred.',
            'quantity' => '1000 Meters',
            'budget' => '200000',
            'delivery_location' => 'Surat, Gujarat',
            'status' => 'open',
            'created_at' => now()->subDays(1),
        ]);

        // Quote (Pending) from Paid Seller to Buyer 1 (via RFQ)
        \App\Models\Quote::create([
            'rfq_id' => $rfqOpen->id,
            'seller_id' => $paidSeller->id,
            'price' => 195000,
            'delivery_timeline' => '10 Days',
            'message' => 'We can supply high quality cotton fabric. Sample available on request.',
            'status' => 'pending',
            'created_at' => now()->subHours(2),
        ]);

        // Inquiry: Process (Viewed)
        Inquiry::create([
            'seller_id' => $paidSeller->id,
            'buyer_id' => $buyer1->id,
            'product_id' => $product1->id,
            'name' => $buyer1User->name,
            'email' => $buyer1User->email,
            'phone' => $buyer1User->phone,
            'message' => 'I am interested in this premium chair. Is it customizable?',
            'status' => 'viewed',
            'created_at' => now()->subDays(1),
            'seller_viewed_at' => now()->subHours(5),
            'seller_response' => 'Yes, we can customize the color and material.',
            'responded_at' => now()->subHours(4),
        ]);

        // Favorites
        if (class_exists(\App\Models\Favorite::class)) {
            \App\Models\Favorite::create(['buyer_id' => $buyer1->id, 'product_id' => $product1->id]);
            \App\Models\Favorite::create(['buyer_id' => $buyer1->id, 'product_id' => $product2->id]);
        }

        // Saved Searches
        if (class_exists(\App\Models\SavedSearch::class)) {
            \App\Models\SavedSearch::create([
                'buyer_id' => $buyer1->id,
                'query' => 'Office Furniture',
                'filters' => json_encode(['category' => 'Furniture']),
            ]);
        }

        // 7. CREATE BUYER 2 (Inquiry Closed)
        $this->command->info('Creating Buyer 2...');
        $buyer2User = User::create([
            'name' => 'Buyer Closed',
            'email' => 'buyer.closed@demo.com',
            'password' => Hash::make('password'),
            'role' => 'buyer',
            'phone' => '9876543213',
            'is_active' => true,
        ]);
        $buyer2User->assignRole($buyerRole);
        $buyer2 = Buyer::create(['user_id' => $buyer2User->id]);

        // RFQ (Closed)
        $rfqClosed = \App\Models\Rfq::create([
            'buyer_id' => $buyer2->id,
            'category_id' => Category::first()->id ?? 1,
            'title' => 'Office Chairs Order',
            'description' => 'Need 50 ergonomic office chairs.',
            'quantity' => '50 Units', 
            'delivery_location' => 'Bangalore',
            'status' => 'closed',
            'created_at' => now()->subMonths(1),
        ]);

        // Quote (Accepted) from Free Seller to Buyer 2
        \App\Models\Quote::create([
            'rfq_id' => $rfqClosed->id,
            'seller_id' => $freeSeller->id,
            'price' => 150000,
            'delivery_timeline' => '15 Days',
            'message' => 'Includes 2 year warranty.',
            'status' => 'accepted',
            'created_at' => now()->subMonths(1)->addDays(1),
        ]);

        // Inquiry: Closed
        Inquiry::create([
            'seller_id' => $freeSeller->id,
            'buyer_id' => $buyer2->id,
            'product_id' => $product2->id,
            'name' => $buyer2User->name,
            'email' => $buyer2User->email,
            'phone' => $buyer2User->phone,
            'message' => 'Do you have this in stock? Need 50 units.',
            'status' => 'closed',
            'created_at' => now()->subDays(5),
            'seller_viewed_at' => now()->subDays(4),
            'responded_at' => now()->subDays(3),
            'seller_response' => 'Sorry, out of stock.',
        ]);

        // Reviews
        // if (class_exists(\App\Models\Review::class)) {
            // ... (keep commented out)
        // }

        // Promotion Packages
        if (class_exists(\App\Models\PromotionPackage::class)) {
            $packages = [
                [
                    'name' => 'Homepage Spotlight',
                    'description' => 'Get featured on the main homepage slider for maximum visibility.',
                    'price' => 2999,
                    'duration_days' => 7,
                    'page_position' => 1, // Homepage
                    'max_products' => 3,
                    'priority_level' => 10,
                    'badge_text' => 'SPOTLIGHT',
                    'badge_color' => '#FFD700',
                    'is_active' => true,
                ],
                [
                    'name' => 'Category Leader',
                    'description' => 'Stay at the top of your specific category pages.',
                    'price' => 1499,
                    'duration_days' => 14,
                    'page_position' => 2, // Category Page
                    'max_products' => 5,
                    'priority_level' => 8,
                    'badge_text' => 'TOP PICK',
                    'badge_color' => '#00C851',
                    'is_active' => true,
                ],
                [
                    'name' => 'Search Booster',
                    'description' => 'Appear in the top 3 results for relevant search queries.',
                    'price' => 999,
                    'duration_days' => 30,
                    'page_position' => 3, // Search Results
                    'max_products' => 10,
                    'priority_level' => 5,
                    'badge_text' => 'FEATURED',
                    'badge_color' => '#33b5e5',
                    'is_active' => true,
                ],
                [
                    'name' => 'Sidebar Ad',
                    'description' => 'Banner ad displayed on the sidebar of buyer dashboards.',
                    'price' => 499,
                    'duration_days' => 7,
                    'page_position' => 4, // Sidebar
                    'max_products' => 1,
                    'priority_level' => 3,
                    'badge_text' => 'AD',
                    'badge_color' => '#ffbb33',
                    'is_active' => true,
                ],
                [
                    'name' => 'Flash Sale Feature',
                    'description' => 'Highlight your discounted products in the Flash Sale section.',
                    'price' => 199,
                    'duration_days' => 3,
                    'page_position' => 1, // Homepage Flash Sale Section
                    'max_products' => 5,
                    'priority_level' => 7,
                    'badge_text' => 'SALE',
                    'badge_color' => '#ff4444',
                    'is_active' => true,
                ],
            ];

            foreach ($packages as $pkg) {
                \App\Models\PromotionPackage::create($pkg);
            }
            $this->command->info('Promotion Packages seeded.');
        }

        $this->command->info('----------------------------------------------');
        $this->command->info('DEMO DATA EXPANSION COMPLETE');
        $this->command->info('----------------------------------------------');
    }

    private function seedAdminModules()
    {
        // Banners
        if (class_exists(\App\Models\Banner::class)) {
            \App\Models\Banner::create([
                'title' => 'Global Trade Expo 2024',
                'description' => 'Join the biggest trade event of the year.',
                'image' => 'banners/banner1.jpg', // Placeholder
                'position' => 'home_slider',
                'active' => true,
            ]);
             \App\Models\Banner::create([
                'title' => 'Premium Suppliers',
                'description' => 'Get access to verified top-tier suppliers.',
                'image' => 'banners/banner2.jpg',
                'position' => 'home_slider',
                'active' => true,
            ]);
        }

        // FAQs
        if (class_exists(\App\Models\HelpFaq::class)) {
            \App\Models\HelpFaq::create(['category' => 'Account', 'question' => 'How to reset password?', 'answer' => 'Go to settings -> Security', 'is_active' => true]);
            \App\Models\HelpFaq::create(['category' => 'Selling', 'question' => 'How to become a verified seller?', 'answer' => 'Submit your GST and PAN details for KYC verification.', 'is_active' => true]);
            \App\Models\HelpFaq::create(['category' => 'Buying', 'question' => 'Is payment secure?', 'answer' => 'Yes, we use escrow services.', 'is_active' => true]);
        }
    }

    private function createProduct($seller, $name, $catName, $imgUrl, $price, $description, $specs = [])
    {
        // Find category
        $category = Category::where('name', 'LIKE', "%$catName%")->first() 
            ?? Category::firstOrCreate(['name' => $catName, 'slug' => Str::slug($catName)]);

        // Image Handling
        $imageName = 'products/' . Str::slug($name) . '.jpg';
        if (!Storage::disk('public')->exists($imageName)) {
            try {
                // Use a proper User-Agent to avoid 403 Forbidden from Unsplash
                $context = stream_context_create([
                    'http' => [
                        'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\r\n"
                    ]
                ]);
                $contents = file_get_contents($imgUrl, false, $context);
                if($contents) Storage::disk('public')->put($imageName, $contents);
            } catch (\Exception $e) {
                // Determine missing image based on category
                if(str_contains($catName, 'Furniture')) $imageName = 'products/furniture_placeholder.jpg';
                elseif(str_contains($catName, 'Electronic')) $imageName = 'products/tech_placeholder.jpg';
                else $imageName = 'products/default_placeholder.jpg';
            }
        }

        return Product::create([
            'seller_id' => $seller->id,
            'category_id' => $category->id,
            'name' => $name,
            'slug' => Str::slug($name) . '-' . Str::random(5),
            'description' => $description,
            'price' => $price,
            'stock' => rand(50, 500),
            'moq' => rand(5, 50),
            'images_json' => json_encode([['thumbnail' => $imageName, 'original' => $imageName]]),
            'specifications' => $specs, 
            'is_approved' => true,
        ]);
    }
}
