<?php

namespace Database\Seeders;

use App\Models\Initiative;
use App\Models\InitiativeResult;
use App\Models\PerformanceCardResult;
use App\Models\User;
use Illuminate\Database\Seeder;

class InitiativeResultSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $user = User::first();
        $initiatives = Initiative::all();

        if ($initiatives->isEmpty()) {
            $this->command->warn('No initiatives found. Please run InitiativeSeeder first.');

            return;
        }

        $createdResults = [];

        foreach ($initiatives as $initiative) {
            // Create 1-2 results per initiative
            $resultCount = rand(1, 2);

            for ($i = 0; $i < $resultCount; $i++) {
                // Generate realistic quarterly data
                $baseExpected = fake()->numberBetween(50, 200);
                $variance = 0.2; // 20% variance

                $result = InitiativeResult::create([
                    'initiative_id' => $initiative->id,
                    'expected_q1' => $baseExpected,
                    'actual_q1' => $this->generateActualValue($baseExpected, $variance),
                    'expected_q2' => $baseExpected * 1.1, // 10% growth
                    'actual_q2' => $this->generateActualValue($baseExpected * 1.1, $variance),
                    'expected_q3' => $baseExpected * 1.2, // 20% growth
                    'actual_q3' => $this->generateActualValue($baseExpected * 1.2, $variance),
                    'expected_q4' => $baseExpected * 1.3, // 30% growth
                    'actual_q4' => $this->generateActualValue($baseExpected * 1.3, $variance),
                    'created_by' => $user->id,
                ]);

                // Optionally link to performance card results (if any exist)
                $performanceCardResults = PerformanceCardResult::inRandomOrder()->limit(rand(0, 2))->get();
                if ($performanceCardResults->count() > 0) {
                    $result->performanceCardResults()->attach($performanceCardResults->pluck('id'));
                }

                $createdResults[] = $result;
            }
        }

        $this->command->info('تم إنشاء '.count($createdResults).' نتيجة مبادرة لـ '.$initiatives->count().' مبادرة');
    }

    /**
     * Generate actual value with some variance from expected value
     */
    private function generateActualValue(float $expected, float $variance): float
    {
        $minVariance = 1 - $variance;
        $maxVariance = 1 + $variance;
        $multiplier = fake()->randomFloat(2, $minVariance, $maxVariance);

        return round($expected * $multiplier, 2);
    }
}
