<?php

namespace App\Console\Commands;

use App\Components\Functions;
use App\Components\MomoServices;
use App\Components\PusherService;
use App\Events\AuthLoginLog;
use App\Events\HostelCreated;
use App\Events\HostelCreatedFindNotification;
use App\Events\NewMessage;
use App\Jobs\AddRenterConversation;
use App\Jobs\AddRenterConversationV2;
use App\Jobs\AddStaffConversation;
use App\Jobs\CreateHostelConservationV2;
use App\Jobs\CreateRoomConservationV2;
use App\Jobs\DeleteHostelConversation;
use App\Jobs\DeleteRenterConversation;
use App\Jobs\ExportMoneyInfo;
use App\Jobs\GenerateDynamicLinkHostel;
use App\Jobs\ImportContract;
use App\Jobs\ImportContractService;
use App\Jobs\RemoveStaffConversation;
use App\Jobs\RemoveUserConversationV2;
use App\Jobs\SendMessageBot;
use App\Jobs\SendNotificationMessage;
use App\Jobs\SendVoucherOwner;
use App\Models\Amenity;
use App\Models\BackupLog;
use App\Models\Category;
use App\Models\CollectSpend;
use App\Models\CollectSpendFile;
use App\Models\Config;
use App\Models\ConfigHostel;
use App\Models\Contract;
use App\Models\ContractFee;
use App\Models\Conversation;
use App\Models\Deposit;
use App\Models\District;
use App\Models\ElectricQuota;
use App\Models\ElectricWater;
use App\Models\Hostel;
use App\Models\HostelFee;
use App\Models\HostelPostCrawl;
use App\Models\HostelPostCrawlMedia;
use App\Models\HostelType;
use App\Models\ImportExport;
use App\Models\Item;
use App\Models\ItemType;
use App\Models\Message;
use App\Models\MoneyDetail;
use App\Models\MoneyInfo;
use App\Models\Notification;
use App\Models\Order;
use App\Models\Package;
use App\Models\PackageChange;
use App\Models\Province;
use App\Models\Renter;
use App\Models\RenterBike;
use App\Models\RenterRoom;
use App\Models\Room;
use App\Models\RoomBed;
use App\Models\RoomNeedMore;
use App\Models\RoomReservation;
use App\Models\RoomType;
use App\Models\SendZaloLog;
use App\Models\Statistic;
use App\Models\StatisticLog;
use App\Models\StatisticMonth;
use App\Models\Transaction;
use App\Models\TypeCollect;
use App\Models\TypeSpend;
use App\Models\UserAchievement;
use App\Models\UserPackage;
use App\Models\UserPackageFindHostel;
use App\Models\Ward;
use App\Models\Warehouse;
use App\Models\WaterQuota;
use App\Models\Workplace;
use App\Models_v2\FindSession;
use App\Notifications\SearchFoundRenter;
use App\Notifications\SendWhenConfirmHostel;
use App\Notifications\SendWhenStaffCollect;
use App\Services\ContractService;
use App\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\Request;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\Html;
use Pusher\Pusher;
use RapidWeb\GoogleOAuth2Handler\GoogleOAuth2Handler;
use RapidWeb\GooglePeopleAPI\Contact;
use RapidWeb\GooglePeopleAPI\GooglePeople;
use Spatie\Activitylog\Models\Activity;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

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

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

    /**
     * Create a new command instance.
     *
     * @return void
     */
    protected $user;

    public function __construct()
    {
        $this->user = null;
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */


    public function updateRoomPrice($room)
    {


        $hostelId = $room->hostel_id;
        $hostel = Hostel::find($hostelId);
        if (!$hostel) {
            return;
        }
        $prices = Functions::getPriceHostelFrontend3($hostel);

        if (!empty($prices)) {
            $smallest = $prices['smallest'];
            $greatest = $prices['greatest'];
            $hostel->smallest_price = $smallest;
            $hostel->greatest_price = $greatest;
            $hostel->save();

//            $hostel->
        }
    }

    public function importContract()
    {


//        $cnt = 0;
//        $file = $request->file('file');
//        if (!\File::exists(public_path('files'))) {
//            \File::makeDirectory(public_path('files'), '0777', true);
//        }
//
//        $filename = time() . '_' . mt_rand(1111, 9999) . '_' . str_slug($request->file('file')->getClientOriginalName());
//        $filename = $filename . '.' . $file->extension();
//        $request->file('file')->move(public_path('files'), $filename);
//
//        $filePath = public_path('files/' . $filename);
//        $ownerId = auth('backend')->user()->id;
//        if (auth('backend')->user()->type == User::STAFF) {
//            $ownerId = auth('backend')->user()->staff_owner_id;
//        }
        $filePath = '/home/itro.vn/public_html/public/nhap-hop-dong-check.xlsx';
        $ownerId = 31746;
        $items = \Excel::selectSheetsByIndex(0)->load($filePath, function ($reader) {
            $reader->noHeading();
        })->skip(1)->get();

        $indexArr = [];
        $headerArr = [];
        $headers = $items[0];
        foreach ($headers as $key => $header) {
            $name = str_replace('(Số đầu)', '', $header);
            $name = str_replace('(Số lượng)', '', $name);
            $name = str_replace('(ngày/tháng/năm)', '', $name);
            $name = trim($name);
            $headerArr[$key] = $name;
        }

        $lastKey = array_key_last($headerArr);
        unset($items[0]);

        foreach ($items as $key => $item) {
            $hostelName = trim($item[0]);
            $roomName = trim($item[1]);

            if (empty($hostelName) || empty($roomName)) {
                continue;
            }

            if ($item[3] instanceof Carbon) {
                $dateContract = $item[3]->format('d/m/Y');
            } else {
                $dateContract = trim($item[3]);
            }


            if ($item[4] instanceof Carbon) {
                $endDate = $item[4]->format('d/m/Y');
            } else {
                $endDate = trim($item[4]);
            }

            if ($item[9] instanceof Carbon) {
                $collectTo = $item[9]->format('d/m/Y');
            } else {
                $collectTo = trim($item[9]);
            }

            if ($item[13] instanceof Carbon) {
                $birthday = $item[13]->format('d/m/Y');
            } else {
                $birthday = trim($item[13]);
            }

            $bedName = trim($item[2]);
            $roomPrice = trim($item[5]);
            $deposit = trim($item[6]);
            $period = trim($item[7]);
            $dayCollect = trim($item[8]);
            $phone = trim($item[10]);
            if (empty($phone)) {
                return [
                    'status' => 0,
                    'message' => 'Không được bỏ trống SĐT khách lập HĐ'
                ];
            }
            $name = trim($item[11]);
            $email = trim($item[12]);

            $idNumber = trim($item[14]);
            $idNumberDate = trim($item[15]);
            $idNumberLocation = trim($item[16]);

            if (empty($endDate)) {
                return [
                    'status' => 0,
                    'message' => 'Không được bỏ trống hạn HĐ'
                ];
            }

            $hostel = Hostel::query()
                ->where('name', $hostelName)
                ->where('owner_id', $ownerId)
                ->first();
            if (!$hostel) {
                return [
                    'status' => 0,
                    'message' => 'Không tìm thấy nhà trọ ' . $hostelName . ' trên hệ thống'
                ];
            }


            $room = Room::query()
                ->where('name', $roomName)
                ->where('hostel_id', $hostel->id)
                ->first();

            if (!$room) {
                return [
                    'status' => 0,
                    'message' => 'Không tìm thấy phòng trọ ' . $roomName . ' thuộc nhà trọ ' . $hostelName . ' trên hệ thống'
                ];
            }


            $bedId = null;

            if ($hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                if (empty($bedName)) {
                    return [
                        'status' => 0,
                        'message' => 'Không được bỏ trống tên giường'
                    ];
                }

                $bed = RoomBed::query()->where('room_id', $room->id)
                    ->where('name', $bedName)
                    ->first();
                if (!$bed) {
                    return [
                        'status' => 0,
                        'message' => 'Không tìm thấy giường ' . $bedName . ' cho phòng ' . $roomName
                    ];
                }

            }


            $data = [
                'hostel' => $hostel,
                'hostel_id' => $hostel->id,
                'period' => empty($period) ? 1 : $period,
                'room' => $room,
                'room_id' => $room->id,
                'date_contract' => $dateContract,
                'end_date' => $endDate,
                'room_price' => $roomPrice,
                'deposit' => $deposit,
                'day_collect' => $dayCollect,
                'collect_to' => $collectTo,
                'is_collected' => !empty($collectTo) ? 'on' : 'off',
                'phone' => $phone,
                'name' => $name,
                'email' => $email,
                'birthday' => $birthday,
                'id_number' => $idNumber,
                'id_number_date' => $idNumberDate,
                'id_number_location' => $idNumberLocation,
                'bed_id' => $bedId,
                'residence_status' => false,
                'date_end_residence' => null,
                'type_rent' => Room::START_PERIOD
            ];


            if (!empty($data['end_date'])) {
                if (is_numeric($data['date_contract'])) {
                    $data['end_date'] = \PHPExcel_Shared_Date::ExcelToPHPObject($data['end_date']);
                    $data['end_date'] = Carbon::instance($data['end_date'])->toDateString();
                } else if (is_string($data['date_contract'])) {
                    $data['end_date'] = Carbon::createFromFormat('d/m/Y', $data['end_date'])->toDateString();
                }
            }
            if (!empty($data['collect_to'])) {
                if (is_numeric($data['collect_to'])) {
                    $data['collect_to'] = \PHPExcel_Shared_Date::ExcelToPHPObject($data['collect_to']);
                    $data['collect_to'] = Carbon::instance($data['collect_to'])->toDateString();
                } else if (is_string($data['collect_to'])) {
                    $data['collect_to'] = Carbon::createFromFormat('d/m/Y', $data['collect_to'])->toDateString();
                }
            }

            if (!empty($data['id_number_date'])) {
                if (is_numeric($data['id_number_date'])) {
                    $data['id_number_date'] = \PHPExcel_Shared_Date::ExcelToPHPObject($data['id_number_date']);
                    $data['id_number_date'] = Carbon::instance($data['id_number_date'])->toDateString();
                } else if (is_string($data['id_number_date'])) {
                    $data['id_number_date'] = Carbon::createFromFormat('d/m/Y', $data['id_number_date'])->toDateString();
                }
            }

            if (!empty($data['date_contract'])) {
                if (is_numeric($data['date_contract'])) {
                    $data['date_contract'] = \PHPExcel_Shared_Date::ExcelToPHPObject($dateContract);
                    $data['date_contract'] = Carbon::instance($data['date_contract'])->toDateString();
                } else if (is_string($data['date_contract'])) {
                    $data['date_contract'] = Carbon::createFromFormat('d/m/Y', $data['date_contract'])->toDateString();
                }
                $data['date_enable'] = $data['date_contract'];
                $data['start_date'] = $data['date_contract'];
                $data['date_join'] = $data['date_contract'];
            }

            $data['fees'] = null;
            for ($i = 17; $i <= $lastKey; $i++) {
                if (!isset($headerArr[$i])) {
                    $this->line('Done --e --header' . $roomName);
                    continue;
                }

                $feeName = $headerArr[$i];
                $fee = HostelFee::query()
                    ->where('name', $feeName)
                    ->where('hostel_id', $hostel->id)
                    ->first();
                if (!$fee) {
                    $this->line('Done -- e -fee' . $roomName);
                    continue;
                }

                if (!is_numeric($item[$i])) {
                    $this->line('Done -- e -numfee' . $roomName);
                    continue;
                }

                $data['fees'][$fee->id] = ['qty' => intval($item[$i])];
            }

            // $this->line(json_encode($data));

            $contractService = new ContractService($data);
            $res = $contractService->store();
            $this->line($res);
            //  dispatch_now(new ImportContractService($data));
//            if (isset($res['status'])) {
//                if ($res['status'] == 0) {
//                    $this->line('Done -- e '.$roomName);
//                   continue;
//                }
//            }
        }
        //$this->line('Done '.$roomName);

        return [
            'status' => 1,
            //'message' => 'Đã import ' . $cnt . ' hợp đồng'
        ];
    }

    public function importMoneyInfoService()
    {
//        $file = $request->file('file');
//
//        if (!\File::exists(public_path('files'))) {
//            \File::makeDirectory(public_path('files'), '0777', true);
//        }
//
//        $filename = time() . '_' . mt_rand(1111, 9999) . '_' . str_slug($request->file('file')->getClientOriginalName());
//        $filename = $filename . '.' . $file->extension();
//        $request->file('file')->move(public_path('files'), $filename);

        $filePath = $filePath = '/home/itro.vn/public_html/public/nhap-dich-vu-check-legend.xlsx';
        $items = \Excel::selectSheetsByIndex(0)->load($filePath, function ($reader) {
            $reader->noHeading();
        })->skip(1)->get();
        //dd($items);
        $ownerId = 31746;
//        if (auth('backend')->user()->type == User::STAFF) {
//            $ownerId = auth('backend')->user()->staff_owner_id;
//        }
        if (!isset($items[0]) || !isset($items[1]) || !isset($items[2])) {
            return [
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ];
        }
        $firstRow = $items[0];
        $secondRow = $items[1]; // Lấy 2 dòng đầu để xác nhận dịch vụ
        $thirdRow = $items[2]; // Lấy dòng 3 để lấy tên nhà, workaroud lỗi submit tên nhà sai

        unset($items[0]);
        unset($items[1]);

        for ($i = 1; $i <= 4; $i++) // Remove 4 cái cột đầu ko dùng đến
        {
            unset($firstRow[$i]);
            unset($secondRow[$i]);
        }

        $indexArr = [];

        if (!isset($thirdRow[1])) {
            [
                'status' => 0,
                'message' => 'Vui lòng kiểm tra dữ liệu'
            ];
        }

        $hostelName = $thirdRow[1];
        $hostel = Hostel::query()
            ->where('name', trim($hostelName))
            ->where('owner_id', $ownerId)
            ->first();

        if (!$hostel) {
            return [
                'status' => 0,
                'message' => 'Không tìm thấy nhà trọ'
            ];
        }


        $hostelId = $hostel->id;


        foreach ($firstRow as $keyFirstRow => $itemFirstRow) {
            if (!empty($itemFirstRow)) {
                $nameItem = trim($itemFirstRow);
                $fee = HostelFee::query()
                    ->where('hostel_id', $hostelId)
                    ->where('name', $nameItem)
                    ->first();

                if ($fee) {
                    if (empty($firstRow[$keyFirstRow + 1])) {
                        $start = $secondRow[$keyFirstRow];
                        if (str_contains($start, 'giá')) {
                            $indexArr[$keyFirstRow] = [
                                'type' => 'value',
                                'fee' => $fee->id
                            ];
                            $indexArr[$keyFirstRow + 1] = [
                                'type' => 'qty',
                                'fee' => $fee->id
                            ];

                        } else if (str_contains($start, 'đầu')) {
                            $indexArr[$keyFirstRow] = [
                                'type' => 'start',
                                'fee' => $fee->id
                            ];
                            $indexArr[$keyFirstRow + 1] = [
                                'type' => 'end',
                                'fee' => $fee->id
                            ];
                        } else {
                            $indexArr[$keyFirstRow] = [
                                'type' => 'qty',
                                'fee' => $fee->id
                            ];
                        }
                    } else {

                        $indexArr[$keyFirstRow] = [
                            'type' => 'qty',
                            'fee' => $fee->id
                        ];
                    }
                }
            }

            //if()
        }


        $moneyDetailArr = [];
        foreach ($items as $itemR) {
            $month = '01/' . $itemR[4];
            $sum = 0;
            $monthItem = $month;


            $roomName = $itemR[2];
            $room = Room::query()->where('name', trim($roomName))
                ->whereHas('hostel', function ($q) use ($ownerId) {
                    $q->where('owner_id', $ownerId);
                })
                ->first();

            $contract = Contract::query()->where('name', trim($itemR[3]))
//                ->whereHas('room', function ($q) use ($itemR) {
//                  $q->where('name', $itemR[2]);
//                })
                ->where('room_id', $room->id)
                ->whereHas('hostel', function ($q) use ($ownerId) {
                    $q->where('owner_id', $ownerId);
                })
                ->first();
            if (!$contract) {
                continue;
            }
            $room = $contract->room;


            $this->line('Process ' . $contract->name);
            $counter = -1;

            foreach ($itemR as $key => $item) {
                $counter++;
                if (isset($indexArr[$key])) {
                    $newKey = $key;
                    $date = Carbon::createFromFormat('d/m/Y', $month);
                    $startTime = $date->copy()->startOfMonth();
                    $endTime = $date->copy()->endOfMonth();

                    $itemIndex = $indexArr[$newKey];
                    $feeId = $itemIndex['fee'];


                    $feeItem = HostelFee::find($feeId);
                    $qty = 0;
                    $value = 0;
                    $start = 0;
                    $end = 0;

                    if ($itemIndex['type'] == 'start') {
                        $start = intval($itemR[$newKey]);
                        $end = intval($itemR[$newKey + 1]);

                    }
                    if ($itemIndex['type'] == 'end') {
                        $start = intval($itemR[$newKey - 1]);
                        $end = intval($itemR[$newKey]);

                    } else if ($itemIndex['type'] == 'value') {
                        $value = intval($itemR[$newKey]);
                        $qty = intval($itemR[$newKey + 1]);
                    } else if ($itemIndex['type'] == 'qty') {
                        $qty = intval($itemR[$newKey]);
                    }


                    $isElectric = 0;
                    $isWater = 0;
                    $feeValue = 1;
                    $feeId = 0;
                    $amount = 0;


                    if ($feeItem) {


                        $feeValue = $feeItem->fee;
                        $qtyItem = $qty;

                        if ($feeItem->type == HostelFee::ELECTRIC || $feeItem->type == HostelFee::ELECTRIC_BY_CLOCK) {

                            $ew = [];
                            $isElectric = 1;
                            if ($start > $end) {
                                continue;
                            }

                            $qtyItem = json_encode([
                                'start' => $start,
                                'end' => $end
                            ]);


                            $ew['end_electric'] = $end;
                            $ew['start_electric'] = $start;
                            $ew['delta_electric'] = $end - $start;
                            $ew['date_action'] = Carbon::createFromFormat('d/m/Y', $month)->toDateString();
                            $ew['room_id'] = $room->id;
                            $ew['hostel_id'] = $room->hostel->id;
                            $ew['contract_id'] = $contract->id;
                            $feeValue = 1;

                            if ($feeItem->type == HostelFee::ELECTRIC) {
                                $amount = Functions::calculateElectricAmount($end - $start, $room, HostelFee::ELECTRIC, $feeItem->id);
                            } else {
                                $feeValue = $feeItem->fee;
                                $amount = ($end - $start) * $feeItem->fee;
                            }


                            $itemEw = ElectricWater::query()->whereBetween('date_action', [
                                $startTime,
                                $endTime
                            ])
                                ->where('room_id', $room->id)->first();

                            if ($itemEw) {
                                $itemEw->update($ew);
                            } else {
                                ElectricWater::create($ew);
                            }

                        } else if ($feeItem->type == HostelFee::WATER || $feeItem->type == HostelFee::WATER_BY_CLOCK) {

                            $isWater = 1;
                            $ew = [];

                            if ($start > $end) {
                                continue;
                            }

                            if (empty($start) && empty($end)) {
                                continue;
                            }
                            $qtyItem = json_encode([
                                'start' => $start,
                                'end' => $end
                            ]);

                            $ew['end_water'] = $end;
                            $ew['start_water'] = $start;
                            $ew['delta_water'] = $ew['end_water'] - $ew['start_water'];
                            $ew['date_action'] = Carbon::createFromFormat('d/m/Y', $month)->toDateString();
                            $ew['room_id'] = $room->id;
                            $ew['hostel_id'] = $room->hostel->id;
                            $ew['contract_id'] = $contract->id;


                            $feeValue = 1;
                            if ($feeItem->type == HostelFee::WATER) {
                                $amount = Functions::calculateElectricAmount($end - $start, $room, HostelFee::WATER, $feeItem->id);
                            } else {
                                $feeValue = $feeItem->fee;
                                $amount = ($end - $start) * $feeItem->fee;
                            }


                            $itemEw = ElectricWater::query()->whereBetween('date_action', [
                                $startTime,
                                $endTime
                            ])
                                ->where('room_id', $room->id)->first();
                            if ($itemEw) {
                                $itemEw->update($ew);
                            } else {
                                ElectricWater::create($ew);
                            }

                        } else if ($feeItem->type == HostelFee::DYNAMIC || $feeItem->type == HostelFee::WATER_DYNAMIC || $feeItem->type == HostelFee::ELECTRIC_DYNAMIC) {

                            $feeValue = Functions::filterInputNumber($value);
                            $amount = $feeValue * $qtyItem;
                        } else {
                            $amount = $feeValue * $qtyItem;
                        }


                        $sum += $amount;
                        $name = $feeItem->name;
                        $feeId = $feeItem->id;

                    } else {

                        $name = 'Khác';
                    }

                    if ($amount != 0) {
                        $moneyDetail = MoneyDetail::query()->updateOrCreate([
                            'hostel_id' => $contract->room->hostel->id,
                            'room_id' => $contract->room->id,
                            'name' => $name,
                            'is_electric' => $isElectric,
                            'is_water' => $isWater,
                            'value' => $feeValue,
                            'qty' => $qtyItem,
                            'amount' => $amount,
                            'hostel_fee_id' => $feeId,
                        ], [
                            'hostel_id' => $contract->room->hostel->id,
                            'room_id' => $contract->room->id,
                            'name' => $name,
                            'is_electric' => $isElectric,
                            'is_water' => $isWater,
                            'value' => $feeValue,
                            'qty' => $qtyItem,
                            'amount' => $amount,
                            'hostel_fee_id' => $feeId,
                        ]);
                        $moneyDetailArr[] = $moneyDetail->id;

                    }

                }

                if (!isset($itemR[$counter + 1])) {
                    if ($contract) {
                        $dateAction = Carbon::createFromFormat('d/m/Y', $monthItem)->toDateString();
                        try {
                            $startTime = Carbon::createFromFormat('d/m/Y', $monthItem)->startOfMonth()->startOfDay()->toDateString();
                            $endTime = Carbon::createFromFormat('d/m/Y', $monthItem)->endOfMonth()->endOfDay()->toDateString();
                            $monthCarbon = Carbon::createFromFormat('d/m/Y', $monthItem);
                        } catch (\Exception $exception) {
                            $moneyDetailArr = [];
                            continue;
                        }


                        $item = MoneyInfo::query()->where('room_id', $contract->room->id)
                            ->where('type', MoneyInfo::VOUCHER_SERVICE)
                            ->validate($contract->id)
                            ->whereBetween(
                                'date_action', [$startTime, $endTime]
                            )->first();

                        $pay = 0;
                        $itemId = null;

                        if ($item) {

                            $cntCollectSpend = CollectSpend::query()
                                ->where('money_info_id', $item->id)
                                ->first();

                            if ($cntCollectSpend) {
                                $moneyDetailArr = [];

                                continue;
                            }
                            $itemId = $item->id;
                            $dateAction = $item->date_action->toDateString();
//                if ($monthCarbon->lessThan(Carbon::now())) {
//                    return response([
//                        'status' => 0,
//                        'message' => 'Hóa đơn cho tháng ' . $monthCarbon->month . ' đã tồn tại'
//                    ]);
//
//                }


                            if ($item->pay > 0) {
                                $pay = $item->pay;
                            }
                            MoneyDetail::query()->where('money_info_id', $item->id)
                                ->whereNotIn('id', $moneyDetailArr)
                                ->delete();
                            MoneyInfo::find($item->id)->delete();
//							ElectricWater::query()->whereBetween( 'date_action', [
//								$startTime,
//								$endTime
//							] )
//							                      ->where( 'room_id', $room->id )
//							                      ->delete();

                        }


                        $moneyInfo = MoneyInfo::create([
                            'hostel_id' => $contract->room->hostel->id,
                            'user_id' => $ownerId,
                            'room_id' => $contract->room->id,
                            'amount' => $sum,
                            'discount' => 0,
                            'pay' => $pay,
                            'remain' => $sum - 0 - $pay,
                            'date_action' => $dateAction,
                            'type' => MoneyInfo::VOUCHER_SERVICE,
                            'contract_id' => $contract->id,
                            'note' => ''
                        ]);


                        if (!empty($moneyDetailArr)) {


                            MoneyDetail::query()
                                ->whereIn('id', array_unique($moneyDetailArr))
                                ->update([
                                    'money_info_id' => $moneyInfo->id
                                ]);

                            $sum = MoneyDetail::query()
                                ->whereIn('id', $moneyDetailArr)
                                ->sum('amount');

                            $moneyInfo->amount = $sum;
                            $moneyInfo->remain = $sum - 0 - $moneyInfo->pay;
                            $moneyInfo->save();
                        }


                        if (!empty($itemId)) {
                            Transaction::query()->where('money_info_id', $itemId)->update([
                                'money_info_id' => $moneyInfo->id
                            ]);

                            CollectSpend::query()->where('money_info_id', $itemId)->update([
                                'money_info_id' => $moneyInfo->id,
                                'money_info_name' => $moneyInfo->name
                            ]);
                        }


                    }
                    $moneyDetailArr = [];
                }
            }
        }


        return [
            'status' => 1
        ];
    }

    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 destroyContract($id)
    {
        $item = Contract::find($id);
        if (!$item) {
            return [
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ];
        }

        $hostelId = $item->hostel_id;
        $hostel = Hostel::find($hostelId);

        $ownerId = $hostel->owner_id;

        if ($hostel) {
            if ($hostel->owner_id != $ownerId) {
                return response([
                    'status' => 0,
                    'message' => 'Bạn không có quyền xóa HĐ này'
                ]);
            }
        }

        $code = $item->code;
        $roomId = $item->room_id;
        $contractId = $item->id;

        try {
            \DB::beginTransaction();

            $collectSpends = CollectSpend::query()->where('contract_id', $contractId)->get();

            foreach ($collectSpends as $collectSpend) {
                $transactionId = $collectSpend->transaction_id;
                $transaction = Transaction::find($transactionId);
                if ($transaction) {
                    $transaction->delete();
                }
            }
            CollectSpend::query()->where('contract_id', $contractId)->delete();
            StatisticLog::query()->where('contract_id', $contractId)->delete();

            $moneyInfos = MoneyInfo::where('contract_id', $contractId)->get();

            foreach ($moneyInfos as $moneyInfo) {
                MoneyDetail::query()->where('money_info_id', $moneyInfo->id)->delete();
                CollectSpend::query()->where('money_info_id', $moneyInfo->id)->delete();
                Statistic::query()->where('money_info_id', $moneyInfo->id)->delete();
            }

            $room = $item->room;

            MoneyInfo::where('contract_id', $contractId)->delete();

            if ($item->status != Contract::LIQUIDATED) {
                $renterRoom = RenterRoom::query()->where('user_id', $item->renter_id)
                    ->where('room_id', $roomId)->first();
                if ($renterRoom) {
                    $renterRoom->delete();
                }

                RenterRoom::query()
                    ->where('room_contract_id', $contractId)
                    ->whereNull('contract_id')
                    ->delete();

                RenterRoom::query()
                    ->where('contract_id', $contractId)
                    ->delete();

                $renter = Renter::query()
                    ->where('user_id', $item->renter_id)
                    ->where('room_id', $roomId)
                    ->first();
                if ($renter) {
                    $renter->delete();
                }

                RenterBike::query()->where('renter_id', $item->renter_id)->where('room_id', $roomId)->delete();

                if ($room->hostel->type_rent == Hostel::TYPE_RENT_ALL) {
                    //RenterRoom::query()->where( 'room_id', $roomId )->delete();
                    RenterBike::query()->where('room_id', $roomId)->delete();
                    //	Renter::query()->where( 'room_id', $roomId )->delete();
                }
            }


            $item->delete();

            \DB::commit();
            if ($hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                RoomBed::query()->where('id', $item->bed_id)->update([
                    'status' => RoomBed::AVAILABLE,
                ]);
            }
            StatisticLog::query()->where('contract_id', $contractId)->delete();
            dispatch(new DeleteRenterConversation($item->renter_id, $item->room_id));

        } catch (\Exception $exception) {
            \DB::rollBack();

            dd($exception->getTraceAsString());

            return response([
                'status' => 0,
                'message' => 'Có lỗi xảy ra vui lòng thử lại sau'
            ]);

        }

        return [
            'status' => 1,
            'message' => 'Thành công'
        ];


    }

    public function genInvoice(Carbon $startDate, Carbon $endDate, $contract)
    {
        $dayCollect = $contract->day_collect;
        $period = Functions::getPeriodNumber($contract->period);
        if (Functions::checkFullPeriod($startDate->copy(), $endDate->copy(), $dayCollect)) {
            $money = $contract->room_price * $period;
        } else {
            $money = Functions::calculateMoneyInRange4($startDate->copy(), $endDate->copy(), $contract->room_price, $contract->day_collect);
        }

        $name = 'Thu tiền phòng từ ' . $startDate->copy()->format('d/m/Y') . ' đến ' . $endDate->copy()->format('d/m/Y');

        $moneyInfo = MoneyInfo::create([
            'hostel_id' => $contract->hostel_id,
            'room_id' => $contract->room_id,
            'bed_id' => $contract->bed_id,
            'date_action' => $startDate->copy()->toDateString(),
            'contract_id' => $contract->id,
            'user_id' => $contract->renter_id,
            'type' => MoneyInfo::VOUCHER_CONTRACT,
            'amount' => $money,
            'pay' => 0,
            'remain' => $money,
            'money_info_name' => $name
        ]);

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

        $range = round($money / ($cost), 2);

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

        dump($contract->id, $contract->name, $contract->phone);
        dump($startDate->copy()->format('d/m/Y'), $endDate->copy()->format('d/m/Y'));
        dump($money);
        dump('---');


    }

    public function pCP($item)
    {
        $moneyInfo = $item->moneyInfo;
        $note = $item->name;
        if ($item->type == CollectSpend::COLLECT) {
            if (!$item->is_deposit) {
                if ($moneyInfo) {
                    $itemStats = StatisticMonth::query()->where('money_info_id', $moneyInfo->id)
                        ->whereRaw('current_paid < amount')
                        ->get();
                    $collect = $item->amount;

                    if ($itemStats->count() > 0) {
                        foreach ($itemStats as $itemStat) {
                            if ($collect > 0) {
                                $paid = $itemStat->current_paid + $collect;
                                if ($paid > $itemStat->amount) {
                                    $collect = $paid - $itemStat->amount;
                                    $logCollect = $itemStat->amount - $itemStat->current_paid;
                                    $paid = $itemStat->amount;
                                } else {
                                    $logCollect = $collect;
                                    $collect = 0;
                                }
                                if ($logCollect > 0) {
                                    StatisticLog::query()->updateOrCreate([
                                        'collect_spend_id' => $item->id,
                                        'statistic_month_id' => $itemStat->id,
                                    ], [
                                        'amount' => $logCollect,
                                        'month' => $itemStat->month,
                                        'year' => $itemStat->year,
                                        'type' => CollectSpend::COLLECT,
                                        'hostel_id' => $itemStat->hostel_id,
                                        'room_id' => $itemStat->room_id,
                                        'collect_spend_id' => $item->id,
                                        'statistic_month_id' => $itemStat->id,
                                        'contract_id' => $moneyInfo->contract_id,
                                        'note' => $note
                                    ]);
                                }
                                $itemStat->current_paid = $paid;
                                $itemStat->save();

                            }
                        }
                    } else {
                        $itemStats = StatisticMonth::query()->where('money_info_id', $moneyInfo->id)->get();
                        if ($itemStats->count() > 0) {
                            foreach ($itemStats as $itemStat) {
                                StatisticLog::query()->updateOrCreate([
                                    'collect_spend_id' => $item->id,
                                    'statistic_month_id' => $itemStat->id,
                                ], [
                                    'amount' => $itemStat->amount,
                                    'month' => !empty($moneyInfo->date_action) ? $moneyInfo->date_action->month : Carbon::now()->month,
                                    'year' => !empty($moneyInfo->date_action) ? $moneyInfo->date_action->year : Carbon::now()->year,
                                    'type' => CollectSpend::COLLECT,
                                    'hostel_id' => $item->hostel_id,
                                    'room_id' => $item->room_id,
                                    'collect_spend_id' => $item->id,
                                    'contract_id' => $moneyInfo->contract_id,
                                    'statistic_month_id' => $itemStat->id,
                                    'note' => $note
                                ]);
                            }
                        } else {
                            StatisticLog::query()->updateOrCreate([
                                'collect_spend_id' => $item->id,
                            ], [
                                'amount' => $item->amount,
                                'month' => !empty($moneyInfo->date_action) ? $moneyInfo->date_action->month : Carbon::now()->month,
                                'year' => !empty($moneyInfo->date_action) ? $moneyInfo->date_action->year : Carbon::now()->year,
                                'type' => CollectSpend::COLLECT,
                                'hostel_id' => $item->hostel_id,
                                'room_id' => $item->room_id,
                                'collect_spend_id' => $item->id,
                                'contract_id' => $moneyInfo->contract_id,
                                'note' => $note
                            ]);
                        }
                    }
                } else {
                    $itemStat = StatisticMonth::create([
                        'month' => !empty($item->date_action) ? $item->date_action->month : Carbon::now()->month,
                        'year' => !empty($item->date_action) ? $item->date_action->year : Carbon::now()->year,
                        'amount' => $item->amount,
                        'contract_id' => $item->contract_id,
                        'room_id' => $item->room_id,
                        'hostel_id' => $item->hostel_id,
                        'money_info_id' => $item->money_info_id,

                    ]);
                    StatisticLog::query()->updateOrCreate([
                        'collect_spend_id' => $item->id,
                    ], [
                        'amount' => $item->amount,
                        'month' => !empty($item->date_action) ? $item->date_action->month : Carbon::now()->month,
                        'year' => !empty($item->date_action) ? $item->date_action->year : Carbon::now()->year,
                        'type' => CollectSpend::COLLECT,
                        'hostel_id' => $item->hostel_id,
                        'room_id' => $item->room_id,
                        'collect_spend_id' => $item->id,
                        'statistic_month_id' => $itemStat->id,
                        'contract_id' => $item->contract_id,
                        'note' => $note
                    ]);
                }
            }
        } else {
            if ($item->is_deposit) {
                $type = TypeSpend::query()
                    ->where('is_default', TypeSpend::TIEN_COC)
                    ->where('owner_id', $item->hostel->owner_id)
                    ->first();
                if ($type) {
                    $item->type_purpose = $type->id;
                }
            }
            if (!$item->is_deposit) {
                StatisticLog::query()->updateOrCreate([
                    'collect_spend_id' => $item->id,
                ], [
                    'amount' => $item->amount,
                    'month' => !empty($item->date_action) ? $item->date_action->month : Carbon::now()->month,
                    'year' => !empty($item->date_action) ? $item->date_action->year : Carbon::now()->year,
                    'type' => CollectSpend::SPEND,
                    'hostel_id' => $item->hostel_id,
                    'room_id' => $item->room_id,
                    'collect_spend_id' => $item->id,
                    'contract_id' => $item->contract_id,
                    'owner_id' => $item->owner_id,
                    'note' => $note
                ]);
            }
        }

    }

    public function handle()
    {

        $items = \File::get(storage_path('workplace.json'));
        $items = json_decode($items, true);
        Workplace::query()->truncate();
        foreach($items as $item)
        {
           //
            $w=  Workplace::create($item);
            $this->line($w->id);
        }
        dd();

        $files = \File::files(public_path('files'));
        foreach($files as $file)
        {
            $name = $file->getFilenameWithoutExtension();
            if(str_contains($name, 'Du-lieu-backup-ngay'))
            {
               \File::delete(public_path('files/'.$file->getRelativePathname()));
               $this->line($file->getRelativePathname());
            }
        }
        dd();

        $moneyInfos = MoneyInfo::query()
            ->where('remain', '<>', 0)
            ->whereHas('hostel', function ($q) {
                $q->where('owner_id', 16457);
            })
            ->where('date_action', '<=', Carbon::now()->startOfMonth()->startOfDay())
            ->get();
        foreach ($moneyInfos as $moneyInfo) {
            $dateAction = $moneyInfo->created_at;
            if ($moneyInfo) {
                try {
                    \DB::beginTransaction();
                    $userId = $this->user->id;

                    $currentRemain = $moneyInfo->remain;

                    $amount = $currentRemain;

                    $transaction = Transaction::create([
                        'amount' => $amount,
                        'hostel_id' => $moneyInfo->hostel_id,
                        'room_id' => $moneyInfo->room_id,
                        'date_action' => $dateAction,
                        'user_id' => $userId,
                        'money_info_id' => $moneyInfo->id,
                        'type' => CollectSpend::COLLECT
                    ]);

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

                    $remain = $moneyInfo->remain - $amount;

                    $moneyInfo->pay = $moneyInfo->pay + $amount;
                    $moneyInfo->remain = $remain;
                    $moneyInfo->save();

                    $cp = CollectSpend::create([
                        'amount' => $amount,
                        'hostel_id' => $moneyInfo->hostel_id,
                        'room_id' => $moneyInfo->room_id,
                        'payment_method' => CollectSpend::MONEY,
                        'date_action' => $dateAction,
                        'type' => CollectSpend::COLLECT,
                        'name' => $this->user->name,
                        'transaction_id' => $transaction->id
                    ]);
                    \DB::commit();
                    $this->line($moneyInfo->id);
                } catch (\Exception $exception)
                {
                    dd($exception->getMessage());
                    \DB::rollBack();
                }
            }
        }

        dd();


        $phone = '0982291844';

        $hostelIds = Hostel::query()
            ->whereHas('owner', function ($q) use ($phone) {
                $q->where('phone', $phone);
            })
            ->pluck('id')
            ->toArray();

        $items = StatisticLog::query()
            ->with('statMonth')
            ->has('statMonth')
            ->whereIn('hostel_id', $hostelIds)
            ->get();
        //   dd($items->count());
        foreach ($items as $item) {
            $item->month = $item->statMonth->month;
            $item->year = $item->statMonth->year;
            $item->save();
        }

        dd();

        $string = '12';
        dd($string[0]);
        $roomId = 32096;
        $moneyInfos = MoneyInfo::query()
            ->onlyTrashed()
            ->where('room_id', $roomId)
            ->get();
        foreach ($moneyInfos as $moneyInfo) {
            $contractId = $moneyInfo->contract_id;
            $contract = Contract::find($contractId);
            if ($contract) {
                $moneyInfo->restore();
                MoneyDetail::query()->where('money_info_id', $moneyInfo->id)->restore();
                CollectSpend::query()->where('money_info_id', $moneyInfo->id)->restore();
            }
            $this->line($moneyInfo->id);
        }
        dd();

        Contract::query()->where('hostel_id', 7892)->restore();
        MoneyInfo::query()->where('hostel_id', 7892)->restore();
        CollectSpend::query()->where('hostel_id', 7892)->restore();
        Transaction::query()->where('hostel_id', 7892)->restore();
        StatisticLog::where('hostel_id', 7892)->restore();
        Statistic::where('hostel_id', 7892)->restore();
        dd();


        dd(Carbon::createFromFormat('Y-m-d', '2021-05-31')->addDay());

        $logs = StatisticLog::query()
            ->has('collectSpend.moneyInfo')
            ->with('collectSpend.moneyInfo')
            ->orderBy('id', 'desc')->chunk(1000, function ($logs) {
                foreach ($logs as $log) {
                    if ($log->month != $log->collectSpend->moneyInfo->date_action->month) {
                        $log->month = $log->collectSpend->moneyInfo->date_action->month;
                    }

                    if ($log->year != $log->collectSpend->moneyInfo->date_action->year) {
                        $log->year = $log->collectSpend->moneyInfo->date_action->year;
                    }

                    $log->save();
                    $this->line($log->id);
                }

            });
        dd();


        $owner = User::query()->where('phone', '0355954088')
            ->first();
        $moneyDetails = MoneyDetail::query()
            ->whereHas('hostel', function ($q) use ($owner) {
                $q->where('owner_id', $owner->id);
            })
            ->where('is_electric', 1)
            ->get();
        foreach ($moneyDetails as $moneyDetail) {
            if (in_array($moneyDetail->hostelFee->type, [

                HostelFee::WATER,
                HostelFee::WATER_BY_CLOCK,
                HostelFee::WATER_BY_PEOPLE,
                HostelFee::WATER_DYNAMIC
            ])) {
                $moneyDetail->is_water = 1;
                $moneyDetail->is_electric = 0;
                $moneyDetail->save();
            }
            $this->line($moneyDetail->id);
        }
        dd();
        CollectSpend::onlyTrashed()
            ->whereHas('hostel', function ($q) {
                $q->where('id', 11015);
            })
            ->whereHas('moneyInfo', function ($q) {
                $q->whereBetween('date_action', [
                    Carbon::now()->startOfMonth(),
                    Carbon::now()->endOfMonth(),
                ])
                    ->whereIn('type', [
                        MoneyInfo::VOUCHER_ROOM_PRICE,
                        MoneyInfo::VOUCHER_CONTRACT
                    ]);
            })->restore();
        MoneyInfo::onlyTrashed()
            ->whereHas('hostel', function ($q) {
                $q->where('id', 11015);
            })
            ->whereBetween('date_action', [
                Carbon::now()->startOfMonth(),
                Carbon::now()->endOfMonth(),
            ])
            ->whereIn('type', [
                MoneyInfo::VOUCHER_ROOM_PRICE,
                MoneyInfo::VOUCHER_CONTRACT
            ])
            ->restore();
        dd();


        dd();

        $filePath = '/home/itro.vn/public_html/public/files/1621656930_4825_202-2xlsx.xlsx';

        $ownerId = 36385;
        $userId = 36385;

        dispatch_now(new ImportContract($filePath, $ownerId, $userId));
        dd();

        //  $phone = '0869171717';
        $phone = '0869171717';

//                $contracts = CollectSpend::query()
//            ->whereHas('hostel.owner', function($q) use ($phone) {
//                $q->where('phone', $phone);
//            })->delete();
//                dd($contracts);
        $contracts = Contract::query()
            ->whereHas('hostel.owner', function ($q) use ($phone) {
                $q->where('phone', $phone);
            })
            ->get();
        foreach ($contracts as $contract) {
            $this->destroyContract($contract->id);
            $this->line($contract->id);
        }
        dd();

        $contractIds = [
            23317,
            23348,
            23374,
            23377,

        ];

        $dateStart = Carbon::createFromFormat('d/m/Y', '01/11/2020');
        $dateEnd = Carbon::createFromFormat('d/m/Y', '30/10/2021');

        Contract::query()
            ->whereIn('id', $contractIds)
            ->update([

                'date_enable' => $dateStart->copy()->toDateString(),
                'date_contract' => $dateStart->copy()->toDateString(),
                'start_date' => $dateStart->copy()->toDateString(),
                'date_join' => $dateStart->copy()->toDateString(),
                'end_date' => $dateEnd->copy()->toDateString(),

            ]);
        dd();

        $item = Room::query()
            ->whereHas('hostel', function ($q) {
                $q->where('owner_id', 31220);
            })
            ->count();
        dd($item);


        Permission::create([
            'name' => 'change-room'
        ]);
        $role = Role::where('name', 'owner')->first();
        $permissions = Permission::all()->pluck('name')->toArray();
        $role->syncPermissions($permissions);

        dd();

        try {
            $phone = '0979652628';

            $owner = User::query()->where('phone', $phone)->first();
            $hostels = Hostel::query()
                ->where('owner_id', $owner->id)
                //  ->where('id', 11600)
                ->get();

            foreach ($hostels as $hostel) {
                $contracts = Contract::query()
                    ->where('hostel_id', $hostel->id)
                    ->get();
                foreach ($contracts as $contract) {
                    $period = Functions::getPeriodNumber($contract->period);
                    $dayCollect = $contract->day_collect;
                    $cost = $contract->room_price;
                    $collectToCarbon = null;
                    if ($contract->is_collected) {
                        $collectToCarbon = Carbon::createFromFormat('Y-m-d', $contract->collect_to);
                    }
                    $moneyInfos = MoneyInfo::query()
                        // ->where('id', 409523)
                        ->where('contract_id', $contract->id)
                        ->whereIn('type', [
                            MoneyInfo::VOUCHER_CONTRACT,
                            MoneyInfo::VOUCHER_ROOM_PRICE
                        ])
                        ->get();

                    foreach ($moneyInfos as $moneyInfo) {
                        $detail = MoneyDetail::query()
                            ->where('money_info_id', $moneyInfo->id)
                            ->where('end_date', '>', $contract->end_date)
                            ->orderBy('end_date', 'desc')
                            ->first();

                        if ($detail) {
                            $detail->end_date = $contract->end_date->copy()->format('Y-m-d');
                            $startDate = Carbon::createFromFormat('Y-m-d', $detail->start_date);

                            if (!empty($collectToCarbon)) {
                                $amount = Functions::calculateMoneyInRange2($startDate->copy(), $contract->end_date->copy(), $dayCollect, $period, $cost, $collectToCarbon);
                            } else {
                                $amount = Functions::calculateMoneyInRange4($startDate->copy(), $contract->end_date->copy(), $cost, $dayCollect);
                            }
                            // $detail->amount = $amount;
                            $detail->sum_amount = $amount;
                            $detail->note = 'Thu tiền phòng từ ' . $startDate->copy()->format('d/m/Y') . ' đến ' . $contract->end_date->copy()->format('d/m/Y');
                            $detail->name = 'Thu tiền phòng từ ' . $startDate->copy()->format('d/m/Y') . ' đến ' . $contract->end_date->copy()->format('d/m/Y');
                            $detail->qty = round($amount / $detail->value, 2);
                            $detail->save();

                            $sum = MoneyDetail::query()
                                ->where('money_info_id', $moneyInfo->id)
                                ->sum('sum_amount');

                            $moneyInfo->amount = $sum;
                            $moneyInfo->remain = $sum - 0 - $moneyInfo->pay;
                            $moneyInfo->money_info_name = 'Thu tiền phòng từ ' . $startDate->copy()->format('d/m/Y') . ' đến ' . $contract->end_date->copy()->format('d/m/Y');
                            $dt = $moneyInfo->created_at->format('dmy');
                            $moneyInfo->name = 'HD' . $moneyInfo->id . $dt;
                            $moneyInfo->save();

                            $this->line($moneyInfo->id);
                        }
                    }
                }
            }
        } catch (\Exception $exception) {
            dd($exception->getTraceAsString());
        }
        dd();

        $hostelId = 11332;

        $moneyInfos = MoneyInfo::query()
            ->where('hostel_id', $hostelId)
            ->where('type', MoneyInfo::VOUCHER_SERVICE)
            ->where('amount', 0)
            ->has('details')
            ->get();
        $fee = HostelFee::find(12225);
        foreach ($moneyInfos as $moneyInfo) {
            $sum = MoneyDetail::query()
                ->where('money_info_id', $moneyInfo->id)
                ->sum('amount');

            $moneyInfo->amount = $sum;
            $moneyInfo->remain = $sum - 0 - $moneyInfo->pay;
            $moneyInfo->save();
        }
        dd();

        $rooms = Room::query()
            ->whereHas('hostel.owner', function ($q) {
                $q->where('phone', '0909640608');
            })
            ->whereHas('hostel', function ($q) {
                $q->where('type_rent', Hostel::TYPE_RENT_ALL);
            })
            ->count();
        $beds = RoomBed::query()
            ->whereHas('hostel.owner', function ($q) {
                $q->where('phone', '0909640608');
            })
            ->whereHas('hostel', function ($q) {
                $q->where('type_rent', Hostel::TYPE_RENT_EVERY);
            })
            ->count();
        dump($beds);
        dd($rooms);


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

        $items = CollectSpend::query()
            ->whereHas('hostel', function ($q) use ($owner) {
                $q->where('owner_id', $owner->id);
            })
            ->whereNotNull('money_info_id')
            ->doesntHave('moneyInfo')
            ->delete();
        dd($items);


        dd(CollectSpend::query()
            ->where('type', CollectSpend::SPEND)
            ->where('is_allow_cycle', true)
            ->count());
        CollectSpend::query()
            ->where('type', CollectSpend::SPEND)
            ->where('is_deposit', false)
            ->where('note', 'LIKE', 'Trả lại tiền phòng từ %')
            ->update([
                'is_allow_cycle' => false
            ]);
        dd();

        $contract = Contract::find(27986);

        $contract->bed_id = 561010;
        $contract->room_id = 34223;
        $contract->save();
        dd();


        $item = CollectSpend::find(211573);
        $moneyInfo = MoneyInfo::find($item->money_info_id);
        $note = $item->name;

        if (!$item->is_deposit) {

            if ($moneyInfo) {
                $moneyDetail = MoneyDetail::query()->where('money_info_id', $moneyInfo->id)->first();
                $startDate = $moneyDetail->start_date;
                $endDate = $moneyDetail->end_date;
                if ($moneyInfo->type == MoneyInfo::VOUCHER_CONTRACT || $moneyInfo->type == MoneyInfo::VOUCHER_ROOM_PRICE) {
                    $contract = $moneyInfo->contract;

                    if (empty($startDate) || empty($endDate)) {
                        return;
                    }

                    $startDateCarbon = Carbon::createFromFormat('Y-m-d', $startDate);
                    $endDateCarbon = Carbon::createFromFormat('Y-m-d', $endDate);
                    $dayCollect = $contract->day_collect;
                    $cost = $contract->room_price;
                    $items = Functions::statFromMoneyInfo($startDateCarbon->copy(), $endDateCarbon->copy(), $cost, $dayCollect);

                    foreach ($items as $itemMonth) {
                        StatisticMonth::create([
                            'month' => $itemMonth['month'],
                            'year' => $itemMonth['year'],
                            'start_date' => $itemMonth['from'],
                            'end_date' => $itemMonth['to'],
                            'amount' => $itemMonth['money'],
                            'contract_id' => $contract->id,
                            'room_id' => !empty($contract->room) ? $contract->room->id : null,
                            'hostel_id' => !empty($contract->hostel) ? $contract->hostel->id : null,
                            'money_info_id' => $moneyInfo->id,
                        ]);
                    }
                }
                $itemStats = StatisticMonth::query()->where('money_info_id', $moneyInfo->id)
                    ->whereRaw('current_paid < amount')
                    ->get();
                $collect = $item->amount;

                if ($itemStats->count() > 0) {
                    foreach ($itemStats as $itemStat) {
                        if ($collect > 0) {
                            $paid = $itemStat->current_paid + $collect;
                            if ($paid > $itemStat->amount) {
                                $collect = $paid - $itemStat->amount;
                                $logCollect = $itemStat->amount - $itemStat->current_paid;
                                $paid = $itemStat->amount;
                            } else {
                                $logCollect = $collect;
                                $collect = 0;
                            }
                            if ($logCollect > 0) {
                                StatisticLog::query()->updateOrCreate([
                                    'collect_spend_id' => $item->id,
                                    'statistic_month_id' => $itemStat->id,
                                ], [
                                    'amount' => $logCollect,
                                    'month' => $itemStat->month,
                                    'year' => $itemStat->year,
                                    'type' => CollectSpend::COLLECT,
                                    'hostel_id' => $itemStat->hostel_id,
                                    'room_id' => $itemStat->room_id,
                                    'collect_spend_id' => $item->id,
                                    'statistic_month_id' => $itemStat->id,
                                    'contract_id' => $moneyInfo->contract_id,
                                    'note' => $note
                                ]);
                            }
                            $itemStat->current_paid = $paid;
                            $itemStat->save();

                        }
                    }
                } else {
                    $itemStats = StatisticMonth::query()->where('money_info_id', $moneyInfo->id)->get();
                    if ($itemStats->count() > 0) {
                        foreach ($itemStats as $itemStat) {
                            StatisticLog::query()->updateOrCreate([
                                'collect_spend_id' => $item->id,
                                'statistic_month_id' => $itemStat->id,
                            ], [
                                'amount' => $itemStat->amount,
                                'month' => $itemStat->month,
                                'year' => $itemStat->year,
                                'type' => CollectSpend::COLLECT,
                                'hostel_id' => $item->hostel_id,
                                'room_id' => $item->room_id,
                                'collect_spend_id' => $item->id,
                                'contract_id' => $moneyInfo->contract_id,
                                'statistic_month_id' => $itemStat->id,
                                'note' => $note
                            ]);
                        }
                    } else {
                        StatisticLog::query()->firstOrCreate([
                            'collect_spend_id' => $item->id,
                        ], [
                            'amount' => $item->amount,
                            'month' => !empty($moneyInfo->date_action) ? $moneyInfo->date_action->month : Carbon::now()->month,
                            'year' => !empty($moneyInfo->date_action) ? $moneyInfo->date_action->year : Carbon::now()->year,
                            'type' => CollectSpend::COLLECT,
                            'hostel_id' => $item->hostel_id,
                            'room_id' => $item->room_id,
                            'collect_spend_id' => $item->id,
                            'contract_id' => $moneyInfo->contract_id,
                            'note' => $note
                        ]);
                    }
                }
            } else {
                $itemStat = StatisticMonth::create([
                    'month' => !empty($item->date_action) ? $item->date_action->month : Carbon::now()->month,
                    'year' => !empty($item->date_action) ? $item->date_action->year : Carbon::now()->year,
                    'amount' => $item->amount,
                    'contract_id' => $item->contract_id,
                    'room_id' => $item->room_id,
                    'hostel_id' => $item->hostel_id,
                    'money_info_id' => $item->money_info_id,

                ]);
                StatisticLog::query()->updateOrCreate([
                    'collect_spend_id' => $item->id,
                ], [
                    'amount' => $item->amount,
                    'month' => !empty($item->date_action) ? $item->date_action->month : Carbon::now()->month,
                    'year' => !empty($item->date_action) ? $item->date_action->year : Carbon::now()->year,
                    'type' => CollectSpend::COLLECT,
                    'hostel_id' => $item->hostel_id,
                    'room_id' => $item->room_id,
                    'collect_spend_id' => $item->id,
                    'statistic_month_id' => $itemStat->id,
                    'contract_id' => $item->contract_id,
                    'note' => $note
                ]);
            }
        }
        dd();
        \Mail::raw('hello', function ($mail) {
            $mail->to('huynt57@gmail.com');
        });

        dd();
        $logs = StatisticLog::query()
            ->has('statMonth')
            ->orderBy('id', 'desc')
            ->get();
        foreach ($logs as $log) {
            if ($log->month != $log->statMonth->month) {
                $log->month = $log->statMonth->month;
            }

            if ($log->year != $log->statMonth->year) {
                $log->year = $log->statMonth->year;
            }

            $log->save();
            $this->line($log->id);
        }
        dd();

        $items = RenterRoom::query()
            ->whereNotNull('room_contract_id')
            ->whereNull('contract_id')
            ->doesntHave('roomContract')
            ->delete();
        dd($items);

        $phone = '0384853993';
        $owner = User::query()->where('phone', $phone)->first();
        $hostelArrs = Hostel::query()->where('owner_id', $owner->id)
            ->pluck('id')
            ->toArray();

        StatisticLog::query()->whereIn('hostel_id', $hostelArrs)
            ->doesntHave('moneyInfo')
            ->whereNotNull('money_info_id')
            ->delete();
        dd();
        $contractId = 27913;

        $moneyInfos = MoneyInfo::query()
            ->where('contract_id', $contractId)
            ->whereIn('type', [
                MoneyInfo::VOUCHER_CONTRACT,
                MoneyInfo::VOUCHER_ROOM_PRICE
            ])
            ->where('date_action', '>', '2021-04-01')
            ->delete();

        $contract = Contract::find($contractId);
        $contract->collect_to = Carbon::createFromFormat('Y-m-d', $contract->collect_to)->subYear()->toDateString();
        $contract->last_invoice_at = $this->getLatestInvoice($contractId);
        $contract->save();


        dd($moneyInfos);

        $owner = User::query()->where('phone', '0982952852')->first();
        $hostels = Hostel::query()->where('owner_id', $owner->id)->get();


        $files = \File::allFiles(public_path('/'));
        $bar = $this->output->createProgressBar(count($files));
        foreach ($files as $file) {
            $bar->advance();
            if (\File::extension($file['filename']) == 'php') {
                $this->line($file['path'] . '/' . $file['filename']);
            }
        }
        $bar->finish();
        dd();


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

        $hostels = Hostel::query()->where('owner_id', $owner->id)->get();
        foreach ($hostels as $hostel) {


            $ews = ElectricWater::query()
                ->where('hostel_id', $hostel->id)
                ->whereBetween('date_action', [
                    Carbon::createFromFormat('d/m/Y', '01/03/2021')->startOfMonth()->startOfDay(),
                    Carbon::createFromFormat('d/m/Y', '01/03/2021')->endOfMonth()->endOfDay(),
                ])
                ->get();

            foreach ($ews as $ew) {
                $previous = ElectricWater::query()
                    ->where('hostel_id', $hostel->id)
                    ->where('contract_id', $ew->contract_id)
                    ->where('room_id', $ew->room_id)
                    ->whereBetween('date_action', [
                        Carbon::createFromFormat('d/m/Y', '01/02/2021')->startOfMonth()->startOfDay(),
                        Carbon::createFromFormat('d/m/Y', '01/02/2021')->endOfMonth()->endOfDay(),
                    ])
                    ->first();

                if ($previous) {
                    if ($previous->start_electric == $ew->start_electric) {
//                        $ew->start_electric = $previous->end_electric;
//                        $ew->delta_electric = $ew->end_electric - $previous->end_electric;
//                        $ew->save();
                        $this->line($ew->id);
                        $this->line($ew->hostel->name);
                        $this->line($ew->room->name);
                        // dd();
                    }
                }
            }

        }
        dd();

        $moneyInfos = MoneyInfo::query()->whereIn('hostel_id', $hostels->pluck('id')->toArray())
            ->where('type', MoneyInfo::VOUCHER_SERVICE)
            ->get();
        foreach ($moneyInfos as $moneyInfo) {
            $details = MoneyDetail::query()
                ->where('money_info_id', $moneyInfo->id)
                ->whereNull('name')
                ->get();
            foreach ($details as $detail) {
                $detail->name = $detail->hostelFee->name;
                $detail->save();
            }
        }
        dd();

        $beds = RoomBed::query()
            ->whereHas('hostel', function ($q) {
                $q->where('hostels.type_rent', Hostel::TYPE_RENT_ALL);
            })
            ->delete();
        dd($beds);

        $from = Carbon::createFromFormat('d/m/Y', '03/03/2021');
        $to = Carbon::createFromFormat('d/m/Y', '01/04/2021');
        dd(Functions::checkFullPeriod($from, $to, 04));
        $contracts = Contract::query()
            ->where('hostel_id', 11111)
            //  ->where('id', 27009)
            ->get();
        $target = Carbon::createFromFormat('d/m/Y', '01/04/2021');
        $collectToCarbon = $target->copy();
        foreach ($contracts as $contract) {
            $check = MoneyInfo::query()->where('contract_id', $contract->id)
                ->whereIn('type', [MoneyInfo::VOUCHER_ROOM_PRICE, MoneyInfo::VOUCHER_CONTRACT])
                ->count();
            if ($check > 0) {
                continue;
            }
            $roomId = $contract->room_id;
            $hostelId = $contract->hostel_id;
            $period = Functions::getPeriodNumber($contract->period);
            $dateEnable = $contract->date_enable;
            $dayCollect = $dateEnable->copy()->day;
            $from = $dateEnable->copy();
            $periodMoney = $period;
            $cost = $contract->room_price;
            $user = $contract->hostel->owner;


            if (!empty($target)) {
                while ($from->lessThanOrEqualTo($target)) {
                    if ($period > 1) {
                        $month = $from->copy()->firstOfMonth()->addMonth($period - 1)->month;
                        $year = $from->copy()->firstOfMonth()->addMonth($period - 1)->year;
                        if ($dayCollect <= $from->copy()->day) {
                            $month = $from->copy()->firstOfMonth()->addMonth($period)->month;
                            $year = $from->copy()->firstOfMonth()->addMonth($period)->year;
                        }
                    } else {
                        $month = $from->copy()->month;
                        $year = $from->copy()->year;
                        if ($dayCollect <= $from->copy()->day) {
                            $month = $from->copy()->firstOfMonth()->addMonth()->month;
                            $year = $from->copy()->firstOfMonth()->addMonth()->year;
                        }
                    }

                    $isValid = true;
                    if (checkdate($month, $dayCollect, $year)) {
                        $to = Carbon::createFromFormat('d-m-Y', $dayCollect . '-' . $month . '-' . $year);
                    } else {
                        $isValid = false;
                        $tempDayCollect = Carbon::createFromFormat('d-m-Y', '01-' . $month . '-' . $year)->lastOfMonth()->day;
                        $to = Carbon::createFromFormat('d-m-Y', $tempDayCollect . '-' . $month . '-' . $year);
                    }
                    if ($to->copy()->month == $collectToCarbon->copy()->month) {
                        $to = $collectToCarbon->copy();
                    }
                    //dump( $from->toDateString() . '|' . $to->toDateString() );
                    $money = $periodMoney * $cost;
                    $sumMoney = $money;
                    $isCollect = true;

                    if ($isValid == true) {
                        if (!empty($collectToCarbon)) {

                            if ($collectToCarbon->greaterThanOrEqualTo($from->copy()) && $collectToCarbon->lessThan($to->copy())) {

                                if ($period > 1) {
                                    $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);

                                } else {
                                    if (!Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect)) {
                                        $diffDays = $collectToCarbon->copy()->diffInDays($from->copy());
                                        $numberDays = 30;
                                        $money = intval($cost / ($numberDays) * ($diffDays + 1));
                                    } else {
                                        if ($to->copy()->day == $dayCollect && $from->copy()->subDay(1)->month == 2) {
//										$numberMonth = $from->copy()->firstOfMonth()->diffInMonths( $to->copy()->firstOfMonth() );
//										$money       = $cost * $numberMonth;
                                            $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
                                        } else {
                                            $diffDays = $collectToCarbon->copy()->diffInDays($from->copy());
                                            $numberDays = $from->copy()->daysInMonth;

                                            //$money = intval( $cost / ( $numberDays + 1 ) * ( $diffDays + 1 ) );
                                            $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
                                        }
                                    }
                                }

                            } else if ($collectToCarbon->greaterThan($to->copy())) {

                                if ($period > 1) {
                                    $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
                                } else {

                                    if ($from->copy()->day != $to->copy()->day) {
                                        // dump($from->copy()->toDateString());
                                        // dump($to->copy()->toDateString());
                                        // dump('--');
                                        if (Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect)) {
                                            $money = $periodMoney * $cost;
                                        } else {
                                            $diffDays = $to->copy()->diffInDays($from->copy());
                                            $numberDays = 30;
                                            $money = intval($cost / ($numberDays) * ($diffDays + 1));
                                        }
                                        //  dump($money);
                                    } else {
                                        $money = $periodMoney * $cost;
                                    }
                                }
                            } else if ($collectToCarbon->equalTo($to->copy())) {
                                if ($period > 1) {
                                    if (Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect)) {
                                        $money = $periodMoney * $cost;
                                    } else {
                                        $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
                                    }
                                } else {
                                    if (Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect)) {
                                        $money = $periodMoney * $cost;
                                    } else {

                                        $diffDays = $to->copy()->diffInDays($from->copy());
                                        $numberDays = 30;
                                        $money = intval($cost / ($numberDays) * ($diffDays + 1));
                                    }
                                }
                            } else {
                                $money = 0;
                            }
                        } else {
                            $money = Functions::calculateMoneyInRange4($from->copy(), $to->copy(), $cost, $dayCollect);
                            $isCollect = false;
                        }
                    } else {

                        if (!empty($collectToCarbon)) {
                            if ($collectToCarbon->greaterThan($to->copy())) {
                                if ($period > 1) {
                                    if (Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect)) {
                                        $money = $periodMoney * $cost;
                                    } else {
                                        $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
                                    }
                                } else {
                                    if (Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect)) {
                                        $money = $periodMoney * $cost;
                                    } else {


                                        $diffDays = $to->copy()->diffInDays($from->copy());
                                        $numberDays = 30;
                                        $money = intval($cost / ($numberDays) * ($diffDays + 1));
                                    }
                                }

                            } else if ($collectToCarbon->lessThan($from->copy())) {
                                $money = 0;
                            } else {
                                if ($period > 1) {

                                    $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
                                } else {


                                    if (Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect)) {

                                        if ($period > 1) {

                                            $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
                                        } else {
                                            $diffDays = $collectToCarbon->copy()->diffInDays($from->copy());
                                            $numberDays = $from->copy()->diffInDays($to->copy());

                                            $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
                                        }
                                    } else {
                                        if ($period > 1) {
                                            $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
                                        } else {
                                            $diffDays = $to->copy()->diffInDays($from->copy());
                                            $numberDays = 30;
                                            $money = intval($cost / ($numberDays) * ($diffDays + 1));
                                        }
                                    }
                                }
                            }
                        } else {
                            $money = Functions::calculateMoneyInRange4($from->copy(), $to->copy(), $cost, $dayCollect);
                            $isCollect = false;
                        }
                    }

                    if (!Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect)) {
                        $sumMoney = Functions::calculateMoneyInRange4($from->copy(), $to->copy(), $cost, $dayCollect);
                    }

