<?php

namespace Database\Seeders;

use App\Models\Category;
use App\Models\Product;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;

class FakeProductsSeeder extends Seeder
{
    public function run()
    {
        // Ensure categories are seeded first
        $this->call(CategorySeeder::class);

        $smartPhoneCategory = Category::where('slug', 'smart-phones')->first();
        $featurePhoneCategory = Category::where('slug', 'feature-phones')->first();
        $accessoriesCategory = Category::where('slug', 'accessories')->first();

        $faker = Faker::create();

        $phoneBrands = [
            'Nokia' => ['105', '106', '110', '3310', '5310', '6300', '2720', '8000'],
            'Samsung' => ['Galaxy A10', 'Galaxy A20', 'Galaxy M10', 'Galaxy S10'],
            'Apple' => ['iPhone 11', 'iPhone 12', 'iPhone 13', 'iPhone SE'],
            'Xiaomi' => ['Redmi 9', 'Redmi 10', 'Redmi Note 10', 'Poco M3'],
        ];

        $phoneImages = [
            'Nokia 105' => 'products/nokia-105.jpg',
            'Nokia 106' => 'products/nokia-106.jpg',
            'Nokia 110' => 'products/nokia-110.jpg',
            'Nokia 3310' => 'products/nokia-3310.jpg',
            'Nokia 5310' => 'products/nokia-5310.jpg',
            'Nokia 6300' => 'products/nokia-6300.jpg',
            'Nokia 2720' => 'products/nokia-2720.jpg',
            'Nokia 8000' => 'products/nokia-8000.jpg',
            'Samsung Galaxy A10' => 'products/samsung-galaxy-a10.jpg',
            'Samsung Galaxy A20' => 'products/samsung-galaxy-a20.jpg',
            'Samsung Galaxy M10' => 'products/samsung-galaxy-m10.jpg',
            'Samsung Galaxy S10' => 'products/samsung-galaxy-s10.jpg',
            'Apple iPhone 11' => 'products/apple-iphone-11.jpg',
            'Apple iPhone 12' => 'products/apple-iphone-12.jpg',
            'Apple iPhone 13' => 'products/apple-iphone-13.jpg',
            'Apple iPhone SE' => 'products/apple-iphone-se.jpg',
            'Xiaomi Redmi 9' => 'products/xiaomi-redmi-9.jpg',
            'Xiaomi Redmi 10' => 'products/xiaomi-redmi-10.jpg',
            'Xiaomi Redmi Note 10' => 'products/xiaomi-redmi-note-10.jpg',
            'Xiaomi Poco M3' => 'products/xiaomi-poco-m3.jpg',
        ];

        $accessoryItems = [
            'Samsung' => ['Galaxy Buds', '25W Charger', 'Wireless Charger Pad'],
            'Apple' => ['AirPods Pro', 'MagSafe Charger', 'Lightning Cable'],
            'Xiaomi' => ['Mi Power Bank', 'Redmi AirDots', 'Mi Band 6'],
            'Generic' => ['Bluetooth Headphone', 'Screen Protector', 'Phone Case', 'Car Charger'],
        ];

        // ... (distributors and retailers arrays remain the same)
        // ...

        $retailers = [
            ['name' => 'Phone House BD', 'code' => 'RET-PH001', 'contact' => '+8801XXXXXX', 'address' => 'Dhaka'],
            ['name' => 'Mobile Gallery', 'code' => 'RET-MG002', 'contact' => '+8801XXXXXX', 'address' => 'Chittagong'],
            ['name' => 'Smart Shop', 'code' => 'RET-SS003', 'contact' => '+8801XXXXXX', 'address' => 'Sylhet'],
        ];

        $distributors = [
            ['name' => 'Mobile Bangla Distributors', 'code' => 'DIST-MB001', 'contact' => '+8801XXXXXX', 'address' => 'Dhaka, Bangladesh'],
            ['name' => 'Tech Solutions BD', 'code' => 'DIST-TS002', 'contact' => '+8801XXXXXX', 'address' => 'Chittagong, Bangladesh'],
            ['name' => 'Gadget World Suppliers', 'code' => 'DIST-GW003', 'contact' => '+8801XXXXXX', 'address' => 'Khulna, Bangladesh'],
        ];


        $products = [];

        echo "Generating 200 fake products with complete information...\n";

        for ($i = 1; $i <= 200; $i++) {
            $isAccessory = $faker->boolean(20); // 20% chance to be an accessory
            $categoryId = null;
            $productName = '';
            $brand = '';
            $model = '';
            $image = 'products/phone-placeholder.jpg'; // Default image

            if ($isAccessory) {
                $brand = array_rand($accessoryItems);
                $model = $accessoryItems[$brand][array_rand($accessoryItems[$brand])];
                $productName = ($brand !== 'Generic' ? $brand . ' ' : '') . $model;
                $categoryId = $accessoriesCategory?->id;
                $image = 'products/accessory-placeholder.jpg'; // Generic accessory image
            } else {
                $brand = array_rand($phoneBrands);
                $model = $phoneBrands[$brand][array_rand($phoneBrands[$brand])];
                $productName = $brand . ' ' . $model;
                if (in_array($brand, ['Samsung', 'Apple', 'Xiaomi'])) {
                    $image = $phoneImages[$productName] ?? 'products/phone-placeholder.jpg';
                    $categoryId = $smartPhoneCategory?->id;
                } elseif ($brand === 'Nokia' && !str_contains($model, 'Galaxy') && !str_contains($model, 'iPhone')) {
                    $categoryId = $featurePhoneCategory?->id;
                }
            }

            $distributor = $distributors[array_rand($distributors)];
            $retailer = $retailers[array_rand($retailers)];

            $status = $this->weightedRandomStatus();

            $price = $faker->numberBetween(5000, 50000);
            if ($isAccessory) {
                $price = $faker->numberBetween(500, 4000);
            }

            $isFeatured = $faker->boolean(25);
            $discountPrice = null;
            if ($isFeatured && $faker->boolean(50)) { // 50% chance of having a discount if featured
                $discountPrice = $price - ($price * $faker->randomFloat(2, 0.1, 0.3)); // 10-30% discount
            }

            $product = [
                'serial_no' => $this->generateSerialNumber($brand),
                'product_name' => $productName,
                'image' => $image,
                'condition' => $faker->randomElement(['New', 'Refurbished', 'Used']),
                'status' => $status,
                'quality' => $faker->randomElement(['Authentic', 'Premium', 'Standard']),
                'imei' => $this->generateIMEI(),
                'color' => $faker->randomElement(['Black', 'White', 'Blue', 'Red', 'Silver', 'Gold']),
                'distributor_name' => $distributor['name'],
                'distributor_code' => $distributor['code'],
                'distributor_contact' => $distributor['contact'],
                'distributor_address' => $distributor['address'],
                'retailer_name' => in_array($status, ['Shipped', 'Delivered', 'Sold']) ? $retailer['name'] : null,
                'retailer_code' => in_array($status, ['Shipped', 'Delivered', 'Sold']) ? $retailer['code'] : null,
                'retailer_contact' => in_array($status, ['Shipped', 'Delivered', 'Sold']) ? $retailer['contact'] : null,
                'retailer_address' => in_array($status, ['Shipped', 'Delivered', 'Sold']) ? $retailer['address'] : null,
                'retailer_assigned_at' => in_array($status, ['Shipped', 'Delivered', 'Sold']) ? $faker->dateTimeBetween('-30 days', 'now') : null,
                'client_name' => $status === 'Sold' ? $faker->name() : null,
                'client_phone' => $status === 'Sold' ? $faker->phoneNumber() : null,
                'client_email' => $status === 'Sold' ? $faker->email() : null,
                'client_address' => $status === 'Sold' ? $faker->address() : null,
                'sold_at' => $status === 'Sold' ? $faker->dateTimeBetween('-7 days', 'now') : null,
                'description' => $this->generateDescription($brand, $model),
                'barcode' => $this->generateBarcode(),
                'category_id' => $categoryId,
                'price' => $price,
                'discount_price' => $discountPrice,
                'featured' => $isFeatured,
                'cost' => $faker->numberBetween(4000, 45000),
                'warranty_period' => '1 Year',
                'manufacture_date' => $faker->dateTimeBetween('-1 year', '-1 month')->format('Y-m-d'),
                'expiry_date' => $faker->dateTimeBetween('now', '+2 years')->format('Y-m-d'),
                'batch_number' => 'BATCH-' . $faker->randomNumber(6),
                'supplier_name' => $brand . ' Official Supplier',
                'location' => $faker->randomElement(['Warehouse A', 'Warehouse B', 'Warehouse C']),
                'notes' => $faker->sentence(),
                'scanned_by' => $faker->randomElement(['Scanner-001', 'Scanner-002', 'Admin']),
                'scanned_at' => $faker->dateTimeBetween('-60 days', 'now'),
                'created_by' => 'System',
                'updated_by' => 'System',
                'created_at' => now(),
                'updated_at' => now(),
            ];

            $products[] = $product;

            if ($i % 50 === 0) {
                echo "Generated {$i} products...\n";
            }

            if ($i % 100 === 0) {
                Product::insert($products);
                $products = [];
            }
        }

        if (!empty($products)) {
            Product::insert($products);
        }

        echo "Successfully generated 200 products with complete information!\n";

        $this->displayStatistics();
    }

