<?php

namespace App\Console\Commands;

use App\Models\Contract;
use App\Models\Notification;
use App\Models\RenterRoom;
use App\Models\Room;
use Carbon\Carbon;
use Illuminate\Console\Command;

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

    /**
     * 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()
    {
        //
        $contracts = Contract::query()
         //   ->where('hostel_id', 6374)
            ->where('status', '<>', Contract::LIQUIDATED)
            ->whereNotNull('end_date')
            ->cursor();

        foreach ($contracts as $contract) {
            $hostel = $contract->hostel;
            if (!$hostel) {
                continue;
            }

            $owner = $hostel->owner;
            if (!$owner) {
                continue;
            }

            if (Carbon::now()->greaterThan($contract->end_date)) {
                continue;
            }

            $remindDay = $owner->day_remind_empty_room;


            $diffDays = Carbon::now()->diffInDays($contract->end_date);

            if ($diffDays != $remindDay) {
                continue;
            }

            $payload = null;
            $content = 'Hợp đồng ' . $contract->name . ', phòng ' . $contract->room->name . ', nhà ' . $contract->hostel->name . ' sẽ hết hạn vào ngày ' . $contract->end_date->format('d/m/Y');

            $payload = json_encode([
                'id' => $contract->id,
                'type' => config('constants.CONTRACT')
            ]);

            //  \Notification::sendNow($owner, new \App\Notifications\RemindEmptyRoom($contract, $content));

            Notification::create([
                'to_user' => $owner->id,
                'title' => 'Thông báo từ itro.vn',
                'user_id' => $owner->id,
                'content' => $content,
                'payload' => $payload,
            ]);
            $this->line('Processed ' . $contract->id);

        }
    }
}