//					if ( $from->copy()->lessThanOrEqualTo( $collectToCarbon ) && $to->greaterThanOrEqualTo( $collectToCarbon ) ) {
//						$sumMoney = $money;
//					}

//					$check = Functions::checkExistDate($hostel, $from->copy(), $to->copy(), $contract, $roomId, $hostelId);
//					// dump($name);
//					var_dump($check);
                    //if ($check == 0) {
                    if (!empty($money)) {
                        $range = round($money / ($cost), 2);
                    } else {
                        $range = round($sumMoney / ($cost), 2);
                    }

                    if ($from->copy()->lessThanOrEqualTo($collectToCarbon) && $to->greaterThanOrEqualTo($collectToCarbon)) {
                        $range = round($sumMoney / ($cost), 2);
                    }
                    $name = 'Thu tiền phòng từ ' . $from->copy()->format('d/m/Y') . ' đến ' . $to->copy()->format('d/m/Y');
//							dump($name);
//							dump($range);
//							//dump($paidMoney);
//							dump($money);

                    if ($money > $sumMoney) {
                        $money = $sumMoney;
                        $range = round($money / ($cost), 2);
                    }

                    //gán lại cái số tiền
                    if ($isCollect == false) {
                        $money = 0;
                    }

                    $moneyInfo = MoneyInfo::create([
                        'hostel_id' => $hostelId,
                        'room_id' => $roomId,
                        'bed_id' => $contract->bed_id,
                        'date_action' => $from->copy()->toDateString(),
                        'contract_id' => $contract->id,
                        'user_id' => $user->id,
                        'type' => MoneyInfo::VOUCHER_CONTRACT,
                        'amount' => $sumMoney,
                        'pay' => 0,
                        'remain' => $sumMoney,
                        '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' => $from->copy()->toDateString(),
                        'end_date' => $to->copy()->toDateString(),
                        'qty' => $range,
                        'renter_id' => $contract->renter_id,
                        'sum_amount' => $sumMoney
                    ]);


                    //}

