<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
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\Unit;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;

class DemoDataSeeder extends Seeder
{
    /**
     * Run the database seeds for professional demo data.
     */
    public function run(): void
    {
        // Clear existing data
        $this->command->info('Clearing existing data...');
        
        // Disable foreign key checks (SQLite compatible)
        DB::statement('PRAGMA foreign_keys = OFF;');
        
        DB::table('product_promotions')->truncate();
        DB::table('products')->truncate();
        DB::table('subscriptions')->truncate();
        DB::table('sellers')->truncate();
        DB::table('buyers')->truncate();
        DB::table('users')->truncate();
        DB::table('model_has_roles')->truncate();
        
        // Re-enable foreign key checks
        DB::statement('PRAGMA foreign_keys = ON;');
        
        $this->command->info('Creating demo data...');

        // Ensure categories exist
        $electronicsCategory = Category::firstOrCreate(
            ['slug' => 'electronics'],
            [
                'name' => 'Electronics',
                'industries' => null
            ]
        );
        
        $furnitureCategory = Category::firstOrCreate(
            ['slug' => 'furniture'],
            [
                'name' => 'Furniture',
                'industries' => null
            ]
        );
        
        $textileCategory = Category::firstOrCreate(
            ['slug' => 'textiles'],
            [
                'name' => 'Textiles',
                'industries' => null
            ]
        );

        // Ensure units exist
        $pieceUnit = Unit::firstOrCreate(
            ['code' => 'PCS'],
            ['name' => 'Pieces', 'is_active' => true]
        );
        
        $kgUnit = Unit::firstOrCreate(
            ['code' => 'KG'],
            ['name' => 'Kilograms', 'is_active' => true]
        );

        // Ensure plans exist
        $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
            ]
        );

        $silverPlan = Plan::firstOrCreate(
            ['slug' => 'silver-plan'],
            [
                'name' => 'Silver Plan',
                'price_inr' => 2999,
                'price_usd' => 36,
                'duration_days' => 180,
                'product_limit' => 10,
                'product_image_limit' => 5,
                'inquiry_limit' => 100,
                'banner_limit' => 3,
                'custom_page_limit' => 2,
                'show_contact_details' => true,
                'view_buyer_contact' => true,
                'has_verified_badge' => true,
                'allow_microsite' => true,
                'is_active' => true
            ]
        );

        // 1. Create Admin User
        $this->command->info('Creating Admin user...');
        $adminRole = Role::firstOrCreate(['name' => 'admin']);
        
        $admin = User::create([
            'name' => 'Admin User',
            'email' => 'admin@theminiport.com',
            'password' => Hash::make('admin123'),
            'role' => 'admin',
            'is_active' => true,
            'phone' => '+91 98765 43210'
        ]);
        $admin->assignRole($adminRole);

        // 2. Create Free Seller (3 Products)
        $this->command->info('Creating Free Seller with 3 products...');
        $sellerRole = Role::firstOrCreate(['name' => 'seller']);
        
        $freeUser = User::create([
            'name' => 'Rajesh Kumar',
            'email' => 'rajesh@greenelectronics.com',
            'password' => Hash::make('seller123'),
            'role' => 'seller',
            'is_active' => true,
            'phone' => '+91 98765 11111'
        ]);
        $freeUser->assignRole($sellerRole);

        $freeSeller = Seller::create([
            'user_id' => $freeUser->id,
            'company_name' => 'Green Electronics Pvt Ltd',
            'slug' => 'green-electronics',
            'mobile' => '+91 98765 11111',
            'gst' => '27AABCU9603R1ZM',
            'city' => 'Mumbai',
            'state' => 'Maharashtra',
            'country' => 'India',
            'pincode' => '400001',
            'address' => 'Shop No. 12, Electronic Market, Lamington Road',
            'about' => 'Leading wholesale distributor of quality electronics and accessories. Serving retailers across India since 2015 with genuine products and competitive pricing.',
            'moq_quantity' => 10,
            'moq_unit_id' => $pieceUnit->id,
            'category_id' => $electronicsCategory->id,
            'is_verified' => true,
            'kyc_status' => 'verified'
        ]);

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

        // Products for Free Seller
        $freeProducts = [
            [
                'name' => 'Wireless Bluetooth Earbuds Pro',
                'description' => 'Premium quality wireless earbuds with active noise cancellation, 30-hour battery life, and IPX7 water resistance. Perfect for music lovers and fitness enthusiasts.',
                'price' => 1299,
                'moq' => 10,
                'category_id' => $electronicsCategory->id,
                'specifications' => json_encode([
                    'Battery Life' => '30 hours',
                    'Bluetooth Version' => '5.2',
                    'Water Resistance' => 'IPX7',
                    'Charging' => 'USB-C Fast Charging'
                ])
            ],
            [
                'name' => 'Smart LED TV 43 Inch',
                'description' => 'Full HD Smart LED TV with built-in WiFi, Android OS, and 3 HDMI ports. Perfect for home entertainment with crystal clear picture quality.',
                'price' => 18999,
                'moq' => 5,
                'category_id' => $electronicsCategory->id,
                'specifications' => json_encode([
                    'Screen Size' => '43 inches',
                    'Resolution' => '1920x1080 Full HD',
                    'OS' => 'Android 11',
                    'Connectivity' => 'WiFi, 3x HDMI, 2x USB'
                ])
            ],
            [
                'name' => 'Power Bank 20000mAh',
                'description' => 'High capacity portable charger with dual USB output and fast charging support. Compact design perfect for travel and daily use.',
                'price' => 899,
                'moq' => 20,
                'category_id' => $electronicsCategory->id,
                'specifications' => json_encode([
                    'Capacity' => '20000mAh',
                    'Output' => '2x USB-A, 1x USB-C',
                    'Input' => 'Micro USB, USB-C',
                    'Fast Charging' => 'Supported'
                ])
            ]
        ];

        foreach ($freeProducts as $productData) {
            Product::create(array_merge($productData, [
                'seller_id' => $freeSeller->id,
                'slug' => \Illuminate\Support\Str::slug($productData['name']),
                'is_approved' => true,
                'is_highlighted' => false,
                'stock' => rand(50, 200)
            ]));
        }

        // 3. Create Paid Seller (5 Products)
        $this->command->info('Creating Paid Seller with 5 products...');
        
        $paidUser = User::create([
            'name' => 'Priya Sharma',
            'email' => 'priya@royalfurniture.com',
            'password' => Hash::make('seller123'),
            'role' => 'seller',
            'is_active' => true,
            'phone' => '+91 98765 22222'
        ]);
        $paidUser->assignRole($sellerRole);

        $paidSeller = Seller::create([
            'user_id' => $paidUser->id,
            'company_name' => 'Royal Furniture & Interiors',
            'slug' => 'royal-furniture',
            'mobile' => '+91 98765 22222',
            'gst' => '29AADCR5783M1Z5',
            'city' => 'Bangalore',
            'state' => 'Karnataka',
            'country' => 'India',
            'pincode' => '560001',
            'address' => '15, MG Road, Commercial Complex',
            'about' => 'Premium furniture manufacturer and exporter. Specializing in modern office furniture and luxury home collections. ISO 9001:2015 certified with 15+ years of excellence.',
            'moq_quantity' => 5,
            'moq_unit_id' => $pieceUnit->id,
            'category_id' => $furnitureCategory->id,
            'is_verified' => true,
            'kyc_status' => 'verified'
        ]);

        // Paid subscription
        Subscription::create([
            'seller_id' => $paidSeller->id,
            'plan_id' => $silverPlan->id,
            'start_date' => now(),
            'end_date' => now()->addMonths(6),
            'status' => 'active',
            'payment_method' => 'razorpay',
            'payment_id' => 'pay_demo' . time()
        ]);

        // Products for Paid Seller
        $paidProducts = [
            [
                'name' => 'Executive Office Chair - Ergonomic Design',
                'description' => 'Premium ergonomic office chair with lumbar support, adjustable armrests, and breathable mesh back. Perfect for long working hours with superior comfort.',
                'price' => 8999,
                'moq' => 5,
                'category_id' => $furnitureCategory->id,
                'is_highlighted' => true,
                'specifications' => json_encode([
                    'Material' => 'Premium Mesh & Leather',
                    'Weight Capacity' => '120 kg',
                    'Adjustability' => 'Height, Armrest, Recline',
                    'Warranty' => '3 Years'
                ])
            ],
            [
                'name' => 'Modern L-Shaped Desk - Walnut Finish',
                'description' => 'Spacious L-shaped executive desk with cable management and storage drawers. Made from engineered wood with premium walnut veneer finish.',
                'price' => 15999,
                'moq' => 3,
                'category_id' => $furnitureCategory->id,
                'is_highlighted' => true,
                'specifications' => json_encode([
                    'Dimensions' => '150cm x 150cm x 75cm',
                    'Material' => 'Engineered Wood',
                    'Storage' => '3 Drawers, 1 Cabinet',
                    'Assembly' => 'Required'
                ])
            ],
            [
                'name' => 'Conference Table 8 Seater',
                'description' => 'Professional conference table for offices and meeting rooms. Solid construction with wire management system and modern design.',
                'price' => 24999,
                'moq' => 2,
                'category_id' => $furnitureCategory->id,
                'specifications' => json_encode([
                    'Seating Capacity' => '8 Persons',
                    'Dimensions' => '240cm x 120cm x 75cm',
                    'Material' => 'Premium MDF with Laminate',
                    'Cable Management' => 'Integrated'
                ])
            ],
            [
                'name' => 'Luxury Sofa Set 3+1+1',
                'description' => 'Elegant 5-seater sofa set with premium fabric upholstery and solid wood frame. Perfect for living rooms and office receptions.',
                'price' => 32999,
                'moq' => 1,
                'category_id' => $furnitureCategory->id,
                'specifications' => json_encode([
                    'Configuration' => '3-Seater + 2x 1-Seater',
                    'Frame' => 'Hardwood',
                    'Upholstery' => 'Premium Velvet Fabric',
                    'Color Options' => 'Grey, Beige, Navy Blue'
                ])
            ],
            [
                'name' => 'Height Adjustable Standing Desk',
                'description' => 'Electric height-adjustable desk for modern offices. Promotes healthy work posture with memory presets and sturdy construction.',
                'price' => 19999,
                'moq' => 3,
                'category_id' => $furnitureCategory->id,
                'is_highlighted' => true,
                'specifications' => json_encode([
                    'Height Range' => '72cm - 120cm',
                    'Motor' => 'Dual Electric Motor',
                    'Desktop' => '140cm x 70cm',
                    'Weight Capacity' => '80 kg',
                    'Presets' => '4 Memory Settings'
                ])
            ]
        ];

        foreach ($paidProducts as $productData) {
            Product::create(array_merge($productData, [
                'seller_id' => $paidSeller->id,
                'slug' => \Illuminate\Support\Str::slug($productData['name']),
                'is_approved' => true,
                'stock' => rand(20, 100)
            ]));
        }

        $this->command->info('✅ Demo data created successfully!');
        $this->command->info('');
        $this->command->info('Login Credentials:');
        $this->command->info('=====================================');
        $this->command->info('Admin:');
        $this->command->info('  Email: admin@theminiport.com');
        $this->command->info('  Password: admin123');
        $this->command->info('');
        $this->command->info('Free Seller (3 products):');
        $this->command->info('  Email: rajesh@greenelectronics.com');
        $this->command->info('  Password: seller123');
        $this->command->info('  Company: Green Electronics Pvt Ltd');
        $this->command->info('');
        $this->command->info('Paid Seller (5 products):');
        $this->command->info('  Email: priya@royalfurniture.com');
        $this->command->info('  Password: seller123');
        $this->command->info('  Company: Royal Furniture & Interiors');
        $this->command->info('=====================================');
    }
}