    private function weightedRandomStatus()
    {
        $statuses = [
            'In Warehouse' => 40,
            'Shipped' => 25,
            'Delivered' => 20,
            'Sold' => 10,
            'Returned' => 5
        ];

        $total = array_sum($statuses);
        $random = mt_rand(1, $total);
        $current = 0;

        foreach ($statuses as $status => $weight) {
            $current += $weight;
            if ($random <= $current) {
                return $status;
            }
        }

        return 'In Warehouse';
    }

    private function generateIMEI()
    {
        return '35' . str_pad(mt_rand(1, 9999999999999), 13, '0', STR_PAD_LEFT);
    }

    private function generateSerialNumber($brand)
    {
        $prefixes = ['Nokia' => 'NOK', 'Samsung' => 'SAM', 'Apple' => 'APL', 'Xiaomi' => 'XIA'];
        $prefix = $prefixes[$brand] ?? 'GEN';
        return $prefix . '-' . date('Y') . '-' . str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
    }

    private function generateBarcode()
    {
        return '88' . str_pad(mt_rand(1, 999999999999), 12, '0', STR_PAD_LEFT);
    }

    private function generateDescription($brand, $model)
    {
        return "Brand new {$brand} {$model} with original packaging and warranty";
    }

    private function displayStatistics()
    {
        echo "\n=== PRODUCT STATISTICS ===\n";
        echo "Total Products: " . Product::count() . "\n";
        echo "In Warehouse: " . Product::where('status', 'In Warehouse')->count() . "\n";
        echo "Shipped: " . Product::where('status', 'Shipped')->count() . "\n";
        echo "Delivered: " . Product::where('status', 'Delivered')->count() . "\n";
        echo "Sold: " . Product::where('status', 'Sold')->count() . "\n";
        echo "Returned: " . Product::where('status', 'Returned')->count() . "\n";

        echo "\n=== SAMPLE PRODUCTS ===\n";
        $samples = Product::limit(3)->get();
        foreach ($samples as $product) {
            echo "Serial: {$product->serial_no} | Product: {$product->product_name}\n";
            echo "Status: {$product->status} | Condition: {$product->condition}\n";
            echo "Distributor: {$product->distributor_name}";
            if ($product->retailer_name) echo " | Retailer: {$product->retailer_name}";
            if ($product->client_name) echo " | Client: {$product->client_name}";
            echo "\n----------------------------------------\n";
        }
    }
}
