CreateAdminChat.php 1.55 KB
<?php

namespace App\Console\Commands;

use App\Models\Chat;
use App\Models\Message;
use App\Models\User;
use Illuminate\Console\Command;

class CreateAdminChat extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'admin:chat';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $superAdmin = User::superAdmin();

        $users = User::where('id', '!=', $superAdmin->id)->get();
        $chats = Chat::query()
            ->where('is_admin_chat', 1)
            ->orWhere('to_user_id', $superAdmin->id)
            ->orWhere('user_id', $superAdmin->id)
            ->get();

        foreach ($chats as $chat) {
            Message::query()->where('chat_id_from', $chat->id)->orWhere('chat_id_to', $chat->id)->delete();
            $chat->delete();
        }

        $loopCount = $users->count();

        if ($superAdmin) {
            foreach ($users as $user) {
                Chat::firstOrCreate([
                    'user_id' => $user->id,
                    'to_user_id' => $superAdmin->id,
                    'is_admin_chat' => 1,
                    'is_removed' => 0,
                ]);

            }

            $this->info("Admin chats created for {$loopCount} users.");

            return Command::SUCCESS;
        }

        $this->error("Admin is missing!");

    }

}