<?php

namespace App\Filament\Resources\ProjectResource\Pages;

use App\Filament\Resources\ProjectResource;
use App\Models\Project;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Facades\DB;

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

    protected array $badgesTargetData = [];

    protected array $badgesAwardData = [];

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

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        // 暫存永續目標資料
        if (isset($data['badgesTarget']) && is_array($data['badgesTarget'])) {
            $this->badgesTargetData = $data['badgesTarget'];
            unset($data['badgesTarget']);
        }

        // 暫存取得標章資料
        if (isset($data['badgesAward']) && is_array($data['badgesAward'])) {
            $this->badgesAwardData = $data['badgesAward'];
            unset($data['badgesAward']);
        }

        return $data;
    }

    protected function afterCreate(): void
    {
        // 儲存永續目標
        if (! empty($this->badgesTargetData)) {
            foreach ($this->badgesTargetData as $index => $item) {
                if (isset($item['badge_id'])) {
                    DB::table('badgeables')->insert([
                        'badge_id' => $item['badge_id'],
                        'badgeable_id' => $this->record->id,
                        'badgeable_type' => Project::class,
                        'award_type' => 1,
                        'award_date' => null,
                        'sort_order' => $index,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                }
            }
        }

        // 儲存取得標章
        if (! empty($this->badgesAwardData)) {
            foreach ($this->badgesAwardData as $index => $item) {
                if (isset($item['badge_id'])) {
                    $awardDate = null;
                    if (isset($item['award_date']) && ! empty($item['award_date'])) {
                        // 處理日期格式：如果是 Y-m 格式，加上 -01
                        $awardDate = $item['award_date'];
                        if (strlen($awardDate) === 7) { // Y-m format
                            $awardDate .= '-01';
                        }
                    }

                    DB::table('badgeables')->insert([
                        'badge_id' => $item['badge_id'],
                        'badgeable_id' => $this->record->id,
                        'badgeable_type' => Project::class,
                        'award_type' => 2,
                        'award_date' => $awardDate,
                        'sort_order' => $index,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                }
            }
        }
    }
}
