<?php

namespace Database\Seeders;

use App\Models\Association;
use App\Models\Center;
use App\Models\Department;
use App\Models\DonorFinancialPortfolio;
use App\Models\Initiative;
use App\Models\InitiativeOperationGoal;
use App\Models\InitiativeProject;
use App\Models\InitiativeResult;
use App\Models\Order;
use App\Models\OrderAgreement;
use App\Models\OrderFinance;
use App\Models\OrderRequirement;
use App\Models\PerformanceCard;
use App\Models\PerformanceCardResult;
use App\Models\PerformanceWallet;
use App\Models\ProjectCharter;
use App\Models\ProjectCharterDeliverable;
use App\Models\SekayaValue;
use App\Models\State;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class ComprehensiveSeeder extends Seeder
{
    /**
     * Run the comprehensive database seeds.
     */
    public function run(): void
    {
        $this->command->info('🚀 Starting comprehensive seeding...');

        DB::transaction(function () {
            // Phase 1: Enhanced Base Data
            $this->seedEnhancedUsers();
            $this->seedEnhancedAssociations();

            // Phase 2: Order Management Workflow
            $this->seedComprehensiveOrders();

            // Phase 3: Performance Management System
            $this->seedEnhancedPerformanceSystem();

            // Phase 4: Financial and Geographic Enhancements
            $this->seedFinancialData();

            // Phase 5: Testing States and Edge Cases
            $this->seedTestingStates();
        });

        $this->command->info('✅ Comprehensive seeding completed successfully!');
    }

    /**
     * Phase 1: Create users with various roles and permission levels
     */
    private function seedEnhancedUsers(): void
    {
        $this->command->info('📝 Seeding enhanced users...');

        // Super Admin
        User::factory()->create([
            'name' => 'Super Administrator',
            'email' => 'superadmin@sekaya.com',
            'password' => Hash::make('Pa$$w0rd!'),
            'association_id' => null,
        ]);

        // Project Managers
        for ($i = 1; $i <= 3; $i++) {
            User::factory()->create([
                'name' => "Project Manager {$i}",
                'email' => "pm{$i}@sekaya.com",
                'password' => Hash::make('Pa$$w0rd!'),
                'association_id' => null,
            ]);
        }

        // Financial Officers
        for ($i = 1; $i <= 2; $i++) {
            User::factory()->create([
                'name' => "Financial Officer {$i}",
                'email' => "finance{$i}@sekaya.com",
                'password' => Hash::make('Pa$$w0rd!'),
                'association_id' => null,
            ]);
        }

        // Technical Reviewers
        for ($i = 1; $i <= 2; $i++) {
            User::factory()->create([
                'name' => "Technical Reviewer {$i}",
                'email' => "tech{$i}@sekaya.com",
                'password' => Hash::make('Pa$$w0rd!'),
                'association_id' => null,
            ]);
        }
    }

    /**
     * Create associations with complete profiles and users
     */
    private function seedEnhancedAssociations(): void
    {
        $this->command->info('🏢 Seeding enhanced associations...');

        $associationData = [
            [
                'name' => 'Northern Water Development Association',
                'license_number' => 'NWDA-2024-001',
                'representative_name' => 'Ahmed Al-Rashid',
                'city' => 'Hail',
                'region' => 'Northern',
                'admin_email' => 'admin@nwda.com',
            ],
            [
                'name' => 'Eastern Province Water Solutions',
                'license_number' => 'EPWS-2024-002',
                'representative_name' => 'Fatima Al-Zahra',
                'city' => 'Dammam',
                'region' => 'Eastern',
                'admin_email' => 'admin@epws.com',
            ],
            [
                'name' => 'Western Coast Water Initiative',
                'license_number' => 'WCWI-2024-003',
                'representative_name' => 'Mohammed Al-Harbi',
                'city' => 'Jeddah',
                'region' => 'Western',
                'admin_email' => 'admin@wcwi.com',
            ],
            [
                'name' => 'Southern Highlands Water Council',
                'license_number' => 'SHWC-2024-004',
                'representative_name' => 'Sara Al-Qahtani',
                'city' => 'Abha',
                'region' => 'Southern',
                'admin_email' => 'admin@shwc.com',
            ],
            [
                'name' => 'Central Valley Water Cooperative',
                'license_number' => 'CVWC-2024-005',
                'representative_name' => 'Omar Al-Mansouri',
                'city' => 'Riyadh',
                'region' => 'Central',
                'admin_email' => 'admin@cvwc.com',
            ],
        ];

        foreach ($associationData as $data) {
            $association = Association::create([
                'name' => $data['name'],
                'license_number' => $data['license_number'],
                'license_expiration_date' => now()->addYears(2),
                'representative_full_name' => $data['representative_name'],
                'representative_position' => fake()->randomElement(['President', 'Executive Director', 'Chairman', 'General Manager']),
                'phone_number' => '+966'.fake()->numerify('#########'),
                'secondary_phone_number' => '+966'.fake()->numerify('#########'),
                'email' => fake()->unique()->safeEmail(),
                'city' => $data['city'],
                'postal_code' => fake()->postcode(),
                'neighborhood' => fake()->streetName(),
                'building_number' => fake()->buildingNumber(),
                'street' => fake()->streetAddress(),
                'branch_number' => fake()->numberBetween(1, 5),
                'lat' => fake()->latitude(15, 35),
                'lng' => fake()->longitude(30, 55),
                'iban' => 'SA'.fake()->numerify('####################'),
                'bank_name' => fake()->randomElement(['Saudi National Bank', 'Al Rajhi Bank', 'Riyad Bank', 'SABB']),
                'account_holder_name' => $data['name'],
                'is_verified' => fake()->boolean(80),
                'is_locked' => fake()->boolean(5),
            ]);

            // Create association admin
            User::factory()->create([
                'name' => $data['representative_name'],
                'email' => $data['admin_email'],
                'password' => Hash::make('Pa$$w0rd!'),
                'association_id' => $association->id,
            ]);

            // Create additional association staff
            for ($i = 1; $i <= fake()->numberBetween(2, 5); $i++) {
                User::factory()->create([
                    'name' => fake()->name(),
                    'email' => fake()->unique()->safeEmail(),
                    'password' => Hash::make('Pa$$w0rd!'),
                    'association_id' => $association->id,
                ]);
            }
        }
    }

    /**
     * Phase 2: Create orders in all workflow states with requirements and finances
     */
    private function seedComprehensiveOrders(): void
    {
        $this->command->info('📋 Seeding comprehensive orders...');

        $associations = Association::all();
        $states = State::with('cities.centers')->get();
        $sekayaValues = SekayaValue::where('type', SekayaValue::TYPE_ORDER_IMPACT_REASONS)->get();
        $donorPortfolios = DonorFinancialPortfolio::all();

        $orderStatuses = [
            Order::STATUS_CREATED,
            Order::STATUS_PENDING_RECOMMENDATION,
            Order::STATUS_RECOMMENDED,
            Order::STATUS_TECHNICAL_FINANCIAL_REQUESTED,
            Order::STATUS_TECHNICAL_FINANCIAL_APPROVED,
            Order::STATUS_PROJECT_MANAGER_APPROVED,
            Order::STATUS_CLASSIFICATION,
            Order::STATUS_AGREEMENT,
            Order::STATUS_CEO_APPROVED,
            Order::STATUS_LAUNCHED,
            Order::STATUS_REJECTED,
        ];

        $orderTypes = [
            Order::TYPE_STATION,
            Order::TYPE_TANKER,
            Order::TYPE_DOMESTIC_STORAGE_TANK,
            Order::TYPE_CENTRAL_STORAGE_TANK,
            Order::TYPE_MAINTENANCE_STATION,
            Order::TYPE_MAINTENANCE_TANKER,
            Order::TYPE_MICRO_NETWORK,
            Order::TYPE_WELL_DRILLING,
            Order::TYPE_RAINWATER_STORAGE,
            Order::TYPE_HOME_FILTERS,
            Order::TYPE_WATER_BOTTLES,
            Order::TYPE_COOLERS,
        ];

        foreach ($associations as $association) {
            $associationUsers = User::where('association_id', $association->id)->get();
            if ($associationUsers->isEmpty()) {
                continue;
            }

            // Create 8-15 orders per association in various states
            $orderCount = fake()->numberBetween(8, 15);

            for ($i = 0; $i < $orderCount; $i++) {
                $state = $states->random();
                $city = $state->cities->random();
                $center = $city->centers->isNotEmpty() ? $city->centers->random() : null;

                $order = Order::create([
                    'association_id' => $association->id,
                    'type' => fake()->randomElement($orderTypes),
                    'status' => fake()->randomElement($orderStatuses),
                    'state_id' => $state->id,
                    'city_id' => $city->id,
                    'lat' => fake()->latitude(15, 35),
                    'lng' => fake()->longitude(30, 55),
                    'number_of_families' => fake()->numberBetween(50, 500),
                    'water_source' => json_encode(fake()->randomElements(['government', 'private', 'charity'], fake()->numberBetween(1, 3))),
                    'water_distance' => fake()->randomFloat(2, 0.5, 50),
                    'order_justifications' => fake()->paragraph(3),
                    'order_description' => fake()->paragraph(5),
                    'created_by' => $associationUsers->random()->id,
                ]);

                // Associate with centers if available
                if ($center) {
                    $order->centers()->attach($center->id);
                }

                // Add development impacts
                if ($sekayaValues->isNotEmpty()) {
                    $order->developmentImpacts()->attach(
                        $sekayaValues->random(fake()->numberBetween(2, 4))->pluck('id')
                    );
                }

                // Add order requirements for orders beyond CREATED status
                if ($order->status !== Order::STATUS_CREATED) {
                    $this->createOrderRequirements($order);
                }

                // Add financial data for orders with financial approval
                if (in_array($order->status, [
                    Order::STATUS_TECHNICAL_FINANCIAL_APPROVED,
                    Order::STATUS_PROJECT_MANAGER_APPROVED,
                    Order::STATUS_CLASSIFICATION,
                    Order::STATUS_AGREEMENT,
                    Order::STATUS_CEO_APPROVED,
                    Order::STATUS_LAUNCHED,
                ])) {
                    $this->createOrderFinances($order);
                }

                // Add agreement for orders in agreement status or beyond
                if (in_array($order->status, [
                    Order::STATUS_AGREEMENT,
                    Order::STATUS_CEO_APPROVED,
                    Order::STATUS_LAUNCHED,
                ])) {
                    $this->createOrderAgreement($order);
                }

                // Allocate donor funding for approved orders
                if (in_array($order->status, [
                    Order::STATUS_CEO_APPROVED,
                    Order::STATUS_LAUNCHED,
                ]) && $donorPortfolios->isNotEmpty()) {
                    $this->allocateDonorFunding($order, $donorPortfolios);
                }
            }
        }
    }

    /**
     * Create order requirements for an order
     */
    private function createOrderRequirements(Order $order): void
    {
        $requirementTypes = [
            'Technical Specifications',
            'Environmental Impact Assessment',
            'Site Survey Report',
            'Water Quality Analysis',
            'Community Approval Letter',
            'Land Ownership Certificate',
            'Construction Permits',
            'Safety Compliance Report',
        ];

        $requirementCount = fake()->numberBetween(3, 6);
        $selectedTypes = fake()->randomElements($requirementTypes, $requirementCount);

        foreach ($selectedTypes as $type) {
            OrderRequirement::create([
                'order_id' => $order->id,
                'name' => $type,
                'status' => fake()->randomElement([
                    OrderRequirement::STATUS_PENDING,
                    OrderRequirement::STATUS_ACCEPTED,
                    OrderRequirement::STATUS_REJECTED,
                    OrderRequirement::STATUS_ASK_MODIFICATION,
                ]),
            ]);
        }
    }

    /**
     * Create financial data for an order
     */
    private function createOrderFinances(Order $order): void
    {
        $requirements = $order->requirements;

        foreach ($requirements as $requirement) {
            OrderFinance::create([
                'order_id' => $order->id,
                'order_requirement_id' => $requirement->id,
                'count' => fake()->numberBetween(1, 10),
                'capacity' => fake()->randomElement(['500L', '1000L', '2000L', '5000L', '10000L']),
                'execution_duration' => fake()->numberBetween(30, 180),
                'company_name' => fake()->company(),
                'offer_price' => fake()->randomFloat(2, 10000, 500000),
                'additional_fees' => fake()->randomFloat(2, 1000, 25000),
                'operation_cost_percentage' => fake()->randomFloat(2, 5, 15),
                'operation_cost' => fake()->randomFloat(2, 5000, 50000),
            ]);
        }
    }

    /**
     * Create order agreement
     */
    private function createOrderAgreement(Order $order): void
    {
        $totalValue = $order->finance ? ($order->finance->offer_price + $order->finance->additional_fees) : 0;

        OrderAgreement::create([
            'order_id' => $order->id,
            'contract_number' => 'CNT-'.date('Y').'-'.str_pad($order->id, 4, '0', STR_PAD_LEFT),
            'total_contract_value' => $totalValue,
            'start_date' => fake()->dateTimeBetween('now', '+30 days'),
        ]);
    }

    /**
     * Allocate donor funding to an order
     */
    private function allocateDonorFunding(Order $order, $donorPortfolios): void
    {
        $agreement = $order->agreement;
        if (! $agreement) {
            return;
        }

        $totalValue = $agreement->total_contract_value;
        $remainingValue = $totalValue;

        // Allocate from 1-3 donor portfolios
        $portfolioCount = fake()->numberBetween(1, min(3, $donorPortfolios->count()));
        $selectedPortfolios = $donorPortfolios->random($portfolioCount);

        foreach ($selectedPortfolios as $index => $portfolio) {
            if ($remainingValue <= 0) {
                break;
            }

            $isLast = ($index === $portfolioCount - 1);
            $allocation = $isLast ? $remainingValue : fake()->randomFloat(2, $remainingValue * 0.3, $remainingValue * 0.7);

            $order->donorFinancialPortfolios()->attach($portfolio->id, [
                'allocated_amount' => $allocation,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            $remainingValue -= $allocation;
        }
    }

    /**
     * Phase 3: Create comprehensive performance management system
     */
    private function seedEnhancedPerformanceSystem(): void
    {
        $this->command->info('🎯 Seeding enhanced performance system...');

        // Ensure departments exist first
        $departmentNames = [
            'Water Quality Management' => 'Responsible for monitoring and improving water quality standards',
            'Infrastructure Development' => 'Manages construction and maintenance of water infrastructure',
            'Community Engagement' => 'Facilitates community involvement and education programs',
            'Strategic Planning' => 'Develops long-term strategies and investment plans',
            'Emergency Response' => 'Handles crisis management and disaster relief operations',
        ];

        foreach ($departmentNames as $name => $description) {
            Department::firstOrCreate(
                ['name' => $name],
                ['description' => $description]
            );
        }

        $departments = Department::all();
        $users = User::whereNull('association_id')->get(); // Internal users only
        $productValues = SekayaValue::where('type', SekayaValue::TYPE_PERFORMANCE_CARD_PRODUCT)->get();

        foreach ($departments as $department) {
            // Create 2-4 performance cards per department
            $cardCount = fake()->numberBetween(2, 4);

            for ($i = 0; $i < $cardCount; $i++) {
                $performanceCard = $this->createEnhancedPerformanceCard($department, $users, $productValues);
                $this->createPerformanceWallet($performanceCard, $users);
                $this->createInitiativesWithProjects($performanceCard);
            }
        }
    }

    /**
     * Create enhanced performance card with full data
     */
    private function createEnhancedPerformanceCard(Department $department, $users, $productValues): PerformanceCard
    {
        $performanceCard = PerformanceCard::create([
            'department_id' => $department->id,
            'project_manner' => fake()->randomElement([
                PerformanceCard::PROJECT_MANNER_DEVELOPMENTAL,
                PerformanceCard::PROJECT_MANNER_SUPPORT,
                PerformanceCard::PROJECT_MANNER_EMPOWERMENT,
                PerformanceCard::PROJECT_MANNER_INVESTMENT,
            ]),
            'goal' => fake()->paragraphs(2, true),
        ]);

        // Add results
        $resultCount = fake()->numberBetween(3, 8);
        for ($i = 0; $i < $resultCount; $i++) {
            PerformanceCardResult::create([
                'performance_card_id' => $performanceCard->id,
                'result' => fake()->sentence(fake()->numberBetween(8, 15)),
            ]);
        }

        // Assign products
        if ($productValues->isNotEmpty()) {
            $productCount = fake()->numberBetween(1, 5);
            $selectedProducts = $productValues->random(min($productCount, $productValues->count()));
            $performanceCard->products()->attach($selectedProducts->pluck('id'));
        }

        // Assign users
        if ($users->isNotEmpty()) {
            $assigneeCount = fake()->numberBetween(1, 4);
            $selectedUsers = $users->random(min($assigneeCount, $users->count()));
            $performanceCard->assignees()->attach($selectedUsers->pluck('id'));
        }

        return $performanceCard;
    }

    /**
     * Create performance wallet for a card
     */
    private function createPerformanceWallet(PerformanceCard $performanceCard, $users): PerformanceWallet
    {
        $startDate = fake()->dateTimeBetween('-6 months', 'now');
        $endDate = fake()->dateTimeBetween($startDate, '+1 year');

        return PerformanceWallet::create([
            'name' => fake()->sentence(3).' Wallet',
            'start_date' => $startDate,
            'expected_end_date' => $endDate,
            'description' => fake()->paragraphs(2, true),
            'performance_card_id' => $performanceCard->id,
            'created_by' => $users->isNotEmpty() ? $users->random()->id : 1,
        ]);
    }

    /**
     * Create initiatives with complete project hierarchies
     */
    private function createInitiativesWithProjects(PerformanceCard $performanceCard): void
    {
        $wallet = $performanceCard->wallet()->first();
        if (! $wallet) {
            return;
        }

        $users = User::whereNull('association_id')->get();
        $productValues = SekayaValue::where('type', SekayaValue::TYPE_PERFORMANCE_CARD_PRODUCT)->get();

        // Create 2-5 initiatives per wallet
        $initiativeCount = fake()->numberBetween(2, 5);

        for ($i = 0; $i < $initiativeCount; $i++) {
            $initiative = $this->createEnhancedInitiative($wallet, $users, $productValues);
            $this->createInitiativeProjects($initiative);
            $this->createOperationGoals($initiative);
            $this->createInitiativeResults($initiative, $performanceCard);
        }
    }

    /**
     * Create enhanced initiative with full data
     */
    private function createEnhancedInitiative(PerformanceWallet $wallet, $users, $productValues): Initiative
    {
        // Safely generate dates with fallbacks
        try {
            $startDate = fake()->dateTimeBetween($wallet->start_date, $wallet->expected_end_date);
        } catch (\Exception $e) {
            $startDate = $wallet->start_date;
        }

        try {
            $endDate = fake()->dateTimeBetween($startDate, $wallet->expected_end_date);
        } catch (\Exception $e) {
            $endDate = $wallet->expected_end_date;
        }

        $initiative = Initiative::create([
            'name' => fake()->sentence(4),
            'start_date' => $startDate,
            'expected_end_date' => $endDate,
            'description' => fake()->paragraphs(3, true),
            'expected_cost' => fake()->randomFloat(2, 50000, 500000),
            'emergency_reserve' => fake()->randomFloat(2, 5000, 50000),
            'performance_wallet_id' => $wallet->id,
            'created_by' => $users->isNotEmpty() ? $users->random()->id : 1,
        ]);

        // Assign products
        if ($productValues->isNotEmpty()) {
            $productCount = fake()->numberBetween(1, 3);
            $selectedProducts = $productValues->random(min($productCount, $productValues->count()));
            $initiative->products()->attach($selectedProducts->pluck('id'));
        }

        return $initiative;
    }

    /**
     * Create initiative projects with charters
     */
    private function createInitiativeProjects(Initiative $initiative): void
    {
        $projectCount = fake()->numberBetween(2, 4);

        // Generate weights that sum to exactly 100
        $weights = [];
        $totalWeight = 100;

        // Generate random weights for all but the last project
        for ($i = 0; $i < $projectCount - 1; $i++) {
            $remainingProjects = $projectCount - $i;
            $maxWeight = min(50, $totalWeight - (($remainingProjects - 1) * 10)); // Leave at least 10% for each remaining project
            $minWeight = max(10, $totalWeight - (($remainingProjects - 1) * 50)); // Use at least 10%

            $weight = fake()->numberBetween($minWeight, $maxWeight);
            $weights[] = $weight;
            $totalWeight -= $weight;
        }

        // Last project gets exactly the remaining weight
        $weights[] = $totalWeight;

        // Create projects with calculated weights
        for ($i = 0; $i < $projectCount; $i++) {
            $project = InitiativeProject::create([
                'name' => fake()->sentence(3),
                'weight' => $weights[$i],
                'initiative_id' => $initiative->id,
            ]);

            // Create project charter for some projects
            if (fake()->boolean(70)) {
                $this->createProjectCharter($project);
            }
        }
    }

    /**
     * Create project charter with deliverables
     */
    private function createProjectCharter(InitiativeProject $project): void
    {
        // Safely generate dates with fallbacks
        try {
            $startDate = fake()->dateTimeBetween($project->initiative->start_date, $project->initiative->expected_end_date);
        } catch (\Exception $e) {
            $startDate = $project->initiative->start_date;
        }

        try {
            $endDate = fake()->dateTimeBetween($startDate, $project->initiative->expected_end_date);
        } catch (\Exception $e) {
            $endDate = $project->initiative->expected_end_date;
        }

        $charter = ProjectCharter::create([
            'name' => $project->name.' Charter',
            'description' => fake()->paragraphs(2, true),
            'start_date' => $startDate,
            'expected_end_date' => $endDate,
            'estimated_cost' => fake()->randomFloat(2, 10000, 100000),
            'total_cost' => fake()->randomFloat(2, 10000, 100000),
            'status' => fake()->randomElement(['draft', 'awaiting_approval', 'approved', 'rejected']),
            'initiative_project_id' => $project->id,
        ]);

        // Create deliverables
        $deliverableCount = fake()->numberBetween(2, 5);
        $totalWeight = 100;
        $remainingWeight = $totalWeight;

        for ($i = 0; $i < $deliverableCount; $i++) {
            $isLast = ($i === $deliverableCount - 1);
            $weight = $isLast ? $remainingWeight : fake()->randomFloat(2, 10, min(40, $remainingWeight - (($deliverableCount - $i - 1) * 10)));
            $remainingWeight -= $weight;

            ProjectCharterDeliverable::create([
                'name' => fake()->sentence(2),
                'description' => fake()->paragraph(),
                'expected_delivery_date' => fake()->dateTimeBetween($charter->start_date, $charter->expected_end_date),
                'weight' => $weight,
                'payment_number' => fake()->boolean(60) ? fake()->numerify('PAY-####') : null,
                'project_charter_id' => $charter->id,
            ]);
        }
    }

    /**
     * Create operation goals for initiative
     */
    private function createOperationGoals(Initiative $initiative): void
    {
        $goalCount = fake()->numberBetween(3, 8);

        for ($i = 0; $i < $goalCount; $i++) {
            InitiativeOperationGoal::create([
                'name' => fake()->sentence(4),
                'performance_criteria' => fake()->paragraph(),
                'target' => fake()->sentence(2),
                'actual' => fake()->boolean(60) ? fake()->sentence(2) : null,
                'initiative_id' => $initiative->id,
            ]);
        }
    }

    /**
     * Create initiative results with quarterly data
     */
    private function createInitiativeResults(Initiative $initiative, PerformanceCard $performanceCard): void
    {
        $resultCount = fake()->numberBetween(2, 4);
        $performanceCardResults = $performanceCard->results;

        for ($i = 0; $i < $resultCount; $i++) {
            $result = InitiativeResult::create([
                'initiative_id' => $initiative->id,
                'expected_q1' => fake()->randomFloat(2, 1000, 10000),
                'actual_q1' => fake()->randomFloat(2, 800, 12000),
                'expected_q2' => fake()->randomFloat(2, 1000, 10000),
                'actual_q2' => fake()->randomFloat(2, 800, 12000),
                'expected_q3' => fake()->randomFloat(2, 1000, 10000),
                'actual_q3' => fake()->boolean(70) ? fake()->randomFloat(2, 800, 12000) : null,
                'expected_q4' => fake()->randomFloat(2, 1000, 10000),
                'actual_q4' => fake()->boolean(40) ? fake()->randomFloat(2, 800, 12000) : null,
            ]);

            // Link to performance card results
            if ($performanceCardResults->isNotEmpty()) {
                $linkedResultsCount = fake()->numberBetween(1, min(3, $performanceCardResults->count()));
                $linkedResults = $performanceCardResults->random($linkedResultsCount);
                $result->performanceCardResults()->attach($linkedResults->pluck('id'));
            }
        }
    }

    /**
     * Phase 4: Enhanced financial and geographic data
     */
    private function seedFinancialData(): void
    {
        $this->command->info('💰 Seeding financial data...');

        // Create additional donor portfolios
        $additionalPortfolios = [
            ['name' => 'Humanitarian Water Relief Fund', 'balance' => 3000000.00],
            ['name' => 'Infrastructure Development Grant', 'balance' => 1500000.00],
            ['name' => 'Emergency Response Portfolio', 'balance' => 800000.00],
            ['name' => 'Community Development Fund', 'balance' => 2200000.00],
            ['name' => 'Sustainable Water Solutions Grant', 'balance' => 1800000.00],
        ];

        foreach ($additionalPortfolios as $portfolioData) {
            DonorFinancialPortfolio::create($portfolioData);
        }

        // Update center data with realistic family counts
        $centers = Center::all();
        foreach ($centers as $center) {
            if ($center->families_count === 0) {
                $center->update([
                    'families_count' => fake()->numberBetween(25, 800),
                ]);
            }
        }
    }

    /**
     * Phase 5: Create testing states and edge cases
     */
    private function seedTestingStates(): void
    {
        $this->command->info('🧪 Seeding testing states...');

        // Create test scenarios for specific workflows
        $this->createRejectedOrderScenario();
        $this->createHighComplexityOrderScenario();
        $this->createMultiPortfolioFundingScenario();
        $this->createDelayedProjectScenario();
        $this->createOverBudgetScenario();
    }

    /**
     * Create a rejected order scenario for testing
     */
    private function createRejectedOrderScenario(): void
    {
        $association = Association::first();
        $user = User::where('association_id', $association->id)->first();
        $state = State::with('cities')->first();
        $city = $state->cities->first();

        $order = Order::create([
            'association_id' => $association->id,
            'type' => Order::TYPE_STATION,
            'status' => Order::STATUS_REJECTED,
            'state_id' => $state->id,
            'city_id' => $city->id,
            'lat' => fake()->latitude(15, 35),
            'lng' => fake()->longitude(30, 55),
            'number_of_families' => 200,
            'water_source' => json_encode(['private']),
            'water_distance' => 15.5,
            'order_justifications' => 'Technical feasibility concerns and environmental impact issues.',
            'order_description' => 'This order was rejected due to multiple technical and environmental constraints.',
            'created_by' => $user->id,
        ]);

        // Add requirements with rejected status
        OrderRequirement::create([
            'order_id' => $order->id,
            'name' => 'Environmental Impact Assessment',
            'status' => OrderRequirement::STATUS_REJECTED,
        ]);
    }

    /**
     * Create high complexity order with many requirements
     */
    private function createHighComplexityOrderScenario(): void
    {
        $association = Association::skip(1)->first();
        $user = User::where('association_id', $association->id)->first();
        $state = State::with('cities')->skip(1)->first();
        $city = $state->cities->first();

        $order = Order::create([
            'association_id' => $association->id,
            'type' => Order::TYPE_CENTRAL_STORAGE_TANK,
            'status' => Order::STATUS_TECHNICAL_FINANCIAL_APPROVED,
            'state_id' => $state->id,
            'city_id' => $city->id,
            'lat' => fake()->latitude(15, 35),
            'lng' => fake()->longitude(30, 55),
            'number_of_families' => 1200,
            'water_source' => json_encode(['government', 'private', 'charity']),
            'water_distance' => 45.2,
            'order_justifications' => 'Large scale infrastructure project to serve multiple communities.',
            'order_description' => 'Complex central storage tank system with multiple distribution points.',
            'created_by' => $user->id,
        ]);

        // Add multiple requirements in various states
        $complexRequirements = [
            ['name' => 'Detailed Engineering Survey', 'status' => OrderRequirement::STATUS_ACCEPTED],
            ['name' => 'Multi-Phase Environmental Assessment', 'status' => OrderRequirement::STATUS_ACCEPTED],
            ['name' => 'Community Stakeholder Agreements', 'status' => OrderRequirement::STATUS_PENDING],
            ['name' => 'Advanced Water Quality Testing', 'status' => OrderRequirement::STATUS_ACCEPTED],
            ['name' => 'Infrastructure Integration Plan', 'status' => OrderRequirement::STATUS_ASK_MODIFICATION],
            ['name' => 'Long-term Maintenance Strategy', 'status' => OrderRequirement::STATUS_ACCEPTED],
            ['name' => 'Financial Sustainability Analysis', 'status' => OrderRequirement::STATUS_ACCEPTED],
        ];

        foreach ($complexRequirements as $req) {
            $requirement = OrderRequirement::create([
                'order_id' => $order->id,
                'name' => $req['name'],
                'status' => $req['status'],
            ]);

            // Add financial data for accepted requirements
            if ($req['status'] === OrderRequirement::STATUS_ACCEPTED) {
                OrderFinance::create([
                    'order_id' => $order->id,
                    'order_requirement_id' => $requirement->id,
                    'count' => fake()->numberBetween(1, 5),
                    'capacity' => '50000L',
                    'execution_duration' => fake()->numberBetween(90, 180),
                    'company_name' => fake()->company().' Engineering',
                    'offer_price' => fake()->randomFloat(2, 100000, 800000),
                    'additional_fees' => fake()->randomFloat(2, 10000, 80000),
                    'operation_cost_percentage' => fake()->randomFloat(2, 8, 12),
                    'operation_cost' => fake()->randomFloat(2, 20000, 100000),
                ]);
            }
        }
    }

    /**
     * Create multi-portfolio funding scenario
     */
    private function createMultiPortfolioFundingScenario(): void
    {
        $association = Association::skip(2)->first();
        $user = User::where('association_id', $association->id)->first();
        $state = State::with('cities')->skip(2)->first();
        $city = $state->cities->first();

        $order = Order::create([
            'association_id' => $association->id,
            'type' => Order::TYPE_MICRO_NETWORK,
            'status' => Order::STATUS_LAUNCHED,
            'state_id' => $state->id,
            'city_id' => $city->id,
            'lat' => fake()->latitude(15, 35),
            'lng' => fake()->longitude(30, 55),
            'number_of_families' => 350,
            'water_source' => json_encode(['government', 'charity']),
            'water_distance' => 8.3,
            'order_justifications' => 'Multi-funded community water network project.',
            'order_description' => 'Innovative micro-network funded by multiple donor portfolios.',
            'created_by' => $user->id,
        ]);

        // Add agreement
        $agreement = OrderAgreement::create([
            'order_id' => $order->id,
            'contract_number' => 'CNT-MULTI-2024-001',
            'total_contract_value' => 450000.00,
            'start_date' => now()->subDays(30),
        ]);

        // Allocate funding from multiple portfolios
        $portfolios = DonorFinancialPortfolio::take(4)->get();
        $allocations = [200000, 150000, 70000, 30000]; // Total: 450000

        foreach ($portfolios as $index => $portfolio) {
            $order->donorFinancialPortfolios()->attach($portfolio->id, [
                'allocated_amount' => $allocations[$index],
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    }

    /**
     * Create delayed project scenario
     */
    private function createDelayedProjectScenario(): void
    {
        $department = Department::first();
        $users = User::whereNull('association_id')->get();

        $performanceCard = PerformanceCard::create([
            'department_id' => $department->id,
            'project_manner' => PerformanceCard::PROJECT_MANNER_DEVELOPMENTAL,
            'goal' => 'Delayed infrastructure development project with multiple challenges.',
        ]);

        $wallet = PerformanceWallet::create([
            'name' => 'Delayed Project Wallet',
            'start_date' => now()->subMonths(8),
            'expected_end_date' => now()->subMonths(2), // Already passed
            'description' => 'Project experiencing significant delays.',
            'performance_card_id' => $performanceCard->id,
            'created_by' => $users->isNotEmpty() ? $users->random()->id : 1,
        ]);

        $initiative = Initiative::create([
            'name' => 'Delayed Infrastructure Initiative',
            'start_date' => now()->subMonths(7),
            'expected_end_date' => now()->subMonths(1), // Already passed
            'description' => 'Initiative experiencing delays due to external factors.',
            'expected_cost' => 200000.00,
            'emergency_reserve' => 30000.00,
            'performance_wallet_id' => $wallet->id,
            'created_by' => $users->isNotEmpty() ? $users->random()->id : 1,
        ]);

        // Create projects with low completion rates
        for ($i = 0; $i < 3; $i++) {
            InitiativeProject::create([
                'name' => 'Delayed Project Component '.($i + 1),
                'weight' => 33.33,
                'initiative_id' => $initiative->id,
            ]);
        }
    }

    /**
     * Create over-budget scenario
     */
    private function createOverBudgetScenario(): void
    {
        $department = Department::skip(1)->first();
        $users = User::whereNull('association_id')->get();

        $performanceCard = PerformanceCard::create([
            'department_id' => $department->id,
            'project_manner' => PerformanceCard::PROJECT_MANNER_INVESTMENT,
            'goal' => 'High-investment project exceeding budget constraints.',
        ]);

        $wallet = PerformanceWallet::create([
            'name' => 'Over-Budget Investment Wallet',
            'start_date' => now()->subMonths(3),
            'expected_end_date' => now()->addMonths(6),
            'description' => 'Investment project experiencing budget overruns.',
            'performance_card_id' => $performanceCard->id,
            'created_by' => $users->isNotEmpty() ? $users->random()->id : 1,
        ]);

        $initiative = Initiative::create([
            'name' => 'High-Cost Infrastructure Initiative',
            'start_date' => now()->subMonths(2),
            'expected_end_date' => now()->addMonths(4),
            'description' => 'Initiative with significant budget overruns.',
            'expected_cost' => 300000.00,
            'emergency_reserve' => 45000.00, // High emergency reserve
            'performance_wallet_id' => $wallet->id,
            'created_by' => $users->isNotEmpty() ? $users->random()->id : 1,
        ]);

        // Create results showing budget concerns
        InitiativeResult::create([
            'initiative_id' => $initiative->id,
            'expected_q1' => 75000.00,
            'actual_q1' => 92000.00, // Over budget
            'expected_q2' => 75000.00,
            'actual_q2' => 88000.00, // Over budget
            'expected_q3' => 75000.00,
            'actual_q3' => null, // Pending
            'expected_q4' => 75000.00,
            'actual_q4' => null, // Pending
        ]);
    }
}
