<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    public function up(): void
    {
        // 각 테넌트의 부가세관리 메뉴를 찾아서 같은 parent_id 아래에 경조사비관리 추가
        $vatMenus = DB::table('menus')
            ->where('url', '/finance/vat')
            ->whereNull('deleted_at')
            ->get();

        foreach ($vatMenus as $vatMenu) {
            // 이미 존재하면 skip
            $exists = DB::table('menus')
                ->where('tenant_id', $vatMenu->tenant_id)
                ->where('url', '/finance/condolence-expenses')
                ->whereNull('deleted_at')
                ->exists();

            if ($exists) {
                continue;
            }

            DB::table('menus')->insert([
                'tenant_id' => $vatMenu->tenant_id,
                'parent_id' => $vatMenu->parent_id,
                'name' => '경조사비관리',
                'url' => '/finance/condolence-expenses',
                'icon' => 'gift',
                'sort_order' => $vatMenu->sort_order + 1,
                'is_active' => true,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    }

    public function down(): void
    {
        DB::table('menus')
            ->where('url', '/finance/condolence-expenses')
            ->delete();
    }
};
