<?php

namespace App\Console\Commands;

use App\Components\Functions;
use App\Models\Contract;
use App\Models\Hostel;
use App\Models\MoneyDetail;
use App\Models\MoneyInfo;
use App\Models\Notification;
use App\Models\RenterRoom;
use App\Models\Room;
use App\User;
use Carbon\Carbon;
use Illuminate\Console\Command;

class CreateBillCustomer extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'create:bill-customer';

    /**
     * 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 getLatestInvoice($contractId)
    {
        $contract = Contract::find($contractId);
        if (!$contract) {
            return null;
        }

        $moneyInfo = MoneyInfo::where('contract_id', $contractId)
            ->whereIn('type', [MoneyInfo::VOUCHER_CONTRACT, MoneyInfo::VOUCHER_ROOM_PRICE])
            ->orderBy('id', 'desc')
            ->first();

        if (!$moneyInfo) {
            $contract->last_invoice_at = null;
            $contract->save();
            return null;
        }

        $moneyDetail = MoneyDetail::where('money_info_id', $moneyInfo->id)
            ->orderBy('id', 'desc')
            ->first();
        if (!$moneyDetail) {
            return null;
        }

        return $moneyDetail->end_date;
    }


    public function handle()
    {

        $phone = '0344240010';
        $owner = User::query()->where('type', User::OWNER)
            ->where('phone', $phone)
            ->first();

        if (!$owner) {
            return;
        }
        $hostelArrs = Hostel::query()->where('owner_id', $owner->id)
            ->pluck('id')
            ->toArray();

        $rooms = Room::query()
            ->whereIn('hostel_id', $hostelArrs)
            ->get();
//        $rooms = Room::where('id', 12962)->get();


        foreach ($rooms as $room) {
            $hostelId = null;
            $roomId = $room->id;

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

            if ($room->hostel) {
                $hostelId = $room->hostel->id;
            }

            $ownerId = $hostel->owner_id;
            $users = User::where('staff_owner_id', $ownerId)
                ->orWhere('id', $ownerId)
                ->get();

            $renters = RenterRoom::where('room_id', $room->id)
                ->with('contract')
                ->get();


            foreach ($renters as $renter) {

                if (!$renter->contract) {

                    continue;
                }

                if ($renter->contract->status == Contract::LIQUIDATED) {

                    continue;
                }

                $isStart = false;

                $contract = $renter->contract;
                if (!$contract) {
                    continue;
                }

                $period = Functions::getPeriodNumber($contract->period);
                $this->getLatestInvoice($contract->id);
                $lastInvoiceDate = $contract->last_invoice_at;

                if (empty($lastInvoiceDate)) {
                    $lastInvoiceDate = $this->getLatestInvoice($contract->id);
                }


                if (empty($lastInvoiceDate)) {
                    $lastInvoiceDate = $contract->start_date->subDay()->format('Y-m-d');
                    $isStart = true;
                }
                if (!empty($lastInvoiceDate)) {

                    $dayCollect = $contract->day_collect;
                    $lastInvoice = Carbon::createFromFormat('Y-m-d', $lastInvoiceDate);
                    //dump($lastInvoice->toDateString());


                    if (!Carbon::now()->greaterThanOrEqualTo($lastInvoice)) {
                        continue;
                    }


                    $startNextInvoiceCarbon = $lastInvoice->addDay();

                    $startNextInvoiceMonth = $startNextInvoiceCarbon->month;
                    $startNextInvoiceYear = $startNextInvoiceCarbon->year;
                    $startNextInvoiceDay = $dayCollect;
                    if (!$isStart) {
                        $startNextInvoiceDay = $dayCollect + 1;
                    }
                    if (checkdate($startNextInvoiceMonth, $startNextInvoiceDay, $startNextInvoiceYear)) {
                        $startNextInvoice = Carbon::createFromFormat('d-m-Y', $startNextInvoiceDay . '-' . $startNextInvoiceMonth . '-' . $startNextInvoiceYear);
                    } else {
                        $startNextInvoiceDay = Carbon::createFromFormat('d-m-Y', '01-' . $startNextInvoiceMonth . '-' . $startNextInvoiceYear)->day;
                        $startNextInvoice = Carbon::createFromFormat('d-m-Y', $startNextInvoiceDay . '-' . $startNextInvoiceMonth . '-' . $startNextInvoiceYear);
                    }


                    if ($period > 1) {
                        $month = $startNextInvoice->copy()->firstOfMonth()->addMonth($period - 1)->month;
                        $year = $startNextInvoice->copy()->firstOfMonth()->addMonth($period - 1)->year;
                        if ($dayCollect <= $startNextInvoice->copy()->day) {
                            $month = $startNextInvoice->copy()->firstOfMonth()->addMonth($period)->month;
                            $year = $startNextInvoice->copy()->firstOfMonth()->addMonth($period)->year;
                        }
                    } else {
                        $month = $startNextInvoice->copy()->month;
                        $year = $startNextInvoice->copy()->year;
                        if ($dayCollect <= $startNextInvoice->copy()->day) {
                            $month = $startNextInvoice->copy()->firstOfMonth()->addMonth()->month;
                            $year = $startNextInvoice->copy()->firstOfMonth()->addMonth()->year;
                        }
                    }
                    if (checkdate($month, $dayCollect, $year)) {

                        $to = Carbon::createFromFormat('d-m-Y', $dayCollect . '-' . $month . '-' . $year);

                    } else {
                        $tempDayCollect = Carbon::createFromFormat('d-m-Y', '01-' . $month . '-' . $year)->lastOfMonth()->day;
                        $to = Carbon::createFromFormat('d-m-Y', $tempDayCollect . '-' . $month . '-' . $year);
                    }

                    $range = $period;
                    $sumMoney = $contract->room_price * $period;
                    $money = 0;
                    $name = 'Thu tiền phòng từ ' . $startNextInvoice->copy()->format('d/m/Y') . ' đến ' . $to->copy()->format('d/m/Y');

                    //dd($startNextInvoice->copy()->format( 'd/m/Y' ),  $to->copy()->format( 'd/m/Y' ) );
                    $moneyInfo = MoneyInfo::create([
                        'hostel_id' => $hostelId,
                        'room_id' => $roomId,
                        'date_action' => $startNextInvoice->copy()->toDateString(),
                        'contract_id' => $contract->id,
                        'user_id' => $contract->renter_id,
                        'type' => MoneyInfo::VOUCHER_ROOM_PRICE,
                        'amount' => $sumMoney,
                        'pay' => $money,
                        'remain' => $sumMoney - $money,
                        'money_info_name' => $name
                    ]);

                    $moneyInfo->update([
                        'name' => 'HD' . $moneyInfo->id . Carbon::now()->format('dmY')
                    ]);

                    MoneyDetail::create([
                        'hostel_id' => $hostelId,
                        'room_id' => $roomId,
                        'name' => $name,
                        'value' => $contract->room_price,
                        'money_info_id' => $moneyInfo->id,
                        'amount' => $money,
                        'note' => $name,
                        'start_date' => $startNextInvoice->copy()->toDateString(),
                        'end_date' => $to->copy()->toDateString(),
                        'qty' => $range,
                        'renter_id' => $contract->renter_id,
                        'sum_amount' => $sumMoney
                    ]);

                    $contract->last_invoice_at = $to->copy()->toDateString();
                    $contract->save();

                    foreach ($users as $user) {
                        Notification::create([
                            'to_user' => $user->id,
                            'title' => 'Thông báo hóa đơn từ itro.vn',
                            'user_id' => $user->id,
                            'content' => 'Đã có hoá đơn tiền phòng ' . $room->name . ' của ' . $renter->contract->name . ' từ ' . $startNextInvoice->copy()->format('d/m/Y') . ' - ' . $to->copy()->format('d/m/Y'),
                            'payload' => json_encode([
                                'id' => $moneyInfo->id,
                                'type' => config('constants.TRANSACTION')
                            ])
                        ]);
                    }


                    $this->line('Process contract: ' . $contract->id);
                    $this->line('Room: ' . $contract->room->name);
                    $this->line($startNextInvoice->copy()->format('d/m/Y'));
                    $this->line($to->copy()->format('d/m/Y'));
                    $this->line($money);
                    $this->line($sumMoney);
                    $this->line('----');
                }

            }
        }

    }
}