//					$returnArr[] = [
//						'start_date' => $from->format( 'd/m/Y' ),
//						'end_date'   => $to->format( 'd/m/Y' ),
//						'money'      => $money,
//						'sum'        => $sumMoney
//					];

                    $from = $to->copy()->addDay();
                    $lastEnd = $to->copy();
                }
            }
            $this->line($contract->id);

        }
        dd();
        //
        $renters = Renter::query()
            ->where('created_at', '>=', Carbon::now()->subDay(5)->startOfDay())
            ->get();
        foreach ($renters as $renter) {
            dispatch_now(new AddRenterConversationV2($renter->room_id, $renter->user_id, $renter->hostel->owner_id));
            $this->line($renter->id);
        }
        dd();
        $hostel = Hostel::find(11423);
        $rooms = Room::query()->where('hostel_id', $hostel->id)->get();
        foreach ($rooms as $room) {
            dispatch_now(new CreateRoomConservationV2($room->id, $hostel->owner->id));
        }
        dd();
        dispatch_now(new CreateHostelConservationV2($hostel->id, $hostel->owner->id));
        dd();

        $ids = [
            1499,
            1503,
            1504
        ];

        $items = RoomReservation::query()->whereIn('id', $ids)->get();
        foreach ($items as $item) {
            $item->delete();
        }
        dd();
        $ewArr = [
            48855,
            48859,
            48825,
            46861,
            50276,
            48887,
            48890
        ];

        $ews = ElectricWater::query()->whereIn('id', $ewArr)->get();
        foreach ($ews as $ew) {
            $contractId = $ew->contract_id;
            $moneyInfo = MoneyInfo::query()
                ->where('type', MoneyInfo::VOUCHER_SERVICE)
                ->where('contract_id', $contractId)
                ->whereBetween('date_action', [
                    Carbon::createFromFormat('d/m/Y', '01/02/2021')->startOfMonth()->startOfDay(),
                    Carbon::createFromFormat('d/m/Y', '01/02/2021')->endOfMonth()->endOfDay(),
                ])
                ->first();

            if ($moneyInfo) {
                $moneyDetail = MoneyDetail::query()->where('money_info_id', $moneyInfo->id)
                    ->where('is_electric', 1)
                    ->first();

                if ($moneyDetail) {
                    $moneyDetail->qty = json_encode([
                        'start' => $ew->start_electric,
                        'end' => $ew->end_electric
                    ]);
                    $newAmount = ($ew->end_electric - $ew->start_electric) * $moneyDetail->value;
                    $deltaAmount = $newAmount - $moneyDetail->amount;
                    $moneyDetail->amount = ($ew->end_electric - $ew->start_electric) * $moneyDetail->value;
                    $moneyDetail->save();

                    $newMoneyInfoAmount = $moneyInfo->amount + $deltaAmount;
                    $moneyInfo->amount = $newMoneyInfoAmount;
                    $moneyInfo->remain = $newMoneyInfoAmount - $moneyInfo->pay - $moneyInfo->discount;
                    $moneyInfo->save();
                }

            }
        }
        dd();

        $moneyInfos = MoneyInfo::query()
            ->where('type', MoneyInfo::VOUCHER_SERVICE)
            ->where('hostel_id', $hostel->id)
            ->get();


        dd();


        $staff = User::query()
            ->where('phone', '0938592302')
            ->where('type', User::STAFF)
            ->first();

        $notifications = Notification::query()->where('to_user', $staff->id)->get();
        $hostels = $staff->staffHostel;

        foreach ($notifications as $notification) {

            $payload = $notification->payload;
            $payload = json_decode($payload, true);

            if ($payload['type'] != config('constants.TRANSACTION')) {
                continue;
            }

            $moneyInfo = MoneyInfo::find($payload['id']);
            if (!$moneyInfo) {
                continue;
            }
            if (in_array($moneyInfo->hostel_id, $hostels->pluck('id')->toArray())) {
                continue;
            }
            $this->line('Done ' . $notification->id);
        }
        dd();

//        $items = MoneyInfo::onlyTrashed()->where('hostel_id', 11386)
//            ->whereBetween('date_action', [
//                Carbon::createFromFormat('d/m/Y', '01/02/2021')->startOfDay(),
//                Carbon::createFromFormat('d/m/Y', '31/03/2021')->endOfDay(),
//            ])
//            ->get();
//
//       foreach ($items as $item)
//       {
//           $item->restore();
//           MoneyDetail::onlyTrashed()->where('money_info_id', $item->id)->restore();
//       CollectSpend::onlyTrashed()->where('money_info_id', $item->id)->restore();
//           Transaction::onlyTrashed()->where('money_info_id', $item->id)->restore();
//       }
//       dd();

        $from = Carbon::createFromFormat('d/m/Y', '01/03/2021');
        $to = Carbon::createFromFormat('d/m/Y', '31/03/2021');
        $dayCollect = 14;
        $cost = 3100000;
        $collectTo = Carbon::createFromFormat('d/m/Y', '31/01/2021');
        $sumMoney = Functions::calculateMoneyInRange4($from->copy(), $to->copy(), $cost, $dayCollect, true);
        dd($sumMoney);

        dd(ElectricWater::query()->where('hostel_id', 11101)
            ->whereBetween('date_action', [
                Carbon::now()->startOfMonth(),
                Carbon::now()->endOfMonth()
            ])
            ->update([
                'date_action' => Carbon::now()->startOfMonth()->subMonth()
            ]));

        $items = CollectSpend::query()->where('contract_id', 25838)
            ->whereNotNull('money_info_id')
            ->doesntHave('moneyInfo')
            ->get();
        $cps = $items->pluck('money_info_id')->toArray();
        $ids = $items->pluck('id')->toArray();

        dump(CollectSpend::query()->whereIn('id', $ids)->delete());
        dd(Transaction::query()->whereIn('money_info_id', $cps)->delete());
        dd(ElectricWater::query()->where('hostel_id', 11285)->update([
            'date_action' => Carbon::createFromFormat('d/m/Y', '01/03/2021')
        ]));
//        $user = User::query()->where('phone', '0909640608')->first();
//        $hostels = Hostel::query()->where('owner_id', $user->id)->pluck('id')->toArray();
//        dd(Contract::query()->where('period', 0)->count());

        $item = Contract::query()->where('period', '=', 0)->update([
            'period' => 1
        ]);
        dd($item);

        $activity = Activity::find(2011460);
        if ($activity) {
            $prop = $activity->properties;
            $moneyInfo = MoneyDetail::find($activity->subject_id);
            $moneyInfo->update($prop['old']);
        }
        dd();
//        $moneyInfo = MoneyInfo::find(344579);
//        $detailAfter = MoneyDetail::query()
//            ->where('money_info_id', $moneyInfo->id)->get();
//        $moneyInfo->amount = $detailAfter->sum('amount');
//        $moneyInfo->remain = $moneyInfo->amount - $moneyInfo->pay - $moneyInfo->discount;
//        $moneyInfo->save();
//        dd();
        $hostels = Hostel::query()->where('owner_id', 31570)
            ->pluck('id')
            ->toArray();
        $items = ElectricWater::query()->whereIn('hostel_id', $hostels)
//            ->where('room_id', 32861)
//            ->where('hostel_id', 11086)
            ->whereBetween('date_action', [
                Carbon::now()->subMonth()->startOfMonth(),
                Carbon::now()->subMonth()->endOfMonth()
            ])
            ->get();
        foreach ($items as $item) {

            $startElectric = $item->start_electric;
            $itemBefore = ElectricWater::query()->whereIn('hostel_id', $hostels)
                ->where('start_electric', $startElectric)
                ->where('contract_id', $item->contract_id)
                ->whereBetween('date_action', [
                    Carbon::now()->subMonths(2)->startOfMonth(),
                    Carbon::now()->subMonths(2)->endOfMonth()
                ])
                ->first();
            if ($itemBefore) {
                $moneyInfo = MoneyInfo::query()
                    ->where('contract_id', $item->contract_id)
                    ->whereBetween('date_action', [
                        Carbon::now()->subMonth()->startOfMonth(),
                        Carbon::now()->subMonth()->endOfMonth()
                    ])
                    ->where('type', MoneyInfo::VOUCHER_SERVICE)
                    ->first();

                $item->start_electric = $itemBefore->end_electric;
                $item->save();

                if ($moneyInfo) {
                    $details = MoneyDetail::query()
                        ->where('money_info_id', $moneyInfo->id)
                        ->where('is_electric', 1)
                        ->get();
                    foreach ($details as $detail) {
                        $qty = json_decode($detail->qty, true);
                        if (is_array($qty)) {
                            $feeItem = HostelFee::find($detail->hostel_fee_id);
                            $start = $item->start_electric;
                            $end = $item->end_electric;
                            $room = $item->room;
                            $amount = Functions::calculateElectricAmount($end - $start, $room, $feeItem->type, $feeItem->id);
                            $detail->qty = json_encode([
                                'start' => $start,
                                'end' => $end
                            ]);
                            if (empty($amount)) {
                                $amount = ($end - $start) * $feeItem->fee;
                            }
                            $detail->amount = $amount;
                            $detail->save();
                            break;
                        }
                    }

                    $detailAfter = MoneyDetail::query()
                        ->where('money_info_id', $moneyInfo->id)->get();
                    $moneyInfo->amount = $detailAfter->sum('amount');
                    $moneyInfo->remain = $moneyInfo->amount - $moneyInfo->pay - $moneyInfo->discount;
                    $moneyInfo->save();

                    $this->line('Processed ' . $moneyInfo->hostel->name . ', ' . $moneyInfo->room->name);
                }
            }
        }
        dd();

        $moneyInfos = MoneyInfo::query()->where('contract_id', 14848)->pluck('id')->toArray();
        Transaction::query()->whereIn('money_info_id', $moneyInfos)->restore();
        MoneyDetail::query()->whereIn('money_info_id', $moneyInfos)->restore();
        dd();
        $id = 10848;
        $room = Room::withTrashed()->find($id);


//        RenterRoom::query()->where('room_id', $room->id)->withTrashed()->restore();
//        Renter::where('room_id', $room->id)->withTrashed()->restore();
        Contract::where('room_id', $room->id)->withTrashed()->restore();
        MoneyInfo::where('room_id', $room->id)->withTrashed()->restore();
        CollectSpend::where('room_id', $room->id)->withTrashed()->restore();
        Transaction::where('room_id', $room->id)->withTrashed()->restore();
        Statistic::where('room_id', $room->id)->withTrashed()->restore();
        StatisticLog::where('room_id', $room->id)->withTrashed()->restore();
        ElectricWater::where('room_id', $room->id)->withTrashed()->restore();
        $room->restore();
        dd();
        $hostels = Hostel::query()->orderBy('id', 'desc')->get();
        foreach ($hostels as $hostel) {
            Functions::updateHostelEmptyRooms($hostel->id);
            $this->line('processed ' . $hostel->id);
        }
        dd();
        $hostelId = 10091;
        $rooms = Room::query()->where('hostel_id', $hostelId)->get();
        foreach ($rooms as $room) {
            $contracts = Contract::query()
                ->where('status', Contract::VALIDATED)
                ->where('room_id', $room->id)->get();
            if ($contracts->count() <= 1) {
                continue;
            }

            foreach ($contracts as $contract) {
                $pay = MoneyInfo::query()->where('contract_id', $contract->id)->sum('pay');
                if ($pay == 0) {
                    $contract->delete();
                    MoneyInfo::query()->where('contract_id', $contract->id)->delete();
                    RenterRoom::query()->where('contract_id', $contract->id)->delete();

                    break;
                }
            }
            $this->line($room->name);

            //dd($room->name);
        }
        dd();
        $date = Carbon::createFromFormat('d/m/Y', '01/12/2021');
        $items = MoneyInfo::query()
            ->whereBetween('date_action', [
                $date->copy()->startOfMonth(),
                $date->copy()->endOfMonth(),
            ])
            ->where('type', MoneyInfo::VOUCHER_SERVICE)
            ->where('hostel_id', 10634)
            ->update([
                'date_action' => Carbon::createFromFormat('d/m/Y', '01/12/2020')
            ]);
        dd();


        dd(\App\Models_v2\Conversation::query()->find('21970')->users()->pluck('users.id')->toArray());
        $str = '{"id":365262,"hostel_id":10598,"room_id":29030,"name":"Ti\u1ec1n gi\u1eef xe m\u00e1y","value":100000,"money_info_id":null,"user_id":null,"created_at":"2020-10-29 14:37:56","updated_at":"2020-10-29 14:37:56","deleted_at":null,"qty":"1","is_electric":0,"is_water":0,"amount":100000,"note":null,"hostel_fee_id":10165,"start_date":null,"end_date":null,"renter_id":null,"type":0,"contract_status":0,"sum_amount":0}';
        $arr = json_decode($str, true);
        unset($arr['id']);
        $arr['money_info_id'] = 284564;
        MoneyDetail::create($arr);
        dd();

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

        $hostelIds = Hostel::query()->where('owner_id', $owner->id)
            ->get();
        $cps = CollectSpend::query()
            ->whereIn('hostel_id', $hostelIds->pluck('id')->toArray())
            ->whereHas('contract', function ($q) {
                $q->where('status', Contract::LIQUIDATED);
            })
            ->where('is_deposit', true)
            ->where('type', CollectSpend::COLLECT)
            ->where('name', 'LIKE', '%Thu tiền đặt cọc%')
            ->where('is_return_deposit', 2)
            ->get();
        foreach ($cps as $cp) {
            Deposit::query()->where('contract_id', $cp->contract_id)->delete();
        }
        dd();

        dispatch_now(new RemoveStaffConversation(34688, 10444));
        dd();
        $items = Hostel::all();
        foreach ($items as $item) {
            dispatch_now(new GenerateDynamicLinkHostel($item->id));
            $this->line('processed: ' . $item->id);
        }
        dd();

        $items = CollectSpend::query()
            ->whereNull('contract_id')
            ->has('transaction.moneyInfo.contract')
            ->get();
        foreach ($items as $item) {
            $item->contract_id = $item->transaction->moneyInfo->contract_id;
            $item->save();
        }
        dd($items->count());

        dd($this->pCP(CollectSpend::find(174626)));
        $hostels = Hostel::all();
        foreach ($hostels as $hostel) {
            Functions::updateHostelEmptyRooms($hostel->id);
        }
        dd();

        $hostel = Hostel::find(11083);
        dd(Functions::generateDynamicLinkHostel($hostel));
        $owner = User::query()
            ->where('phone', '0909743101')
            ->where('type', User::OWNER)
            ->first();
        $moneyInfos = MoneyInfo::onlyTrashed()
            ->whereHas('hostel', function ($q) use ($owner) {
                $q->where('owner_id', $owner->id);
            })
            ->whereIn('type', [
                MoneyInfo::VOUCHER_ROOM_PRICE,
                MoneyInfo::VOUCHER_CONTRACT
            ])
            ->get();

        $collectSpends = CollectSpend::query()
            ->whereHas('hostel', function ($q) use ($owner) {
                $q->where('owner_id', $owner->id);
            })
            ->whereIn('money_info_id', $moneyInfos->pluck('id')->toArray())
            ->delete();

        //    ->delete();

        dd($moneyInfos->pluck('id')->toArray());
        $user = $owner;
        foreach ($contracts as $contract) {

            $contract->day_collect = 31;
            $contract->save();

            $dateContract = $contract->date_contract;
            if ($dateContract->day < 15) {
                $newDateContract = $contract->date_contract->startOfMonth();
            } else {
                $newDateContract = Carbon::createFromFormat('d-m-Y', '15-' . $contract->date_contract->month . '-' . $contract->date_contract->year);
            }
            $contract->date_contract = $newDateContract;
            $contract->date_enable = $newDateContract;
            $contract->start_date = $newDateContract;
            $contract->date_join = $newDateContract;
            $contract->last_invoice_at = null;
            $contract->save();

            $items = MoneyInfo::query()
                ->whereIn('type', [
                    MoneyInfo::VOUCHER_CONTRACT,
                    MoneyInfo::VOUCHER_ROOM_PRICE
                ])
                ->where('contract_id', $contract->id)
                ->get();
            foreach ($items as $item) {
                MoneyDetail::query()->where('money_info_id', $item->id)->delete();
                $item->delete();
            }

            $period = Functions::getPeriodNumber($contract->period);
            $target = Carbon::createFromFormat('Y-m-d', $contract->collect_to);
            $cost = $contract->room_price;
            $periodMoney = Functions::getPeriodNumber($contract->period);
            $collectToCarbon = null;
            $from = $contract->date_enable->copy();
            $dayCollect = $contract->day_collect;
            $hostelId = $contract->hostel_id;
            $roomId = $contract->room_id;
            $data = $contract->toArray();

            if (!empty($target)) {
                while ($from->lessThanOrEqualTo($target)) {
                    if ($period > 1) {
                        $month = $from->copy()->firstOfMonth()->addMonth($period - 1)->month;
                        $year = $from->copy()->firstOfMonth()->addMonth($period - 1)->year;
                        if ($dayCollect <= $from->copy()->day) {
                            $month = $from->copy()->firstOfMonth()->addMonth($period)->month;
                            $year = $from->copy()->firstOfMonth()->addMonth($period)->year;
                        }
                    } else {
                        $month = $from->copy()->month;
                        $year = $from->copy()->year;
                        if ($dayCollect <= $from->copy()->day) {
                            $month = $from->copy()->firstOfMonth()->addMonth()->month;
                            $year = $from->copy()->firstOfMonth()->addMonth()->year;
                        }
                    }

                    $isValid = true;
                    if (checkdate($month, $dayCollect, $year)) {
                        $to = Carbon::createFromFormat('d-m-Y', $dayCollect . '-' . $month . '-' . $year);
                    } else {
                        $isValid = false;
                        $tempDayCollect = Carbon::createFromFormat('d-m-Y', '01-' . $month . '-' . $year)->lastOfMonth()->day;
                        $to = Carbon::createFromFormat('d-m-Y', $tempDayCollect . '-' . $month . '-' . $year);
                    }
                    //dump( $from->toDateString() . '|' . $to->toDateString() );
                    $money = $periodMoney * $cost;
                    $sumMoney = $money;
                    $isCollect = true;

                    if ($isValid == true) {
                        if (!empty($collectToCarbon)) {

                            if ($collectToCarbon->greaterThanOrEqualTo($from->copy()) && $collectToCarbon->lessThan($to->copy())) {

                                if ($period > 1) {
                                    $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);

                                } else {
                                    if (!Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect)) {
                                        $diffDays = $collectToCarbon->copy()->diffInDays($from->copy());
                                        $numberDays = 30;
                                        $money = intval($cost / ($numberDays) * ($diffDays + 1));
                                    } else {
                                        if ($to->copy()->day == $dayCollect && $from->copy()->subDay(1)->month == 2) {
//										$numberMonth = $from->copy()->firstOfMonth()->diffInMonths( $to->copy()->firstOfMonth() );
//										$money       = $cost * $numberMonth;
                                            $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
                                        } else {
                                            $diffDays = $collectToCarbon->copy()->diffInDays($from->copy());
                                            $numberDays = $from->copy()->daysInMonth;

                                            //$money = intval( $cost / ( $numberDays + 1 ) * ( $diffDays + 1 ) );
                                            $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
                                        }
                                    }
                                }

                            } else if ($collectToCarbon->greaterThan($to->copy())) {

                                if ($period > 1) {
                                    $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
                                } else {

                                    if ($from->copy()->day != $to->copy()->day) {
                                        // dump($from->copy()->toDateString());
                                        // dump($to->copy()->toDateString());
                                        // dump('--');
                                        if (Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect)) {
                                            $money = $periodMoney * $cost;
                                        } else {
                                            $diffDays = $to->copy()->diffInDays($from->copy());
                                            $numberDays = 30;
                                            $money = intval($cost / ($numberDays) * ($diffDays + 1));
                                        }
                                        //  dump($money);
                                    } else {
                                        $money = $periodMoney * $cost;
                                    }
                                }
                            } else if ($collectToCarbon->equalTo($to->copy())) {
                                if ($period > 1) {
                                    if (Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect)) {
                                        $money = $periodMoney * $cost;
                                    } else {
                                        $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
                                    }
                                } else {
                                    if (Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect)) {
                                        $money = $periodMoney * $cost;
                                    } else {

                                        $diffDays = $to->copy()->diffInDays($from->copy());
                                        $numberDays = 30;
                                        $money = intval($cost / ($numberDays) * ($diffDays + 1));
                                    }
                                }
                            } else {
                                $money = 0;
                            }
                        } else {
                            $money = Functions::calculateMoneyInRange4($from->copy(), $to->copy(), $cost, $dayCollect);
                            $isCollect = false;
                        }
                    } else {

                        if (!empty($collectToCarbon)) {
                            if ($collectToCarbon->greaterThan($to->copy())) {
                                if ($period > 1) {
                                    if (Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect)) {
                                        $money = $periodMoney * $cost;
                                    } else {
                                        $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
                                    }
                                } else {
                                    if (Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect)) {
                                        $money = $periodMoney * $cost;
                                    } else {


                                        $diffDays = $to->copy()->diffInDays($from->copy());
                                        $numberDays = 30;
                                        $money = intval($cost / ($numberDays) * ($diffDays + 1));
                                    }
                                }

                            } else if ($collectToCarbon->lessThan($from->copy())) {
                                $money = 0;
                            } else {
                                if ($period > 1) {

                                    $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
                                } else {


                                    if (Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect)) {

                                        if ($period > 1) {

                                            $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
                                        } else {
                                            $diffDays = $collectToCarbon->copy()->diffInDays($from->copy());
                                            $numberDays = $from->copy()->diffInDays($to->copy());

                                            $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
                                        }
                                    } else {
                                        if ($period > 1) {
                                            $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
                                        } else {
                                            $diffDays = $to->copy()->diffInDays($from->copy());
                                            $numberDays = 30;
                                            $money = intval($cost / ($numberDays) * ($diffDays + 1));
                                        }
                                    }
                                }
                            }
                        } else {
                            $money = Functions::calculateMoneyInRange4($from->copy(), $to->copy(), $cost, $dayCollect);
                            $isCollect = false;
                        }
                    }

                    if (!Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect)) {
                        $sumMoney = Functions::calculateMoneyInRange4($from->copy(), $to->copy(), $cost, $dayCollect);
                    }

