<?php

namespace App\Filament\Resources\ProjectResource\Pages;

use App\Filament\Resources\ProjectResource;
use App\Models\Project;
use Filament\Actions;
use Filament\Resources\Pages\CreateRecord;

class CreateProject extends CreateRecord
{
    protected static string $resource = ProjectResource::class;

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('index');
    }

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        // 暫存標籤資料
        if (isset($data['badgesTarget'])) {
            $this->badgesTargetData = $data['badgesTarget'];
            unset($data['badgesTarget']);
        }
        // 暫存標籤資料
        if (isset($data['badgesAward'])) {
            $this->badgesAwardData = $data['badgesAward'];
            unset($data['badgesAward']);
        }
        return $data;
    }

    protected function afterCreate(): void
    {
        $syncData = [];
        if (!empty($this->badgesTargetData)) {
            foreach ($this->badgesTargetData as $item) {
                $syncData[$item['badge_id'] . '_1'] = [
                    'badge_id' => $item['badge_id'],
                    'award_type' => 1,
                    'award_date' => null,
                ];
            }
        }

        if (!empty($this->badgesAwardData)) {
            foreach ($this->badgesAwardData as $item) {
                $syncData[$item['badge_id'] . '_2'] = [
                    'badge_id' => $item['badge_id'],
                    'award_type' => 2,
                    'award_date' => $item['award_date'] . "-01",
                ];
            }
        }

        foreach ($syncData as $data) {
            \DB::table('badgeables')->insert([
                'badge_id' => $data['badge_id'],
                'badgeable_id' => $this->record->id,
                'badgeable_type' => Project::class,
                'award_type' => $data['award_type'],
                'award_date' => $data['award_date'],
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    }
}
