<?php

namespace App\Console\Commands;

use App\Jobs\DeleteRoomConversation;
use App\Models\CollectSpend;
use App\Models\Contract;
use App\Models\MoneyInfo;
use App\Models\Renter;
use App\Models\RenterRoom;
use App\Models\Room;
use App\Models\Statistic;
use App\Models\StatisticLog;
use App\Models\Transaction;
use Illuminate\Console\Command;

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

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

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
	    $rooms = Room::all();
	    foreach ($rooms as $room)
	    {
			$name = $room->name;
			$roomSameNames = Room::query()->where('name', $name)->where('hostel_id', $room->hostel_id)->get();
			if($roomSameNames->count() == 1)
			{
				continue;
			}

			foreach ($roomSameNames as $roomSameName)
			{
				$checkRenter = RenterRoom::query()->where('room_id', $roomSameName->id)->count();
				if($checkRenter == 0)
				{
					$this->line($roomSameName->name);
					$this->line($roomSameName->id);
					$this->line('----');
				}
			}
	    }
    }

    public function deleteRoom($id)
    {
	    $room = Room::find($id);
	    RenterRoom::where('room_id', $room->id)->delete();
	    $hostel = $room->hostel;
	    $blockName = $room->block_name;

	    Renter::where('room_id', $room->id)->delete();
	    Contract::where('room_id', $room->id)->delete();
	    MoneyInfo::where('room_id', $room->id)->delete();
	    CollectSpend::where('room_id', $room->id)->delete();
	    Transaction::where('room_id', $room->id)->delete();
	    Statistic::where('room_id', $room->id)->delete();
	    StatisticLog::where('room_id', $room->id)->delete();

	    if (auth('backend')->check()) {
		    $userCreate = auth('backend')->user()->id;
	    } else {
		    $token = \request()->header('authorization');
		    $user = \JWTAuth::parseToken()->toUser();
		    $userCreate = $user->id;
	    }

	    dispatch(new DeleteRoomConversation($room->id, $room->hostel->id, $userCreate, auth('backend')->user()));


	    $room->delete();
    }
}
