<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\Models\Store;
use App\Models\RawMaterial;
use App\Models\StockOpname;
use App\Models\StockOpnameDetail;
use App\Models\ItemRequest;
use App\Models\ItemRequestDetail;
use App\Models\Forecast;

class AdditionalTestDataSeeder extends Seeder
{
    public function run()
    {
        DB::beginTransaction();
        
        try {
            // Create additional Stock Opname with different scenarios
            $stores = Store::all();
            $rawMaterials = RawMaterial::all();
            
            // Scenario 1: Stock Opname with low stock (need urgent ordering)
            $urgentSO = StockOpname::create([
                'store_id' => $stores[0]->id,
                'so_date' => Carbon::now()->subHours(2),
                'status' => 'Submitted',
                'notes' => 'Urgent stock check - low inventory detected',
                'delete_flag' => 0,
                'created_by' => 1,
            ]);

            foreach ($rawMaterials->take(5) as $rm) {
                StockOpnameDetail::create([
                    'so_id' => $urgentSO->id,
                    'raw_material_id' => $rm->id,
                    'qty_utuh' => rand(1, 5), // Very low stock
                    'qty_pakai' => rand(5, 15),
                    'qty_converted' => 0,
                    'qty_total' => 0,
                    'notes' => 'Critical low stock - urgent reorder needed',
                ]);
            }

            // Create SPB from urgent SO with high forecast variance
            $urgentSPB = ItemRequest::create([
                'store_id' => $urgentSO->store_id,
                'stock_opname_id' => $urgentSO->id,
                'request_type' => 'Additional',
                'request_date' => Carbon::now(),
                'delivery_date' => Carbon::now()->addDay(),
                'status' => 'Draft',
                'notes' => 'Urgent SPB due to critical low stock',
                'delete_flag' => 0,
                'created_by' => 1,
            ]);

            // Create SPB details with various forecast scenarios
            $currentMonth = date('n');
            $currentYear = date('Y');
            $forecasts = Forecast::where('store_id', $urgentSO->store_id)
                ->where('month', $currentMonth)
                ->where('year', $currentYear)
                ->get()->keyBy('raw_material_id');

            foreach ($urgentSO->details as $soDetail) {
                $forecast = $forecasts->get($soDetail->raw_material_id);
                $forecastQty = $forecast ? $forecast->forecast_qty : 0;
                
                // Create different scenarios
                $scenarios = [
                    'over_forecast_high' => $forecastQty * 1.5, // 50% over forecast
                    'over_forecast_low' => $forecastQty * 1.1,  // 10% over forecast
                    'under_forecast_high' => $forecastQty * 0.7, // 30% under forecast
                    'under_forecast_low' => $forecastQty * 0.9,  // 10% under forecast
                    'match_forecast' => $forecastQty, // Exact match
                ];
                
                $scenarioKeys = array_keys($scenarios);
                $randomScenario = $scenarioKeys[array_rand($scenarioKeys)];
                $requestedQty = $scenarios[$randomScenario];
                
                ItemRequestDetail::create([
                    'item_request_id' => $urgentSPB->id,
                    'raw_material_id' => $soDetail->raw_material_id,
                    'forecast_qty' => $forecastQty,
                    'so_qty' => $soDetail->qty_total,
                    'tsm_qty' => rand(80, 120),
                    'suggested_qty' => $requestedQty * 0.8,
                    'adjusted_qty' => $requestedQty,
                    'notes' => "Scenario: {$randomScenario} - Forecast: {$forecastQty}, Requested: {$requestedQty}",
                ]);
            }

            // Create a completed workflow (SO -> SPB -> DO -> CSV)
            $completedSO = StockOpname::create([
                'store_id' => $stores[1]->id,
                'so_date' => Carbon::now()->subDays(3),
                'status' => 'Submitted',
                'notes' => 'Regular weekly stock opname - completed workflow',
                'delete_flag' => 0,
                'created_by' => 1,
            ]);

            foreach ($rawMaterials->take(6) as $rm) {
                StockOpnameDetail::create([
                    'so_id' => $completedSO->id,
                    'raw_material_id' => $rm->id,
                    'qty_utuh' => rand(10, 25),
                    'qty_pakai' => rand(20, 40),
                    'qty_converted' => 0,
                    'qty_total' => 0,
                    'notes' => 'Regular stock count',
                ]);
            }

            $completedSPB = ItemRequest::create([
                'store_id' => $completedSO->store_id,
                'stock_opname_id' => $completedSO->id,
                'request_type' => 'Regular',
                'request_date' => Carbon::now()->subDays(2),
                'delivery_date' => Carbon::now()->subDay(),
                'status' => 'Approved',
                'notes' => 'Approved SPB - ready for delivery',
                'delete_flag' => 0,
                'created_by' => 1,
            ]);

            foreach ($completedSO->details as $soDetail) {
                $forecast = $forecasts->get($soDetail->raw_material_id);
                $forecastQty = $forecast ? $forecast->forecast_qty : rand(100, 300);
                
                ItemRequestDetail::create([
                    'item_request_id' => $completedSPB->id,
                    'raw_material_id' => $soDetail->raw_material_id,
                    'forecast_qty' => $forecastQty,
                    'so_qty' => $soDetail->qty_total,
                    'tsm_qty' => rand(80, 120),
                    'suggested_qty' => rand(50, 100),
                    'adjusted_qty' => rand(60, 110),
                    'notes' => 'Standard order quantity',
                ]);
            }

            // Approve completed SPB (no DO generation - will use CSV export instead)
            $completedSPB->update(['status' => 'Approved']);

            DB::commit();
            
            $this->command->info('Additional test data created successfully!');
            $this->command->info('Created scenarios:');
            $this->command->info('1. Urgent Stock Opname with critical low stock');
            $this->command->info('2. SPB with various forecast comparison scenarios');
            $this->command->info('3. Complete workflow: SO -> SPB (Approved) - ready for CSV export');
            
        } catch (\Exception $e) {
            DB::rollback();
            $this->command->error('Error creating additional test data: ' . $e->getMessage());
        }
    }
}