//					if ( $from->copy()->lessThanOrEqualTo( $collectToCarbon ) && $to->greaterThanOrEqualTo( $collectToCarbon ) ) {
//						$sumMoney = $money;
//					}

//					$check = Functions::checkExistDate($hostel, $from->copy(), $to->copy(), $contract, $roomId, $hostelId);
//					// dump($name);
//					var_dump($check);
                    //if ($check == 0) {
                    if (!empty($money)) {
                        $range = round($money / ($cost), 2);
                    } else {
                        $range = round($sumMoney / ($cost), 2);
                    }

                    if ($from->copy()->lessThanOrEqualTo($collectToCarbon) && $to->greaterThanOrEqualTo($collectToCarbon)) {
                        $range = round($sumMoney / ($cost), 2);
                    }
                    $name = 'Thu tiền phòng từ ' . $from->copy()->format('d/m/Y') . ' đến ' . $to->copy()->format('d/m/Y');
//							dump($name);
//							dump($range);
//							//dump($paidMoney);
//							dump($money);

                    if ($money > $sumMoney) {
                        $money = $sumMoney;
                        $range = round($money / ($cost), 2);
                    }

                    //gán lại cái số tiền
                    $isCollect = false;
                    if ($isCollect == false) {
                        $money = 0;
                    }

                    $moneyInfo = MoneyInfo::create([
                        'hostel_id' => $hostelId,
                        'room_id' => $roomId,
                        'bed_id' => $contract->bed_id,
                        'date_action' => $from->copy()->toDateString(),
                        'contract_id' => $contract->id,
                        'user_id' => $user->id,
                        'type' => MoneyInfo::VOUCHER_CONTRACT,
                        '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' => $from->copy()->toDateString(),
                        'end_date' => $to->copy()->toDateString(),
                        'qty' => $range,
                        'renter_id' => $contract->renter_id,
                        'sum_amount' => $sumMoney
                    ]);

                    if ($isCollect == true) {

                        $transaction = Transaction::create([
                            'money_info_id' => $moneyInfo->id,
                            'amount' => $money,
                            'note' => $name,
                            'room_id' => $roomId,
                            'hostel_id' => $hostelId,
                            'date_action' => Carbon::now()->toDateString(),
                            'type' => CollectSpend::COLLECT
                        ]);

                        CollectSpend::create([
                            'amount' => $money,
                            'hostel_id' => $hostelId,
                            'room_id' => $roomId,
                            'note' => $name,
                            'payment_method' => CollectSpend::MONEY,
                            'date_action' => $from->copy()->toDateString(),
                            'user_id' => $contract->renter_id,
                            'money_info_id' => $moneyInfo->id,
                            'type' => CollectSpend::COLLECT,
                            'transaction_id' => $transaction->id
                        ]);
                    }


                    //}

//					$returnArr[] = [
//						'start_date' => $from->format( 'd/m/Y' ),
//						'end_date'   => $to->format( 'd/m/Y' ),
//						'money'      => $money,
//						'sum'        => $sumMoney
//					];

                    $from = $to->copy()->addDay();
                    $lastEnd = $to->copy();
                }
            }

            if (!empty($lastEnd)) {
//	        dump($lastEnd);
//	        dump(Carbon::now());

                if ($lastEnd->copy()->startOfDay()->equalTo(Carbon::now()->startOfDay())) {

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

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

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

//	            $money2 = $cost * $period;
//	            if(!Functions::checkFullPeriod($lastEnd->copy(), $to2->copy(), $dayCollect))
//	            {
//	            	$money2 = Functions::calculateMoneyInRange3($lastEnd->copy(), $to2->copy(), $dayCollect);
//	            }


                    $name = 'Thu tiền phòng từ ' . $from->copy()->format('d/m/Y') . ' đến ' . $to2->copy()->format('d/m/Y');
//                    dump('---');
//							dump($name);
//							dump($period);
//							//dump($paidMoney);
//							dump($money);
                    $moneyInfo = MoneyInfo::create([
                        'hostel_id' => $hostelId,
                        'room_id' => $roomId,
                        'bed_id' => $contract->bed_id,
                        'date_action' => $from->copy()->toDateString(),
                        'contract_id' => $contract->id,
                        'user_id' => $user->id,
                        'type' => MoneyInfo::VOUCHER_CONTRACT,
                        'amount' => $period * $cost,
                        'pay' => 0,
                        'remain' => $period * $cost,
                        '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' => 0,
                        'note' => $name,
                        'start_date' => $lastEnd->copy()->toDateString(),
                        'end_date' => $to2->copy()->toDateString(),
                        'qty' => $period,
                        'renter_id' => $contract->renter_id,
                        'sum_amount' => $period * $cost
                    ]);

//					$returnArr[] = [
//						'start_date' => $lastEnd->format('d/m/Y'),
//						'end_date' => $to2->format('d/m/Y'),
//						'money' => 0,
//						'sum' =>  $cost*$period
//					];
                }
            }

            //xử lý case tương lai

            $from2 = $contract->date_enable->copy();
            if ($from2->copy()->startOfDay()->greaterThan($target->copy()->startOfDay())) {
                if ($period > 1) {
                    $month = $from2->copy()->firstOfMonth()->addMonth($period - 1)->month;
                    $year = $from2->copy()->firstOfMonth()->addMonth($period - 1)->year;
                    if ($dayCollect <= $from2->copy()->day) {
                        $month = $from2->copy()->firstOfMonth()->addMonth($period)->month;
                        $year = $from2->copy()->firstOfMonth()->addMonth($period)->year;
                    }
                } else {
                    $month = $from2->copy()->month;
                    $year = $from2->copy()->year;
                    if ($dayCollect <= $from2->copy()->day) {
                        $month = $from2->copy()->firstOfMonth()->addMonth()->month;
                        $year = $from2->copy()->firstOfMonth()->addMonth()->year;
                    }
                }
                if (checkdate($month, $dayCollect, $year)) {

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

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

                if ($period > 1) {
                    $money = $periodMoney * $cost;
                } else {

                    if ($from2->copy()->day != $to3->copy()->day) {
                        // dump($from->copy()->toDateString());
                        // dump($to->copy()->toDateString());
                        // dump('--');
                        if (Functions::checkFullPeriod($from2->copy(), $to3->copy(), $dayCollect)) {
                            $money = $period * $cost;
                        } else {
                            $diffDays = $to3->copy()->diffInDays($from2->copy());
                            $numberDays = 30;
                            $money = intval($cost / ($numberDays) * ($diffDays + 1));
                            $money = Functions::calculateMoneyInRange4($from2->copy(), $to3->copy(), $cost, $dayCollect);
                        }
                        //  dump($money);
                    } else {
                        $money = $periodMoney * $cost;
                    }
                }

                $range = $period;
                if (!empty($money)) {
                    $range = round($money / ($periodMoney * $cost), 2);
                }

                if (empty($money)) {
                    $money = $periodMoney * $cost;
                }

                $name = 'Thu tiền phòng từ ' . $from2->copy()->format('d/m/Y') . ' đến ' . $to3->copy()->format('d/m/Y');
//                    dump('---');
//							dump($name);
//							dump($period);
//							//dump($paidMoney);
//							dump($money);
                $moneyInfo = MoneyInfo::create([
                    'hostel_id' => $hostelId,
                    'room_id' => $roomId,
                    'bed_id' => $data['bed_id'],
                    'date_action' => $from2->copy()->toDateString(),
                    'contract_id' => $contract->id,
                    'user_id' => $user->id,
                    'type' => MoneyInfo::VOUCHER_CONTRACT,
                    'amount' => $money,
                    'pay' => 0,
                    'remain' => $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' => 0,
                    'note' => $name,
                    'start_date' => $from2->copy()->toDateString(),
                    'end_date' => $to3->copy()->toDateString(),
                    'qty' => $range,
                    'renter_id' => $contract->renter_id,
                    'sum_amount' => $money
                ]);

//	            $money2 = $cost * $period;
//	            if(!Functions::checkFullPeriod($lastEnd->copy(), $to2->copy(), $dayCollect))
//	            {
//	            	$money2 = Functions::calculateMoneyInRange3($lastEnd->copy(), $to2->copy(), $dayCollect);
//	            }

//                $returnArr[] = [
//                    'start_date' => $from2->format('d/m/Y'),
//                    'end_date' => $to3->format('d/m/Y'),
//                    'money' => $money,
//                    'sum' => $money
//                ];
            }


            $moneyInfos = MoneyInfo::query()
                ->where('contract_id', $contract->id)
                ->whereIn('type', [
                    MoneyInfo::VOUCHER_CONTRACT,
                    MoneyInfo::VOUCHER_ROOM_PRICE
                ])
                ->get();
            foreach ($moneyInfos as $moneyInfo) {
                $detail = $moneyInfo->details->first();
                $startDate = $detail->start_date;
                $startDate = Carbon::createFromFormat('Y-m-d', $startDate);
                if ($startDate->day != 15) {
                    continue;
                }

                $moneyInfo->amount = $detail->value / 2;
                $moneyInfo->remain = $detail->value / 2;
                $moneyInfo->save();
                $detail->qty = 0.5;
                $detail->sum_amount = $detail->value / 2;
                $detail->save();
            }


        }


        dd();
        Permission::create([
            'name' => 'send-voucher'
        ]);
        $role = Role::where('name', 'owner')->first();
        $permissions = Permission::query()->where('is_admin', false)->pluck('name')->toArray();
        $role->syncPermissions($permissions);
        dd();
        $momoService = new MomoServices();
        $response = $momoService->confirmPayApp([
            'partner_ref_id' => '581',
            'momo_trans_id' => '2338430140',
            'request_type' => 'capture',
        ]);
        dd($response);

        //  dd(Carbon::createFromFormat('d/m/Y', '11/30/2020'));

//        $hostelId = 6780;
//
//
//        $moneyInfos = MoneyInfo::onlyTrashed()
//            ->where('hostel_id', $hostelId)
//            ->whereIn('type', [MoneyInfo::VOUCHER_SERVICE])
//            ->whereBetween('date_action', [
//                Carbon::now()->subMonth()->startOfMonth()->startOfDay(),
//                Carbon::now()->subMonth()->endOfMonth()->endOfDay()
//            ])
//            ->restore();
//
//        dd();
        $hostelId = 10950;
        Renter::query()->where('hostel_id', $hostelId)->delete();
        Contract::query()->where('hostel_id', $hostelId)->delete();
        MoneyInfo::query()->where('hostel_id', $hostelId)->delete();
        RenterRoom::query()->where('hostel_id', $hostelId)->delete();
        StatisticLog::query()->where('hostel_id', $hostelId)->delete();
        CollectSpend::query()->where('hostel_id', $hostelId)->delete();
        dd();

        $hostelId = 10634;

        $contracts = Contract::query()
            ->where('status', '<>', Contract::LIQUIDATED)
            ->whereIn('id', [
                //22114,
                //  21892,
                21105,
                22816,

                //  22113,
                //22136,
//                21894,
//                21928,
//                21926


//                21718,
//                21755,
//                29460,
//                21097,
//                21094,
//                21827,
//                21270,
//                21092,
//                21099,
//                21102,
//                21095,
//                21067,
//                21711,
//                21714,
//                21812,
//                21824,
//                21823,
//                21829,
//                21894,
//                21892,
//                21711,
//                21928,
//                21813,
//                21101,
//                21713,
//                21717,
//                21090,
//                21811,
//                21812,
//                21824,
//                21823,
//                21829,
//                21827,
//                21834,
//                21894,
//                21928,
//                21926

            ])
            ->where('hostel_id', $hostelId)
            ->get();

        foreach ($contracts as $contract) {
            $contractId = $contract->id;
            MoneyInfo::query()
                ->where('contract_id', $contractId)
                ->whereIn('type', [MoneyInfo::VOUCHER_ROOM_PRICE, MoneyInfo::VOUCHER_CONTRACT])
                ->delete();

            $period = Functions::getPeriodNumber($contract->period);
            $startDate = $contract->start_date;
            $endDate = $startDate->copy()->addMonths($period);
            $dayCollect = $contract->day_collect;
            //Hoa don 1
            $this->genInvoice($startDate->copy(), $endDate->copy()->subDay(1), $contract);

            //Hoa don 2
            $this->genInvoice($endDate->copy()->copy(), $endDate->copy()->endOfMonth(), $contract);

            //Hoa don 3
            $this->genInvoice($endDate->copy()->endOfMonth()->addDay(),
                $endDate->copy()->endOfMonth()->addDay()->addMonth($period)->subDay(), $contract);
        }
        dd();


        $items = SendZaloLog::query()->get();
        foreach ($items as $item) {
            $properties = $item->properties;
            $hostelName = $properties['template_data']['hostel_name'];
            $roomName = $properties['template_data']['room_name'];

            $userId = $item->user_id;
            $user = User::find($userId);
            if ($user->type == User::OWNER) {
                $ownerId = $user->id;
            } else {
                $ownerId = $user->staff_owner_id;

            }
            $hostel = Hostel::query()->where('name', $hostelName)->where('owner_id', $ownerId)->first();
            $room = Room::query()->where('name', $roomName)
                ->where('hostel_id', $hostel->id)
                ->first();
            $item->hostel_id = $hostel->id;
            $item->room_id = $room->id;
            $item->customer_name = $properties['template_data']['customer_name'];
            $item->customer_phone = $properties['phone'];
            $item->save();

        }
        dd();

        $contracts = Contract::query()
            ->where('hostel_id', null)
            ->get();
        foreach ($contracts as $contract) {
            dd($contract);
        }
        dd(1);
//        $roomId = 20996;
//
//        $items = MoneyInfo::query()
//            ->where('room_id', $roomId)
//            ->get();
//        foreach($items as $item)
//        {
//            if($item->amount - $item->pay - $item->discount < 0)
//            {
//                dump($item->id);
//            }
//        }
//        dd();
//
//        $hostelId = 8783;
//
//        $moneyInfos = MoneyInfo::query()->where('money_info_name', 'Thu tiền phòng từ 01/11/2020 đến 30/11/2020')
//            ->where('hostel_id', 10634)
//            ->get();
//        foreach($moneyInfos as $moneyInfo)
//        {
//            MoneyDetail::query()->onlyTrashed()
//                ->where('money_info_id', $moneyInfo->id)
//                ->restore();
//        }
//        dd();
//
//
//
////        $items=  ElectricWater::onlyTrashed()
////            ->where('hostel_id', $hostelId)
////           ->whereBetween('date_action', [
////               Carbon::now()->subMonth()->startOfMonth()->startOfDay(),
////               Carbon::now()->endOfMonth()->endOfDay()
////           ])
////            ->get();
////        foreach($items as $item)
////        {
////            if(!empty($item->start_electric_image) ||
////                !empty($item->end_electric_image) ||
////                !empty($item->start_water_image) ||
////                !empty($item->end_water_image)
////            )
////            {
////                $item->restore();
////            }
////        }
////        dd();
//
//
//       $contracts = Contract::query()
//           ->where('hostel_id', $hostelId)
//          // ->where('status', '<>', Contract::LIQUIDATED)
//           ->get();
//       $date = Carbon::createFromFormat('d/m/Y', '01/09/2020');
////       dd($moneyDetail = MoneyDetail::query()
////           ->whereHas('moneyInfo', function($q) use ($hostelId, $date){
////               $q->where('money_infos.hostel_id', $hostelId);
////              // $q->where('money_infos.contract_id', $contract->id);
////               $q->whereBetween('money_infos.date_action', [
////                   $date->copy()->startOfMonth()->startOfDay(),
////                   $date->copy()->endOfMonth()->endOfDay(),
////               ]);
////               $q->where('money_infos.type', MoneyInfo::VOUCHER_SERVICE);
////           })
////           ->where('is_electric', 1)->count())
//        $i=0;
//       foreach($contracts as $contract)
//       {
//            $moneyDetail = MoneyDetail::query()
//                ->whereHas('moneyInfo', function($q) use ($contract, $date){
//                    //$q->where('money_infos.hostel_id', $hostelId);
//                    $q->where('money_infos.contract_id', $contract->id);
//                    $q->whereBetween('money_infos.date_action', [
//                        $date->copy()->startOfMonth()->startOfDay(),
//                        $date->copy()->endOfMonth()->endOfDay(),
//                    ]);
//                    $q->where('money_infos.type', MoneyInfo::VOUCHER_SERVICE);
//                })
//                ->where('is_electric', 1)
//                ->first();
//            $i++;
//
//            if($moneyDetail)
//            {
//                $startIndex = $moneyDetail->start_index;
//                $endIndex = $moneyDetail->end_index;
//
////                ElectricWater::query()->where('contract_id', $contract->id)
////                    ->whereNull('delta_electric')
////                    ->delete();
//
//                $ew = ElectricWater::query()
//                    ->where('start_electric', $startIndex)
//                    ->where('contract_id', $contract->id)
//                    ->where('end_electric', $endIndex)
//                    ->whereBetween('date_action', [
//                        $date->copy()->startOfMonth()->startOfDay(),
//                        $date->copy()->endOfMonth()->endOfDay(),
//                    ])
//                    ->first();
//
//                if($ew)
//                {
//                    $ew->restore();
//                } else{
//
//                    ElectricWater::create([
//                        'hostel_id' => $hostelId,
//                        'room_id' => $contract->room_id,
//                        'contract_id' => $contract->id,
//                        'start_electric' => $startIndex,
//                        'end_electric' => $endIndex,
//                        'delta_electric'=>$endIndex - $startIndex,
//                        'date_action'=>$date->copy()->startOfMonth()
//                    ]);
//                }
//            }
//       }
//       dump($i);
//       dd();
//        $contract = Contract::find(20787);
//        $amountReturnDeposit = $contract->deposit;
//        $amountReturnDeposit = Functions::filterInputNumber($amountReturnDeposit);
//        $roomId = $contract->room_id;
//        $hostel = $contract->hostel;
//        if ($amountReturnDeposit <= 0) {
//            return response([
//                'status' => 0,
//                'message' => 'Số tiền trả cọc phải lớn hơn 0'
//            ]);
//        }
//
//        if ($amountReturnDeposit > $contract->deposit) {
//            return response([
//                'status' => 0,
//                'message' => 'Số tiền trả cọc không được vượt quá cọc Hợp đồng'
//            ]);
//        }
//        $transaction = Transaction::create([
//            'money_info_id' => null,
//            'amount' => $amountReturnDeposit,
//            'note' => 'Thanh toán tiền cọc HĐ ' . $contract->code,
//            'room_id' => $roomId,
//            'hostel_id' => $hostel->id,
//            'date_action' => Carbon::now()->toDateString(),
//            'type' => CollectSpend::SPEND,
//            'is_statistic' => false
//        ]);
//
//        CollectSpend::create([
//            'amount' => $amountReturnDeposit,
//            'hostel_id' => $hostel->id,
//            'room_id' => $roomId,
//            'note' => 'Thanh toán tiền cọc HĐ ' . $contract->code,
//            'name' => 'Thanh toán tiền cọc HĐ ' . $contract->code,
//            'payment_method' => CollectSpend::MONEY,
//            'date_action' => Carbon::now()->toDateString(),
//            'user_id' => $contract->renter_id,
//            'money_info_id' => null,
//            'type' => CollectSpend::SPEND,
//            'transaction_id' => $transaction->id,
//            'contract_id' => $contract->id,
//            'is_deposit' => true,
//            'is_return_deposit' => true,
//            'receiver' => $contract->name,
//            'is_statistic' => false
//        ]);
//        $contract->is_return_deposit = true;
//        $contract->amount_return_deposit = $amountReturnDeposit;
//        $contract->save();
//
//        if ($contract->deposit - $amountReturnDeposit > 0) {
//            $statMonth = StatisticMonth::create([
//                'month' => Carbon::now()->month,
//                'year' => Carbon::now()->year,
//                'amount' => $contract->deposit - $amountReturnDeposit,
//                'current_paid' => $amountReturnDeposit,
//                'hostel_id' => $hostel->id,
//                'room_id' => $roomId,
//                'contract_id' => $contract->id,
//            ]);
//            StatisticLog::create([
//                'amount' => $contract->deposit - $amountReturnDeposit,
//                'month' => Carbon::now()->month,
//                'year' => Carbon::now()->year,
//                'type' => CollectSpend::COLLECT,
//                'hostel_id' => $hostel->id,
//                'room_id' => $roomId,
//                'contract_id' => $contract->id,
//                'statistic_month_id' => $statMonth->id,
//                'note' => 'Thu tiền đặt cọc HĐ: ' . $contract->code
//            ]);
//        }
//
//        CollectSpend::query()->where('contract_id', $contract->id)
//            ->where('is_deposit', true)
//            ->where('type', CollectSpend::COLLECT)
//            ->where('name', 'LIKE', '%Thu tiền đặt cọc%')
//            ->update([
//                'is_return_deposit' => true
//            ]);
//
//        dd();
//
//        $ownerId = 31220;
//
//        $items = StatisticLog::query()
//            ->whereHas('hostel', function($q) use ($ownerId) {
//                $q->where('hostels.owner_id', $ownerId);
//            })
//            ->has('moneyInfo')
//            ->get();
//        foreach($items as $item)
//        {
//            if(empty($item->moneyInfo->date_action))
//            {
//                continue;
//            }
//
//            $month = $item->moneyInfo->date_action->month;
//            $year = $item->moneyInfo->date_action->year;
//
//            if($item->month != $month)
//            {
//                $item->month = $month;
//            }
//
//            if($item->year != $year)
//            {
//                $item->year = $year;
//            }
//            $item->save();
//            $this->line('Done '.$item->id);
//        }
//        dd();
//
//
//        $ownerId = 29280;
//        $date = Carbon::createFromFormat('d/m/Y', '01/10/2020');
//        dispatch_now(new ExportMoneyInfo($ownerId, $date->copy()));
//        dd();
//


        $date = Carbon::createFromFormat('d/m/Y', '01/09/2020');
        ElectricWater::query()
            ->where('hostel_id', 10660)
//            ->where('type', MoneyInfo::VOUCHER_SERVICE)
            ->whereBetween('date_action', [
                $date->copy()->startOfMonth()->startOfDay(),
                $date->copy()->endOfMonth()->endOfDay()
            ])
            ->delete();
        dd();

        $renters = Renter::query()
            ->withTrashed()
            ->where('hostel_id', 10660)
            ->get();
        foreach ($renters as $renter) {
            $check = Contract::query()
                ->where('status', '<>', Contract::LIQUIDATED)
                ->where('hostel_id', 10660)
                ->where('created_at', $renter->created_at)
                ->first();
            if ($check) {
                $renter->restore();
            }
        }

        dd();

//        $contracts=  Contract::query()->where('hostel_id', 10634)->get();
//      foreach ($contracts as $contract)
//      {
//         dump( $this->destroyContract($contract->id));
//      }
//      dd();
        $pusher = \PusherService::getClient();
        $res = $pusher->trigger('job-actions-29280', 'error', 'test');
        dd($res);

        $hostelId = 9267;

        $date = Carbon::createFromFormat('d/m/Y', '01/11/2020');

        $items = MoneyInfo::query()
            ->whereBetween('date_action', [
                $date->copy()->startOfMonth()->startOfDay(),
                $date->copy()->endOfMonth()->endOfDay()
            ])
            ->where('type', MoneyInfo::VOUCHER_ROOM_PRICE)
            ->where('hostel_id', $hostelId)
            ->get();
        foreach ($items as $item) {
            $contract = $item->contract;
            $item->delete();
            $date = $this->getLatestInvoice($contract->id);
            $contract->last_invoice_at = $date;
            $contract->save();

        }
        dd();


        $hostelId = 10509;

        $items = MoneyInfo::query()->onlyTrashed()
            ->whereBetween('deleted_at', [
                Carbon::now()->startOfDay(),
                Carbon::now()->endOfDay()
            ])
            ->where('type', MoneyInfo::VOUCHER_ROOM_PRICE)
            ->where('hostel_id', $hostelId)
            ->restore();

        dd($items->count());

        $hostelId = 8924;

        $tenDate = Carbon::createFromFormat('d/m/Y', '01/10/2020');
        $nineDate = Carbon::createFromFormat('d/m/Y', '01/09/2020');
        $eightDate = Carbon::createFromFormat('d/m/Y', '01/08/2020');
        $sevenDate = Carbon::createFromFormat('d/m/Y', '01/07/2020');

        $moneyInfos = MoneyInfo::query()->where('hostel_id', $hostelId)
            ->where('type', MoneyInfo::VOUCHER_SERVICE)
            ->where('contract_id', '<>', 15538)
            ->get();
        foreach ($moneyInfos as $moneyInfo) {
            $dateAction = $moneyInfo->date_action;
            $moneyInfo->date_action = $dateAction->copy()->subMonth()->startOfDay();
            $moneyInfo->save();
        }
        dd();


//        $date = Carbon::createFromFormat('Y-m-d H:i:s', '2020-09-30 13:33:39');
//        $moneyInfos = MoneyInfo::query()->where('hostel_id', $hostelId)
//            ->where('type', MoneyInfo::VOUCHER_SERVICE)
//            ->whereBetween('updated_at', [
//                $date->copy()->startOfMinute(),
//                $date->copy()->endOfMinute()
//            ])
//            ->get();
//       foreach ($moneyInfos as $moneyInfo)
//       {
//           $props = Activity::query()->where('subject_id', $moneyInfo->id)
//               ->latest('id')
//               ->first();
//           if($props)
//           {
//               $properties = $props->properties;
//               $attr=  $properties['attributes'];
//               unset($attr['id']);
//               unset($attr['updated_at']);
//               $moneyInfo->update($attr);
//           }
//       }
//
//       dd();


        $eight = MoneyInfo::query()
            ->where('contract_id', 15538)
            ->where('type', MoneyInfo::VOUCHER_SERVICE)
            ->whereBetween('date_action', [
                $eightDate->copy()->startOfMonth()->startOfDay(),
                $eightDate->copy()->endOfMonth()->endOfDay()
            ])
            ->where('hostel_id', $hostelId)
            ->update([
                'date_action' => $sevenDate->copy()->startOfDay()
            ]);

        $nine = MoneyInfo::query()
            ->where('contract_id', 15538)
            ->where('type', MoneyInfo::VOUCHER_SERVICE)
            ->whereBetween('date_action', [
                $nineDate->copy()->startOfMonth()->startOfDay(),
                $nineDate->copy()->endOfMonth()->endOfDay()
            ])
            ->where('hostel_id', $hostelId)
            ->update([
                'date_action' => $eightDate->copy()->startOfDay()
            ]);

        $nine = MoneyInfo::query()
            ->where('contract_id', 15538)
            ->where('type', MoneyInfo::VOUCHER_SERVICE)
            ->whereBetween('date_action', [
                $tenDate->copy()->startOfMonth()->startOfDay(),
                $tenDate->copy()->endOfMonth()->endOfDay()
            ])
            ->where('hostel_id', $hostelId)
            ->update([
                'date_action' => $nineDate->copy()->startOfDay()
            ]);
        dd();


//        ElectricWater::query()
//            ->whereBetween('date_action', [
//                $tenDate->copy()->startOfMonth(),
//                $tenDate->copy()->endOfMonth()
//            ])
//            ->where('hostel_id', $hostelId)
//            ->update([
//                'date_action' => $nineDate
//            ]);


