<?php

namespace App\Console\Commands;

use App\Jobs\SendMessageBot;
use App\Models\ElectricWater;
use App\Models\Hostel;
use App\Models\Room;
use Carbon\Carbon;
use Illuminate\Console\Command;

class SendReminOwnerEw extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'remind-owner:ew';

    /**
     * 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()
    {
        //
        $hostels = Hostel::query()->groupBy([
            'owner_id',
            'date_money'
        ])->get();

        foreach ($hostels as $hostel) {

            if (Carbon::now()->day == ($hostel->date_ew + 1)) {
                if ($hostel->type_rent == Hostel::TYPE_RENT_ALL) {
                    $rooms = Room::where('hostel_id', $hostel->id)->get();
                    if ($rooms->count() > 0) {
                        $message = null;
                        foreach ($rooms as $room) {
                            $check = ElectricWater::where('room_id', $room->id)
                                ->whereBetween('date_action', [Carbon::now()->startOfMonth()->toDateTimeString(), Carbon::now()->endOfMonth()->toDateTimeString()])
                                ->count();
                            if ($check > 0) {
                                $message = 'Dường như bạn chưa chốt điện nước của tất cả các phòng có người ở. Hãy đi chốt điện nước để lập hoá đơn nhé';
                                break;
                            }
                        }

                        if (!empty($message)) {
                            dispatch(new SendMessageBot($message, $hostel->owner_id));
                        }
                    }
                }
            }

            if (Carbon::now()->day == $hostel->date_ew) {
                $message = 'Đã đến ngày đi chốt điện nước của nhà trọ ' . $hostel->name . '.Bạn đừng quên chốt điện nước nhé';
                dispatch(new SendMessageBot($message, $hostel->owner_id));
            }

            if (Carbon::now()->day == $hostel->date_money) {
                $message = 'Hôm nay là ' . Carbon::now()->format('d/m') . ', hãy lập hoá đơn và thu tiền người ở trọ nhé';
                dispatch(new SendMessageBot($message, $hostel->owner_id));
            }
        }

    }
}
