<?php

namespace Database\Seeders;

use App\Models\Activity;
use App\Models\User;
use Illuminate\Database\Seeder;

class ActivitySeeder extends Seeder
{
    public function run(): void
    {
        $pengurus = User::role('pengurus')->first();
        $ketua    = User::role('ketua')->first();
        $anggota  = User::role('anggota')->get();

        $activities = [
            [
                'title'       => 'Kerja Bakti Desa',
                'description' => 'Kegiatan bersih-bersih lingkungan desa',
                'start_date'  => now()->addDays(7),
                'end_date'    => now()->addDays(7),
                'status'      => 'approved',
                'approved_by' => $ketua?->id,
                'approved_at' => now(),
            ],
            [
                'title'       => 'Pelatihan Kewirausahaan',
                'description' => 'Pelatihan usaha kecil untuk pemuda desa',
                'start_date'  => now()->addDays(14),
                'end_date'    => now()->addDays(15),
                'status'      => 'pending',
            ],
            [
                'title'       => 'Turnamen Voli Antar RT',
                'description' => 'Kompetisi voli untuk mempererat silaturahmi',
                'start_date'  => now()->subDays(10),
                'end_date'    => now()->subDays(8),
                'status'      => 'approved',
                'approved_by' => $ketua?->id,
                'approved_at' => now()->subDays(15),
                'executed_at' => now()->subDays(10),
                'execution_notes' => 'Kegiatan berjalan lancar, diikuti 8 tim.',
            ],
        ];

        foreach ($activities as $data) {
            $activity = Activity::create(array_merge($data, ['created_by' => $pengurus?->id]));

            // Hanya kegiatan yang sudah executed yang punya data kehadiran
            if (! empty($data['executed_at'])) {
                $syncData = $anggota->mapWithKeys(fn ($user, $i) => [
                    $user->id => [
                        'status' => $i % 4 === 0 ? 'izin' : 'hadir',
                        'notes'  => null,
                    ]
                ])->toArray();
                $activity->participants()->sync($syncData);
            }
        }
    }
}
