<?php

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

return new class extends Migration
{
    public function up(): void
    {
        DB::transaction(function () {
            // Get the next available ID range
            $maxId = DB::table('admin_menu')->lockForUpdate()->max('id');
            $parentId = $maxId + 1;

            // Insert parent menu item for B2B
            DB::table('admin_menu')->insert([
                'id' => $parentId,
                'sub_id' => 0,
                'title' => 'B2B Trade',
                'path' => '',
                'activePath' => '',
                'constant' => 'B2B_ENABLED',
                'icon' => 'fa fa-building',
                'new_window' => 0,
                'order' => 10,
            ]);

            // Insert sub-menu items
            $subItems = [
                [
                    'title' => 'Trade Customers',
                    'path' => '/modules/B2B/admin/customers.php',
                    'activePath' => 'modules/B2B/admin/customers',
                    'icon' => 'fa fa-users',
                    'order' => 0,
                ],
                [
                    'title' => 'Trade Tiers',
                    'path' => '/modules/B2B/admin/tiers.php',
                    'activePath' => 'modules/B2B/admin/tiers',
                    'icon' => 'fa fa-layer-group',
                    'order' => 1,
                ],
                [
                    'title' => 'Account Orders',
                    'path' => '/modules/B2B/admin/orders.php',
                    'activePath' => 'modules/B2B/admin/orders',
                    'icon' => 'fa fa-file-invoice',
                    'order' => 2,
                ],
                [
                    'title' => 'Trade Pricing',
                    'path' => '/modules/B2B/admin/pricing.php',
                    'activePath' => 'modules/B2B/admin/pricing',
                    'icon' => 'fa fa-tags',
                    'order' => 3,
                ],
            ];

            foreach ($subItems as $item) {
                $maxId++;
                DB::table('admin_menu')->insert(array_merge($item, [
                    'id' => $maxId + 1,
                    'sub_id' => $parentId,
                    'constant' => '',
                    'new_window' => 0,
                ]));
            }
        });
    }

    public function down(): void
    {
        DB::table('admin_menu')
            ->where('path', 'like', '%/modules/B2B/admin/%')
            ->delete();

        DB::table('admin_menu')
            ->where('title', 'B2B Trade')
            ->where('sub_id', 0)
            ->delete();
    }
};
