<?php

namespace App\Filament\Resources\ProjectResource\Pages;

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

class EditProject extends EditRecord
{
    protected static string $resource = ProjectResource::class;

    protected array $badgesTargetData = [];

    protected array $badgesAwardData = [];

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

    protected function mutateFormDataBeforeFill(array $data): array
    {
        $project = $this->record;

        // 載入永續目標
        $data['badgesTarget'] = DB::table('badgeables')
            ->where('badgeable_id', $project->id)
            ->where('badgeable_type', Project::class)
            ->where('award_type', 1)
            ->orderBy('sort_order')
            ->get()
            ->map(fn ($item) => [
                'badge_id' => $item->badge_id,
            ])->toArray();

        // 載入取得標章
        $data['badgesAward'] = DB::table('badgeables')
            ->where('badgeable_id', $project->id)
            ->where('badgeable_type', Project::class)
            ->where('award_type', 2)
            ->orderBy('sort_order')
            ->get()
            ->map(function ($item) {
                // 轉換日期格式從 Y-m-d 到 Y-m
                $awardDate = null;
                if ($item->award_date) {
                    $awardDate = substr($item->award_date, 0, 7); // 取前7個字元 (Y-m)
                }

                return [
                    'badge_id' => $item->badge_id,
                    'award_date' => $awardDate,
                ];
            })->toArray();

        return $data;
    }

    protected function mutateFormDataBeforeSave(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 afterSave(): void
    {
        // 先刪除所有舊的標籤關聯
        DB::table('badgeables')
            ->where('badgeable_id', $this->record->id)
            ->where('badgeable_type', Project::class)
            ->delete();

        // 儲存永續目標
        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(),
                    ]);
                }
            }
        }
    }
}
