<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Mtc\Core\Admin\Menu;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        $configurationExists = Menu::query()
            ->where('sub_id', 0)
            ->where('title', Menu::MENU_CONFIGURATION)
            ->exists();

        if ($configurationExists) {
            return;
        }
        $lastTopLevelItem = Menu::query()
            ->where('sub_id', 0)
            ->orderByDesc('order')
            ->first();

        $configurationMenuItem = Menu::query()
            ->create([
                'sub_id' => 0,
                'title' => Menu::MENU_CONFIGURATION,
                'order' => ($lastTopLevelItem->order ?? 0) + 1,
            ]);

        Menu::query()
            ->create([
                'sub_id' => $configurationMenuItem->id,
                'title' => 'Roles and permissions',
                'path' => '/admin/roles/index.php',
                'activePath' => '/admin/roles/',
                'icon' => 'fa fa-cog',
                'order' => 0,
            ]);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        $configurationMenuItem = Menu::query()
            ->where('sub_id', 0)
            ->where('title', Menu::MENU_CONFIGURATION)
            ->first();

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

        Menu::query()
            ->where('id', $configurationMenuItem->id)
            ->orWhere('sub_id', $configurationMenuItem->id)
            ->delete();
    }
};
