<?php

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

return new class extends Migration
{
    public function up(): void
    {
        $exists = DB::table('admin_menu')
            ->where('path', '/admin/cms-audit-log')
            ->exists();

        if ($exists) {
            return;
        }

        // Prefer the Content section; fall back to Administration
        $section = DB::table('admin_menu')
            ->where('sub_id', 0)
            ->whereIn('title', ['Content', 'Administration'])
            ->orderByRaw("FIELD(title, 'Content', 'Administration')")
            ->first();

        if (empty($section)) {
            return;
        }

        $nextOrder = (int) DB::table('admin_menu')
            ->where('sub_id', $section->id)
            ->max('order') + 1;

        DB::table('admin_menu')->insert([
            'sub_id' => $section->id,
            'title' => 'CMS Change Log',
            'path' => '/admin/cms-audit-log',
            'activePath' => '/admin/cms-audit-log',
            'constant' => '',
            'icon' => 'fa fa-history',
            'new_window' => 0,
            'order' => $nextOrder,
        ]);
    }

    public function down(): void
    {
        DB::table('admin_menu')
            ->where('path', '/admin/cms-audit-log')
            ->delete();
    }
};
