<?php

use Illuminate\Database\Seeder;
use App\Modules\Stock\Stock;
use App\Modules\Stock\StockGroup;
use App\Modules\Stock\Supplier;
use App\Modules\Invoices\Invoice;
use App\Modules\Invoices\InvoiceItem;
use App\Modules\Bookings\Task;
use App\Modules\Clients\Client;
use App\Modules\Clients\Customer;

class StockInvoicesSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // Create suppliers
        $suppliers = [
            'Ingram Micro',
            'Tech Data',
            'Westcoast',
            'Exertis',
            'Midwich',
            'Computacenter',
            'SCC',
            'Insight'
        ];

        foreach ($suppliers as $supplierName) {
            Supplier::firstOrCreate(['name' => $supplierName]);
        }

        // Create stock groups
        $stockGroups = [
            ['name' => 'Laptops', 'margin' => 15.00, 'business_margin' => 20.00],
            ['name' => 'Desktop PCs', 'margin' => 12.00, 'business_margin' => 18.00],
            ['name' => 'Monitors', 'margin' => 10.00, 'business_margin' => 15.00],
            ['name' => 'Printers', 'margin' => 8.00, 'business_margin' => 12.00],
            ['name' => 'Networking', 'margin' => 20.00, 'business_margin' => 25.00],
            ['name' => 'Storage', 'margin' => 18.00, 'business_margin' => 22.00],
            ['name' => 'Memory', 'margin' => 25.00, 'business_margin' => 30.00],
            ['name' => 'Cables & Accessories', 'margin' => 35.00, 'business_margin' => 40.00],
            ['name' => 'Software', 'margin' => 5.00, 'business_margin' => 8.00],
            ['name' => 'Services', 'margin' => 0.00, 'business_margin' => 0.00]
        ];

        foreach ($stockGroups as $groupData) {
            StockGroup::firstOrCreate(['name' => $groupData['name']], $groupData);
        }

        // Create stock items
        $stockItems = [
            // Laptops
            [
                'name' => 'Dell Latitude 5520 15.6" i5-1135G7 8GB 256GB SSD',
                'group' => 'Laptops',
                'type' => 'stock',
                'price_excluding_vat' => 650.00,
                'retail' => 780.00,
                'quantity' => 5,
                'buffer' => 2
            ],
            [
                'name' => 'HP EliteBook 840 G8 14" i7-1165G7 16GB 512GB SSD',
                'group' => 'Laptops',
                'type' => 'stock',
                'price_excluding_vat' => 850.00,
                'retail' => 1020.00,
                'quantity' => 3,
                'buffer' => 1
            ],
            [
                'name' => 'Lenovo ThinkPad E15 15.6" i5-1135G7 8GB 256GB SSD',
                'group' => 'Laptops',
                'type' => 'stock',
                'price_excluding_vat' => 580.00,
                'retail' => 696.00,
                'quantity' => 7,
                'buffer' => 3
            ],
            
            // Desktop PCs
            [
                'name' => 'Dell OptiPlex 3090 SFF i5-11500 8GB 256GB SSD',
                'group' => 'Desktop PCs',
                'type' => 'stock',
                'price_excluding_vat' => 520.00,
                'retail' => 624.00,
                'quantity' => 4,
                'buffer' => 2
            ],
            [
                'name' => 'HP ProDesk 400 G7 MT i3-10100 4GB 1TB HDD',
                'group' => 'Desktop PCs',
                'type' => 'stock',
                'price_excluding_vat' => 380.00,
                'retail' => 456.00,
                'quantity' => 6,
                'buffer' => 2
            ],
            
            // Monitors
            [
                'name' => 'Dell P2422H 24" 1920x1080 IPS Monitor',
                'group' => 'Monitors',
                'type' => 'stock',
                'price_excluding_vat' => 180.00,
                'retail' => 216.00,
                'quantity' => 12,
                'buffer' => 5
            ],
            [
                'name' => 'Samsung F24T450FQU 24" 1920x1080 IPS Monitor',
                'group' => 'Monitors',
                'type' => 'stock',
                'price_excluding_vat' => 145.00,
                'retail' => 174.00,
                'quantity' => 8,
                'buffer' => 3
            ],
            
            // Printers
            [
                'name' => 'HP LaserJet Pro M404dn Monochrome Printer',
                'group' => 'Printers',
                'type' => 'stock',
                'price_excluding_vat' => 220.00,
                'retail' => 264.00,
                'quantity' => 3,
                'buffer' => 1
            ],
            [
                'name' => 'Canon PIXMA TS3350 All-in-One Inkjet Printer',
                'group' => 'Printers',
                'type' => 'stock',
                'price_excluding_vat' => 65.00,
                'retail' => 78.00,
                'quantity' => 10,
                'buffer' => 4
            ],
            
            // Memory
            [
                'name' => 'Crucial 8GB DDR4-3200 SODIMM Memory',
                'group' => 'Memory',
                'type' => 'stock',
                'price_excluding_vat' => 28.00,
                'retail' => 42.00,
                'quantity' => 25,
                'buffer' => 10
            ],
            [
                'name' => 'Kingston 16GB DDR4-2666 DIMM Memory',
                'group' => 'Memory',
                'type' => 'stock',
                'price_excluding_vat' => 55.00,
                'retail' => 82.50,
                'quantity' => 15,
                'buffer' => 8
            ],
            
            // Storage
            [
                'name' => 'Samsung 980 500GB NVMe M.2 SSD',
                'group' => 'Storage',
                'type' => 'stock',
                'price_excluding_vat' => 45.00,
                'retail' => 67.50,
                'quantity' => 20,
                'buffer' => 8
            ],
            [
                'name' => 'WD Blue 1TB 2.5" SATA SSD',
                'group' => 'Storage',
                'type' => 'stock',
                'price_excluding_vat' => 85.00,
                'retail' => 127.50,
                'quantity' => 12,
                'buffer' => 5
            ],
            
            // Services
            [
                'name' => 'Data Recovery Service - Standard',
                'group' => 'Services',
                'type' => 'service',
                'price_excluding_vat' => 150.00,
                'retail' => 150.00,
                'quantity' => 0,
                'unlimited' => 1
            ],
            [
                'name' => 'Virus Removal and System Cleanup',
                'group' => 'Services',
                'type' => 'service',
                'price_excluding_vat' => 75.00,
                'retail' => 75.00,
                'quantity' => 0,
                'unlimited' => 1
            ],
            [
                'name' => 'Hardware Diagnostic Service',
                'group' => 'Services',
                'type' => 'service',
                'price_excluding_vat' => 45.00,
                'retail' => 45.00,
                'quantity' => 0,
                'unlimited' => 1
            ]
        ];

        $suppliers = Supplier::all();
        $groups = StockGroup::all();

        foreach ($stockItems as $itemData) {
            $group = $groups->where('name', $itemData['group'])->first();
            unset($itemData['group']);
            
            Stock::firstOrCreate(
                ['name' => $itemData['name']],
                array_merge($itemData, [
                    'group_id' => $group->id,
                    'supplier_id' => $suppliers->random()->id,
                    'severity_id' => 2, // Medium severity
                    'approval_required' => $itemData['type'] === 'service' ? 0 : rand(0, 1),
                    'unlimited' => $itemData['unlimited'] ?? 0
                ])
            );
        }

        // Create invoices
        $this->createInvoices();

        $this->command->info('Created ' . Stock::count() . ' stock items across ' . StockGroup::count() . ' categories');
        $this->command->info('Created ' . Supplier::count() . ' suppliers');
        $this->command->info('Created ' . Invoice::count() . ' invoices with items');
    }

    private function createInvoices()
    {
        $clients = Client::all();
        $customers = Customer::all();
        $tasks = Task::all();
        $stockItems = Stock::all();

        // Create various types of invoices
        $invoiceTypes = ['sale', 'invoice', 'quote'];
        
        for ($i = 0; $i < 15; $i++) {
            $isCustomer = rand(0, 1);
            $client = $isCustomer ? $customers->random() : $clients->random();
            $type = $invoiceTypes[rand(0, 2)];
            
            $invoice = Invoice::create([
                'client_id' => $client->id,
                'client_type' => $isCustomer ? 'customer' : 'client',
                'type' => $type,
                'invoice_number' => $type === 'quote' ? null : 1000 + $i,
                'task_id' => rand(0, 1) ? $tasks->random()->id : null,
                'total_price' => 0, // Will be calculated from items
                'include_vat' => 1,
                'vat' => 20,
                'discount' => rand(0, 1) ? rand(5, 15) : 0,
                'invoice_date' => now()->subDays(rand(1, 60))->format('Y-m-d'),
                'invoiced_at' => $type !== 'quote' ? now()->subDays(rand(1, 30)) : null,
                'paid' => $type === 'sale' ? rand(0, 1) : 0,
                'paid_at' => null,
                'created_by' => 1,
                'updated_by' => 1,
                'created_at' => now()->subDays(rand(1, 90)),
            ]);

            // Add items to invoice
            $itemCount = rand(1, 5);
            $totalPrice = 0;

            for ($j = 0; $j < $itemCount; $j++) {
                $stock = $stockItems->random();
                $quantity = rand(1, 3);
                $price = $stock->retail;
                
                // Apply business margin for client invoices
                if (!$isCustomer && $stock->group) {
                    $businessMargin = $stock->group->business_margin / 100;
                    $price = $stock->price_excluding_vat * (1 + $businessMargin);
                }

                InvoiceItem::create([
                    'invoice_id' => $invoice->id,
                    'name' => $stock->name,
                    'type' => $stock->type,
                    'stock_id' => $stock->id,
                    'quantity' => $quantity,
                    'price_sold_exc' => $price,
                    'discount' => 0,
                    'created_by' => 1,
                    'updated_by' => 1
                ]);

                $totalPrice += $price * $quantity;
            }

            // Apply discount
            if ($invoice->discount > 0) {
                $totalPrice = $totalPrice * (1 - $invoice->discount / 100);
            }

            $invoice->update(['total_price' => $totalPrice]);

            // Set paid date for paid invoices
            if ($invoice->paid) {
                $invoice->update(['paid_at' => $invoice->invoiced_at->addDays(rand(1, 30))]);
            }
        }
    }
} 