//        ElectricWater::query()
//            ->whereBetween('date_action', [
//                $nineDate->copy()->startOfMonth(),
//                $nineDate->copy()->endOfMonth()
//            ])
//            ->where('hostel_id', $hostelId)
//            ->update([
//                'date_action' => $eightDate
//            ]);
        dd();
        $reserves = RoomReservation::query()->where('hostel_id', 10514)->onlyTrashed()->get();
        foreach ($reserves as $reserve) {

            $contract = Contract::query()->where('reserve_id', $reserve->id)
                ->where('status', Contract::VALIDATED)
                ->first();
            if (!$contract) {
                continue;
            }
            $reserveDeposit = $reserve->deposit;
            $roomId = $contract->room_id;
            $hostel = $contract->hostel;
            if (!empty($reserveDeposit)) {
                $transaction = Transaction::create([
                    'money_info_id' => null,
                    'amount' => $reserveDeposit,
                    'note' => 'Thanh toán tiền đặt cọc giữ chỗ HĐ ' . 'HD' . $contract->id . Carbon::now()->format('dmY'),
                    'room_id' => $roomId,
                    'hostel_id' => $hostel->id,
                    'date_action' => Carbon::now()->toDateString(),
                    'type' => CollectSpend::SPEND
                ]);

                CollectSpend::create([
                    'amount' => $reserveDeposit,
                    'hostel_id' => $hostel->id,
                    'room_id' => $roomId,
                    'note' => 'Thanh toán tiền cọc giữ chỗ HĐ ' . 'HD' . $contract->id . Carbon::now()->format('dmY'),
                    'name' => 'Thanh toán tiền cọc giữ chỗ HĐ ' . 'HD' . $contract->id . Carbon::now()->format('dmY'),
                    'payment_method' => CollectSpend::MONEY,
                    'date_action' => Carbon::now()->toDateString(),
                    'user_id' => $contract->renter_id,
                    'money_info_id' => null,
                    'type' => CollectSpend::SPEND,
                    'transaction_id' => $transaction->id,
                    'contract_id' => $contract->id,
                    'is_deposit' => true,
                    'is_return_deposit' => true
                ]);
            }
            $this->line('done ' . $roomId . ', deposit: ' . $reserveDeposit);
        }
        dd();
        dd($this->importContract());
        \Spatie\Permission\Models\Permission::create([
            'name' => 'view-spend',
            'display_name' => 'Xem'
        ]);
//        \Spatie\Permission\Models\Permission::create([
//            'name' => 'add-reserve',
//            'display_name' => 'Thêm cọc giữ chỗ'
//        ]);
        dd();
        $items = StatisticLog::query()->has('statMonth')->get();
        foreach ($items as $item) {
            if ($item->month != $item->statMonth->month) {
                $item->month = $item->statMonth->month;
            }
            if ($item->year != $item->statMonth->year) {
                $item->year = $item->statMonth->year;
            }
            $item->save();
            $this->line('Success ' . $item->id);
        }
        dd();
        $hostels = Hostel::all();
        foreach ($hostels as $hostel) {
            $items = StatisticLog::query()
                ->whereNotNull('collect_spend_id')
                ->groupBy('collect_spend_id')
                ->where('hostel_id', $hostel->id)
                ->pluck('id')
                ->toArray();

            StatisticLog::query()
                ->whereNotNull('collect_spend_id')
                ->where('hostel_id', $hostel->id)
                ->whereNotIn('id', $items)
                ->delete();
            $this->line('Process ' . $hostel->id);
        }
        dd();


        dd(User::query()->where('type', User::RENTER)->whereNotNull('id_number')->count());
        dd(Renter::query()
            ->where(function ($q) {
                $q->orwhereNotNull('id_number_front');
                $q->orwhereNotNull('id_number_back');
            })
            ->count());

        $items = HostelPostCrawlMedia::query()
            ->whereHas('hostelPostCrawl', function ($q) {
                $q->where('from', HostelPostCrawl::FROM_PHONGTRO_123);
            })
            ->get();
        foreach ($items as $item) {
            $image = str_replace('900x600', '450x300', $item->media);
            $item->media = $image;
            $item->save();
        }
        dd();
        $items = MoneyInfo::query()
            ->where('amount', 0)
            ->where('type', MoneyInfo::VOUCHER_SERVICE)
            ->get();
        foreach ($items as $item) {
            $amount = MoneyDetail::query()
                ->where('money_info_id', $item->id)
                ->sum('amount');
            $item->amount = $amount;
            $item->remain = $amount - $item->pay;
            $item->save();
        }
        dd();

        ElectricWater::query()
            ->where('hostel_id', 8887)
            ->where('date_action', '>=', '2020-10-01 00:00:00')
            ->update([
                'date_action' => Carbon::createFromFormat('d/m/Y', '01/09/2020')->toDateString()
            ]);
        dd();
        $user = User::find(30155);
        $regions = null;
        if ($user->regions->count() > 0) {
            $regions = implode(', ', $user->regions->pluck('name')->toArray());
        }
        dd($regions);
        District::query()->update([
            'is_search' => true
        ]);
        Ward::query()->update([
            'is_search' => true
        ]);
        dd();
        $role = Role::where('name', 'owner')->first();
        $permissions = Permission::query()->where('is_admin', false)->pluck('name')->toArray();
        $role->syncPermissions($permissions);
        dd();

        $items = HostelPostCrawl::query()
            ->whereNull('dynamic_link')
            ->orderBy('id', 'desc')
            ->get();
        foreach ($items as $item) {
            $dynamicLink = Functions::generateDynamicLinkHostelPostCrawl($item);
            $item->dynamic_link = $dynamicLink;
            $item->save();

            $this->line('Done with ' . $item->id);
        }
        dd();
        $from = Carbon::createFromFormat('d/m/Y', '01/08/2020');
        $to = Carbon::createFromFormat('d/m/Y', '31/08/2020');
        dd(Functions::checkFullPeriod($from, $to, 31));
        $hostel = Hostel::find(9476);
        $contracts = Contract::query()
            ->where('hostel_id', $hostel->id)
            ->where('status', '<>', Contract::LIQUIDATED)
            ->whereNull('bed_id')
            ->get();
        foreach ($contracts as $contract) {
            $room = $contract->room;
            $roomBed = RoomBed::query()
                ->where('room_id', $room->id)
                ->where('status', RoomBed::AVAILABLE)
                ->first();
            if ($roomBed) {
                $contract->bed_id = optional($roomBed)->id;
                $roomBed->status = RoomBed::UNAVAILABLE;
                $roomBed->save();
                $contract->save();
            }

            $bed = $contract->bed;
            if ($bed) {
                $bed->status = RoomBed::UNAVAILABLE;
                $bed->save();
            }
        }

        dd();

        \Spatie\Permission\Models\Permission::create([
            'name' => 'edit-renter-password',
            'display_name' => 'Đổi mật khẩu khách thuê'
        ]);

        dd();
        $items = Province::query()
            ->withCount('owners')
            ->get();

        foreach ($items as $item) {
            $itemArr = [];
            $itemArr['name'] = $item->name;
            $itemArr['cnt'] = $item->owners_count;
            $responseArr[] = $itemArr;
        }

        $name = 'province-owner';
        \Excel::create($name . '-' . time(), function ($excel) use ($responseArr, $name) {
            $excel->sheet($name, function ($sheet) use ($responseArr) {
                $sheet->fromArray($responseArr);
            });
        })->store('xls', storage_path('files/'));


        dd();
        $items = \DB::connection('crm')
            ->table('tblleads')
            ->where('source', 3)
            ->get();

        foreach ($items as $item) {
            $itemArr = [];
            $itemArr['name'] = $item->name;
            $itemArr['email'] = $item->email;
            $itemArr['phonenumber'] = $item->phonenumber;
            $user = User::query()
                ->where('phone', $item->phonenumber)
                ->where('type', User::OWNER)
                ->first();
            if ($user) {
                $itemArr['city'] = $user->province_name;
                $itemArr['type'] = $user->branch_app_text;
            } else {
                $itemArr['city'] = null;
                $itemArr['type'] = null;
            }

            $status = $item->status;
            $statusItem = \DB::connection('crm')
                ->table('tblleads_status')
                ->where('id', $status)
                ->first();
            $itemArr['status'] = optional($statusItem)->name;
            $itemArr['created_at'] = optional(optional($user)->created_at)->format('d/m/Y');
            $responseArr[] = $itemArr;
        }

        $name = 'Lead';
        \Excel::create($name . '-' . time(), function ($excel) use ($responseArr, $name) {
            $excel->sheet($name, function ($sheet) use ($responseArr) {
                $sheet->fromArray($responseArr);
            });
        })->store('xls', storage_path('files/'));
        dd();


        $pusher = \PusherService::getClient();
        $channelName = 'presence-online-status-v2';
        $usersChannel = $pusher->get('/channels/' . $channelName . '/users');

        $userOnlineArr = [];
        if (isset($usersChannel['result'])) {
            if (isset($usersChannel['result']['users'])) {
                foreach ($usersChannel['result']['users'] as $item) {
                    $userIdOnline = $item['id'];
                    $userOnlineArr[] = $userIdOnline;
                }
            }
        }
        dd($userOnlineArr);
        $users = User::query()
            ->whereNull('aff_link')
            ->orderBy('id', 'desc')
            ->get();
        foreach ($users as $user) {

            $user->aff_link = Functions::generateDynamicLinkAff($user);
            $user->save();
            $this->line($user->id);

        }
        dd();

        $userIds = [19673, 29026];
        $conversation = \App\Models_v2\Conversation::query()
            ->whereHas('users', function ($q) use ($userIds) {

                $q->whereIn('user_id', [19673, 29026])->whereIn('user_id', [29026]);

            })
            ->has('users', count($userIds))
            ->first();
        dd($conversation);

        dispatch_now(new RemoveUserConversationV2(29008, 10072, null));
        dd();

        $hostel = Hostel::find(10062);
        $owner = $hostel->owner;
        \Notification::sendNow($owner, new SendWhenConfirmHostel(
            $hostel, 'test'
        ));
        dd();

        $startTime = Carbon::createFromFormat('d/m/Y', '1/8/2020')->copy()->startOfMonth();
        $endTime = Carbon::createFromFormat('d/m/Y', '1/8/2020')->copy()->endOfMonth();
        $itemEw = ElectricWater::query()->whereBetween('date_action', [
            $startTime,
            $endTime
        ])
            ->where('room_id', 21762)->first();
        dd($itemEw);


        $a = [1, 2, 3, 4];
        foreach ($a as $key => $b) {
            if ($b == 1) {
                continue;
            }
            dump($key);
        }
        dd();

        $hostelId = 9398;

        $items = MoneyInfo::query()
            ->where('hostel_id', $hostelId)
            ->where('type', MoneyInfo::VOUCHER_SERVICE)
            ->where('remain', '>', 0)
            ->get();
        $delete = [];
        foreach ($items as $item) {
            $amount = $item->details->sum('amount');
            $item->amount = $amount;
            $item->remain = $amount - $item->pay - $item->discount;
            $item->save();

        }
        dd();
        foreach ($delete as $iDelete) {
            if (count($iDelete) == 2) {
                MoneyDetail::query()
                    ->where('id', $iDelete[0])->delete();
            }
        }
        dd();

        // dd($contracts);

        $items = CollectSpend::query()
            ->where('note', 'LIKE', 'Trả lại tiền phòng từ %')
            ->whereNull('type_purpose')
            ->get();
        foreach ($items as $item) {
            $ownerId = $item->hostel->owner_id;

            $typeSpend = TypeSpend::query()
                ->where('owner_id', $ownerId)
                ->where('is_default', 1)
                ->first();
            $item->type_purpose = optional($typeSpend)->id;
            $item->save();
            $this->line($item->id);
        }

        dd();

        $users = User::query()
            ->get();
        foreach ($users as $user) {
            if (empty(trim($user->name))) {
                $user->name = $user->first_name . ' ' . $user->last_name;
                $user->save();
                $this->line($user->id);
            }
        }

        dd();

        $renters = Renter::query()
            ->with('user')
            ->whereNull('last_name')
            ->get();
        foreach ($renters as $renter) {
            if (!$renter->user) {
                continue;
            }
            $nameArr = explode(' ', $renter->user->name_text);
            if (!is_array($nameArr)) {
                continue;
            }
            $renter->last_name = $nameArr[count($nameArr) - 1];
            $renter->save();
            $this->line('Done ' . $renter->id);
        }
        dd();

