<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Store;
use App\Models\RawMaterial;
use App\Models\CurrentStock;
use App\Models\StockMovement;
use Carbon\Carbon;

class StockDataSeeder extends Seeder
{
    /**
     * Run the database seeder.
     */
    public function run(): void
    {
        $this->command->info('Creating sample stock data...');

        try {
            $stores = Store::where('delete_flag', 0)->get();
            $rawMaterials = RawMaterial::where('delete_flag', 0)->get();

            if ($stores->isEmpty() || $rawMaterials->isEmpty()) {
                $this->command->warn('No stores or raw materials found. Please run master data seeders first.');
                return;
            }

            foreach ($stores as $store) {
                $this->command->info("Creating stock data for store: {$store->name}");
                
                foreach ($rawMaterials as $rm) {
                    // Generate random stock levels
                    $qtyUtuh = rand(0, 50);
                    $qtyPakai = rand(0, 1000) / 10; // 0 to 100.0
                    $conversionFactor = $rm->conversion_factor ?? 1;
                    $qtyTotalConverted = ($qtyUtuh * $conversionFactor) + $qtyPakai;

                    // Create current stock record
                    CurrentStock::updateOrCreate(
                        [
                            'store_id' => $store->id,
                            'raw_material_id' => $rm->id
                        ],
                        [
                            'qty_utuh' => $qtyUtuh,
                            'qty_pakai' => $qtyPakai,
                            'qty_total_converted' => $qtyTotalConverted,
                            'uom_utuh' => $rm->uom ?? 'PCS',
                            'uom_pakai' => $rm->uom_pakai ?? 'GR',
                            'conversion_factor' => $conversionFactor,
                            'last_updated_date' => Carbon::now()->subDays(rand(0, 7)),
                            'last_movement_time' => Carbon::now()->subHours(rand(1, 168)), // Last week
                            'last_updated_by' => 1,
                            'delete_flag' => false
                        ]
                    );

                    // Create some sample stock movements
                    $this->createSampleMovements($store->id, $rm->id, $qtyTotalConverted, $rm->uom_pakai ?? 'GR');
                }
            }

            $this->command->info('Sample stock data created successfully!');
            $this->command->info('Created stock records for:');
            $this->command->info('- ' . $stores->count() . ' stores');
            $this->command->info('- ' . $rawMaterials->count() . ' raw materials');
            $this->command->info('- ' . ($stores->count() * $rawMaterials->count()) . ' stock records');

        } catch (\Exception $e) {
            $this->command->error('Error creating stock data: ' . $e->getMessage());
        }
    }

    private function createSampleMovements($storeId, $rawMaterialId, $currentQty, $uom)
    {
        $movements = [
            [
                'type' => 'OPENING',
                'qty' => $currentQty * 0.8,
                'days_ago' => 30,
                'notes' => 'Opening stock balance'
            ],
            [
                'type' => 'IN',
                'qty' => rand(50, 200),
                'days_ago' => 15,
                'notes' => 'Stock receipt from supplier'
            ],
            [
                'type' => 'OUT',
                'qty' => rand(20, 80),
                'days_ago' => 10,
                'notes' => 'Production usage'
            ],
            [
                'type' => 'OUT',
                'qty' => rand(10, 50),
                'days_ago' => 5,
                'notes' => 'Daily consumption'
            ],
            [
                'type' => 'ADJUSTMENT',
                'qty' => $currentQty,
                'days_ago' => 1,
                'notes' => 'Stock adjustment from physical count'
            ]
        ];

        $runningQty = 0;
        foreach ($movements as $movement) {
            $movementDate = Carbon::now()->subDays($movement['days_ago']);
            
            switch ($movement['type']) {
                case 'OPENING':
                    $qtyBefore = 0;
                    $qtyAfter = $movement['qty'];
                    break;
                case 'IN':
                    $qtyBefore = $runningQty;
                    $qtyAfter = $qtyBefore + $movement['qty'];
                    break;
                case 'OUT':
                    $qtyBefore = $runningQty;
                    $qtyAfter = max(0, $qtyBefore - $movement['qty']);
                    break;
                case 'ADJUSTMENT':
                    $qtyBefore = $runningQty;
                    $qtyAfter = $movement['qty'];
                    break;
            }

            StockMovement::create([
                'store_id' => $storeId,
                'raw_material_id' => $rawMaterialId,
                'movement_type' => $movement['type'],
                'reference_type' => $movement['type'] === 'ADJUSTMENT' ? 'SO' : 'MANUAL',
                'reference_id' => null,
                'qty_before' => $qtyBefore,
                'qty_movement' => $movement['qty'],
                'qty_after' => $qtyAfter,
                'uom' => $uom,
                'notes' => $movement['notes'],
                'movement_date' => $movementDate->toDateString(),
                'movement_time' => $movementDate,
                'created_by' => 1,
                'delete_flag' => false
            ]);

            $runningQty = $qtyAfter;
        }
    }
}