<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;


return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
       $users = DB::table('users')->get();
        if ($users->isEmpty()) {          
            DB::table('groups')->insert([
                'name' => 'Default',
                'section_id' => 5,
                'user_id' => 2,
                'parent_group_id'=>1,
                'field_order' => 1,
            ]);
        }
        else {
            $getUsers = DB::table('users')
            ->where('is_client', 1)
            ->orWhere('id', 2)
            ->pluck('id')
            ->toArray();
            foreach ($getUsers as $userId) {
            
                $groupDefaultExists = DB::table('groups')
                    ->where('section_id', 5)
                    ->where('user_id',$userId)
                    ->where('name', 'Default')
                    ->exists();       
                if (!$groupDefaultExists) {
                    $get_order2 = DB::table('groups')
                    ->where('section_id', 5)
                    ->where('user_id', $userId)
                    ->orderBy('field_order', 'desc')
                    ->value('field_order');
                    DB::table('groups')->insert([
                        'name' => 'Default',
                        'section_id' => 5,
                        'user_id' => $userId,
                        'parent_group_id'=>1 ,
                        'field_order' => $get_order2 + 1,
                    ]);
                }
                
                $groupUnsortedExists = DB::table('groups')
                ->where('section_id', 5)
                ->where('user_id',$userId)
                ->where('name', 'Unsorted')
                ->exists();       
                if (!$groupUnsortedExists) {
                    $get_order = DB::table('groups')
                    ->where('section_id', 5)
                    ->where('user_id', $userId)
                    ->orderBy('field_order', 'desc')
                    ->value('field_order');

                    DB::table('groups')->insert([
                        'name' => 'Unsorted',
                        'section_id' => 5,
                        'user_id' => $userId,
                        'parent_group_id'=>1,
                        'field_order'=> $get_order+1 ,
                    ]);
                }


            }

        }       
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('groups', function (Blueprint $table) {
            //
        });
    }
};
