<?php

namespace Database\Seeders;

use App\Enums\ProjectCharterState;
use App\Models\InitiativeProject;
use App\Models\Org;
use App\Models\ProjectCharter;
use App\Models\User;
use Illuminate\Database\Seeder;

class ProjectCharterSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $org = Org::first() ?? Org::create(['name' => 'مؤسسة سدو']);
        $user = User::first();
        $initiativeProjects = InitiativeProject::all();

        if ($initiativeProjects->isEmpty()) {
            $this->command->warn('لم يتم العثور على مشاريع مبادرة. يرجى تشغيل InitiativeProjectSeeder أولاً.');

            return;
        }

        // We'll create charters for about 60% of the projects (some projects might not have charters yet)
        $projectsWithoutCharters = $initiativeProjects->filter(function ($project) {
            return $project->charter === null;
        });

        if ($projectsWithoutCharters->isEmpty()) {
            $this->command->info('جميع المشاريع لديها مواثيق بالفعل.');

            return;
        }

        $projectsToCreateCharters = $projectsWithoutCharters->random(
            min(ceil($projectsWithoutCharters->count() * 0.6), $projectsWithoutCharters->count())
        );

        $charterTemplates = [
            [
                'name_suffix' => 'ميثاق مشروع',
                'description' => 'يهدف هذا المشروع إلى تحقيق أهداف محددة ضمن الخطة الاستراتيجية للمؤسسة، مع التركيز على الجودة والفعالية في التنفيذ.',
                'cost_range' => [50000, 200000],
            ],
            [
                'name_suffix' => 'خطة تنفيذ',
                'description' => 'مشروع استراتيجي يساهم في تطوير قدرات المؤسسة وتحسين مستوى الخدمات المقدمة للمستفيدين.',
                'cost_range' => [100000, 500000],
            ],
            [
                'name_suffix' => 'برنامج عمل',
                'description' => 'برنامج شامل يتضمن مجموعة من الأنشطة والمهام المترابطة لتحقيق النتائج المرجوة بأعلى معايير الجودة.',
                'cost_range' => [75000, 350000],
            ],
        ];

        $createdCharters = [];

        foreach ($projectsToCreateCharters as $project) {
            $template = fake()->randomElement($charterTemplates);

            // Calculate charter dates based on initiative dates with safer logic
            $initiative = $project->initiative;
            $initiativeStart = $initiative->start_date;
            $initiativeEnd = $initiative->expected_end_date;

            // Calculate initiative duration in days
            $initiativeDuration = $initiativeStart->diff($initiativeEnd)->days;

            // Skip if initiative is too short (less than 7 days)
            if ($initiativeDuration < 7) {
                continue;
            }

            // Charter starts within first 25% of initiative duration or max 30 days
            $maxStartOffset = min(30, (int) ($initiativeDuration * 0.25));
            $charterStartDate = fake()->dateTimeBetween(
                $initiativeStart,
                (clone $initiativeStart)->modify("+{$maxStartOffset} days")
            );

            // Charter duration is 30-60 days or up to 75% of remaining initiative time
            $remainingDays = $charterStartDate->diff($initiativeEnd)->days;
            $maxCharterDuration = min(60, (int) ($remainingDays * 0.75));
            $minCharterDuration = min(30, $maxCharterDuration);

            if ($maxCharterDuration < $minCharterDuration) {
                $maxCharterDuration = $minCharterDuration;
            }

            $charterEndDate = fake()->dateTimeBetween(
                (clone $charterStartDate)->modify("+{$minCharterDuration} days"),
                (clone $charterStartDate)->modify("+{$maxCharterDuration} days")
            );

            // Ensure charter end doesn't exceed initiative end
            if ($charterEndDate > $initiativeEnd) {
                $charterEndDate = (clone $initiativeEnd)->modify('-1 day');
            }

            // Determine charter state based on dates
            $now = now();
            $state = match (true) {
                $charterEndDate < $now => fake()->randomElement([
                    ProjectCharterState::COMPLETED,
                    ProjectCharterState::CANCELED,
                ]),
                $charterStartDate > $now => ProjectCharterState::ACTIVE,
                default => fake()->randomElement([
                    ProjectCharterState::ACTIVE,
                    ProjectCharterState::SUSPENDED,
                ]),
            };

            $charter = ProjectCharter::create([
                'initiative_project_id' => $project->id,
                'initiative_id' => $project->initiative_id,
                'name' => $template['name_suffix'].' - '.$project->name,
                'description' => $template['description'],
                'state' => $state,
                'start_date' => $charterStartDate,
                'expected_end_date' => $charterEndDate,
                'total_cost' => fake()->randomFloat(2, $template['cost_range'][0], $template['cost_range'][1]),
                'created_by' => $user->id,
                'org_id' => $org->id,
            ]);

            $createdCharters[] = $charter;
        }        // Summary statistics
        $stateStats = collect($createdCharters)->groupBy(fn ($charter) => $charter->state->value);

        $this->command->info('تم إنشاء '.count($createdCharters).' ميثاق مشروع لـ '.$projectsToCreateCharters->count().' مشروع مبادرة');
        $this->command->info('توزيع حالات المواثيق:');
        foreach ($stateStats as $state => $charters) {
            $this->command->info("  - {$state}: {$charters->count()}");
        }
    }
}