//	    $moneyInfos = MoneyInfo::query()
//            ->where('remain', 0)
//            ->where('pay', '=', 0)
//            ->where('amount', '>', 0)
//            ->where('type', MoneyInfo::VOUCHER_CONTRACT)
//            ->doesntHave('collectSpends')
//            ->get();
//	    foreach ($moneyInfos as $moneyInfo)
//        {
//            $moneyInfo->remain = $moneyInfo->amount;
//            $moneyInfo->save();
//            $this->line($moneyInfo->id);
//        }
//	    dd();

        $contracts = Contract::query()
            ->whereNull('collect_to')
            ->get();
        foreach ($contracts as $contract) {
            $moneyInfos = MoneyInfo::query()
                ->where('contract_id', $contract->id)
                ->where('type', MoneyInfo::VOUCHER_CONTRACT)
                ->where('remain', 0)
                ->where('created_at', $contract->created_at)
                ->get();
            foreach ($moneyInfos as $moneyInfo) {
                $collectSpend = CollectSpend::query()
                    ->where('money_info_id', $moneyInfo->id)
                    ->first();
                if ($collectSpend) {
                    if ($collectSpend->created_at == $moneyInfo->created_at) {

                        $this->line($contract->hostel->owner->phone);
                        $this->line($contract->hostel->name);
                        $this->line($contract->room->name);
                        $this->line($contract->id);
                        $this->line($moneyInfo->id);
                        $this->line('---');

                    }
                }
            }
        }
        dd();

        $items = MoneyInfo::query()
            ->whereIn('id', [
                232961,
                232962,
            ])
            ->get();


        CollectSpend::query()
            ->whereIn('money_info_id', $items->pluck('id')->toArray())
            ->delete();

        Transaction::query()
            ->whereIn('money_info_id', $items->pluck('id')->toArray())
            ->delete();

        foreach ($items as $item) {
            $item->pay = 0;
            $item->remain = $item->amount;
            $item->save();
        }

        dd();


        $items = CollectSpend::query()
            ->whereNull('owner_id')
            ->orderBy('id', 'desc')
            ->get();
        foreach ($items as $item) {

            $user = $item->user;
            if ($user) {
                if ($user->type == User::OWNER) {
                    $item->owner_id = $user->id;
                } else {
                    $item->owner_id = $user->staff_owner_id;
                }

            } else if ($item->hostel) {
                $item->owner_id = $item->hostel->owner_id;
            }
            $item->save();
            $this->line('Done ' . $item->id);
        }
        dd();


        dd();

        $users = User::query()
            ->whereNotNull('refer_id')
            ->get();
        foreach ($users as $user) {
            if ($user->type == User::RENTER) {
                $checkFindSession = FindSession::query()
                    ->where('user_id', $user->id)
                    ->count();
                if ($checkFindSession > 0) {
                    $user->refer_status = User::REFER_STATUS_SUCCESS;
                    $user->refer_reason = null;
                } else {
                    $user->refer_status = User::REFER_STATUS_NOT_SUCCESS;
                    $user->refer_reason = User::REFER_REASON_NOT_CREATE_REQUEST;
                }
            } else if ($user->type == User::OWNER) {
                $checkHostel = Hostel::query()
                    ->where('owner_id', $user->id)
                    ->count();

                $checkConfirm = Hostel::query()
                    ->where('owner_id', $user->id)
                    ->where('status_confirm', Hostel::CONFIRMED)
                    ->count();

                if ($checkHostel > 0 && $checkConfirm == 0) {
                    $user->refer_status = User::REFER_STATUS_NOT_SUCCESS;
                    $user->refer_reason = User::REFER_REASON_CREATED_NOT_CONFIRM;
                } else if ($checkHostel == 0) {
                    $user->refer_status = User::REFER_STATUS_NOT_SUCCESS;
                    $user->refer_reason = User::REFER_REASON_NOT_CREATED;
                } else if ($checkHostel > 0 && $checkConfirm > 0) {
                    $user->refer_status = User::REFER_STATUS_SUCCESS;
                    $user->refer_reason = null;
                }
            }
            $user->refer_date = $user->created_at;
            $user->save();
        }

        dd();


        $filePath = public_path('sample_import_contract.xlsx');
        $items = \Excel::selectSheetsByIndex(0)->load($filePath, function ($reader) {
            $reader->noHeading();
        })->skip(1)->get();

        $indexArr = [];
        $headerArr = [];
        $headers = $items[0];
        foreach ($headers as $key => $header) {
            $name = str_replace('(Số đầu)', '', $header);
            $name = str_replace('(Số lượng)', '', $name);
            $name = str_replace('(ngày/tháng/năm)', '', $name);
            $name = trim($name);
            $headerArr[$key] = $name;
        }

        $lastKey = array_key_last($headerArr);
        unset($items[0]);


        foreach ($items as $key => $item) {
            $hostelName = trim($item[0]);
            $roomName = trim($item[1]);

            if (empty($hostelName) || empty($roomName)) {
                continue;
            }


            $bedName = trim($item[2]);
            $dateContract = trim($item[3]);
            $endDate = trim($item[4]);
            $roomPrice = trim($item[5]);
            $deposit = trim($item[6]);
            $period = trim($item[7]);
            $dayCollect = trim($item[8]);
            $collectTo = trim($item[9]);
            $phone = trim($item[10]);
            $name = trim($item[11]);
            $email = trim($item[12]);
            $birthday = trim($item[13]);
            $idNumber = trim($item[14]);
            $idNumberDate = trim($item[15]);
            $idNumberLocation = trim($item[16]);

            if (empty($endDate)) {
                return response([
                    'status' => 0,
                    'message' => 'Không được bỏ trống hạn HĐ'
                ]);
            }

            $hostel = Hostel::query()
                ->where('name', $hostelName)
                ->first();
            if (!$hostel) {
                return response([
                    'status' => 0,
                    'message' => 'Không tìm thấy nhà trọ ' . $hostelName . ' trên hệ thống'
                ]);
            }


            $room = Room::query()
                ->where('name', $roomName)
                ->where('hostel_id', $hostel->id)
                ->first();

            if (!$room) {
                return response([
                    'status' => 0,
                    'message' => 'Không tìm thấy phòng trọ ' . $roomName . ' thuộc nhà trọ ' . $hostelName . ' trên hệ thống'
                ]);
            }

            $bedId = null;

            if ($hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                if (empty($bedName)) {
                    return response([
                        'status' => 0,
                        'message' => 'Không được bỏ trống tên giường'
                    ]);
                }

                $bed = RoomBed::query()->where('room_id', $room->id)
                    ->where('name', $bedName)
                    ->first();
                if (!$bed) {
                    return response([
                        'status' => 0,
                        'message' => 'Không tìm thấy giường ' . $bedName . ' cho phòng ' . $roomName
                    ]);
                }

            }


            $data = [
                'hostel' => $hostel,
                'hostel_id' => $hostel->id,
                'period' => empty($period) ? 1 : $period,
                'room' => $room,
                'room_id' => $room->id,
                'date_contract' => !empty($dateContract) ? \PHPExcel_Shared_Date::ExcelToPHPObject($dateContract) : null,
                'end_date' => !empty($endDate) ? \PHPExcel_Shared_Date::ExcelToPHPObject($endDate) : null,
                'room_price' => $roomPrice,
                'deposit' => $deposit,
                'day_collect' => $dayCollect,
                'collect_to' => !empty($collectTo) ? \PHPExcel_Shared_Date::ExcelToPHPObject($collectTo) : null,
                'is_collected' => !empty($collectTo) ? 'on' : 'off',
                'phone' => $phone,
                'name' => $name,
                'email' => $email,
                'birthday' => $birthday,
                'id_number' => $idNumber,
                'id_number_date' => $idNumberDate,
                'id_number_location' => $idNumberLocation,
                'bed_id' => $bedId,
                'residence_status' => false,
                'date_end_residence' => null,
                'type_rent' => Room::START_PERIOD
            ];

            if (!empty($data['end_date'])) {
                $data['end_date'] = Carbon::instance($data['end_date'])->toDateString();
            }
            if (!empty($data['collect_to'])) {
                $data['collect_to'] = Carbon::instance($data['collect_to'])->toDateString();
            }

            if (!empty($data['id_number_date'])) {
                $data['id_number_date'] = Carbon::instance($data['id_number_date'])->toDateString();
            }

            if (!empty($data['date_contract'])) {
                $data['date_contract'] = Carbon::instance($data['date_contract'])->toDateString();
                $data['date_enable'] = $data['date_contract'];
                $data['start_date'] = $data['date_contract'];
                $data['date_join'] = $data['date_contract'];
            }

            $data['fees'] = null;
            for ($i = 17; $i <= $lastKey; $i++) {
                if (!isset($headerArr[$i])) {
                    continue;
                }

                $feeName = $headerArr[$i];
                $fee = HostelFee::query()
                    ->where('name', $feeName)
                    ->where('hostel_id', $hostel->id)
                    ->first();
                if (!$fee) {
                    continue;
                }

                if (!is_numeric($item[$i])) {
                    continue;
                }

                $data['fees'][$fee->id] = ['qty' => intval($item[$i])];
            }


            $contractService = new ContractService($data);
            $res = $contractService->store();
            dd($res);
        }
        dd();
        dd(Functions::convertFileSize(2000));
        $from = Carbon::createFromFormat('d/m/Y', '13/07/2020');
        $to = Carbon::createFromFormat('d/m/Y', '13/07/2020');
        $cost = 5500000;
        $dayCollect = 14;
        $money = Functions::calculateMoneyInRange4($from->copy(), $to->copy(), $cost, $dayCollect);
        dd($money);


        $owners = User::query()
            ->where('type', User::OWNER)
            ->where(function ($q) {
                $q->orWhereHas('hostels', function ($q) {
                    $q->where('province_id', 79);
                });
                $q->orWhere('province_id', 79);
            })
            ->get();
        $responseArr = [];
        foreach ($owners as $owner) {


            $itemArr['Tên'] = $owner->name;
            $itemArr['email'] = $owner->email;
            $itemArr['SDT'] = $owner->phone;
            $itemArr['Địa chỉ'] = $owner->address_text;
            $itemArr['Ngày đăng ký'] = $owner->created_at->format('d/m/Y');
            $itemArr['Thiết bị đăng ký'] = $owner->from_text;
            $itemArr['Số nhà đã tạo'] = $owner->hostels->count();
            $responseArr[] = $itemArr;
        }

        $name = 'chu-tro-hcm';

        return \Excel::create($name . '-' . time(), function ($excel) use ($responseArr, $name) {
            $excel->sheet($name, function ($sheet) use ($responseArr) {
                $sheet->fromArray($responseArr);
            });
        })->store('xls', storage_path('excel/exports'));
        dd();


        $from = Carbon::createFromFormat('d/m/Y', '30/05/2020');
        $to = Carbon::createFromFormat('d/m/Y', '05/06/2020');
        $dayCollect = 5;
        $period = 1;
        $cost = 1700000;


        $money = Functions::calculateMoneyInRange3($from->copy(), $to->copy(), $cost, $dayCollect);
        //dd(Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect));
        dd($money);

        $ews = ElectricWater::query()
            ->whereBetween('date_action', [
                Carbon::now()->startOfMonth(),
                Carbon::now()->endOfMonth()
            ])
            ->whereIn('hostel_id', [9108, 9452])
            ->where('start_water', 0)
            ->get();

        foreach ($ews as $ew) {
            $contract = Contract::find($ew->contract_id);
            if ($contract) {
                $fee = ContractFee::query()
                    ->where('contract_id', $contract->id)
                    ->whereHas('fee', function ($q) {
                        $q->whereIn('type', [
                            HostelFee::WATER_BY_CLOCK,
                        ]);
                    })
                    ->first();

                if ($fee) {
                    $ew->start_water = $fee->qty;
                    $ew->save();
                }
            }
        }

        dd();


        $items = MoneyInfo::query()
            //->where('id', 217914)
            ->where('type', MoneyInfo::VOUCHER_SERVICE)
            ->whereBetween('date_action', [
                Carbon::now()->startOfMonth(),
                Carbon::now()->endOfMonth()
            ])
            ->whereIn('hostel_id', [9108, 9452])
            ->get();

        $startDateAction = Carbon::now()->startOfMonth()->toDateTimeString();

        foreach ($items as $item) {
            $dateContract = $item->contract->date_contract;
            $detailElectric = MoneyDetail::query()
                ->where('money_info_id', $item->id)
                ->where('is_electric', 1)
                ->first();

            $detailWater = MoneyDetail::query()
                ->where('money_info_id', $item->id)
                ->where('is_water', 1)
                ->first();

            $qtyElectric = $detailElectric->qty;
            $arrE = json_decode($qtyElectric, true);
            $startE = $arrE['start'];
            $endE = $arrE['end'];

            $qtyWater = $detailWater->qty;
            $arrW = json_decode($qtyWater, true);
            $startW = $arrW['start'];
            $endW = $arrW['end'];

            $itemBefore = ElectricWater::query()
                ->where('date_action', '<=', $startDateAction)
                ->whereMonth('date_action', '>=', $dateContract->copy()->startOfDay())
                ->whereYear('date_action', '>=', $dateContract->copy()->startOfDay())
                ->where('room_id', $item->room_id)
                ->where('contract_id', $item->contract_id)
                ->orderBy('date_action', 'desc')->first();
            if ($itemBefore) {
                $arrE['start'] = $itemBefore->end_electric;
                $arrW['start'] = $itemBefore->end_water;
            }

            $detailElectric->qty = json_encode($arrE);
            $detailWater->qty = json_encode($arrW);
            $detailElectric->amount = ($arrE['end'] - $arrE['start']) * $detailElectric->value;
            $detailElectric->save();
            $detailWater->amount = ($arrW['end'] - $arrW['start']) * $detailWater->value;
            $detailWater->save();

            $item->amount = MoneyDetail::query()->where('money_info_id', $item->id)->sum('amount');
            $item->remain = $item->amount - $item->pay - $item->discount;
            $item->save();

            ElectricWater::query()
                ->whereBetween('date_action', [Carbon::now()->startOfMonth(), Carbon::now()->endOfMonth()])
                ->where('hostel_id', $item->hostel_id)
                ->where('room_id', $item->room_id)
                ->where('contract_id', $item->contract_id)
                ->update([
                    'start_electric' => $arrE['start'],
                    'start_water' => $arrW['start']
                ]);

            $this->line('Processed ' . $item->id);

        }


        dd();
        $room = Room::find(24175);
        $maxRenters = $room->max_renters;
        $numberBeds = $room->beds->count();

        if ($maxRenters > $numberBeds) {
            while ($numberBeds < $maxRenters) {
                $numberBeds++;
                RoomBed::create([
                    'name' => 'Giường ' . $numberBeds,
                    'hostel_id' => $room->hostel_id,
                    'room_id' => $room->id,
                    'status' => RoomBed::AVAILABLE,
                ]);
            }
        }
        dd();


        $items = Renter::query();


        $items = $items->select(\DB::raw('renters.*'))
            ->with('renterRoom')
            ->with('hostel')
            ->with('room')
            ->has('hostel')
            ->with('user')->whereHas('user', function ($q) {
                $q->where(function ($q) {
                    $q->whereNull('ios_token');
                    $q->whereNull('android_token');
                });
            })->whereHas('hostel.owner', function ($q) {
                $q->where('payment_status', 1);
            });
        $itemsExcel = clone $items;
        $itemsExcel = $itemsExcel
            ->where('renters.status', Renter::LIVING)
            ->groupBy('renters.phone')
            ->orderBy('renters.created_at', 'desc')
            ->limit(200)
            ->get();
        $responseArr = [];
        foreach ($itemsExcel as $itemE) {
            $user = $itemE->user;
            $message = 'Chưa khai báo';
            if ($itemE->residence_status == RenterRoom::RESIDENCE_LIMIT) {
                $message = 'Có thời hạn';
            }
            if ($itemE->residence_status == RenterRoom::RESIDENCE_NOT_LIMIT) {
                $message = 'Không thời hạn';
            }

            $itemArr['Tên'] = $itemE->name;
            $itemArr['SDT'] = $itemE->phone;
            $itemArr['Ngày sinh'] = !empty($itemE->birthday) ? $itemE->birthday->format('d/m/Y') : '';
            $itemArr['Quê quán'] = $itemE->address_text;
            $itemArr['CMT'] = !empty($user) ? $user->id_number : '';
            $itemArr['Ngày cấp'] = !empty($itemE->id_number_date) ? Carbon::createFromFormat('Y-m-d', $itemE->id_number_date)->format('d/m/Y') : '';
            $itemArr['Nơi cấp'] = $itemE->id_number_location;
            $itemArr['Nhà trọ'] = $itemE->hostel_name;
            $itemArr['Phòng trọ'] = $itemE->room_name;
            $itemArr['Ngày vào'] = !empty($itemE->date_joined) ? $itemE->date_joined->format('d/m/Y') : '';
            $itemArr['Tạm trú'] = $message;
            $itemArr['Thời hạn tạm trú'] = !empty($itemE->date_end_residence) ? $itemE->date_end_residence->format('d/m/Y') : '';
            $responseArr[] = $itemArr;
        }

        $name = 'Nguoi-o-tro';

        return \Excel::create($name . '-' . time(), function ($excel) use ($responseArr, $name) {
            $excel->sheet($name, function ($sheet) use ($responseArr) {
                $sheet->fromArray($responseArr);
            });
        })->store('xls', storage_path('excel/exports'));

        dd();


        HostelPostCrawl::query()->doesntHave('medias')->whereNull('content')->delete();
        dd();

        $items = MoneyInfo::query()
            //->where('id', 217914)
            ->where('type', MoneyInfo::VOUCHER_SERVICE)
            ->whereBetween('date_action', [
                Carbon::now()->startOfMonth(),
                Carbon::now()->endOfMonth()
            ])
            ->where('hostel_id', 7435)
            ->get();

        $startDateAction = Carbon::now()->startOfMonth()->toDateTimeString();

        foreach ($items as $item) {
            $dateContract = $item->contract->date_contract;
            $detailElectric = MoneyDetail::query()
                ->where('money_info_id', $item->id)
                ->where('is_electric', 1)
                ->first();

            $detailWater = MoneyDetail::query()
                ->where('money_info_id', $item->id)
                ->where('is_water', 1)
                ->first();

            $qtyElectric = $detailElectric->qty;
            $arrE = json_decode($qtyElectric, true);
            $startE = $arrE['start'];
            $endE = $arrE['end'];

            $qtyWater = $detailWater->qty;
            $arrW = json_decode($qtyWater, true);
            $startW = $arrW['start'];
            $endW = $arrW['end'];

            $itemBefore = ElectricWater::query()
                ->where('date_action', '<=', $startDateAction)
                ->whereMonth('date_action', '>=', $dateContract->copy()->startOfDay())
                ->whereYear('date_action', '>=', $dateContract->copy()->startOfDay())
                ->where('room_id', $item->room_id)
                ->where('contract_id', $item->contract_id)
                ->orderBy('date_action', 'desc')->first();
            if ($itemBefore) {
                $arrE['start'] = $itemBefore->end_electric;
                $arrW['start'] = $itemBefore->end_water;
            }

            $detailElectric->qty = json_encode($arrE);
            $detailWater->qty = json_encode($arrW);
            $detailElectric->amount = ($arrE['end'] - $arrE['start']) * $detailElectric->value;
            $detailElectric->save();
            $detailWater->amount = ($arrW['end'] - $arrW['start']) * $detailWater->value;
            $detailWater->save();

            $item->amount = MoneyDetail::query()->where('money_info_id', $item->id)->sum('amount');
            $item->remain = $item->amount - $item->pay - $item->discount;
            $item->save();

            ElectricWater::query()
                ->whereBetween('date_action', [Carbon::now()->startOfMonth(), Carbon::now()->endOfMonth()])
                ->where('hostel_id', $item->hostel_id)
                ->where('room_id', $item->room_id)
                ->where('contract_id', $item->contract_id)
                ->update([
                    'start_electric' => $arrE['start'],
                    'start_water' => $arrW['start']
                ]);

            $this->line('Processed ' . $item->id);

        }

        dd();

        $dateContract = Contract::find(7608)->date_contract;

        $startDateAction = Carbon::now()->startOfMonth()->toDateTimeString();
        //	dd($dateContract, $startDateAction);
        $itemBefore = ElectricWater::query()->where('room_id', '14089')
            ->where('date_action', '<=', $startDateAction)
            ->whereMonth('date_action', '>=', $dateContract->copy()->startOfDay())
            ->orderBy('date_action', 'desc')->first();
        dd($itemBefore);

        $date = Carbon::createFromFormat('Y-m-d H:i:s', '2020-06-11 14:33:15');
        $startTime = $date->copy()->subMonth()->startOfMonth()->startOfDay()->toDateTimeString();
        $endTime = $date->copy()->subMonth()->endOfMonth()->endOfDay()->toDateTimeString();

        $previousInfo = \App\Models\ElectricWater::query()
            ->where('room_id', 14089)
            ->whereBetween('date_action', [$startTime, $endTime])
            ->latest('id')->first();
        dd($previousInfo);

        $contracts = Contract::query()
            ->where('room_id', 11455)
            ->where('status', '<>', Contract::LIQUIDATED)
            ->get();
        foreach ($contracts as $contract) {
            $renterId = $contract->renter_id;
            $room = $contract->room;
            $hostel = $contract->hostel;
            $hostelId = $hostel->id;
            $user = User::find($renterId);
            $data = $contract->toArray();
            $check = Renter::query()
                ->where('user_id', $user->id)
                ->count();
            if ($check > 0) {
                continue;
            }

            $renterRoom = RenterRoom::query()
                ->where('contract_id', $contract->id)
                ->first();

            if ($renterRoom) {

                Renter::create([
                    'image' => $contract->image,
                    'name' => $user->name,
                    'room_id' => $room->id,
                    'note' => $contract->note,
                    'hostel_id' => $hostelId,
                    'room_name' => $room->name,
                    'hostel_name' => $hostel->name,
                    'address' => isset($data['address']) ? $data['address'] : '',
                    'province_id' => isset($data['province_id']) ? $data['province_id'] : '',
                    'district_id' => isset($data['district_id']) ? $data['district_id'] : '',
                    'ward_id' => isset($data['ward_id']) ? $data['ward_id'] : '',
                    'date_joined' => $data['date_join'],
                    'birthday' => $contract->birthday,
                    'phone' => $data['phone'],
                    'status' => Renter::LIVING,
                    'user_id' => $user->id,
//				'residence_status'   => $data['residence_status'],
                    //'date_end_residence' => $data['date_end_residence'],
                    'id_number_front' => isset($data['id_number_front']) ? $data['id_number_front'] : null,
                    'id_number_back' => isset($data['id_number_back']) ? $data['id_number_back'] : null,
                    'id_number_location' => isset($data['id_number_location']) ? $data['id_number_location'] : null,
                    'id_number_date' => isset($data['id_number_date']) ? $data['id_number_date'] : null,
//                    'residence_status' => $data['residence_status'],
//                    ''
                ]);
            }

        }

        dd();

        HostelPostCrawl::query()
            ->where(function ($q) {
                $q->orWhereNull('content');
                $q->orDoesntHave('medias');
            })
            ->delete();
        dd();

        $users = User::all();
        foreach ($users as $user) {
            $affLink = $user->aff_link;
            if (empty($affLink)) {
                $affLink = Functions::generateDynamicLinkAff($user);
                $user->aff_link = $affLink;
                $user->save();
            }
        }
        dd();

        $startNextInvoice = Carbon::createFromFormat('d/m/Y', '01/06/2020');
        $to = Carbon::createFromFormat('d/m/Y', '09/06/2020');
        $sumMoney = Functions::calculateMoneyInRange4($startNextInvoice->copy(), $to->copy(), 2300000, 9);
        dd($sumMoney);

        $moneyInfo = MoneyInfo::create([
            'hostel_id' => 8276,
            'room_id' => 18416,
            'date_action' => '2020-05-01',
            'contract_id' => 11817,
            'user_id' => 20092,
            'type' => MoneyInfo::VOUCHER_ROOM_PRICE,
            'amount' => 5500000,
            'pay' => 0,
            'remain' => 5500000,
            'money_info_name' => 'Thu tiền phòng từ 01/05/2020 đến 30/05/2020'
        ]);

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

        MoneyDetail::create([
            'hostel_id' => 8276,
            'room_id' => 18416,
            'name' => 'Thu tiền phòng từ 01/05/2020 đến 30/05/2020',
            'value' => 5500000,
            'money_info_id' => $moneyInfo->id,
            'amount' => 5500000,
            'note' => 'Thu tiền phòng từ 01/05/2020 đến 30/05/2020',
            'start_date' => '2020-05-01',
            'end_date' => '2020-05-30',
            'qty' => 1,
            'renter_id' => 20092,
            'sum_amount' => 5500000
        ]);
        dd();
        //quyền xóa HĐ
        \Spatie\Permission\Models\Permission::create([
            'name' => 'delete-contract'
        ]);
        dd();

        //quyền sửa hóa đơn
        \Spatie\Permission\Models\Permission::create([
            'name' => 'edit-money-info'
        ]);

        //quyền sinh hóa đơn tiền nhà
        \Spatie\Permission\Models\Permission::create([
            'name' => 'create-room-money-info'
        ]);

        //quyền đính kèm file
        \Spatie\Permission\Models\Permission::create([
            'name' => 'attach-file'
        ]);
        $filePath = public_path('import-nhanh-dịch-vụ.xlsx');
        $items = \Excel::selectSheetsByIndex(0)->load($filePath, function ($reader) {
            $reader->noHeading();
        })->skip(1)->get();
        dd($items);

        $hostels = Hostel::query()->whereIn('id', [
            8346,
            8346,
            8348,
            8767
        ])->get();

        $moneyInfos = MoneyInfo::query()
            ->whereIn('type', [
                MoneyInfo::VOUCHER_CONTRACT,
                MoneyInfo::VOUCHER_ROOM_PRICE
            ])
            ->whereIn('hostel_id', $hostels->pluck('id')->toArray())
            ->where('amount', '<', 0)
            ->get();

        foreach ($moneyInfos as $moneyInfo) {
            $amount = $moneyInfo->details->sum('sum_amount');
            $moneyInfo->amount = $amount;
            $moneyInfo->save();
        }

        dd();


        $user = User::query()->where('phone', '0964449404')->where('type', User::OWNER)->orderBy('id', 'desc')->first();
        \Notification::send($user, new SendWhenStaffCollect(103627));
        dd();
        $items = Hostel::all();
        foreach ($items as $item) {
            cache()->delete('image-hostel-' . $item->id);
        }
        dd();

        $items = CollectSpend::query()
            ->where('type_purpose', Statistic::ROOM_PRICE)
            ->get();
        foreach ($items as $item) {
            if ($item->hostel) {
                $owner = $item->hostel->owner;
                if ($owner) {
                    $typeSpend = TypeSpend::query()
                        ->where('owner_id', $owner->id)
                        ->where('is_default', 1)
                        ->first();
                    if ($typeSpend) {
                        $item->type_purpose = $typeSpend->id;
                        $item->save();
                    }
                }
            }
        }
        dd();

        \Spatie\Permission\Models\Permission::create([
            'name' => 'end-contract'
        ]);
        dd();

        dd();


        dd();
        User::query()->whereNull('country_phone_code')->update([
            'country_phone_code' => '+84'
        ]);

        dd();
        $contracts = Contract::query()
            ->where('hostel_id', 8130)
            ->where('status', '<>', Contract::LIQUIDATED)
            ->get();
        foreach ($contracts as $contract) {
            $renterId = $contract->renter_id;
            $room = $contract->room;
            $hostel = $contract->hostel;
            $hostelId = $hostel->id;
            $user = User::find($renterId);
            $data = $contract->toArray();
            $check = Renter::query()
                ->where('user_id', $user->id)
                ->count();
            if ($check > 0) {
                continue;
            }

            $renterRoom = RenterRoom::query()
                ->where('contract_id', $contract->id)
                ->first();

            if ($renterRoom) {

                Renter::create([
                    'image' => $contract->image,
                    'name' => $user->name,
                    'room_id' => $room->id,
                    'note' => $contract->note,
                    'hostel_id' => $hostelId,
                    'room_name' => $room->name,
                    'hostel_name' => $hostel->name,
                    'address' => isset($data['address']) ? $data['address'] : '',
                    'province_id' => isset($data['province_id']) ? $data['province_id'] : '',
                    'district_id' => isset($data['district_id']) ? $data['district_id'] : '',
                    'ward_id' => isset($data['ward_id']) ? $data['ward_id'] : '',
                    'date_joined' => $data['date_join'],
                    'birthday' => $contract->birthday,
                    'phone' => $data['phone'],
                    'status' => Renter::LIVING,
                    'user_id' => $user->id,
//				'residence_status'   => $data['residence_status'],
                    //'date_end_residence' => $data['date_end_residence'],
                    'id_number_front' => isset($data['id_number_front']) ? $data['id_number_front'] : null,
                    'id_number_back' => isset($data['id_number_back']) ? $data['id_number_back'] : null,
                    'id_number_location' => isset($data['id_number_location']) ? $data['id_number_location'] : null,
                    'id_number_date' => isset($data['id_number_date']) ? $data['id_number_date'] : null,
//                    'residence_status' => $data['residence_status'],
//                    ''
                ]);
            }

        }

        dd();


        User::query()
            ->where('is_agent', true)
            ->update([
                'number_interacts' => 1000000000
            ]);
        dd();
        dd(Carbon::now()->diffInDays(Carbon::createFromFormat('d/m/Y', '25/03/2020')));
        dd();
        $hostel = Hostel::find(8988);
        event(new HostelCreatedFindNotification($hostel));
        dd();

        $users = User::query()->where('branch_app', User::BRANCH_MANAGE)->get();
        foreach ($users as $user) {
            $log = \App\Models\AuthLoginLog::query()
                ->where('user_id', $user->id)
                ->orderBy('login_at', 'desc')
                ->first();

            if ($log) {
                $user->last_login_at = $log->login_at;
                $user->save();
            }
        }
        dd();

        $hostels = Hostel::query()
            ->whereNull('dynamic_link')
            ->whereNotNull('name')
            ->get();
        foreach ($hostels as $hostel) {
            $link = Functions::generateDynamicLinkHostel($hostel);

            $hostel->dynamic_link = $link;
            $hostel->save();
            $this->line($hostel->id);
        }
        dd();

        $item = Hostel::withTrashed()
            ->where('owner_id', 23220)
            //->orderBy( 'id', 'asc' )
            ->first();
        dd($item->id);

        $transactions = \App\Models_v2\Transaction::all();
        foreach ($transactions as $transaction) {
            if ($transaction->achievement) {
                $achievement = $transaction->achievement;
                if ($achievement) {
                    $userAchievement = UserAchievement::query()
                        ->where('user_id', $transaction->user_id)
                        ->where('achievement_id', $transaction->achievement_id)
                        ->first();
                    if (!$userAchievement) {
                        $userAchievement = UserAchievement::create([
                            'user_id' => $transaction->user_id,
                            'achievement_id' => $achievement->id,
                            'target' => $achievement->target,
                            'done' => 0
                        ]);
                    }

                    $userAchievement->increment('done');
                }
            }
        }
        dd();

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


        $hostelArr = Hostel::query()->where('owner_id', $owner->id)->pluck('id')->toArray();

        RenterRoom::query()->whereIn('hostel_id', $hostelArr)->delete();
        Deposit::query()->whereIn('hostel_id', $hostelArr)->delete();
        Renter::query()->whereIn('hostel_id', $hostelArr)->delete();
        Contract::query()->whereIn('hostel_id', $hostelArr)->delete();
        MoneyInfo::query()->whereIn('hostel_id', $hostelArr)->delete();
        CollectSpend::query()->whereIn('hostel_id', $hostelArr)->delete();
        Transaction::query()->whereIn('hostel_id', $hostelArr)->delete();
        ElectricWater::query()->whereIn('hostel_id', $hostelArr)->delete();
        StatisticLog::query()->whereIn('hostel_id', $hostelArr)->delete();

        dd();

        $owners = User::query()->where('type', User::OWNER)->get();
        foreach ($owners as $owner) {
            $infoFindHostel = UserPackageFindHostel::query()->where('user_id', $owner->id)->first();
            if ($infoFindHostel) {
                if ($infoFindHostel->package_id == 2) {
                    $currentPackage = UserPackage::query()->where('user_id', $owner->id)->first();
                    if ($currentPackage) {

                        $packageChange = PackageChange::query()->where('user_id', $owner->id)
                            ->where('number_rooms', '>', 100)
                            ->where('created_at', '<', Carbon::now()->startOfDay())
                            ->latest()
                            ->first();
                        if ($packageChange) {
                            $currentPackage->number_rooms = $packageChange->number_rooms;
                            $currentPackage->save();
                        }

                    }
                }
            }
            $this->line('Done ' . $owner->id);
        }

        dd();

        $items = Hostel::query()
            ->orderBy('id', 'desc')
            ->get();
        foreach ($items as $item) {
            $addressText = $item->address_text;
            $latlng = Functions::geocode($addressText);
            if (!empty($latlng['lat']) && !empty($latlng['lng'])) {
                $item->lat = $latlng['lat'];
                $item->lng = $latlng['lng'];

                $item->save();

            }
            $this->line($item->id);

        }

        dd();

        $items = \App\Models_v2\Conversation::all();
        foreach ($items as $item) {
            $users = $item->users->pluck('id')->toArray();
            sort($users);
            $item->members = json_encode($users);
            $item->save();
        }

        dd();

        User::query()
            ->where('type', User::OWNER)
            ->where('number_interacts', 0)
            ->update([
                'number_interacts' => 20
            ]);
        dd();

        $items = ElectricWater::all();
        foreach ($items as $item) {

            $priceWater = 0;
            $priceElectric = 0;
            $feeElectric = HostelFee::query()
                ->where('hostel_id', $item->hostel_id)
                ->where('type', HostelFee::ELECTRIC_BY_CLOCK)
                ->first();

            if ($feeElectric) {
                $priceElectric = $feeElectric->fee;
            }

            $feeWater = HostelFee::query()
                ->where('hostel_id', $item->hostel_id)
                ->where('type', HostelFee::WATER_BY_CLOCK)
                ->first();

            if ($feeWater) {
                $priceWater = $feeWater->fee;
            }
            $item->price_electric = $priceElectric;
            $item->price_water = $priceWater;
            $item->save();
        }

        dd();

        $hostel = Hostel::find(8684);
        $param = [
            'url' => url('nha-tro/') . '/' . str_slug($hostel->name) . '-' . $hostel->id,
            'title' => $hostel->name,
            'desc' => \Illuminate\Support\Str::words(strip_tags(html_entity_decode($hostel->desc)), 100),
            'image' => url($hostel->image)
        ];


        dd(Functions::generateDynamicLink($param));

        Hostel::query()
            ->where('status_confirm', Hostel::CONFIRMED)
            ->update([
                'status_confirm' => Hostel::NOT_CONFIRM
            ]);
        dd();
        $users = User::query()
            ->where('branch_app', User::BRANCH_FIND)
            ->where('type', User::RENTER)
            ->get();
        foreach ($users as $user) {
            $log = \App\Models\AuthLoginLog::query()
                ->where('user_id', $user->id)
                ->latest()
                ->first();
            if ($log) {
                $user->last_login_at = $log->login_at;
            } else {
                $user->last_login_at = $user->created_at;
            }

            $findSession = FindSession::query()
                ->where('user_id', $user->id)
                ->latest()
                ->first();

            if ($findSession) {
                $user->last_find_at = $findSession->created_at;
            }

            $user->save();
        }

        dd();

        $hostels = Hostel::all();
        foreach ($hostels as $hostel) {
            $prices = Functions::getPriceHostelForFinding($hostel);

            if (!empty($prices)) {
                $smallest = $prices['smallest'];
                $greatest = $prices['greatest'];
                $hostel->min_price = $smallest;
                $hostel->max_price = $greatest;
                $hostel->save();
//            $hostel->
            } else {
                $hostel->max_price = $hostel->greatest_price;
                $hostel->min_price = $hostel->smallest_price;
                $hostel->save();
            }
            $this->line('processed ' . $hostel->id);
        }
        dd();


        $item = Hostel::find(8799);
        event(new HostelCreated($item));

        $config = Config::query()->first();
        $cHostel = ConfigHostel::query()->where('hostel_id', 8771)->first();
        $cHostel->contract = $config->contract;
        $cHostel->save();
        dd();

        FindSession::query()->update([
            'type' => 6
        ]);
        dd(FindSession::all()->pluck('type')->toArray());

        dd();

        Conversation::query()
            ->whereIn('id', [
                15313,
                15314,
                15315,
                15316,
                15318,
                15319,
                15320,
                15321,
                15322,
                15323,
                15324,
                15325,
                15326,
                15327,
                15464,
                15511,
                16641,
                17495,
                17496,
                17497,
                17498,
            ])->delete();

        dd();

        \Mail::send('frontend3.mail.survey', [], function ($message) {
            $message->from('support@itro.vn', 'iTro.vn');
            $message->subject('TẶNG NGAY 50K KHI CHỦ TRỌ THAM GIA CHƯƠNG TRÌNH "KHẢO SÁT Ý KIẾN KHÁCH HÀNG VỀ DỊCH VỤ TÌM KHÁCH THUÊ TRÊN ỨNG DỤNG ITRO"');
            $message->to([
                //'lelinh280296@gmail.com',
                'huynt57@gmail.com'
            ]);
        });

        dd(config('constants.REMIND_RENTER_SEARCH_HOURS'));

        \Notification::send((new SearchFoundRenter())->delay());
        $item = User::query()->where('phone', '0907309666')->first();
        Functions::syncCrm($item);
        dd();

        $items = FindSession::all();
        foreach ($items as $item) {
            $properties = $item->properties;
            if (isset($properties['min_price'])) {
                $item->min_price = $properties['min_price'];
            }
            if (isset($properties['max_price'])) {
                $item->max_price = $properties['max_price'];
            }
            if (isset($properties['province_id'])) {
                $item->province_id = $properties['province_id'];
            }
            if (isset($properties['type'])) {
                $item->type = $properties['type'];
            }
            if (isset($properties['district_id'])) {
                $item->districts()->sync($properties['district_id']);
            }
            $item->save();
        }
        dd();

        $user = User::query()->where('phone', '0868987355')->first();
        event(new AuthLoginLog($user, request()));
        dd();

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

        $hostels = Hostel::query()->where('owner_id', $owner->id)->get();

        $moneyInfos = MoneyInfo::query()
            ->whereIn('hostel_id', $hostels->pluck('id')->toArray())
            ->whereIn('type', [MoneyInfo::VOUCHER_ROOM_PRICE, MoneyInfo::VOUCHER_CONTRACT])
            ->get();

        foreach ($moneyInfos as $moneyInfo) {
            $detail = $moneyInfo->details->first();
            if ($detail->qty == 1) {
                if ($detail->sum_amount == $detail->value - 1) {
                    $detail->sum_amount = $detail->value;
                    $detail->save();
                }
            }
        }

        dd();

        $from = Carbon::createFromFormat('d/m/Y', '01/03/2020');
        $to = Carbon::createFromFormat('d/m/Y', '31/03/2020');
        dd(Functions::checkFullPeriod($from, $to, 31));

        $moneyInfos = MoneyInfo::query()
            ->where('discount', '>', 0)
            ->get();
        foreach ($moneyInfos as $moneyInfo) {
            if ($moneyInfo->remain != $moneyInfo->amount - $moneyInfo->pay - $moneyInfo->discount) {
                $moneyInfo->remain = $moneyInfo->amount - $moneyInfo->pay - $moneyInfo->discount;
                $moneyInfo->save();
            }
        }
        dd();

        $items = \DB::connection('crm')->table('tblleads')
            ->where('dateadded', '>=', Carbon::createFromFormat('d/m/Y', '01/04/2020')->startOfDay()->toDateTimeString())
            ->get();
        foreach ($items as $item) {
            $phone = $item->phonenumber;
            $user = User::query()->where('phone', $phone)->where('type', User::OWNER)->first();
            if ($user) {
                if ($user->created_at->month != 4 && $user->created_at->year == 2020) {
                    \DB::connection('crm')->table('tblleads')
                        ->where('id', $item->id)
                        ->delete();
                }
            }
        }
        dd();

        $item = User::find(21490);
        Functions::syncCrm($item);
        dd();

        $cnt = \DB::connection('crm')->table('tblleads')
            ->where('phonenumber', null)
            ->count();
        dd($cnt);
        $users = User::query()->where('is_partner_logo', true)
            ->has('logoExist')
            ->with('logoExist')
            ->where('type', User::OWNER)
            ->get();
        dd($users->pluck('logoExist'));
//$user = User::query()->where('phone', '0868987355')->first();
//		$token = app('auth.password.broker')->createToken($user);
//		dd($token);


        \Mail::send('frontend3.mail.survey', [], function ($message) {
            $message->from('phongnn@meboo.vn', 'iTro.vn');
            $message->subject('TẶNG NGAY 50K KHI CHỦ TRỌ THAM GIA CHƯƠNG TRÌNH "KHẢO SÁT Ý KIẾN KHÁCH HÀNG VỀ DỊCH VỤ TÌM KHÁCH THUÊ TRÊN ỨNG DỤNG ITRO"');
            $message->to([
                //'lelinh280296@gmail.com',
                'huynt57@gmail.com'
            ]);
        });

        dd();


        User::query()->where('type', User::OWNER)->update([
            'number_interacts' => 5
        ]);
        dd();
        $hostel = Hostel::find(8100);
        dd(Functions::getNumberRoomsHostel($hostel));


        $pusher = \PusherService::getClient();
        $conversationId = 1;
        $channelConversationName = 'presence-read-conversation-v2-' . $conversationId;
        $usersChannelConversation = $pusher->get('/channels/' . $channelConversationName . '/users');
        $userOnlineConversationArr = [];
        if (isset($usersChannelConversation['result'])) {
            if (isset($usersChannelConversation['result']['users'])) {
                foreach ($usersChannelConversation['result']['users'] as $item2) {
                    $userIdOnlineConversation = $item2['id'];
                    $userOnlineConversationArr[] = $userIdOnlineConversation;
                }
            }
        }
        dd($userOnlineConversationArr);


        $channelName = 'presence-online-status-v2';
        $usersChannel = $pusher->get('/channels/' . $channelName . '/users');

        $userOnlineArr = [];
        if (isset($usersChannel['result'])) {
            if (isset($usersChannel['result']['users'])) {
                foreach ($usersChannel['result']['users'] as $item) {
                    $userIdOnline = $item['id'];
                    $userOnlineArr[] = $userIdOnline;
                }
            }
        }
        dd($userOnlineArr);
        dd($data = \OpenGraph::fetch("https://youtube.com", true));

        $cvs = \App\Models_v2\Conversation::query()
            ->get();

        foreach ($cvs as $cv) {
            $message = optional($cv->messages->last())->created_at;
            $cv->date_message = $message;
            $cv->save();
        }

        dd();

        $from = Carbon::createFromFormat('Y-m-d', '2019-12-16');
        $to = Carbon::createFromFormat('Y-m-d', '2020-03-15');
        $dayCollect = 15;
        $period = 3;
        $cost = 3500000;
        $collectToCarbon = Carbon::createFromFormat('Y-m-d', '2020-03-15');
        $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
        dd(round($money / ($cost), 2));
        dd();
        dd();

        StatisticLog::query()->whereNotNull('collect_spend_id')
            ->get();

        $owners = User::query()
            ->where('type', User::OWNER)
            ->get();
        foreach ($owners as $owner) {
            TypeSpend::create([
                'owner_id' => $owner->id,
                'name' => 'Tiền cọc',
                'is_default' => TypeSpend::TIEN_COC
            ]);
            $this->line($owner->id);
        }

        dd();


        $items = CollectSpend::query()
            ->where('type', CollectSpend::COLLECT)
            ->get();

        foreach ($items as $item) {
            $moneyInfo = $item->moneyInfo;
            if ($moneyInfo) {
                if ($item->hostel) {
                    $type = null;
                    if (in_array($moneyInfo->type, [
                        MoneyInfo::VOUCHER_ROOM_PRICE,
                        MoneyInfo::VOUCHER_CONTRACT
                    ])) {
                        $type = TypeCollect::query()
                            ->where('type', TypeCollect::ROOM_PRICE)
                            ->where('owner_id', $item->hostel->owner_id)
                            ->first();

                    } else if ($moneyInfo->type == MoneyInfo::VOUCHER_DEPOSIT) {
                        $type = TypeCollect::query()
                            ->where('type', TypeCollect::DEPOSIT)
                            ->where('owner_id', $item->hostel->owner_id)
                            ->first();
                    } else if ($moneyInfo->type == MoneyInfo::VOUCHER_SERVICE) {
                        $type = TypeCollect::query()
                            ->where('type', TypeCollect::SERVICE)
                            ->where('owner_id', $item->hostel->owner_id)
                            ->first();
                    }

                    if (!empty($type)) {
                        $item->type_collect_id = $type->id;
                        $item->save();
                    }
                }
            } else {
                if ($item->hostel) {
                    if ($item->is_deposit == true) {
                        $type = TypeCollect::query()
                            ->where('type', TypeCollect::DEPOSIT)
                            ->where('owner_id', $item->hostel->owner_id)
                            ->first();
                        if (!empty($type)) {
                            $item->type_collect_id = $type->id;
                            $item->save();
                        }
                    }
                }
            }
            $this->line($item->id);
        }

        dd();

        TypeCollect::query()
            ->where('can_delete', false)
            ->forceDelete();

        $owners = User::query()
            ->where('type', User::OWNER)
            ->get();
        foreach ($owners as $owner) {
            TypeCollect::create([
                'owner_id' => $owner->id,
                'name' => 'Tiền nhà',
                'can_delete' => false,
                'type' => TypeCollect::ROOM_PRICE
            ]);
            TypeCollect::create([
                'owner_id' => $owner->id,
                'name' => 'Tiền cọc',
                'can_delete' => false,
                'type' => TypeCollect::DEPOSIT
            ]);
            TypeCollect::create([
                'owner_id' => $owner->id,
                'name' => 'Tiền dịch vụ',
                'can_delete' => false,
                'type' => TypeCollect::SERVICE
            ]);
            $this->line($owner->id);
        }

        dd();
        //dd(ord(1));
        $hostel = Hostel::find(8378);
        $conversations = Conversation::query()
            ->where('hostel_id', $hostel->id)
            ->get();
        dd($conversations->pluck('id')->toArray());
        $messages = Message::query()
            ->whereIn('conversation_id', $conversations->pluck('id')->toArray())
            ->delete();
        dd();
        //dd($messages->count());

        $items = StatisticLog::query()->with('room')->get();
        foreach ($items as $item) {
//			if($item->hostel)
//			{
//				$item->hostel_name = $item->hostel->name;
//			}

            if ($item->room) {
                if (is_numeric($item->room->name)) {
                    $item->order = $item->room->name;
                } else {
                    $item->order = ord($item->room->name);

                }

            } else {
                $item->order = 9999;
            }

            $item->save();
            $this->line('done with ' . $item->id);
        }

        dd();

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

        $hostels = Hostel::query()
            ->where('owner_id', $owner->id)
            ->get();

        $moneyInfos = MoneyInfo::query()
            ->whereIn('type', [MoneyInfo::VOUCHER_ROOM_PRICE, MoneyInfo::VOUCHER_CONTRACT])
            ->with('details')
            ->whereIn('hostel_id', $hostels->pluck('id')->toArray())
            ->get();


        foreach ($moneyInfos as $moneyInfo) {

            $detail = $moneyInfo->details->first();

            $endDate = Carbon::createFromFormat('Y-m-d', $detail->end_date);
            $checkDate = Carbon::createFromFormat('d/m/Y', '01/01/2020');
            if ($endDate->copy()->greaterThan($checkDate->copy()->endOfMonth()->endOfDay())) {
                continue;
            }

            $moneyInfo->remain = 0;
            $moneyInfo->pay = $moneyInfo->amount - $moneyInfo->discount;
            $moneyInfo->save();

            $moneyInfoId = $moneyInfo->id;
            $hostelId = $moneyInfo->hostel_id;
            $dateAction = Carbon::now()->toDateString();
            $userId = $owner->id;
            $amount = $moneyInfo->amount - $moneyInfo->discount;
            $payer = null;
            $roomId = $moneyInfo->room_id;
            $paymentMethod = CollectSpend::BANK;

            $check = Transaction::query()
                ->where('money_info_id', $moneyInfo->id)
                ->count();

            if ($check > 0) {
                continue;
            }

            $transaction = Transaction::create([
                'amount' => $amount,
                'hostel_id' => $hostelId,
                'date_action' => $dateAction,
                'user_id' => $userId,
                'money_info_id' => $moneyInfoId,
                'type' => CollectSpend::COLLECT,
                'payer' => $payer
            ]);

            $collectSpend = CollectSpend::create([
                'amount' => $amount,
                'hostel_id' => $hostelId,
                'room_id' => $roomId,
                'payment_method' => $paymentMethod,
                'date_action' => $dateAction,
                'user_id' => $userId,
                'money_info_id' => $moneyInfoId,
                'type' => CollectSpend::COLLECT,
                'transaction_id' => $transaction->id,
                'payer' => $payer
            ]);


            $this->line('Done ' . $moneyInfo->id);
        }

        dd();


        $leads = \DB::connection('crm')->table('tblleads')
            ->get();

        foreach ($leads as $lead) {
            $phoneNumber = $lead->phonenumber;
            $user = User::query()
                ->where('phone', $phoneNumber)
                ->first();
            if ($user) {
                if ($user->type != User::OWNER) {
                    $this->line($phoneNumber);
                    $this->line($user->type);
                    \DB::connection('crm')->table('tblleads')->where('id', $lead->id)->delete();
                }
            }
        }

        dd();

