<?php

namespace Database\Seeders;

use App\Models\Product;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class NokiaProductsSeeder extends Seeder
{
    public function run()
    {
        $nokiaModels = [
            // Classic Models
            '3310' => ['colors' => ['Blue', 'Red', 'Gray', 'Yellow'], 'years' => [2017, 2020]],
            '105' => ['colors' => ['Black', 'Blue', 'Red', 'White'], 'years' => [2015, 2017, 2019, 2023]],
            '106' => ['colors' => ['Black', 'Blue', 'Red'], 'years' => [2023]],
            '110' => ['colors' => ['Black', 'Blue', 'Red', 'Yellow'], 'years' => [2019, 2022]],
            '130' => ['colors' => ['Black', 'Red', 'White'], 'years' => [2017, 2020]],
            '150' => ['colors' => ['Black', 'Blue', 'Red'], 'years' => [2017, 2020]],
            '210' => ['colors' => ['Black', 'White', 'Blue', 'Red'], 'years' => [2013, 2017]],
            '215' => ['colors' => ['Black', 'White', 'Green'], 'years' => [2020]],
            '220' => ['colors' => ['Black', 'Blue', 'Yellow'], 'years' => [2014, 2019]],
            '225' => ['colors' => ['Black', 'Blue', 'Red', 'Yellow'], 'years' => [2020]],
            
            // Music Series
            '5310' => ['colors' => ['White', 'Red', 'Black', 'Blue'], 'years' => [2020]],
            '5330' => ['colors' => ['Black', 'Silver', 'Red'], 'years' => [2023]],
            '6300' => ['colors' => ['Black', 'White', 'Cyan', 'Red'], 'years' => [2020, 2021]],
            '8000' => ['colors' => ['Black', 'White', 'Gold', 'Blue'], 'years' => [2020]],
            
            // Smart Feature Phones
            '2720' => ['colors' => ['Black', 'Gray', 'Red'], 'years' => [2019]],
            '8110' => ['colors' => ['Black', 'Yellow'], 'years' => [2018]],
            '800' => ['colors' => ['Black', 'White', 'Blue'], 'years' => [2021]],
            
            // Lumia Series (for variety)
            'Lumia 520' => ['colors' => ['Black', 'White', 'Red', 'Yellow'], 'years' => [2013]],
            'Lumia 620' => ['colors' => ['Black', 'White', 'Yellow', 'Cyan'], 'years' => [2013]],
            'Lumia 720' => ['colors' => ['Black', 'White', 'Red', 'Yellow'], 'years' => [2013]],
        ];

        $qualities = ['Authentic', 'Premium', 'Standard'];
        $statuses = ['In Warehouse', 'Shipped', 'Delivered'];
        $warehouses = ['Dhaka Central Warehouse', 'Chittagong Port Storage', 'Khulna Distribution Center'];
        $distributors = [
            ['name' => 'Mobile Bangla Ltd.', 'code' => 'DIST-MBL'],
            ['name' => 'Nokia Center BD', 'code' => 'DIST-NCB'],
            ['name' => 'Gadget World Bangladesh', 'code' => 'DIST-GWB'],
            ['name' => 'Tech Solutions BD', 'code' => 'DIST-TSB'],
        ];

        $productImages = [
            '3310' => 'products/nokia-3310.jpg',
            '105' => 'products/nokia-105.jpg',
            '106' => 'products/nokia-106.jpg',
            '110' => 'products/nokia-110.jpg',
            '130' => 'products/nokia-130.jpg',
            '150' => 'products/nokia-150.jpg',
            '210' => 'products/nokia-210.jpg',
            '215' => 'products/nokia-215.jpg',
            '220' => 'products/nokia-220.jpg',
            '225' => 'products/nokia-225.jpg',
            '5310' => 'products/nokia-5310.jpg',
            '5330' => 'products/nokia-5330.jpg',
            '6300' => 'products/nokia-6300.jpg',
            '8000' => 'products/nokia-8000.jpg',
            '2720' => 'products/nokia-2720.jpg',
            '8110' => 'products/nokia-8110.jpg',
            '800' => 'products/nokia-800.jpg',
            'Lumia 520' => 'products/nokia-lumia-520.jpg',
            'Lumia 620' => 'products/nokia-lumia-620.jpg',
            'Lumia 720' => 'products/nokia-lumia-720.jpg',
        ];

        $products = [];
        $batchSize = 50;
        $totalProducts = 300;

        echo "Generating {$totalProducts} Nokia products...\n";

        for ($i = 1; $i <= $totalProducts; $i++) {
            $model = array_rand($nokiaModels);
            $modelInfo = $nokiaModels[$model];
            $year = $modelInfo['years'][array_rand($modelInfo['years'])];
            $color = $modelInfo['colors'][array_rand($modelInfo['colors'])];
            
            $productName = "Nokia {$model}";
            if (in_array($model, ['3310', '105', '106', '110'])) {
                $productName .= " ({$year})";
            }

            // Generate realistic data
            $imei = $this->generateNokiaIMEI();
            $serialNo = $this->generateNokiaSerial($model, $year);
            $barcode = $this->generateBarcode();
            $image = $productImages[$model] ?? 'products/phone-placeholder.jpg';

            $scannedDate = $this->generateScannedDate();
            $status = $this->weightedRandomStatus();
            $distributor = $distributors[array_rand($distributors)];

            $products[] = [
                'image' => $image,
                'serial_no' => $serialNo,
                'imei' => $imei,
                'barcode' => $barcode,
                'product_name' => $productName,
                'quality' => $qualities[array_rand($qualities)],
                'description' => $this->generateNokiaDescription($model, $year, $color),
                'distributor_name' => $distributor['name'],
                'distributor_code' => $distributor['code'],
                'color' => $color,
                'status' => $status,
                'scanned_by' => 'Scanner-' . str_pad(mt_rand(1, 10), 3, '0', STR_PAD_LEFT),
                'scanned_at' => $scannedDate,
                'created_at' => $scannedDate,
                'updated_at' => $scannedDate,
            ];

            // Insert in batches
            if ($i % $batchSize === 0) {
                Product::insert($products);
                $products = [];
                echo "Generated {$i} products...\n";
            }
        }

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

        echo "Successfully generated {$totalProducts} Nokia products!\n";
        
        // Display sample data
        $this->displaySampleData();
    }

    private function generateNokiaIMEI()
    {
        // Nokia IMEI often starts with 35
        return '35' . str_pad(mt_rand(1, 9999999999999), 13, '0', STR_PAD_LEFT);
    }

    private function generateNokiaSerial($model, $year)
    {
        $prefix = 'NOK';
        $modelCode = str_pad(str_replace(['Lumia ', ' '], '', $model), 3, '0', STR_PAD_LEFT);
        $sequence = str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
        
        return "{$prefix}-{$year}-{$modelCode}{$sequence}";
    }

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

    private function generateScannedDate()
    {
        $start = strtotime('-180 days');
        $end = time();
        $randomTimestamp = mt_rand($start, $end);
        
        return date('Y-m-d H:i:s', $randomTimestamp);
    }

    private function weightedRandomStatus()
    {
        $statuses = [
            'In Warehouse' => 40, // 40% chance
            'Shipped' => 35,      // 35% chance
            'Delivered' => 25     // 25% chance
        ];

        $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 generateNokiaDescription($model, $year, $color)
    {
        $features = [
            '3310' => "Legendary durable phone with month-long battery life",
            '105' => "Essential phone with built-in flashlight and long battery",
            '106' => "Compact design with large buttons and clear sound",
            '5310' => "Music phone with dedicated music keys and dual speakers",
            '6300' => "4G capable feature phone with WhatsApp support",
            'Lumia 520' => "Windows Phone with responsive touch screen"
        ];

        $base = $features[$model] ?? "Reliable {$model} model with Nokia quality";
        
        return "{$color} {$base}. Manufactured in {$year}. Original Nokia product with warranty.";
    }

    private function displaySampleData()
    {
        echo "\n=== SAMPLE GENERATED DATA ===\n";
        
        $sampleProducts = Product::inRandomOrder()->limit(5)->get();
        
        foreach ($sampleProducts as $product) {
            echo "Product: {$product->product_name}\n";
            echo "Serial: {$product->serial_no} | IMEI: {$product->imei}\n";
            echo "Color: {$product->color} | Quality: {$product->quality}\n";
            echo "Status: {$product->status} | Scanned: {$product->scanned_at}\n";
            echo "----------------------------------------\n";
        }
    }
}