<?php

namespace App\Console\Commands;

use App\Components\Functions;
use App\Models\CollectSpend;
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\Models\Transaction;
use App\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Mpdf\Tag\U;

ini_set('memory_limit', '1024M');


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

    /**
     * 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::query()->where('contract_id', $contractId)
            ->whereIn('type', [MoneyInfo::VOUCHER_CONTRACT, MoneyInfo::VOUCHER_ROOM_PRICE])
            ->orderBy('id', 'desc')
            ->first();

        if (!$moneyInfo) {
            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()
    {


        $excepts = config('constants.EXCEPT_MONEY_INFO_NOTI');

        $rooms = Room::query()
            ->with('hostel')
         //   ->where( 'id', 37156 )
            ->orderBy('id', 'desc')
            ->get();
//        $rooms = Room::where('id', 12962)->get();


        foreach ($rooms as $room) {
            $this->line('Processing ' . $room->id);

            $hostelId = null;
            $owner = null;
            $roomId = $room->id;

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

            $hostel = $room->hostel;

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

            $ownerId = $hostel->owner_id;
            $owners = User::query()->where('id', $ownerId)
                ->get();
            $users = $hostel->staffs;
            if (empty($users->count())) {
                $users =$owners;
            } else {
                $users = $users->merge($owners);
            }

            $renters = RenterRoom::query()->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;
                }

                if ($contract->room_price <= 0) {
                    continue;
                }

                $period = Functions::getPeriodNumber($contract->period);
                $lastInvoiceDate = $contract->last_invoice_at;
                $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->copy()->addDay();

                    $startNextInvoiceMonth = $startNextInvoiceCarbon->month;
                    $startNextInvoiceYear = $startNextInvoiceCarbon->year;
                    $startNextInvoiceDay = $dayCollect;
//                    if (!$isStart) {
//                        if ($lastInvoice->copy()->day == 1) {
//                            $startNextInvoiceDay = 1;
//                        } else {
//                            $startNextInvoiceDay = $startNextInvoiceCarbon->day;
//                        }
//                    }
                    if (!$isStart) {
                        $startNextInvoiceDay = $startNextInvoiceCarbon->day;
                    }
                    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 * $range;
                    $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' ) );
                    if (!Functions::checkFullPeriod($startNextInvoice->copy(), $to->copy(), $dayCollect)) {
                        $sumMoney = Functions::calculateMoneyInRange4($startNextInvoice->copy(), $to->copy(), $contract->room_price, $dayCollect);
                        $range = round($sumMoney / $contract->room_price, 1);
                    }
                    $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();

                    if (!in_array($ownerId, $excepts)) {
                        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('----');
                }

            }
        }

    }

}