//		$from = Carbon::createFromFormat('d/m/Y', '01/03/2020');
//		$to = Carbon::createFromFormat('d/m/Y', '29/03/2020');
//		$dayCollect = 31;
//		$c = Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect);
//
//		dd($c);
//		$from            = Carbon::createFromFormat( 'd/m/Y', '03/02/2020' );
//		$to              = Carbon::createFromFormat( 'd/m/Y', '02/03/2020' );
//		$dayCollect      = 2;
//		$cost            = 5000000;
//		$collectToCarbon = Carbon::createFromFormat( 'd/m/Y', '29/02/2020' );
//		$period          = 1;
//		$money           = Functions::calculateMoneyInRange2( $from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon );
//		dd( $money );

        $moneyDetails = MoneyDetail::query()
            ->whereHas('moneyInfo', function ($q) {
                $q->whereIn('type', [
                    MoneyInfo::VOUCHER_CONTRACT,
                    MoneyInfo::VOUCHER_ROOM_PRICE
                ]);
            })
            ->whereNotNull('start_date')
            ->whereNotNull('end_date')
            ->orderBy('id', 'desc')
            ->get();
        foreach ($moneyDetails as $moneyDetail) {
            $moneyInfo = $moneyDetail->moneyInfo;
            $contract = $moneyInfo->contract;
            $startDate = Carbon::createFromFormat('Y-m-d', $moneyDetail->start_date);
            $endDate = Carbon::createFromFormat('Y-m-d', $moneyDetail->end_date);
            if (empty($contract->collect_to)) {
                continue;
            }

            if (Functions::checkFullPeriod($startDate->copy(), $endDate->copy(), $contract->day_collect)) {
                $dateCollect = Carbon::createFromFormat('Y-m-d', $contract->collect_to);

                if ($dateCollect->greaterThan($startDate->copy()) && $dateCollect->lessThan($endDate->copy())) {
                    dump($startDate->copy()->format('d/m/Y'));
                    dump($dateCollect->copy()->format('d/m/Y'));
                    dump($endDate->copy()->format('d/m/Y'));
                    dump($moneyInfo->id);
                    dump($moneyInfo->amount);
                    dump($moneyInfo->pay);
                    dump($moneyInfo->remain);
                    dump(Functions::calculateMoneyInRange2($startDate->copy(), $endDate->copy(), $contract->day_collect, $contract->period, $contract->room_price, $dateCollect->copy()));
                    dump('-------');
                }
            }

        }

        dd();


        $item = User::query()->where('phone', '0968648895')->first();
        Functions::syncCrm($item);
        $item = User::query()->where('phone', '0963225108')->first();
        Functions::syncCrm($item);
        dd();

        dd(\DB::connection('crm')->table('tblleads')
            ->where('phonenumber', '0968648895')
            ->count());

        $fromE = Carbon::createFromFormat('d/m/Y H:i', '02/02/2020 13:16');
        $toE = Carbon::createFromFormat('d/m/Y H:i', '02/02/2020 13:16');


        $moneyInfoEs = MoneyInfo::query()
            ->whereBetween('updated_at', [
                $fromE->copy()->startOfMinute()->toDateTimeString(),
                $toE->copy()->endOfMinute()->toDateTimeString()
            ])
            ->get();
        foreach ($moneyInfoEs as $money_info_e) {
            $id = $money_info_e->id;
            $real = \DB::connection('data2')
                ->table('money_infos')
                ->where('id', $id)
                ->first();
            $amount = $real->amount;
            $money_info_e->amount = $amount;
            $money_info_e->remain = $real->remain;
            $money_info_e->save();

            $moneyDetail = MoneyDetail::query()
                ->where('money_info_id', $money_info_e->id)
                ->first();
            $realMoneyDetail = \DB::connection('data2')
                ->table('money_details')
                ->where('money_info_id', $id)
                ->first();
            $moneyDetail->value = $realMoneyDetail->value;
            $moneyDetail->sum_amount = $realMoneyDetail->sum_amount;
            $moneyDetail->save();

            $this->line('E-' . $money_info_e->id);
        }

        $phone = '0984549489';
        $owner = User::query()
            ->where('phone', $phone)
            ->where('type', User::OWNER)
            ->first();
        $hostels = Hostel::query()->where('owner_id', $owner->id)->pluck('id')->toArray();

        $moneyInfos = MoneyInfo::query()
            ->where('type', MoneyInfo::VOUCHER_ROOM_PRICE)
            ->whereIn('hostel_id', $hostels)
            ->whereBetween('date_action', [
                Carbon::now()->startOfMonth()->startOfDay()->toDateString(),
                Carbon::now()->endOfMonth()->endOfDay()->toDateString()
            ])
            ->get();
        foreach ($moneyInfos as $moneyInfo) {
            $amount = $moneyInfo->contract->room_price;
            $moneyInfo->amount = $amount;
            $moneyInfo->remain = $amount - $moneyInfo->pay;
            $moneyInfo->save();

            $moneyDetail = MoneyDetail::query()
                ->where('money_info_id', $moneyInfo->id)
                ->first();
            $moneyDetail->value = $amount;
            $moneyDetail->sum_amount = $amount;
            $moneyDetail->save();

            $this->line($moneyInfo->id);

        }
        dd();


        $from = Carbon::createFromFormat('Y-m-d', '2020-02-04');
        $to = Carbon::createFromFormat('Y-m-d', '2020-02-21');
        dd(Functions::checkFullPeriod($from->copy(), $to->copy(), 21));
        //dd(Functions::calculateMoneyInRange3($from->copy(), $to->copy(), 1100000, 21));
        $cost = 1100000;
        $diffDays = $to->copy()->diffInDays($from->copy());
        $numberDays = 30;
        $money = intval($cost / ($numberDays) * ($diffDays + 1));
        dd($money);

        Category::fixTree();
        dd();
        $from = Carbon::createFromFormat('Y-m-d', '2019-12-18');
        $to = Carbon::createFromFormat('Y-m-d', '2020-02-29');
        $dayCollect = 31;
        $cost = 7000000;
        dd(Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect));
        dd(Functions::calculateMoneyInRange3($from->copy(), $to->copy(), $cost, $dayCollect));

        $items = MoneyInfo::query()
            ->where('amount', 0)
            ->where('pay', 0)
            ->whereIn('type', [MoneyInfo::VOUCHER_ROOM_PRICE, MoneyInfo::VOUCHER_CONTRACT])
            ->latest('id')
            ->get();

        foreach ($items as $item) {
            $moneyDetail = MoneyDetail::query()
                ->where('money_info_id', $item->id)
                ->first();
            if ($moneyDetail) {
                $qty = $moneyDetail->qty;
                $contract = $item->contract;
                if ($contract) {
                    $roomPrice = $contract->room_price;
                    if (!empty($roomPrice)) {
                        $amount = $roomPrice * $qty;
                        $item->amount = $amount;
                        $item->save();
                        $moneyDetail->amount = $amount;
                        $moneyDetail->sum_amount = $amount;
                        $moneyDetail->save();
                    }
                }
            }
        }

        dd();
        $items = StatisticLog::query()->whereNull('collect_spend_id')->get();
        foreach ($items as $item) {
            //Thu tiền đặt cọc HĐ: HD813505102019
            if (str_contains($item->note, 'Thu tiền đặt cọc HĐ')) {

                $code = str_replace('Thu tiền đặt cọc HĐ: ', '', $item->note);
                $code = trim($code);
                $contract = Contract::query()->where('code', $code)->first();
                if ($contract) {
                    $cp = CollectSpend::query()->where('contract_id', $contract->id)
                        ->where('is_deposit', true)
                        ->where('type', CollectSpend::COLLECT)
                        ->where('name', 'LIKE', '%Thu tiền đặt cọc%')
                        ->first();
                    if ($cp) {
                        $item->collect_spend_id = $cp->id;
                        $item->save();
                    }
                }

            }
        }
        dd();

        $from2 = Carbon::createFromFormat('d/m/Y', '12/01/2020');
        $to3 = Carbon::createFromFormat('d/m/Y', '11/04/2020');
        dd(Functions::calculateMoneyInRange2($from2->copy(), $to3->copy(), 11, 3, 3000000, null));

        $month = Carbon::createFromFormat('d/m/Y', '01/12/2019');
        $moneyInfos = MoneyInfo::query()->where('hostel_id', 7697)
            ->where('remain', '<', 0)
            ->whereBetween('date_action', [
                $month->copy()->startOfMonth()->startOfDay(),
                $month->copy()->endOfMonth()->endOfDay()
            ])
            ->get();
        foreach ($moneyInfos as $money_info) {
            $money_info->remain = $money_info->amount;
            $money_info->pay = 0;

            $money_info->save();
            CollectSpend::query()->where('money_info_id', $money_info->id)->delete();
            Transaction::query()->where('money_info_id', $money_info->id)->delete();
        }
        dd();

        $phone = '0963561687';

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

        $hostels = Hostel::query()
            ->where('owner_id', $owner->id)
            ->get();

        $moneyInfos = MoneyInfo::query()->whereIn('hostel_id', $hostels->pluck('id')->toArray())
            ->where('remain', '<', 0)
            ->get();
        foreach ($moneyInfos as $moneyInfo) {
            $moneyInfo->pay = $moneyInfo->amount;
            $moneyInfo->remain = 0;
            $moneyInfo->save();
            CollectSpend::query()
                ->where('money_info_id', $moneyInfo->id)
                ->update([
                    'amount' => $moneyInfo->amount
                ]);

            Transaction::query()
                ->where('money_info_id', $moneyInfo->id)
                ->update([
                    'amount' => $moneyInfo->amount
                ]);
        }


        dd();
        $phone = '0961787686';

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

        $hostels = Hostel::query()
            ->where('owner_id', $owner->id)
            ->get();

        $collectSpends = CollectSpend::query()
            ->whereIn('hostel_id', $hostels->pluck('id')->toArray())
            ->where('name', 'LIKE', '%Trả lại tiền phòng từ%')
            ->get();
        foreach ($collectSpends as $collectSpend) {
            $name = $collectSpend->name;
            $name = str_replace('Trả lại tiền phòng từ', '', $name);
            $name = str_replace('đến', '', $name);
            $name = str_replace(', HĐ:', '', $name);
            $name = trim($name);
            $name = explode(' ', $name);
            $dateAction = Carbon::createFromFormat('d/m/Y', $name[0]);
            $realDate = $dateAction->copy()->startOfDay()->subDay();

            if (!$realDate->copy()->equalTo($collectSpend->date_action)) {
                $collectSpend->date_action = $realDate->copy();
                $collectSpend->save();
            }
        }
        dd();

        $items = Hostel::query()
            ->whereNotNull('owner_id')
            ->orderBy('id', 'desc')
            ->get();
        foreach ($items as $item) {
            $owner = User::query()->find($item->owner_id);
            if (!$owner) {
                continue;
            }

            if ($owner->type == User::STAFF) {
                $item->owner_id = $owner->staff_owner_id;
                $item->save();
            }
            $this->line('Done with ' . $item->id);
        }

        dd();

//		$from            = Carbon::createFromFormat( 'Y-m-d', '2019-11-01' );
//		$to              = Carbon::createFromFormat( 'Y-m-d', '2019-11-30' );
//		$dayCollect      = 31;
//		$cost            = 3500000;
//		$collectToCarbon = Carbon::createFromFormat( 'Y-m-d', '2019-11-30' );
//		$money           = Functions::calculateMoneyInRange2( $from->copy(), $to->copy(), $dayCollect, 1, $cost, $collectToCarbon );
//		dd( $money );
        $startDate = Carbon::now()->subDay(100)->startOfDay();
        $endDate = Carbon::now()->endOfDay();
        //dd(MoneyInfo::find(106009)->toArray());

        $moneyInfos = MoneyInfo::query()
            ->where('type', MoneyInfo::VOUCHER_CONTRACT)
            ->where('remain', 0)
            ->whereBetween('created_at', [
                $startDate->copy()->toDateTimeString(),
                $endDate->copy()->toDateTimeString()
            ])
            ->get();

        foreach ($moneyInfos as $moneyInfo) {
            $detail = MoneyDetail::query()->where('money_info_id', $moneyInfo->id)->first();
            $startDate = Carbon::createFromFormat('Y-m-d', $detail->start_date);
            $endDate = Carbon::createFromFormat('Y-m-d', $detail->end_date);
            $contract = $moneyInfo->contract;
            $dayCollect = $contract->day_collect;
            if (Functions::checkFullPeriod($startDate->copy(), $endDate->copy(), $dayCollect)) {
                if ($moneyInfo->remain == 0) {
                    $detail->amount = $moneyInfo->amount;
                    $detail->sum_amount = $moneyInfo->amount;
                    $detail->save();

                    CollectSpend::query()
                        ->where('money_info_id', $moneyInfo->id)
                        ->update([
                            'amount' => $moneyInfo->amount
                        ]);

                    Transaction::query()
                        ->where('money_info_id', $moneyInfo->id)
                        ->update([
                            'amount' => $moneyInfo->amount
                        ]);

                }
            }
            $this->line('Done: ' . $moneyInfo->id);

        }
        dd();

        $moneyInfoIds = [
            104978,
            105071,
            105128,
            105235,
            105333,
            105362,
            105522,
            105595,
            105611,
            105627,
            105656,
        ];


        $moneyInfoIds = $moneyInfos->pluck('id')->toArray();
        foreach ($moneyInfos as $moneyInfo) {
            $moneyInfo->pay = $moneyInfo->amount;
            $moneyInfo->remain = 0;
            $moneyInfo->save();
        }

        $moneyDetails = MoneyDetail::query()
            ->whereIn('money_info_id', $moneyInfoIds)
            ->get();

        foreach ($moneyDetails as $moneyDetail) {
            $moneyDetail->amount = $moneyDetail->moneyInfo->amount;
            $moneyDetail->sum_amount = $moneyDetail->moneyInfo->amount;
            $moneyDetail->save();
        }
        dd();

        //	dd(MoneyInfo::find(104978)->toArray());

        dd($moneyInfos->pluck('id')->toArray());


//		$from       = Carbon::createFromFormat( 'Y-m-d', '2019-10-31' );
//		$to         = Carbon::createFromFormat( 'Y-m-d', '2019-11-30' );
//		$dayCollect = 30;
//		$cost       = 3700000;
//		$sumMoney   = Functions::calculateMoneyInRange3( $from->copy(), $to->copy(), $cost, $dayCollect );
//		dd( $sumMoney );


        $ownerId = 17020;
        $hostels = Hostel::query()
            ->where('owner_id', $ownerId)
            ->get();

        $moneyInfos = MoneyInfo::query()
            ->where('type', MoneyInfo::VOUCHER_SERVICE)
            ->whereIn('hostel_id', $hostels->pluck('id')->toArray())
            ->get();
        foreach ($moneyInfos as $moneyInfo) {
            //	$moneyInfo = MoneyInfo::find( 102183 );
            $details = MoneyDetail::query()->where('money_info_id', $moneyInfo->id)->get();
            $full = $moneyInfo->amount;
            foreach ($details as $detail) {

                $qty = null;
                $hostelFee = HostelFee::find($detail->hostel_fee_id);

                if ($detail->is_electric == 1) {

                    if (empty($qty)) {
                        $ew = ElectricWater::query()->where('room_id', $detail->room_id)->first();
                        if ($ew) {
                            $start = $ew->start_electric;
                            $end = $ew->end_electric;
                            $detail->qty = json_encode([
                                'start' => $start,
                                'end' => $end
                            ]);
                            $detail->save();
                        }
                    } else {
                        $qty = json_decode($detail->qty, true);
                        $start = $qty['start'];
                        $end = $qty['end'];
                    }
                    $amount = ($end - $start) * 4000;
                    $full -= $amount;
                    $detail->amount = $amount;
                    $detail->save();
                } else if (str_contains($hostelFee->name, 'dịch vụ')) {
                    $qty = 1;
                    $amount = $qty * $detail->value;
                    $full -= $amount;
                    $detail->qty = $qty;
                    $detail->amount = $amount;
                    $detail->save();
                } else if (str_contains($hostelFee->name, 'xe')) {
                    $qty = $full / $detail->value;
                    $amount = $full;
                    $detail->qty = $qty;
                    $detail->amount = $amount;
                    $detail->save();
                }


            }
        }
        dd();

        foreach ($moneyInfos as $moneyInfo) {

        }
        foreach ($hostels as $hostel) {
            $rooms = Room::query()->where('hostel_id', $hostel->id)->get();
            foreach ($rooms as $room) {
                $moneyDetails = MoneyDetail::query()->where('room_id', $room->id)->get();

                foreach ($moneyDetails as $moneyDetail) {


                    $startDate = null;
                    $endDate = null;
                    if (!empty($moneyDetail->start_date)) {
                        $startDate = Carbon::createFromFormat('Y-m-d', $moneyDetail->start_date);
                    }
                    if (!empty($moneyDetail->end_date)) {
                        $endDate = Carbon::createFromFormat('Y-m-d', $moneyDetail->end_date);
                    }
                    $moneyInfo = $moneyDetail->moneyInfo;
                    if (!$moneyInfo) {
                        continue;
                    }
                    $contract = $moneyInfo->contract;

                    if (!$contract) {
                        continue;
                    }


                    if (!empty($startDate) && !empty($endDate)) {
                        if (!empty($contract->collect_to)) {
                            $collectTo = Carbon::createFromFormat('Y-m-d', $contract->collect_to);
                            if ($collectTo->greaterThanOrEqualTo($endDate) || $collectTo->lessThanOrEqualTo($startDate)) {
                                if (in_array($moneyInfo->type, [
                                    MoneyInfo::VOUCHER_CONTRACT,
                                    MoneyInfo::VOUCHER_ROOM_PRICE
                                ])) {
                                    if ($moneyDetail->qty != ($moneyDetail->sum_amount / $moneyDetail->value)) {

                                        if ($moneyInfo->remain != 0) {
                                            $moneyDetail->qty = ($moneyDetail->sum_amount / $moneyDetail->value);
                                            $moneyDetail->save();
                                        }

                                    }
                                }
                            }
                            if ($collectTo->greaterThanOrEqualTo($endDate)) {
                                if (in_array($moneyInfo->type, [
                                    MoneyInfo::VOUCHER_CONTRACT,
                                    MoneyInfo::VOUCHER_ROOM_PRICE
                                ])) {
                                    $moneyDetail->amount = $moneyDetail->sum_amount;
                                    if ($moneyDetail->qty != ($moneyDetail->sum_amount / $moneyDetail->value)) {
                                        $moneyDetail->qty = ($moneyDetail->sum_amount / $moneyDetail->value);
                                    }
                                    $moneyDetail->save();
                                }

                                if ($moneyDetail->amount != $moneyDetail->sum_amount) {
                                    if ($moneyInfo->remain != 0) {
                                        if (in_array($moneyInfo->type, [
                                            MoneyInfo::VOUCHER_CONTRACT,
                                            MoneyInfo::VOUCHER_ROOM_PRICE
                                        ])) {
                                            $moneyInfo->pay = $moneyInfo->amount;
                                            $moneyInfo->remain = 0;
                                            $moneyInfo->save();

                                            Transaction::query()->where('money_info_id', $moneyInfo->id)->update([
                                                'amount' => $moneyInfo->amount
                                            ]);

                                            CollectSpend::query()->where('money_info_id', $moneyInfo->id)->update([
                                                'collect' => $moneyInfo->amount
                                            ]);
                                        }
                                    }
                                }
                            } else {
                                if (in_array($moneyInfo->type, [
                                    MoneyInfo::VOUCHER_CONTRACT,
                                    MoneyInfo::VOUCHER_ROOM_PRICE
                                ])) {
                                    $moneyDetail->amount = $moneyDetail->sum_amount;
                                    if ($moneyDetail->qty != ($moneyDetail->sum_amount / $moneyDetail->value)) {
                                        $moneyDetail->qty = ($moneyDetail->sum_amount / $moneyDetail->value);
                                    }
                                    $moneyDetail->save();
                                }
                                $amount = Functions::calculateMoneyInRange2($startDate->copy(), $endDate->copy(), $contract->day_collect, $contract->period, $contract->room_price, $collectTo);
                                if ($amount != $moneyDetail->amount) {
                                    if (in_array($moneyInfo->type, [
                                        MoneyInfo::VOUCHER_CONTRACT,
                                        MoneyInfo::VOUCHER_ROOM_PRICE
                                    ])) {
                                        $moneyDetail->amount = $amount;

                                        if ($moneyDetail->qty != ($moneyDetail->sum_amount / $moneyDetail->value)) {
                                            $moneyDetail->qty = ($moneyDetail->sum_amount / $moneyDetail->value);
                                        }

                                        $moneyDetail->save();


                                        $moneyInfo->pay = $amount;
                                        $moneyInfo->remain = $moneyInfo->amount - $amount;
                                        $moneyInfo->save();

                                        Transaction::query()->where('money_info_id', $moneyInfo->id)->update([
                                            'amount' => $amount
                                        ]);

                                        CollectSpend::query()->where('money_info_id', $moneyInfo->id)->update([
                                            'collect' => $amount
                                        ]);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        dd();


        $rooms = Room::query()->get();
        $bar = $this->output->createProgressBar($rooms->count());
        foreach ($rooms as $room) {

            $checkDeleted = \DB::table('collect_spends')
                ->where('room_id', $room->id)
                ->first();

            $checkDeletedAll = \DB::table('collect_spends')
                ->where('room_id', $room->id)
                ->whereNull('deleted_at')
                ->count();
            if ($checkDeletedAll == 0) {
                if ($checkDeleted) {
                    if (!empty($checkDeleted->deleted_at)) {

                        if ($room->updated_at == '2019-12-04 16:39:47') {
                            $this->line($room->id);
                            $room->update([
                                'deleted_at' => $checkDeleted->deleted_at
                            ]);
                        }
                    }
                }
            }
            $bar->advance();

        }
        $bar->finish();
        dd();


        $from = Carbon::createFromFormat('d/m/Y', '01/10/2019');
        $period = 3;
        $dayCollect = 31;
        if ($period > 1) {
            $month = $from->copy()->firstOfMonth()->addMonth($period - 1)->month;
            $year = $from->copy()->firstOfMonth()->addMonth($period - 1)->year;
            if ($dayCollect <= $from->copy()->day) {
                $month = $from->copy()->firstOfMonth()->addMonth($period)->month;
                $year = $from->copy()->firstOfMonth()->addMonth($period)->year;
            }
        } else {
            $month = $from->copy()->month;
            $year = $from->copy()->year;
            if ($dayCollect <= $from->copy()->day) {
                $month = $from->copy()->firstOfMonth()->addMonth()->month;
                $year = $from->copy()->firstOfMonth()->addMonth()->year;
            }
        }

        $isValid = true;
        if (checkdate($month, $dayCollect, $year)) {
            $to = Carbon::createFromFormat('d-m-Y', $dayCollect . '-' . $month . '-' . $year);
        } else {
            $isValid = false;
            $tempDayCollect = Carbon::createFromFormat('d-m-Y', '01-' . $month . '-' . $year)->lastOfMonth()->day;
            $to = Carbon::createFromFormat('d-m-Y', $tempDayCollect . '-' . $month . '-' . $year);
        }
        $collectToCarbon = Carbon::createFromFormat('Y-m-d', '2019-12-31');
        $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, 23000000, $collectToCarbon);
        dd($from->copy()->toDateString(), $to->copy()->toDateString());

        $room = Room::withTrashed()->find(12314);
        $room->restore();
        RenterRoom::where('room_id', $room->id)->withTrashed()->restore();
        //	Renter::where( 'room_id', $room->id )->withTrashed()->restore();
        Contract::where('room_id', $room->id)->withTrashed()->restore();
        MoneyInfo::where('room_id', $room->id)->withTrashed()->restore();
        CollectSpend::where('room_id', $room->id)->withTrashed()->restore();
        Transaction::where('room_id', $room->id)->withTrashed()->restore();
        Statistic::where('room_id', $room->id)->withTrashed()->restore();
        StatisticLog::where('room_id', $room->id)->withTrashed()->restore();
        dd();


//		if (!Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect)) {
//
//			$sumMoney = Functions::calculateMoneyInRange3($from->copy(), $to->copy(), $cost, $dayCollect);
//		}
        dd('ehheee');

        $pusher = \PusherService::getClient();


        //  dd($pusher->trigger('test', 'new-messge', 'huy'));
        $channelName = 'service-chat-298';
        //    $channelName = 'presence-read-conversation-' . 115;
        $res = $pusher->trigger($channelName, 'new-message', 'hello');
        dd($res);


        $item = MoneyDetail::find(109975);
        $moneyInfoId = $item->money_info_id;
        $moneyInfo = MoneyInfo::find($moneyInfoId);
        $contract = $moneyInfo->contract;
        $startDate = $item->start_date;
        $endDate = $item->end_date;
        $startDateCarbon = Carbon::createFromFormat('Y-m-d', $startDate);
        $endDateCarbon = Carbon::createFromFormat('Y-m-d', $endDate);
        $dayCollect = $contract->day_collect;
        $cost = $contract->room_price;
        $items = Functions::statFromMoneyInfo($startDateCarbon->copy(), $endDateCarbon->copy(), $cost, $dayCollect, $contract->period);
        dd($items);

        $rooms = Room::withTrashed()
            ->where('hostel_id', 7027)
            ->get();
        try {
            foreach ($rooms as $room) {

                $room->restore();
                RenterRoom::where('room_id', $room->id)->withTrashed()->restore();
                Renter::where('room_id', $room->id)->withTrashed()->restore();
                Contract::where('room_id', $room->id)->withTrashed()->restore();
                MoneyInfo::where('room_id', $room->id)->withTrashed()->restore();
                CollectSpend::where('room_id', $room->id)->withTrashed()->restore();
                Transaction::where('room_id', $room->id)->withTrashed()->restore();
                Statistic::where('room_id', $room->id)->withTrashed()->restore();
                StatisticLog::where('room_id', $room->id)->withTrashed()->restore();
            }
        } catch (\Exception $exception) {
            dd($exception->getTraceAsString());
        }

        dd();

        dispatch_now(new SendMessageBot('Xin chào, đây là tin nhắn test từ huy', 14797, 6336));
        dd();
        $items = MoneyDetail::query()->with('hostelFee')->get();
        foreach ($items as $item) {
            $hostelFee = $item->hostelFee;
            if ($hostelFee) {
                if (in_array($hostelFee->type, [
                    HostelFee::ELECTRIC,
                    HostelFee::ELECTRIC_BY_CLOCK,
                    HostelFee::ELECTRIC_BY_PEOPLE,
                    HostelFee::ELECTRIC_DYNAMIC
                ])) {
                    $item->is_electric = true;
                } else if (in_array($hostelFee->type, [
                    HostelFee::WATER,
                    HostelFee::WATER_BY_CLOCK,
                    HostelFee::WATER_BY_PEOPLE,
                    HostelFee::WATER_DYNAMIC
                ])) {
                    $item->is_water = true;
                }
                $item->save();
            }
        }

        dd();


        $firstArr = collect([1, 2, 3, 4]);
        $secondArr = collect([5, 6, 7]);
        dd($firstArr->merge($secondArr));


        $cps = CollectSpend::all();
        foreach ($cps as $cp) {
            $contract = RoomReservation::find($cp->reserve_id);
            if ($contract) {
                if (empty($contract->user_id)) {
                    $contract->user_id = $cp->user_id;
                    $contract->save();
                }
            }
        }

        dd();

        $item = CollectSpend::query()->where('money_info_id', 88613)->first();
        if (!$item->is_deposit) {
            dd(1);
        } else {
            dd(0);
        }
        dd(MoneyInfo::query()->first()->date_action);
        dd(MoneyInfo::query()->count());


        $rooms = Room::all();
        foreach ($rooms as $room) {
            $roomContract = RenterRoom::query()->where('room_id', $room->id)
                ->whereNotNull('contract_id')
                ->first();

            RenterRoom::query()->where('room_id', $room->id)
                ->whereNull('room_contract_id')
                ->update([
                    'room_contract_id' => optional($roomContract)->contract_id
                ]);
        }

        dd();

        $moneyInfos = MoneyInfo::query()->where('type', MoneyInfo::VOUCHER_CONTRACT)
            ->get();
        foreach ($moneyInfos as $moneyInfo) {
            $cnt = MoneyDetail::query()->where('money_info_id', $moneyInfo->id)
                ->count();
            if ($cnt != 1) {
                continue;
            }

            $item = MoneyDetail::query()->where('money_info_id', $moneyInfo->id)->first();
            if (!$item) {
                continue;
            }

            if ($item->sum_amount == $moneyInfo->amount) {
                continue;
            }

            $item->sum_amount = $moneyInfo->amount;
            $item->save();
        }

        dd();


        $items = MoneyInfo::whereNull('money_info_name')->get();
        foreach ($items as $item) {
            if (!in_array($item->type, [MoneyInfo::VOUCHER_CONTRACT, MoneyInfo::VOUCHER_ROOM_PRICE])) {
                if ($item->date_action) {
                    $name = 'Thu tiền dịch vụ tháng ' . $item->date_action->format('m/Y');
                } else {
                    $name = 'Thu tiền dịch vụ';
                }
                $item->money_info_name = $name;
                $item->save();
            }
        }

        dd();
        $phone = '0909848454';
        $owner = User::where('phone', $phone)
            ->where('type', User::OWNER)
            ->first();
        $hostelArr = Hostel::where('owner_id', $owner->id)->pluck('id')->toArray();
        $eight = Carbon::createFromFormat('d/m/Y', '01/08/2019');

        $moneyInfos = MoneyInfo::whereIn('hostel_id', $hostelArr)
            ->where('date_action', '>=', $eight->startOfMonth())
            ->whereIn('type', [MoneyInfo::VOUCHER_CONTRACT, MoneyInfo::VOUCHER_ROOM_PRICE])
            ->get();

        Transaction::whereIn('money_info_id', $moneyInfos->pluck('id')->toArray())->delete();
        CollectSpend::whereIn('money_info_id', $moneyInfos->pluck('id')->toArray())->delete();

        foreach ($moneyInfos as $moneyInfo) {
            $moneyInfo->remain = $moneyInfo->amount;
            $moneyInfo->pay = 0;
            $moneyInfo->save();
        }
        dd();

        dd(\App\Components\Functions::calculateAmountForOrder(66933));


        $eight = Carbon::createFromFormat('d/m/Y', '01/08/2019');
        $seven = Carbon::createFromFormat('d/m/Y', '01/07/2019');
        $moneyInfos = MoneyInfo::whereIn('hostel_id', $hostelArr)
            ->whereNotBetween('date_action', [
                $eight->copy()->startOfMonth(),
                $eight->copy()->endOfMonth()
            ])
            ->whereIn('type', [MoneyInfo::VOUCHER_CONTRACT, MoneyInfo::VOUCHER_ROOM_PRICE])
            ->get();

        Transaction::whereIn('money_info_id', $moneyInfos->pluck('id')->toArray())->delete();
        CollectSpend::whereIn('money_info_id', $moneyInfos->pluck('id')->toArray())->delete();

        foreach ($moneyInfos as $moneyInfo) {
            $moneyInfo->remain = $moneyInfo->amount;
            $moneyInfo->pay = 0;
            $moneyInfo->save();
        }


        $moneyInfos = MoneyInfo::whereIn('hostel_id', $hostelArr)
            ->where('date_action', '<', $eight->copy()->startOfMonth())
            ->whereIn('type', [MoneyInfo::VOUCHER_CONTRACT, MoneyInfo::VOUCHER_ROOM_PRICE])
            ->get();


        $moneyInfos2 = MoneyInfo::whereIn('hostel_id', $hostelArr)
            ->whereNotBetween('date_action', [
                $seven->copy()->startOfMonth(),
                $seven->copy()->endOfMonth()
            ])
            ->whereIn('type', [MoneyInfo::VOUCHER_SERVICE])
            ->get();

        Transaction::whereIn('money_info_id', $moneyInfos2->pluck('id')->toArray())->delete();
        CollectSpend::whereIn('money_info_id', $moneyInfos2->pluck('id')->toArray())->delete();

        foreach ($moneyInfos2 as $moneyInfo2) {
            $moneyInfo2->remain = $moneyInfo2->amount;
            $moneyInfo2->pay = 0;
            $moneyInfo2->save();
        }

        $moneyInfos = $moneyInfos->merge($moneyInfos2);

        $bar = $this->output->createProgressBar($moneyInfos->count());

        foreach ($moneyInfos as $moneyInfo) {
            $bar->advance();
            $amount = $moneyInfo->remain;
            $hostelId = $moneyInfo->hostel_id;
            $dateAction = Carbon::now()->subDay()->toDateString();
            $userId = $owner->id;
            $moneyInfoId = $moneyInfo->id;
            $roomId = $moneyInfo->room_id;
            $payer = optional($moneyInfo->contract)->name;
            $transaction = Transaction::create([
                'amount' => $amount,
                'hostel_id' => $hostelId,
                'date_action' => $dateAction,
                'user_id' => $userId,
                'money_info_id' => $moneyInfoId,
                'type' => CollectSpend::COLLECT,
                'payer' => $payer
            ]);

            CollectSpend::create([
                'amount' => $amount,
                'hostel_id' => $hostelId,
                'room_id' => $roomId,
                'payment_method' => CollectSpend::MONEY,
                'date_action' => $dateAction,
                'user_id' => $userId,
                'money_info_id' => $moneyInfoId,
                'type' => CollectSpend::COLLECT,
                'transaction_id' => $transaction->id,
                'payer' => $payer
            ]);

            $remain = $moneyInfo->remain - $amount;
            $moneyInfo->pay = $moneyInfo->pay + $amount;
            $moneyInfo->remain = $remain;
            $moneyInfo->save();
        }

        $bar->finish();
        dd();


        $id = 11499;
        $room = Room::withTrashed()->find($id);


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

        dd();

//        $startDate = '2019-06-18';
//        $endDate = '2019-06-19';
//        $startDateCarbon = Carbon::createFromFormat('Y-m-d', $startDate);
//        $endDateCarbon = Carbon::createFromFormat('Y-m-d', $endDate);
//        $dayCollect = 19;
//        $cost = 2200000;
//        $items = Functions::statFromMoneyInfo($startDateCarbon->copy(), $endDateCarbon->copy(), $cost, $dayCollect);
//
//        dd($items);
        $app_id = config('constants.PUSHER_APP_ID');
        $app_key = config('constants.PUSHER_APP_KEY');
        $app_secret = config('constants.PUSHER_APP_SECRET');
        $app_cluster = config('constants.PUSHER_APP_CLUSTER');
        $host = config('constants.PUSHER_HOST');
        $port = config('constants.PUSHER_PORT');
        $pusher = new Pusher($app_key,
            $app_secret,
            $app_id,
            ['cluster' => $app_cluster, 'debug' => true, 'scheme' => 'https'],
            $host,
            $port);

        $pusher = \PusherService::getClient();

        //  dd($pusher->trigger('test', 'new-messge', 'huy'));
        $channelName = 'service-chat-298';
        //    $channelName = 'presence-read-conversation-' . 115;
        $res = $pusher->trigger($channelName, 'new-message', 'hello');
        dd($res);


        $startDateCarbon = Carbon::createFromFormat('d/m/Y', '07/07/2019');
        $endDateCarbon = Carbon::createFromFormat('d/m/Y', '07/07/2020');
        $cost = 500;
        $dayCollect = 7;

        $items = Functions::statFromMoneyInfo($startDateCarbon->copy(), $endDateCarbon->copy(), $cost, $dayCollect);

        dd($items);

        $items = StatisticLog::all();
        foreach ($items as $item) {
            if (!empty($item->collect_spend_id)) {
                if (empty($item->collectSpend)) {
                    $item->delete();
                }
            }
        }
        dd();

        $user = User::where('phone', '0937280391')->first();
        $user->assignRole('owner');
        dd();

        dd($hostels);


        $items = Room::all();
        foreach ($items as $item) {
            $this->updateRoomPrice($item);
        }

        dd();

        $owners = User::where('type', User::OWNER)->get();
        foreach ($owners as $user) {
            $type_spend_default = [
                [
                    'owner_id' => $user->id,
                    'name' => 'Tiền Nhà',
                    'is_default' => TypeSpend::TIEN_NHA,
                ],
                [
                    'owner_id' => $user->id,
                    'name' => 'Tiền Điện',
                    'is_default' => TypeSpend::TIEN_DIEN,
                ],
                [
                    'owner_id' => $user->id,
                    'name' => 'Tiền Nước',
                    'is_default' => TypeSpend::TIEN_NUOC,
                ]

            ];
            TypeSpend::insert($type_spend_default);
        }
        dd();

        dd(\Hash::make('123456'));
//        dd(Functions::getNumberRoomsHostel(Hostel::find(7005)));
        $items = Hostel::all();
        foreach ($items as $item) {
            Functions::updateHostelEmptyRooms($item->id);
        }
        dd();
        dd(cache()->get('spatie.permission.cache'));
        $items = StatisticLog::whereNotNull('collect_spend_id')->get();
        foreach ($items as $item) {
            $item->owner_id = !empty($item->collectSpend) ? $item->collectSpend->owner_id : null;
            $item->save();
        }
        dd();

        $range = round(1000000 / (1000000), 2);
        dd($range);
        $from = Carbon::createFromFormat('d/m/Y', '2/5/2019');
        $to = Carbon::createFromFormat('d/m/Y', '01/06/2019');
        $period = 1;
        $dayCollect = 1;
        $cost = 1000000;
        $collectToCarbon = Carbon::createFromFormat('d/m/Y', '01/06/2019');
        $diffDays = $to->copy()->diffInDays($from->copy());
        $numberDays = 30;
        $money = intval($cost / ($numberDays) * ($diffDays + 1));

        if ($collectToCarbon->equalTo($to->copy())) {
            dd($sumMoney = Functions::calculateMoneyInRange3($from->copy(), $to->copy(), $cost, $dayCollect));
        }
        $money = Functions::calculateMoneyInRange2($from->copy(), $to->copy(), $dayCollect, $period, $cost, $collectToCarbon);
        dd($money);
        dd(empty(""));


        $owner = User::where('phone', '0906358899')->first();
        if ($owner) {
            $hostelArrs = Hostel::where('owner_id', $owner->id)->pluck('id')->toArray();

        }

        dispatch(new SendNotificationMessage(1, 'Test'));
        dd();


        $from = Carbon::createFromFormat('Y-m-d', '2019-01-04');
        $to = Carbon::createFromFormat('Y-m-d', '2019-02-28');
        $res = Functions::statFromMoneyInfo($from, $to, 3000000, 31, 1);
        dd($res);
        \DB::table('statistics')->truncate();

        $type = Statistic::ROOM_PRICE;
        $moneyInfos = MoneyInfo::whereIn('type', [
            MoneyInfo::VOUCHER_CONTRACT,
            MoneyInfo::VOUCHER_ROOM_PRICE
        ])->get();
        $bar = $this->output->createProgressBar($moneyInfos->count());
        foreach ($moneyInfos as $moneyInfo) {
            $bar->advance();
            if ($moneyInfo) {
                $collectSpendItem = CollectSpend::where('money_info_id', $moneyInfo->id)->first();
                if (in_array($moneyInfo->type, [MoneyInfo::VOUCHER_CONTRACT, MoneyInfo::VOUCHER_ROOM_PRICE])) {
                    $moneyDetails = MoneyDetail::where('money_info_id', $moneyInfo->id)->get();
                    foreach ($moneyDetails as $item) {
                        $startDate = $item->start_date;
                        $endDate = $item->end_date;
                        if (!empty($startDate) && !empty($endDate)) {

                            $from = Carbon::createFromFormat('Y-m-d', $startDate);
                            $to = Carbon::createFromFormat('Y-m-d', $endDate);
                            $contract = $moneyInfo->contract;
                            if ($contract) {
                                $cost = $contract->room_price;
                                $dayCollect = $contract->day_collect;
                                $period = $contract->period;
                                $moneys = Functions::statFromMoneyInfo($from, $to, $cost, $dayCollect, $period);
                                foreach ($moneys as $money) {

                                    Statistic::create([
                                        'money_info_id' => $moneyInfo->id,
                                        'money_info_code' => $moneyInfo->name,
                                        'collect_spend_id' => !empty($collectSpendItem) ? $collectSpendItem->id : null,
                                        'collect_spend_code' => !empty($collectSpendItem) ? $collectSpendItem->code : null,
                                        'type_collect_spend' => !empty($collectSpendItem) ? $collectSpendItem->type : CollectSpend::COLLECT,
                                        'amount' => $money['money'],
                                        'type' => $type,
                                        'hostel_id' => $moneyInfo->hostel_id,
                                        'room_id' => $moneyInfo->room_id,
                                        'owner_id' => !empty($moneyInfo->hostel) ? $moneyInfo->hostel->owner_id : null,
                                        'start_date' => $money['from'],
                                        'end_date' => $money['to'],
                                        'date_action' => $money['from'],
                                        'month' => $money['month'],
                                        'year' => $money['year']
                                    ]);
                                }

                            }

                        }
                    }
                }
            }
        }
        $bar->finish();


        dd();

        $moneyDetails = MoneyDetail::where('sum_amount', '>', 0)->get();
        foreach ($moneyDetails as $money_detail) {
            $money_detail->qty = round($money_detail->sum_amount / $money_detail->value, 2);
            $money_detail->save();
        }

        dd();


        dd(htmlspecialchars('%'));

        $owner = User::where('phone', '0784784333')
            ->where('type', User::OWNER)
            ->first();
        $hostels = Hostel::where('owner_id', $owner->id)->pluck('id')->toArray();
        $rooms = Room::whereIn('hostel_id', $hostels)
            ->onlyTrashed()
            ->pluck('name')
            ->toArray();
        dd($rooms);


//        $name = uniqid().'-'.$item->id.'.pdf';
//
//        $pdf = \PDF::loadHtml($html->render());
//
//        $pdf->save(public_path('hoa-don/'.$name));
//        dd();
//
//    	$phpWord = new PhpWord();
//	    $section = $phpWord->addSection();
//    	$html = view('html')->render();
//    	Html::addHtml($section, $html);
//	    $objectWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
//	    $objectWriter->save(public_path('html.docx'));
//
//    	dd();

        $first = Carbon::createFromFormat('Y-m-d', '2019-1-10');
        $second = Carbon::createFromFormat('Y-m-d', '2019-2-5');
        dd($first->diffInDays($second));
        $collectTo = Carbon::createFromFormat('Y-m-d', '2019-4-30');
        dd(Functions::calculateMoneyInRange2($first, $second, 10, 2, 1000000, $collectTo));

        $hostels = Hostel::where('owner_id', 6875)->where('name', 'LIKE', '%25/17/8%')->get();

        foreach ($hostels as $hostel) {
            $rooms = Room::where('hostel_id', $hostel->id)->get();
            foreach ($rooms as $room) {
                $moneyInfos = MoneyInfo::where('room_id', $room->id)->get();
                foreach ($moneyInfos as $moneyInfo) {
                    $moneyInfo->date_action = $moneyInfo->created_at;
                    $moneyInfo->save();
                }
                $this->line('done ' . $room->name . '-' . $room->id);
            }

        }

        dd();

        $items = Conversation::all();

        foreach ($items as $item) {
            Functions::updateMemberName($item->id);
        }
        dd();

        $items = Contract::all();
        foreach ($items as $item) {
            if (empty($item->hostel)) {
                dump($item->id);
                $item->delete();
            }

            if (empty($item->room)) {
                dump($item->id);
                $item->delete();
            }
        }
        dd();

        $items = CollectSpend::all();
        foreach ($items as $item) {
            if ($item->contract) {
                if ($item->contract->is_return_deposit == true) {
                    $item->is_return_deposit = true;
                    $item->save();
                }
            }
        }

        dd();
        $items = Warehouse::all();
        foreach ($items as $item) {
            $cnt = \DB::table('item_warehouses')
                ->join('item_types', 'item_warehouses.item_type_id', '=', 'item_types.id')
                ->where('warehouse_id', $item->id)
                ->sum(\DB::raw('`item_warehouses`.`amount`'));
            $item->remain = $cnt;
            $item->save();
        }
        dd();


        $contractId = 2399;
        $contract = Contract::find(2399);
        $dateEnableCarbon = $contract->date_enable;
        //  $dateEnableCarbon = Carbon::createFromFormat('Y-m-d', $dateEnable);

        $endDate = Carbon::createFromFormat('Y-m-d', '2019-7-15');
        while ($dateEnableCarbon->lessThan($endDate)) {
            $dateEnableCarbon = $dateEnableCarbon->startOfMonth();
            $dateEnableCarbon2 = clone $dateEnableCarbon;
//            $check = ElectricWater::where('contract_id', $contractId)
//                ->whereBetween('date_action', [$dateEnableCarbon2->toDateString(), $dateEnableCarbon2->endOfMonth()->toDateString()])->count();
            $check = 1;
            dump($dateEnableCarbon2->toDateString(), $dateEnableCarbon2->endOfMonth()->toDateString());
            if ($check == 0) {
                $status = 0;
                break;
            }
            $dateEnableCarbon = $dateEnableCarbon->startOfMonth()->addMonth(1);
        }

        dd();


        $clientId = env('GOOGLE_CONTACT_CLIENT');
        $clientSecret = env('GOOGLE_CONTACT_SECRET');
        $refreshToken = env('GOOGLE_CONTACT_REFRESH_TOKEN');
        $scopes = [
            'https://www.googleapis.com/auth/userinfo.profile',
            'https://www.googleapis.com/auth/contacts',
            'https://www.googleapis.com/auth/contacts.readonly'
        ];
        $googleOAuth2Handler = new GoogleOAuth2Handler($clientId, $clientSecret, $scopes, $refreshToken);

        $people = new GooglePeople($googleOAuth2Handler);

        $items = User::where('type', User::OWNER)->get();

        foreach ($items as $item) {
            $contact = new Contact($people);
            // $contact->emailAddresses[0] = new \stdClass();

            $contact->names[0]['displayName'] = $item->name_text;
            $contact->phoneNumbers[0]['value'] = $item->phone;
            $contact->emailAddresses[0]['value'] = $item->email;
            $contact->emailAddresses[0]['displayName'] = $item->name_text;
            $contact->save();
        }

        dd();

//       $contacts = $people->all();
//       dd($contacts);


        $i = \Newsletter::isSubscribed('phongnn57+10@gmail.com');
        dd($i);
        $items = User::where('type', User::OWNER)->pluck('email')->toArray();
        dd(count($items));
        foreach ($items as $item) {
            if (filter_var($item, FILTER_VALIDATE_EMAIL)) {
                \Newsletter::subscribe($item);
            }
        }
        dd();

        $hostels = Hostel::where('owner_id', 7395)->pluck('id')->toArray();
        $cntRoom = Room::whereIn('hostel_id', $hostels)->count();

        $userPackage = UserPackage::where('user_id', 7395)->first();
        $numberRoom = 0;
        if ($userPackage) {

            $numberRoom = $userPackage->number_rooms;
        }

        dd($numberRoom);
        \DB::table('hostels')->update([
            'status_confirm' => 1
        ]);
        $hostels = Hostel::where('owner_id', 7711)->get();
        foreach ($hostels as $hostel) {
            $hostel->status_confirm = Hostel::NOT_CONFIRM;
            $hostel->save();
        }
        dd();
        $items = HostelFee::all();
        foreach ($items as $item) {
            if ($item->type == HostelFee::ELECTRIC) {
                ElectricQuota::where('hostel_id', $item->hostel_id)
                    ->update([
                        'fee_id' => $item->id
                    ]);
            }

            if ($item->type == HostelFee::WATER) {
                WaterQuota::where('hostel_id', $item->hostel_id)
                    ->update([
                        'fee_id' => $item->id
                    ]);
            }
        }
        dd();


        $items = Amenity::all();
        foreach ($items as $item) {

            $name = stripcslashes($item->name);
            $name = preg_replace('/^(\'(.*)\'|"(.*)")$/', '$2$3', $name);
            $item->name = $name;
            $item->save();
        }
        dd();
        $items = Hostel::all();
        foreach ($items as $hostel) {
            $prices = Functions::getPriceHostelFrontend3($hostel);

            if (!empty($prices)) {
                $smallest = $prices['smallest'];
                $greatest = $prices['greatest'];
                $hostel->smallest_price = $smallest;
                $hostel->greatest_price = $greatest;
                $hostel->save();

//            $hostel->
            }
        }

        dd();


        \Newsletter::subscribe('hungtmvt12@gmail.com');
        dd();
        //$apis = \Newsletter::isSubscribed('huynt57@gmail.com');
        //    $apis = \Newsletter::getApi();

        $html = view('layouts.app')->render();
        $return = \Newsletter::createCampaign('iTro.vn', 'contact@itro.vn', 'Test đăng ký bản tin', $html);
        $id = $return['id'];
        $api = \Newsletter::getApi();
        $api->post('campaigns/' . $id . '/actions/send');
        dd();


        dd($return);
        $items = Order::all();
        foreach ($items as $item) {
            if ($item->status == Order::PROCESSED) {
                $item->payment_type = 1;
                $item->save();
            }
        }

        dd();
        $items = ImportExport::all();

        foreach ($items as $item) {
            $itemTypeId = $item->item_type_id;
            $itemType = ItemType::find($itemTypeId);
            if ($itemType) {
                $item->item_type_name = $itemType->name;
                $item->save();
            }

            $itemId = $item->item_id;
            $itemModel = Item::find($itemId);
            if ($itemModel) {
                if (empty($item->item_type_name)) {
                    $itemTypeId = $itemModel->item_type_id;
                    $itemType = ItemType::find($itemTypeId);
                    if ($itemType) {
                        $item->item_type_name = $itemType->name;
                        $item->save();
                    }
                }
            }
        }

        dd();
        $items = \DB::table('import_export_table')->get();
        foreach ($items as $item) {
            $importExportId = $item->import_export_id;
            $ie = ImportExport::find($importExportId);
            if ($ie) {
                $ie->item_type_id = $item->item_type_id;
                $ie->save();
            }
        }
        dd();
        dd(Functions::getFacebookFromToken('EMAWdwie0995DphG90OflFgzN3oI7AJAopWT4e0Owsy8OOojDGYCJemkAUZBW88eVhAxGZCrJYTQbGlN7NUjTRkMC91SrWAJS07Th9elCAZDZD'));

        $f = Carbon::createFromFormat('Y-m-d', '2018-10-31');
        dd($f->addMonth(1));

//        $item = RoomNeedMore::find(14);
//
//        dd($item->image);
//
//        \Image::make('https://itro.vn/random/pic13.jpg')->encode('webp')->save(public_path('pic13.webp'));
//        dd(1);
//        $permissions = Permission::all()->pluck('name')->toArray();
//        $user = User::find(7261);
//        $user->syncPermissions($permissions);
//        dd();
        //
//        $items = Contract::all();
//
//        foreach ($items as $item)
//        {
//            $code = $item->code;
//
//            $cs = CollectSpend::where('name', 'LIKE', '%'.$code.'%')
//                ->orWhere('note', 'LIKE', '%'.$code.'%')->first();
//
//            if($cs)
//            {
//                $cs->contract_id = $item->id;
//                $cs->save();
//                $this->line($cs->id);
//            }
//        }
//
//        dd();

        //7204
//        $u = User::create([
//            'name' => 'Hệ thống itro',
//            'image' => '/frontend3/assets/img/placeholder.png',
//            'type' => User::SYSTEM
//        ]);
//
//        dd($u->id);


//        dispatch(new SendMessageBot( 'Test đọc bot 22232', 6336));
//        dd();

//        dispatch(new SendVoucherOwner('123', 'phongnn57@gmail.com'));
        //  dd();

//        \Spatie\Permission\Models\Permission::create([
//            'name' => 'edit-spend'
//        ]);
//
//        \Spatie\Permission\Models\Permission::create([
//            'name' => 'delete-spend'
//        ]);
//
//        \Spatie\Permission\Models\Permission::create([
//            'name' => 'edit-collect'
//        ]);
//
//        \Spatie\Permission\Models\Permission::create([
//            'name' => 'delete-collect'
//        ]);
//
//
//        \Spatie\Permission\Models\Permission::create([
//            'name' => 'edit-voucher'
//        ]);
//
//        \Spatie\Permission\Models\Permission::create([
//            'name' => 'delete-voucher'
//        ]);

//	    $rooms = Room::where( 'hostel_id', 5303 )->groupBy( 'block_group' )->pluck( 'block_group' )->toArray();
//
//	    dd($rooms);


        $userOnlineArr = [];
        if (isset($usersChannel['result'])) {
            if (isset($usersChannel['result']['users'])) {
                foreach ($usersChannel['result']['users'] as $item) {
                    $userIdOnline = $item['id'];
                    $userOnlineArr[] = $userIdOnline;
                }
            }
        }
        dd($userOnlineArr);
        // dd($pusher->get( 'test', 'new-message', 'hello poxa' ));
        //dd($pusher->get_channel_info('test'));
        //dd($pusher->get('presence-online-status', array('info' => 'user_count')));
        User::where('name', 'Đang cập nhật')->delete();
        $hostels = Hostel::where('source', 1)->get();
        foreach ($hostels as $hostel) {
            Room::where('hostel_id', $hostel->id)->delete();
            $hostel->delete();
        }
        \Excel::load(public_path('ntsv.xlsx'), function ($reader) {

            // reader methods

            $items = [];

            $data = $reader->all();

            foreach ($data as $item) {
                foreach ($reader->toArray() as $key => $value) {


                    \DB::beginTransaction();

                    try {
                        $check = Hostel::where('name', $value['subject'])->count();

                        if ($check == 0) {

                            $owner = User::create([
                                'name' => 'Đang cập nhật',
                                'phone' => $value['phone'],
                                'password' => bcrypt('itro@2018'),
                                'address' => $value['address'],
                            ]);

                            $item = [
                                'name' => $value['subject'],
                                'lat' => $value['lat'],
                                'lng' => $value['lng'],
                                'address' => $value['address'],
                                'phone' => $value['phone'],
                                'desc' => $value['description'],
                                'owner_id' => $owner->id,
                                'source' => 1
                            ];


                            $hostel = Hostel::create($item);

                            $roomType = RoomType::create([
                                'name' => 'Phòng loại 1',
                                'price' => intval($value['price'] * 1000),
                                'max_peoples' => empty($data['max_people']) ? 0 : $data['max_people'],
                                'owner_id' => $owner->id,
                                'hostel_id' => $hostel->id
                            ]);
                            Room::create([
                                'hostel_id' => $hostel->id,
                                'lat' => $value['lat'],
                                'lng' => $value['lng'],
                                'name' => 'P101',
                                'size' => intval($value['area']),
                                'price' => intval($value['price'] * 1000),
                                'type' => $roomType->id
                            ]);

                            $this->line('Done with ' . $hostel->id);
                        }
                        \DB::commit();
                    } catch (\Exception $exception) {
                        \DB::rollBack();
                        dd($exception->getMessage());
                    }
                }

            }

//            foreach ($data as $item) {
//                $dataAccountInfo[] = [
//                    'phone' => $item->sdt,
//                    'name' => $item->ho_ten,
//                    'email' => $item->email,
//                    'address' => $item->dia_chi,
//                    'bank_number' => $item->so_tk_nganhang,
//                    'company_store' => $item->congty_cuahang,
//                    'tax_code' => $item->ms_thue,
//                    'type_text' => config('constants.NHOM_2'),
//                ];
//            }

        });

    }
}
