<?php

namespace App\Http\Controllers\Backend2;

use App\Components\Functions;
use App\Events\LogAction;
use App\Http\Controllers\Backend\AdminController;
use App\Jobs\CreateRoomConservation;
use App\Jobs\CreateRoomConservationV2;
use App\Jobs\DeleteRenterConversation;
use App\Jobs\DeleteRoomConversation;
use App\Models\Amenity;
use App\Models\BreakHistory;
use App\Models\CollectSpend;
use App\Models\Contract;
use App\Models\ContractFee;
use App\Models\ElectricWater;
use App\Models\Hostel;
use App\Models\HostelFee;
use App\Models\HostelSchedule;
use App\Models\ImportExport;
use App\Models\ImportExportItem;
use App\Models\Item;
use App\Models\ItemType;
use App\Models\MoneyDetail;
use App\Models\MoneyInfo;
use App\Models\Notification;
use App\Models\Renter;
use App\Models\RenterBike;
use App\Models\RenterRoom;
use App\Models\ReportBreak;
use App\Models\Room;
use App\Models\RoomBed;
use App\Models\RoomReservation;
use App\Models\RoomType;
use App\Models\Statistic;
use App\Models\StatisticLog;
use App\Models\StatisticMonth;
use App\Models\Transaction;
use App\Models\UserPackage;
use App\Models\Warehouse;
use App\Notifications\ExtendContract;
use App\User;
use Carbon\Carbon;
use Dompdf\Exception;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use League\Fractal\Pagination\PagerfantaPaginatorAdapter;
use phpDocumentor\Reflection\DocBlock\Description;
use PhpParser\Node\Stmt\Label;
use Yajra\Datatables\Datatables;

class RoomController extends AdminController
{
    //
    public function getList()
    {
        $userId = auth('backend')->user()->id;
        $hostels = Hostel::where('owner_id', $userId)->orderBy('name', 'asc')->get();

        if (auth('backend')->user()->type == User::STAFF) {
            $hostelArrs = Functions::getHostelArrStaff();
            $hostels = Hostel::whereIn('id', $hostelArrs)->orderBy('name', 'asc')->get();
        }

        return view('admin2.room.index', compact('hostels'));
    }


    public function create(Request $request)
    {
        if (auth('backend')->user()->cannot('add-room')) {
            return response([
                'status' => 0,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }

        $hostelId = $request->input('hostel_id');
        $roomTypeBefore = $request->input('room_type');
        $hostel = Hostel::find($hostelId);
        if (!$hostel) {
            return response([
                'status' => 0
            ]);
        }
        $amenities = Amenity::where('type', Amenity::AMENITY)->whereIn('user_id', [
            0,
            auth('backend')->user()->id
        ])->get();
        $roomTypes = RoomType::where('hostel_id', $hostelId)->get();
        if ($roomTypes->count() == 0) {
            return response([
                'status' => 0,
                'message' => 'Bạn cần tạo loại phòng trọ cho nhà trọ của bạn trước khi thêm phòng trọ'
            ]);
        }

        return response([
            'status' => 1,
            'data' => view('admin2.room.create', compact('amenities', 'roomTypes', 'hostelId', 'hostel', 'roomTypeBefore'))->render()
        ]);
    }

    public function createContract(Request $request)
    {
        if (auth('backend')->user()->cannot('add-contract')) {
            return response([
                'status' => 0,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }
        $roomId = $request->input('room_id');
        $reserveId = $request->input('reserve_id');
        $bedId = $request->input('bed_id');
        $room = Room::find($roomId);
        if (!$room) {
            return response([
                'status' => 0,
                'data' => null
            ]);
        }

        $reserve = RoomReservation::find($reserveId);

        if (!$reserve) {
            if ($room->hostel->type_rent == Hostel::TYPE_RENT_ALL) {
                $reserve = RoomReservation::where('room_id', $roomId)->first();
            }
        }

        $hostel = $room->hostel;
        $hostelTypeRent = $hostel->type_rent;

        if ($hostelTypeRent == Hostel::TYPE_RENT_EVERY) {

            $maxRenters = $room->max_renters;

            $numberCurrentRenter = RenterRoom::where('room_id', $roomId)->count();

            if ($numberCurrentRenter == $maxRenters) {
                return response([
                    'status' => 3,
                    'message' => 'Bạn không thể thêm vượt quá số người tối đa'
                ]);
            }

            return response([
                'status' => 1,
                'data' => view('admin2.room.create_contract', compact('roomId', 'room', 'reserve', 'bedId'))->render()
            ]);
        } else {

            $checkContractExist = Contract::query()
                ->has('renter')
                ->where('room_id', $roomId)
                ->where('status', '<>', Contract::LIQUIDATED)
                ->count();
            if ($checkContractExist) {
                //  dd( Contract::where('room_id', $roomId)->where('status', '<>', Contract::LIQUIDATED)->first()->id);
                $checkContractExpireExist = Contract::where('room_id', $roomId)->where('status', '<>', Contract::LIQUIDATED)
                    ->where('end_date', '>', Carbon::now()->toDateString())->count();


                return response([
                    'status' => 2,
                    'message' => 'Bạn cần thanh lý Hợp đồng trước khi tạo mới'
                ]);

            } else {
                return response([
                    'status' => 1,
                    'data' => view('admin2.room.create_contract', compact('roomId', 'room', 'reserve'))->render()
                ]);
            }
        }

    }

    public function detailReserve(Request $request)
    {
        $reserveId = $request->input('reserve_id');
        $reserve = RoomReservation::find($reserveId);
        if (!$reserve) {
            return response([
                'status' => 0,
                'data' => null
            ]);
        }


        return response([
            'status' => 1,
            'data' => view('admin2.room.detail_reserve', compact('reserve'))->render()
        ]);
    }

    public function getRenters($roomId)
    {
        $room = Room::find($roomId);
        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }


        return response([
            'status' => 1,
            'data' => view('admin2.room.renters', compact('room'))->render()
        ]);

    }

    public function updateReserve(Request $request)
    {
        $reserveId = $request->input('reserve_id');
        $reserve = RoomReservation::find($reserveId);
        if (!$reserve) {
            return response([
                'status' => 0,
                'data' => null
            ]);
        }
        $roomId = $reserve->room_id;
        $hostelId = $reserve->hostel_id;
        $data = $request->all();

        if (!empty($data['date_join'])) {
            $data['date_join'] = Carbon::createFromFormat('d/m/Y', $data['date_join'])->toDateString();
        }

        $reserve->update($data);

        if (isset($data['deposit'])) {
            $collectSpend = CollectSpend::query()
                ->where('reserve_id', $reserveId)
                ->first();

            if ($collectSpend) {

                if ($collectSpend->amount != $data['deposit']) {
                    $collectSpend->amount = $data['deposit'];
                    $collectSpend->save();

                    Transaction::query()->where('note', $collectSpend->note)
                        ->update([
                            'amount' => $data['deposit']
                        ]);
                }
            } else {
                if (!empty($data['deposit'])) {
                    $transaction = Transaction::create([
                        'amount' => $data['deposit'],
                        'hostel_id' => $hostelId,
                        'room_id' => $roomId,
                        'date_action' => Carbon::now()->toDateString(),
                        'type' => CollectSpend::COLLECT,
                        'note' => 'Thu tiền đặt cọc giữ chỗ ' . $data['name'] . ', SĐT: ' . $data['phone'],
                        'is_statistic' => false
                    ]);

                    CollectSpend::create([
                        'amount' => $data['deposit'],
                        'hostel_id' => $hostelId,
                        'room_id' => $roomId,
                        'note' => 'Thu tiền đặt cọc giữ chỗ ' . $data['name'] . ', SĐT: ' . $data['phone'],
                        'payment_method' => CollectSpend::MONEY,
                        'date_action' => Carbon::now()->toDateString(),
                        'type' => CollectSpend::COLLECT,
                        //  'note' => 'Thu tiền đặt cọc giữ chỗ ' . $data['name'] . ', SĐT: ' . $data['phone'],
                        'transaction_id' => $transaction->id,
                        'reserve_id' => $reserve->id,
                        'payer' => $data['name'],
                        'is_deposit' => true,
                        'is_statistic' => false
                    ]);
                }
            }
        }


        $user = Functions::getCurrentUser();
        $desc = '{' . optional($user)->name . '} sửa cọc giữ chỗ phòng {' . $reserve->room->name . '} nhà {' . $reserve->room->hostel->name . '} số tiền {' . number_format($reserve->deposit, 0, '.', '.') . '}';
        if ($reserve->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
            $desc = '{' . optional($user)->name . '} sửa cọc giữ chỗ giường {' . optional($reserve->bed)->name . '}phòng {' . $reserve->room->name . '} nhà {' . $reserve->room->hostel->name . '} số tiền {' . number_format($reserve->deposit, 0, '.', '.') . '}';
        }

        event(new LogAction([
            'type' => 'update-reserve',
            'user_id' => optional($user)->id,
            'object_id' => $reserve->id,
            'hostel_id' => $reserve->hostel_id,
            'room_id' => $reserve->room_id,
            'properties' => $reserve->toArray(),
            'desc' => $desc
        ]));

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

    public function deleteReserve(Request $request)
    {
        $reserveId = $request->input('reserve_id');
        $reserve = RoomReservation::find($reserveId);
        $backDeposit = $request->input('back_deposit', 0);
        $backDeposit = Functions::filterInputNumber($backDeposit);
        if (!$reserve) {
            return response([
                'status' => 0,
                'data' => null
            ]);
        }

        if ($backDeposit > 0) {

            $deposit = $reserve->deposit;
            if ($backDeposit > $deposit) {
                return response([
                    'status' => 0,
                    'message' => 'Tiền trả lại không được lớn hơn tiền cọc'
                ]);
            }

            $transaction = Transaction::create([
                'amount' => $backDeposit,
                'hostel_id' => $reserve->hostel_id,
                'room_id' => $reserve->room_id,
                'date_action' => Carbon::now()->toDateString(),
                'type' => CollectSpend::SPEND,
                'note' => 'Trả lại tiền đặt cọc giữ chỗ ' . $reserve->name . ', SĐT: ' . $reserve->phone,
                'is_statistic' => false
            ]);

            CollectSpend::create([
                'amount' => $backDeposit,
                'hostel_id' => $reserve->hostel_id,
                'room_id' => $reserve->room_id,
                'note' => 'Trả lại tiền đặt cọc giữ chỗ ' . $reserve->name . ', SĐT: ' . $reserve->phone,
                'payment_method' => CollectSpend::MONEY,
                'date_action' => Carbon::now()->toDateString(),
                'type' => CollectSpend::SPEND,
                'transaction_id' => $transaction->id,
                'reserve_id' => $reserve->id,
                'receiver' => $reserve->name,
                'is_deposit' => true,
                'is_return_deposit' => true,
                'is_statistic' => false
            ]);

        }

        if ($backDeposit != $reserve->deposit && $backDeposit >= 0) {
            $remainDeposit = $reserve->deposit - $backDeposit;

            if ($remainDeposit > 0) {
                $itemStat = StatisticMonth::create([
                    'month' => Carbon::now()->month,
                    'year' => Carbon::now()->year,
                    'amount' => $remainDeposit,
                    'room_id' => $reserve->room_id,
                    'hostel_id' => $reserve->hostel_id,

                ]);
                StatisticLog::create([
                    'amount' => $remainDeposit,
                    'month' => Carbon::now()->month,
                    'year' => Carbon::now()->year,
                    'type' => CollectSpend::COLLECT,
                    'room_id' => $reserve->room_id,
                    'hostel_id' => $reserve->hostel_id,
                    'statistic_month_id' => $itemStat->id,
                    'note' => 'Tiền còn lại sau khi thanh toán cọc: ' . $reserve->name . ', SĐT: ' . $reserve->phone,
                    'reserve_id' => $reserve->id
                ]);
            }
        } else if (empty($backDeposit)) {
            $itemStat = StatisticMonth::create([
                'month' => Carbon::now()->month,
                'year' => Carbon::now()->year,
                'amount' => $reserve->deposit,
                'room_id' => $reserve->room_id,
                'hostel_id' => $reserve->hostel_id,
            ]);
            StatisticLog::create([
                'amount' => $reserve->deposit,
                'month' => Carbon::now()->month,
                'year' => Carbon::now()->year,
                'type' => CollectSpend::COLLECT,
                'room_id' => $reserve->room_id,
                'hostel_id' => $reserve->hostel_id,
                'statistic_month_id' => $itemStat->id,
                'reserve_id' => $reserve->id,
                'note' => 'Tiền còn lại sau khi thanh toán cọc: ' . $reserve->name . ', SĐT: ' . $reserve->phone,
            ]);
        }


        $reserve->delete();
        $bed = $reserve->bed_id;
        if (!empty($bed)) {
            //change status of bed
            RoomBed::find($bed)->update([
                'status' => RoomBed::AVAILABLE,
            ]);
        }

        $user = Functions::getCurrentUser();
        $desc = '{' . optional($user)->name . '} xóa cọc giữ chỗ phòng {' . $reserve->room->name . '} nhà {' . $reserve->room->hostel->name . '} số tiền {' . number_format($reserve->deposit, 0, '.', '.') . '}';
        if ($reserve->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
            $desc = '{' . optional($user)->name . '} xóa cọc giữ chỗ giường {' . optional($reserve->bed)->name . '}phòng {' . $reserve->room->name . '} nhà {' . $reserve->room->hostel->name . '} số tiền {' . number_format($reserve->deposit, 0, '.', '.') . '}';
        }
        event(new LogAction([
            'type' => 'delete-reserve',
            'user_id' => optional($user)->id,
            'object_id' => $reserve->id,
            'hostel_id' => $reserve->hostel_id,
            'room_id' => $reserve->room_id,
            'properties' => $reserve->toArray(),
            'desc' => $desc
        ]));

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

    public function getEW($roomId, Request $request)
    {
        $startElectric = 0;
        $startWater = 0;
        $room = Room::find($roomId);
        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        $hostel = $room->hostel;

        $lastInfo = ElectricWater::where('room_id', $roomId)->where('room_id', $roomId)->latest()->first();

        if ($lastInfo) {
            $startElectric = $lastInfo->end_electric;
            $startWater = $lastInfo->end_water;
        }

        return response([
            'status' => 1,
            'data' => view('admin2.room.ew', compact('roomId', 'room', 'hostel', 'startWater', 'startElectric'))->render()
        ]);
    }

    public function getInfo($roomId, Request $request)
    {
        $room = Room::find($roomId);
        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        $hostel = $room->hostel;

        return response([
            'status' => 1,
            'data' => view('admin2.room.info', compact('roomId', 'room', 'hostel'))->render()
        ]);
    }

    public function getContracts($roomId, Request $request)
    {
        $contract_id = $request->contract_id;
        $room = Room::find($roomId);
        if (!$room) {
            return response([
                'status' => 0,
                'data' => null
            ]);
        }
        $hostel = $room->hostel;
        $code = $request->input('code');

        if (!empty($contract_id)) {
            $items = Contract::query()
                ->where('id', $contract_id)
                ->has('renterWithTrashed')
                ->get();
        } else {
            $items = Contract::query()
                ->where('room_id', $roomId)
                ->where('status', '<>', Contract::LIQUIDATED)
                ->has('renterWithTrashed')
                ->get();
        }

        return response([
            'status' => 1,
            'data' => view('admin2.room.contracts', compact('items', 'room', 'roomId', 'hostel', 'code', 'contract_id'))->render()
        ]);
    }

    public function getExtendContract(Request $request)
    {
        if (auth('backend')->user()->cannot('extend-contract')) {
            return response([
                'status' => 0,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }
        $contractId = $request->input('contract_id');
        $contract = Contract::find($contractId);

        if (!$contract) {
            return response([
                'status' => 0,
                'data' => null
            ]);
        }

        return response([
            'status' => 1,
            'data' => view('admin2.room.extend_contract', compact('contract'))->render()
        ]);
    }

    public function extendContract(Request $request)
    {
        if (auth('backend')->user()->cannot('extend-contract')) {
            return response([
                'status' => 0,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }

        $endDate = $request->input('end_date');
        $contractId = $request->input('contract_id');
        $contract = Contract::find($contractId);
        if (!$contract) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

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

        try {

            $endDate = Carbon::createFromFormat('d/m/Y', $endDate);
            $endDateContract = $contract->end_date;

            if (!$endDate->greaterThan($endDateContract)) {
                return response([
                    'status' => 0,
                    'message' => 'Ngày gia hạn mới phải lớn hơn ngày gia hạn hiện tại của HĐ'
                ]);
            }

            $endDateStr = $endDate->copy()->toDateString();
            $contract->end_date = $endDateStr;
            $contract->save();
        } catch (\Exception $exception) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $user = auth('backend')->user();
        $owner = auth('backend')->user();
        $ownerMessage = null;
        $renterMessage = 'Hợp đồng của bạn đã được gia hạn đến ngày ' . $endDate->copy()->format('d/m/y');
        if ($user->type == User::STAFF) {
            $owner = $user->owner;
            $ownerMessage = 'Quản lý ' . $user->name . ' vừa gia hạn hợp đồng khách ' . $contract->name . ', phòng ' . $contract->room->name . ' đến ngày ' . $endDate->copy()->format('d/m/Y');
        }
        $renter = RenterRoom::query()->where('contract_id', $contractId)->first();
        if ($renter) {
            \Notification::send($renter->account, new ExtendContract($renterMessage, $contractId));
        }

        if (!empty($ownerMessage)) {
            \Notification::send($owner, new ExtendContract($ownerMessage, $contractId));
        }

        $user = Functions::getCurrentUser();
        $desc = '{' . optional($user)->name . '} đã gia hạn hợp đồng khách {' . $contract->name . '}, phòng {' . $contract->room->name . '} nhà {' . $contract->hostel->name . '}';
        if ($contract->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
            $desc = '{' . optional($user)->name . '} đã gia hạn hợp đồng khách {' . $contract->name . '}, giường {' . $contract->bed->name . '} phòng {' . $contract->room->name . '} nhà {' . $contract->hostel->name . '}';
        }

        event(new LogAction([
            'type' => 'extend-contract',
            'user_id' => optional($user)->id,
            'object_id' => $contract->id,
            'hostel_id' => $contract->hostel_id,
            'room_id' => $contract->room_id,
            'properties' => $contract->toArray(),
            'desc' => $desc
        ]));

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

    public function getFilterEndContracts(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $type = $request->input('type');

        if (empty($hostelId)) {
            if (auth('backend')->user()->type == User::STAFF) {
                $hostelArrs = Functions::getHostelArrStaff();
            } else {
                $hostelArrs = Hostel::where('owner_id', auth('backend')->user()->id)->pluck('id')->toArray();
            }

        } else {
            $hostelArrs[] = $hostelId;
        }

        $items = Contract::whereIn('hostel_id', $hostelArrs)->where('status', '<>', Contract::LIQUIDATED)
            ->whereBetween('end_date', [
                Carbon::now()->toDateString(),
                Carbon::now()->addDay($type)->toDateString()
            ])->get();
        $room = null;
        $roomId = null;
        $hostel = null;

        $title = 'Danh sách hợp đồng hết hạn trong vòng ' . $type . ' ngày';

        return response([
            'status' => 1,
            'data' => view('admin2.room.contract_table', compact('items', 'room', 'roomId', 'hostel'))->render(),
            'title' => $title
        ]);
    }

    public function getFilterReportBreak(Request $request)
    {

        $hostelId = $request->input('hostel_id');
        $status = $request->input('status');

        if (empty($hostelId)) {
            if (auth('backend')->user()->type == User::STAFF) {
                $hostelArrs = Functions::getHostelArrStaff();
            } else {
                $hostelArrs = Hostel::where('owner_id', auth('backend')->user()->id)->pluck('id')->toArray();
            }

        } else {
            $hostelArrs[] = $hostelId;
        }

        $items = ReportBreak::where('status', $status)->whereIn('hostel_id', $hostelArrs)->orderBy('id', 'desc')->get();
        foreach ($items as $item) {
            //image report break
            $imageArr = [];
            $images = \DB::table('report_break_images')
                ->where('report_break_id', $item->id)
                ->get();
            foreach ($images as $image) {
                $imageArr[] = [
                    'id' => $image->id,
                    'image' => '/files/' . $image->image
                ];
            }
            //image report break fixed
            $imageFixedArr = [];
            $imagesFixeds = \DB::table('report_break_images_fixed')
                ->where('report_break_id', $item->id)
                ->get();

            foreach ($imagesFixeds as $imageFixed) {
                $imageFixedArr[] = [
                    'id' => $imageFixed->id,
                    'image' => '/files/' . $imageFixed->image
                ];
            }

            $item->images = $imageArr;
            $item->imagesFixeds = $imageFixedArr;
        }
        $title = 'Danh sách Sự cố';

        return response([
            'status' => 1,
            'data' => view('admin2.room.report_break', compact('items'))->render(),
            'title' => $title
        ]);
    }

    public function getAddReportBreak(Request $request)
    {
        $ownerId = auth('backend')->user()->id;
        $hostelArrs = Hostel::where('owner_id', $ownerId)->get();

        $title = 'Thêm sự cố mới';

        return response([
            'status' => 1,
            'data' => view('admin2.room.add_report_break', compact('hostelArrs', 'rooms'))->render(),
            'title' => $title
        ]);
    }

    public function getRoom(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        if (!empty($hostelId)) {
            $rooms = Room::where('hostel_id', $hostelId)->get();
        }

        return response([
            'status' => 1,
            'data' => $rooms,
        ]);
    }

    public function addReportBreak(Request $request)
    {
        $roomId = $request->input('room_id');
        $hostelId = $request->input('hostel_id');
        $content = $request->input('content');
        $images = $request->file('images');
        $images2 = $request->file('images2');
        $title = $request->input('title');


        $hostel = Hostel::find($hostelId);
        if (!$hostel) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $room = Room::find($roomId);
        $owner = $hostel->owner;
        $user = auth('backend')->user()->id;
        if (!$owner) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $userReportRoomId = null;
        if (auth('backend')->user()->type == User::RENTER) {
            $userReportRenter = RenterRoom::query()
                ->where('user_id', auth('backend')->user()->id)
                ->orderBy('id', 'desc')
                ->first();
            if ($userReportRenter) {
                $userReportRoomId = $userReportRenter->room_id;
            }
        }

        $item = ReportBreak::create([
            'room_id' => $roomId,
            'hostel_id' => $hostel->id,
            'content' => $content,
            'user_report' => $user,
            'title' => $title,
            'user_report_room_id' => $userReportRoomId
        ]);

        $notificationContent = 'Có một sự cố, báo lỗi vừa được khách thuê báo cáo.';

        $payload = json_encode([
            'id' => $item->id,
            'type' => config('constants.REPORT_BREAK')
        ]);
        if (auth('backend')->user()->id != $owner->id) {
            Notification::create([
                'hostel_id' => $hostel->id,
                'room_id' => optional($room)->id,
                'title' => 'Thông báo từ itro.vn',
                'to_user' => $owner->id,
                'content' => $notificationContent,
                'user_id' => $user,
                'payload' => $payload
            ]);
        }


        $staffArrs = \DB::table('staff_hostels')
            ->where('hostel_id', $hostel->id)
            ->pluck('user_id')
            ->toArray();

        foreach ($staffArrs as $staffId) {
            Notification::create([
                'hostel_id' => $hostel->id,
                'room_id' => optional($room)->id,
                'title' => 'Thông báo từ itro.vn',
                'to_user' => $staffId,
                'content' => $notificationContent,
                'user_id' => $user,
                'payload' => $payload
            ]);
        }
        if (!empty($images)) {
            foreach ($images as $image) {

                $imageItem = Functions::uploadImage($image);

                \DB::table('report_break_images')
                    ->insert([
                        'report_break_id' => $item->id,
                        'image' => $imageItem
                    ]);
            }
        }

        return response([
            'status' => 1,
            'message' => 'Success'
        ]);

    }

    public function getEditReportBreak(Request $request)
    {
        $id = $request->input('id');
        $ownerId = auth('backend')->user()->id;
        $hostelArrs = Hostel::where('owner_id', $ownerId)->get();
        $item = ReportBreak::find($id);
        if (!$item) {
            return response([
                'status' => 0,
                'message' => 'dữ liệu không hợp lệ',
            ]);
        }

        $images = \DB::table('report_break_images')
            ->where('report_break_id', $item->id)
            ->get();

        $imagesFixeds = \DB::table('report_break_images_fixed')
            ->where('report_break_id', $item->id)
            ->get();

        $title = 'Cập nhật sự cố';

        return response([
            'status' => 1,
            'data' => view('admin2.room.edit_report_break', compact('item', 'hostelArrs', 'rooms', 'images', 'imagesFixeds'))->render(),
            'title' => $title
        ]);
    }

    public function updateReportBreak(Request $request)
    {
        $id = $request->input('id');
        $status = $request->input('status');
        $images = $request->file('images-fixed');
        $title = $request->input('title');
        $content = $request->input('content');
        $responseContent = $request->input('response_content');
        $imagesDeleted = $request->input('images-deleted');
        $imageAdds = $request->file('images');
        $item = ReportBreak::find($id);

        $user = auth('backend')->user()->id;
        if (!$item) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if (!empty($status)) {
            if ($status < $item->status) {
                return response([
                    'status' => 0,

                    'message' => 'Không thể đổi về trạng thái trước đó'
                ]);
            }
        }
        if (!empty($title)) {
            $item->title = $title;
        }

        if (!empty($content)) {
            $item->content = $content;
        }
        if (!empty($status)) {
            $item->status = $status;
        }

        if (!empty($responseContent)) {
            $item->response_content = $responseContent;
        }


        $hostel = $item->hostel;
        $room = $item->room;
        if ($room) {
            $roomId = $item->room->id;
        } else {
            $roomId = null;
        }

        if (!empty($images)) {

            foreach ($images as $image) {
                $imageItem = Functions::uploadImage($image);
                \DB::table('report_break_images_fixed')
                    ->insert([
                        'report_break_id' => $item->id,
                        'image' => $imageItem
                    ]);
            }

        }

        if (!empty($imageAdds)) {

            foreach ($imageAdds as $imageAdd) {
                $imageItem2 = Functions::uploadImage($imageAdd);
                \DB::table('report_break_images')
                    ->insert([
                        'report_break_id' => $item->id,
                        'image' => $imageItem2
                    ]);
            }

        }

        if (is_array($imagesDeleted)) {
            \DB::table('report_break_images')
                ->whereIn('id', $imagesDeleted)
                ->delete();
        }

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

        if ($status == ReportBreak::PROCESSING) {

            $item->user_take_care = $user;
            $item->processing_date = Carbon::now()->toDateTimeString();
            Notification::create([
                'hostel_id' => $hostel->id,
                'room_id' => $roomId,
                'title' => 'Thông báo từ itro.vn',
                'to_user' => $item->user_report,
                'content' => 'Sự cố đã được tiếp nhận và sẽ xử lý sớm',
                'user_id' => $user,
                'payload' => $payload
            ]);

            if ($user != $hostel->owner->id) {
                Notification::create([
                    'hostel_id' => $hostel->id,
                    'room_id' => $roomId,
                    'title' => 'Thông báo từ itro.vn',
                    'to_user' => $hostel->owner->id,
                    'content' => 'Nhân viên ' . $this->user->name_text . ' đã tiếp nhận và đang xử lý sự cố',
                    'user_id' => $user,
                    'payload' => $payload
                ]);
            }

        }

        if ($status == ReportBreak::PROCESSED) {
            $item->processed_date = Carbon::now()->toDateTimeString();
//            if ($user != $hostel->owner->id) {
//                if ($user != $item->user_take_care && !empty($item->user_take_care)) {
//                    return response([
//                        'status' => 0,
//                        'message' => 'Sự cố này đã có người tiếp nhận, bạn không thể thay đổi trạng thái'
//                    ]);
//                }
//            }

            Notification::create([
                'hostel_id' => $hostel->id,
                'room_id' => $roomId,
                'title' => 'Thông báo từ itro.vn',
                'to_user' => $item->user_report,
                'content' => 'Sự cố mà bạn báo cáo đã được xử lý. Cảm ơn bạn đã đóng góp thông tin',
                'user_id' => $user,
                'payload' => $payload
            ]);

            if ($user != $hostel->owner->id) {
                Notification::create([
                    'hostel_id' => $hostel->id,
                    'room_id' => $roomId,
                    'title' => 'Thông báo từ itro.vn',
                    'to_user' => $hostel->owner->id,
                    'content' => 'Nhân viên ' . $this->user->name_text . ' đã xử lý xong một sự cố',
                    'user_id' => $user,
                    'payload' => $payload
                ]);
            }
        }

        $item->save();

        return response([
            'status' => 1,
            'message' => 'Success'
        ]);


    }

    public function deleteReportBreak(Request $request)
    {
        $id = $request->input('id');
        $item = ReportBreak::find($id);
        if (!$item) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $item->delete();

        return response([
            'status' => 1,
            'message' => 'Success'
        ]);
    }

    public function getFilterContracts(Request $request)
    {
        $status = $request->input('status');
        $code = $request->input('code');
        $startTime = $request->input('start_time');
        $endTime = $request->input('end_time');
        $roomId = $request->input('room_id');
        $contract_id = $request->input('contract_id', null);


        $room = Room::find($roomId);

        if (!$room) {
            return response([
                'status' => 0,
                'data' => null
            ]);
        }

        $hostel = $room->hostel;

        $items = Contract::query()->where('room_id', $roomId)->has('renter');

        if (isset($status)) {
            //dump($status);
            $items = $items->where('status', $status);
        }

        if (!empty($code)) {
            $items = $items->where('code', 'LIKE', '%' . $code . '%');
        }

        if (!empty($startTime)) {
            $startTime = Carbon::createFromFormat('d/m/Y', '01/'.$startTime)->startOfMonth()->toDateString();
            $items = $items->where('start_date', '>=', $startTime);
        }

        if (!empty($endTime)) {
            $endTime = Carbon::createFromFormat('d/m/Y', '01/'.$endTime)->startOfMonth()->toDateString();
            $items = $items->where('end_date', '<=', $endTime);
        }
        if (!empty($contract_id)) {
            $items->where('id', $contract_id);
        }

        $items = $items->get();

        return response([
            'status' => 1,
            'data' => view('admin2.room.contract_fillter', compact('items', 'room', 'roomId', 'hostel', 'code', 'contract_id'))->render()
        ]);
    }

    public function destroy(Request $request)
    {
        $id = $request->input('id');
        $room = Room::find($id);

        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        RenterRoom::where('room_id', $room->id)->delete();
        $hostel = $room->hostel;
        $blockName = $room->block_name;

        Renter::where('room_id', $room->id)->delete();
        Contract::where('room_id', $room->id)->delete();
        MoneyInfo::where('room_id', $room->id)->delete();
        CollectSpend::where('room_id', $room->id)->delete();
        Transaction::where('room_id', $room->id)->delete();
        Statistic::where('room_id', $room->id)->delete();
        StatisticLog::where('room_id', $room->id)->delete();
        ElectricWater::query()->where('room_id', $room->id)->delete();

        if (auth('backend')->check()) {
            $userCreate = auth('backend')->user()->id;
        } else {
            $token = \request()->header('authorization');
            $user = \JWTAuth::parseToken()->toUser();
            $userCreate = $user->id;
        }

        dispatch(new DeleteRoomConversation($room->id, $room->hostel->id, $userCreate, auth('backend')->user()));


        $room->delete();


        return response([
            'status' => 1,
            'message' => 'Thành công',
            'button' => view('admin2.room.button_progress', compact('hostel', 'blockName'))->render()
        ]);
    }


    public function restore(Request $request)
    {
        $id = $request->input('id');
        $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();

//        if (auth('backend')->check()) {
//            $userCreate = auth('backend')->user()->id;
//        } else {
//            $token = \request()->header('authorization');
//            $user = \JWTAuth::parseToken()->toUser();
//            $userCreate = $user->id;
//        }
//
//        dispatch(new DeleteRoomConversation($room->id, $room->hostel->id, $userCreate, auth('backend')->user()));
//
//
//        $room->delete();


        return response([
            'status' => 1,
            'message' => 'Thành công',
            'button' => view('admin2.room.button_progress', compact('hostel', 'blockName'))->render()
        ]);
    }

    public function createReserve(Request $request)
    {
        if (auth('backend')->user()->cannot('add-reserve')) {
            return response([
                'status' => 0,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }
        $roomId = $request->input('room_id');
        $bedId = $request->input('bed_id');

        $room = Room::find($roomId);

        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $currentReserve = RoomReservation::query()
            ->where('room_id', $roomId)
            ->when(!empty($bedId), function ($q) use ($bedId) {
                $q->where('bed_id', $bedId);
            })
            ->first();

        if ($currentReserve) {
            return response([
                'status' => 1,
                'is_reserve' => 1,
                'data' => view('admin2.room.current_reserve', compact('room', 'bedId', 'currentReserve'))->render()
            ]);
        }

        return response([
            'status' => 1,
            'is_reserve' => 0,
            'data' => view('admin2.room.reserve', compact('room', 'bedId'))->render()
        ]);
    }

    public function storeReserve(Request $request)
    {
        if (auth('backend')->user()->cannot('add-reserve')) {
            return response([
                'status' => 0,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }

        $data = $request->all();

        if (!empty($data['date_join'])) {
            $data['date_join'] = Carbon::createFromFormat('d/m/Y', $data['date_join'])->toDateString();
        }

        $roomId = $data['room_id'];
        $room = Room::find($roomId);

        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $data['hostel_id'] = $room->hostel->id;

        if ($room->hostel->type_rent == Hostel::TYPE_RENT_ALL) {
            $check = RoomReservation::query()->where('room_id', $data['room_id'])->count();
            if ($check) {
                return response([
                    'status' => 0,
                    'message' => 'Mỗi phòng chỉ được phép tạo một giữ chỗ tại một thời điểm.'
                ]);
            }
        } else if ($room->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
            $check = RoomReservation::query()->where('bed_id', $data['bed_id'])->count();
            if ($check) {
                return response([
                    'status' => 0,
                    'message' => 'Mỗi giường chỉ được phép tạo một giữ chỗ tại một thời điểm.'
                ]);
            }
            $maxRenters = $room->max_renters;
            $numberCurrentRenter = RenterRoom::where('room_id', $roomId)->count();

            RoomBed::find($data['bed_id'])->update([
                'status' => RoomBed::DEPOSIT,
            ]);

            if ($numberCurrentRenter == $maxRenters) {
                return response([
                    'status' => 0,
                    'message' => 'Bạn không thể giữ chỗ vượt quá số người tối đa'
                ]);
            }
        }


        if (empty($data['deposit'])) {
            $data['deposit'] = 0;
        }
        $data['user_id'] = auth('backend')->user()->id;

        $reserve = RoomReservation::create($data);

        if (!empty($data['deposit'])) {
            if ($data['deposit'] > 0) {
                $transaction = Transaction::create([
                    'amount' => $data['deposit'],
                    'hostel_id' => $data['hostel_id'],
                    'room_id' => $roomId,
                    'date_action' => Carbon::now()->toDateString(),
                    'type' => CollectSpend::COLLECT,
                    'note' => 'Thu tiền đặt cọc giữ chỗ ' . $data['name'] . ', SĐT: ' . $data['phone'],
                    'is_statistic' => false
                ]);

                CollectSpend::create([
                    'amount' => $data['deposit'],
                    'hostel_id' => $data['hostel_id'],
                    'room_id' => $roomId,
                    'note' => 'Thu tiền đặt cọc giữ chỗ ' . $data['name'] . ', SĐT: ' . $data['phone'],
                    'payment_method' => CollectSpend::MONEY,
                    'date_action' => Carbon::now()->toDateString(),
                    'type' => CollectSpend::COLLECT,
                    //  'note' => 'Thu tiền đặt cọc giữ chỗ ' . $data['name'] . ', SĐT: ' . $data['phone'],
                    'transaction_id' => $transaction->id,
                    'reserve_id' => $reserve->id,
                    'payer' => $data['name'],
                    'is_deposit' => true,
                    'is_statistic' => false
                ]);
            }
        }
        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);
    }

    public function backReserve(Request $request)
    {
        $reserveId = $request->input('reserve_id');
        $reserve = RoomReservation::find($reserveId);
        if (!$reserve) {
            return response([
                'status' => 0,
                'message' => 'Wrong data'
            ]);
        }

        return response([
            'status' => 1,
            'data' => view('admin2.room.back_reserve', compact('reserve'))->render()
        ]);
    }

    public function detailReservation(Request $request)
    {
        $reserveId = $request->input('reserve_id');
        $reserve = RoomReservation::find($reserveId);
        if (!$reserve) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        return response([
            'status' => 1,
            'data' => view('admin2.room.detail_reserve', compact('reserve'))->render()
        ]);
    }

    public function getRenterByCode(Request $request)
    {
        $phone = $request->input('phone');

        $ownerId = auth('backend')->user()->id;
        if (auth('backend')->user()->type == User::STAFF) {
            $ownerId = auth('backend')->user()->staff_owner_id;
        }

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

        if (!$data) {
            return response([
                'status' => 0,
                'data' => null
            ]);
        }

        $checkRenter = RenterRoom::query()
            ->withTrashed()
            ->where('user_id', $data->id)
            ->whereHas('hostel', function ($q) use ($ownerId) {
                $q->where('owner_id', $ownerId);
            })
            ->count();
        if (empty($checkRenter)) {
            return response([
                'status' => 0,
                'data' => null
            ]);
        }

        $selectProvince = '';
        $selectDistrict = '';
        $selectWard = '';


        if (!empty($data->province_id)) {
            $name = 'provinceid';
            $selectProvince = view('admin2.contract.select_locations', [
                'items' => Functions::getProvinces(),
                'dt' => $data->province_id,
                'itemId' => $name
            ])->render();
        }

        if (!empty($data->province_id)) {
            $name2 = 'districtid';
            $districts = \DB::table('district')->where('provinceid', $data->province_id)->get();
            $selectDistrict = view('admin2.contract.select_locations', [
                'items' => $districts,
                'dt' => $data->district_id,
                'itemId' => $name2
            ])->render();
        }

        if (!empty($data->district_id)) {
            $name3 = 'wardid';
            $wards = \DB::table('ward')->where('districtid', $data->district_id)->get();
            $selectWard = view('admin2.contract.select_locations', [
                'items' => $wards,
                'dt' => $data->ward_id,
                'itemId' => $name3
            ])->render();
        }

        return response([
            'status' => 1,
            'data' => $data,
            'select_province' => $selectProvince,
            'select_district' => $selectDistrict,
            'select_ward' => $selectWard
        ]);


    }

    public function detailRoomType(Request $request)
    {
        $type = $request->input('type');
        $item = RoomType::find($type);
        if (!$item) {
            return response([
                'status' => 0,
                'message' => 'Bạn vui lòng tạo loại phòng cho nhà trọ của bạn trước khi thêm phòng trọ'
            ]);
        }

        return response([
            'status' => 1,
            'data' => [
                'width' => $item->width,
                'long' => $item->long,
                'max_renters' => $item->max_peoples,
                'price' => number_format($item->price, 0, '.', '.'),
                'size' => $item->size
            ]
        ]);
    }

    public function getRoomPaymentHistory($roomId, Request $request)
    {
        $contractId = $request->input('contract_id');
        $room = Room::find($roomId);
        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $hostel = $room->hostel;

        $items = MoneyInfo::select(\DB::raw('room_id, date_action, CONCAT(MONTH(date_action),"/", YEAR(date_action)) as date_action_group'))
            ->where('room_id', $roomId)
            ->groupBy(\DB::raw('MONTH(date_action), YEAR(date_action)'))
            ->orderBy(\DB::raw('date_action', 'asc'));

        $startTime = Carbon::now()->subMonth(3)->startOfMonth()->toDateString();
        $endTime = Carbon::now()->addMonth(3)->endOfMonth()->toDateString();

        $items = $items->whereBetween('date_action', [$startTime, $endTime]);
        if (!empty($contractId)) {
            $items = $items->where('contract_id', $contractId);
        }

        $items = $items->get();


        return response([
            'status' => 1,
            'data' => view('admin2.room.payment_history', compact('items', 'roomId', 'room', 'hostel', 'startTime', 'endTime', 'contractId'))->render(),
            'message' => 'Thành công'
        ]);
    }

    public function getFilterPaymentHistory(Request $request)
    {
        $type = $request->input('type');
        $startTime = $request->input('start_time');
        $endTime = $request->input('end_time');
        $roomId = $request->input('room_id');
        //$contractCode = $request->input('contract_code', null);
        $contractId = $request->input('contract_id', null);
//        if (!empty($contractCode)) {
//
//            $contract = Contract::where('code', 'LIKE', '%' . $contractCode . '%')->first();
//            if ($contract) {
//                $contractId = $contract->id;
//            }
//        }

        $room = Room::find($roomId);

        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $hostel = $room->hostel;

        $items = MoneyInfo::query()->select(\DB::raw('date_action, CONCAT(MONTH(date_action),"/", YEAR(date_action)) as date_action_group'))
            ->groupBy(\DB::raw('MONTH(date_action), YEAR(date_action)'))
            ->orderBy(\DB::raw('date_action', 'asc'));


        if (!empty($startTime) && !empty($endTime)) {
            $startTime = Carbon::createFromFormat('d/m/Y', '01/' . $startTime)->startOfMonth()->toDateString();
            $endTime = Carbon::createFromFormat('d/m/Y', '01/' . $endTime)->endOfMonth()->toDateString();
            $items = $items->whereBetween('date_action', [$startTime, $endTime]);
        } else {
            $startTime = Carbon::now()->startOfMonth()->toDateString();
            $endTime = Carbon::now()->addMonth(3)->endOfMonth()->toDateString();
        }
        if (!empty($contractId)) {
            $items = $items->where('contract_id', $contractId);
        }

        $items = $items->get();

        return response([
            'status' => 1,
            'data' => view('admin2.room.pay_history_table', compact('items', 'roomId', 'room', 'hostel', 'type', 'contractId', 'startTime', 'endTime'))->render(),
            'payment_data' => view('admin2.room.payment_data', compact('startTime', 'endTime'))
        ]);
    }

    public function createRoomImages()
    {
        return response([
            'status' => 1,
            'data' => view('admin2.room.room_images2')->render()
        ]);
    }

    public function uploadImage(Request $request)
    {
        $file = $request->file('file');
        $image = Functions::uploadImage($file);

        return response([
            'status' => 1,
            'data' => $image
        ]);
    }

    public function createAmenity()
    {
        return response([
            'status' => 1,
            'data' => view('admin2.room.add_amenity')->render()
        ]);
    }

    public function createPolicy()
    {
        return response([
            'status' => 1,
            'data' => view('admin2.room.add_policy')->render()
        ]);
    }

    public function edit($id)
    {
        if (auth('backend')->user()->cannot('edit-room')) {
            return response([
                'status' => 0,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }

        $room = Room::find($id);
        if (!$room) {
            return response([
                'status' => 0,
                'data' => null
            ]);
        }

        $roomTypes = RoomType::where('hostel_id', $room->hostel->id)->get();
        $amenities = Amenity::where('type', Amenity::AMENITY)->whereIn('user_id', [
            0,
            auth('backend')->user()->id
        ])->get();

        return response([
            'status' => 1,
            'data' => view('admin2.room.edit', compact('room', 'roomTypes', 'amenities'))->render()
        ]);
    }

    public function update($id, Request $request)
    {

        if (auth('backend')->user()->cannot('edit-room')) {
            return response([
                'status' => 2,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }

        $room = Room::find($id);
        if (!$room) {
            return response([
                'status' => 0,
                'data' => null
            ]);
        }

        $data = $request->except('images');
        $amenities = $request->input('amenities', []);

        $imagesInput = $request->file('images');
        $userAmenities = $request->input('user_amenities');
        $imageTypes = $request->input('image-types');
        $types = $request->input('types');
        $dateAvailable = $request->input('date_available');


        try {

            $images = [];
            if (isset($imagesInput)) {
                foreach ($imagesInput as $imageItem) {
                    $images[] = Functions::uploadImage($imageItem);
                }
            }

            \DB::beginTransaction();
            $data['block_group'] = mb_strtoupper(trim($data['block_name']));
            $data['price'] = Functions::filterInputNumber($data['price']);

            if (!is_numeric($data['price'])) {
                return response([
                    'status' => 0,
                    'message' => 'Giá phải là số'
                ]);
            }

            if (!empty($dateAvailable)) {

                $availableObject = Carbon::createFromFormat('d/m/Y', $dateAvailable);

                if (Carbon::now()->greaterThan($availableObject)) {
                    return response([
                        'status' => 0,
                        'message' => 'Ngày trống phòng không được nhỏ hơn ngày hiện tại'
                    ]);
                }

                $data['date_available'] = Carbon::createFromFormat('d/m/Y', $dateAvailable)->toDateString();
            }

            $room->update($data);

            if (is_array($imageTypes)) {
                foreach ($imageTypes as $key => $value) {
                    foreach ($value as $item) {
                        \DB::table('room_images')->where('id', $key)
                            ->update([
                                'type' => $item
                            ]);
                    }
                }
            }

            if (is_array($images)) {
                foreach ($images as $key => $image) {
                    $type = $types[$key];
                    \DB::table('room_images')->insert([
                        'room_id' => $room->id,
                        'image' => $image,
                        'type' => $type,
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'updated_at' => Carbon::now()->toDateTimeString(),
                    ]);
                }
            }

            $amenityArr = [];

            if (is_array($userAmenities)) {
                foreach ($userAmenities as $amenity) {
                    if (!empty($amenity)) {
                        $createdAmenity = Amenity::create([
                            'user_id' => auth('backend')->user()->id,
                            'type' => Amenity::AMENITY,
                            'name' => $amenity,
                        ]);

                        $amenityArr[] = $createdAmenity->id;
                    }
                }
            }

            $amenities = array_merge($amenities, $amenityArr);


            $room->amenities()->sync($amenities);

            \DB::commit();

            $user = Functions::getCurrentUser();
            event(new LogAction([
                'type' => 'update-room',
                'user_id' => optional($user)->id,
                'object_id' => $room->id,
                'hostel_id' => $room->hostel->id,
                'room_id' => $room->id,
                'properties' => $room->toArray(),
                'desc' => '{' . $user->name . '} đã cập nhật phòng {' . $room->name . '}, nhà {' . $room->hostel->name . '}'
            ]));

        } catch (\Exception $exception) {
            \DB::rollBack();
            dump($exception->getMessage());

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

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

    }

    public function deleteImage(Request $request)
    {
        $id = $request->input('id');

        $item = \DB::table('room_images')->where('id', $id)->first();

        if ($item) {
            $roomId = $item->room_id;
            \DB::table('room_images')->where('id', $id)->delete();
            $images = \DB::table('room_images')->where('room_id', $roomId)->get();

            return response([
                'status' => 1,
                'data' => view('admin2.room.edit_images', compact('images', 'roomId'))->render()
            ]);
        }


    }

    public function storeRoomType(Request $request)
    {
        $data = $request->all();
        $roomTypeNames = $request->input('room_type_name');
        $roomTypePrices = $request->input('room_type_price');
//        $roomTypeLongs = $request->input('room_type_long');
//        $roomTypeWidths = $request->input('room_type_width');
        $roomTypeSizes = $request->input('room_type_size');
        $roomTypeMaxPeoples = $request->input('room_type_max_people');
        $hostelId = $request->input('hostel_id');


        $roomTypeNameEdits = $request->input('room_type_name_edit');
        $roomTypePriceEdits = $request->input('room_type_price_edit');
//        $roomTypeLongs = $request->input('room_type_long');
//        $roomTypeWidths = $request->input('room_type_width');
        $roomTypeSizeEdits = $request->input('room_type_size_edit');
        $roomTypeMaxPeopleEdits = $request->input('room_type_max_people_edit');
        $ids = $request->input('edit_id');


        if (!is_array($roomTypeNames) && empty($ids)) {
            return response([
                'status' => 0
            ]);
        }

        if (is_array($ids)) {
            foreach ($ids as $key => $id) {
                $roomTypePrice = empty($roomTypePriceEdits[$key]) ? 0 : Functions::filterInputNumber($roomTypePriceEdits[$key]);
//            $roomTypeLong = empty($roomTypeLongs[$key]) ? 0 : $roomTypeLongs[$key];
//            $roomTypeWidth = empty($roomTypeWidths[$key]) ? 0 : $roomTypeWidths[$key];
                $roomTypeMaxPeople = empty($roomTypeMaxPeopleEdits[$key]) ? 0 : $roomTypeMaxPeopleEdits[$key];
                $roomTypeSize = empty($roomTypeSizeEdits[$key]) ? 0 : $roomTypeSizeEdits[$key];
                $roomTypeName = empty($roomTypeNameEdits[$key]) ? 0 : $roomTypeNameEdits[$key];


                RoomType::where('id', $id)->update([
                    'name' => $roomTypeName,
                    'price' => $roomTypePrice,
                    'size' => $roomTypeSize,
                    'max_peoples' => $roomTypeMaxPeople,
                ]);
            }
        }

        if (is_array($roomTypeNames)) {
            foreach ($roomTypeNames as $key => $roomTypeName) {
                $roomTypePrice = empty($roomTypePrices[$key]) ? 0 : Functions::filterInputNumber($roomTypePrices[$key]);
//            $roomTypeLong = empty($roomTypeLongs[$key]) ? 0 : $roomTypeLongs[$key];
//            $roomTypeWidth = empty($roomTypeWidths[$key]) ? 0 : $roomTypeWidths[$key];
                $roomTypeMaxPeople = empty($roomTypeMaxPeoples[$key]) ? 0 : $roomTypeMaxPeoples[$key];
                $roomTypeSize = empty($roomTypeSizes[$key]) ? 0 : $roomTypeSizes[$key];

                RoomType::create([
                    'name' => $roomTypeName,
                    'price' => $roomTypePrice,
                    'size' => $roomTypeSize,
                    'max_peoples' => $roomTypeMaxPeople,
                    'owner_id' => auth('backend')->user()->id,
                    'hostel_id' => $hostelId
                ]);
            }
        }

        $roomTypes = RoomType::where('hostel_id', $hostelId)->get();

        return response([
            'status' => 1,
            'message' => 'Thành công',
            'data' => view('admin2.room.room_types_table', compact('roomTypes'))->render()
        ]);
    }

    public function createRoomType(Request $request)
    {
        if (auth('backend')->user()->cannot('add-room-type')) {
            return response([
                'status' => 2,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }

        $hostelId = $request->input('hostel_id');

        return response([
            'status' => 1,
            'data' => view('admin2.room.create_room_type', compact('hostelId'))->render()
        ]);
    }

    public function storeItemRoom(Request $request)
    {
        $itemIds = $request->input('item_id');
        $itemTypeId = $request->input('item_type_id');
        $receiver = $request->input('receiver');
        $mover = $request->input('mover');

        $roomId = $request->input('room_id');
        $warehouseId = $request->input('warehouse_id');
        $hostelId = null;
        $number = 1;

        $room = Room::find($roomId);
        if (!$room) {

            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if (empty($itemIds)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống danh sách tài sản'
            ]);
        }
        $hostelId = $room->hostel->id;

        try {
            \DB::beginTransaction();
            $warehouseItem = Warehouse::find($warehouseId);
            if ($warehouseItem) {
                $warehouseItem->remain = $warehouseItem->remain - count($itemIds);
                $warehouseItem->save();
            }

            $ie = ImportExport::create([
                'item_type_id' => $itemTypeId,
                'warehouse_id' => $warehouseId,
                'import' => 0,
                'export' => count($itemIds),
                'type' => Warehouse::EXPORT,
                'user_id' => auth('backend')->user()->id,
                'hostel_id' => $hostelId,
                'room_id' => $roomId,
                'receiver' => $receiver,
                'mover' => $mover,
            ]);

            foreach ($itemIds as $itemId) {
                $item = Item::find($itemId);
                if (!$item) {
                    continue;
                }

                $check = \DB::table('room_items')
                    ->where('room_id', $roomId)
                    ->where('item_id', $itemId)
                    ->count();

                if ($check > 0) {

                    \DB::table('room_items')
                        ->where('room_id', $roomId)
                        ->where('item_id', $itemId)
                        ->where('warehouse_id', $warehouseId)
                        ->update([
                            'number' => $number,
                            'updated_at' => Carbon::now()->toDateTimeString(),
                            'receiver' => $receiver,
                            'mover' => $mover,
                        ]);
                } else {
                    \DB::table('room_items')->insert([
                        'room_id' => $roomId,
                        'item_id' => $itemId,
                        'number' => $number,
                        'warehouse_id' => $warehouseId,
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'updated_at' => Carbon::now()->toDateTimeString(),
                        'receiver' => $receiver,
                        'mover' => $mover,
                    ]);
                }


                $itemWarehouse = \DB::table('item_warehouses')
                    ->where('warehouse_id', $warehouseId)
                    ->where('item_id', $itemId)->count();

                if ($itemWarehouse) {
                    \DB::table('item_warehouses')
                        ->where('warehouse_id', $warehouseId)
                        ->where('item_id', $itemId)
                        ->decrement('amount', $number, [
                            'updated_at' => Carbon::now()->toDateTimeString()
                        ]);
                } else {
                    \DB::table('item_warehouses')->insert([
                        'item_id' => $itemId,
                        'warehouse_id' => $warehouseId,
                        'amount' => 0 - $number,
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'updated_at' => Carbon::now()->toDateTimeString()
                    ]);
                }

                ImportExportItem::create([
                    'item_type_id' => $item->item_type_id,
                    'item_id' => $item->id,
                    'import_export_id' => $ie->id,
                ]);


            }


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

            return response([
                'status' => 0,
                'message' => 'Có lỗi xảy ra'
            ]);
        }

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

    }

    public function createItemRoom(Request $request)
    {
        $roomId = $request->input('room_id');

        $userId = auth('backend')->user()->id;

        if (auth('backend')->user()->type == User::STAFF) {
            $userId = auth('backend')->user()->staff_owner_id;
        }

        $itemTypes = ItemType::where('owner_id', $userId)->get();
        $warehouses = Warehouse::where('owner_id', $userId)->get();
        Functions::createWarehouseIfEmpty($userId);

        return response([
            'status' => 1,
            'data' => view('admin2.room.create_item', compact('roomId', 'itemTypes', 'warehouses'))->render()
        ]);

    }

    public function getDetailRoom($id, Request $request)
    {
        $room = Room::find($id);
        if ($room) {
            return response([
                'status' => 1,
                'data' => view('admin2.room.room', compact('room'))->render(),
                'name' => 'Chi tiết phòng ' . $room->name . ', nhà ' . $room->hostel->name
            ]);
        }
    }

    public function getDetailRooms(Request $request, $hostelId, $blockName)
    {
        $isEmpty = $request->input('is_empty');
        $alterblockName = str_replace('-', '/', $blockName);
        $hostel = Hostel::find($hostelId);
        if ($isEmpty == 'on') {
            if ($hostel->type_rent == Hostel::TYPE_RENT_ALL) {
                $roomRenters = RenterRoom::where('hostel_id', $hostelId)->pluck('room_id')->toArray();
                $rooms = Room::query()->where('hostel_id', $hostelId)
                    ->where(function ($q) use ($blockName, $alterblockName) {
                        $q->orwhere('block_name', $blockName);
                        $q->orwhere('block_name', $alterblockName);
                        $q->orwhere('block_group', $blockName);
                        $q->orwhere('block_group', $alterblockName);
                    })
                    ->with('reserves')->with('beds')
                    ->whereNotIn('id', array_unique($roomRenters))
                    ->get();
            } else {
                $roomArrs = [];
                $roomItems = Room::query()->where('hostel_id', $hostel->id)->get();
                foreach ($roomItems as $roomItem) {
                    $numberRenter = RenterRoom::where('room_id', $roomItem->id)->count();
                    $maxRenter = $roomItem->max_renters;
                    if ($numberRenter < $maxRenter) {
                        $roomArrs[] = $roomItem->id;
                    }
                }
                $rooms = Room::query()->whereIn('id', $roomArrs)->with('reserves')->with('beds')->get();
            }
        } else {
            //dd('không tích phòng trống');
            $rooms = Room::query()->where('hostel_id', $hostelId)
                ->where(function ($q) use ($blockName, $alterblockName) {
                    $q->orwhere('block_name', $blockName);
                    $q->orwhere('block_name', $alterblockName);
                    $q->orwhere('block_group', $blockName);
                    $q->orwhere('block_group', $alterblockName);

                })
                ->with('reserves')->with('beds')
                ->get();
//            $rooms->load(['room_bed' => function($query){
//                $query->whereRaw('room_bed.room_id = room.id');
//            }]);
//			if ( ! empty( $rooms ) ) {
//				foreach ( $rooms as $room ) {
//					$room->beds = RoomBed::query()->where( 'room_id', $room->id )->get();
//				}
//			}

            //dd($rooms);
        }

        return response([
            'status' => 1,
            'data' => view('admin2.room.rooms', compact('rooms'))->render()
        ]);
    }

    public function getDetailRoomsWithoutUrlParam(Request $request)
    {
        //dd($request->all());
        $isEmpty = $request->input('is_empty');
        $hostelId = $request->input('hostel_id');
        $blockName = $request->input('block_name');
        $hostel = Hostel::find($hostelId);
        if ($isEmpty == 'on') {
            if ($hostel->type_rent == Hostel::TYPE_RENT_ALL) {
                $roomRenters = RenterRoom::where('hostel_id', $hostelId)->pluck('room_id')->toArray();
                $rooms = Room::query()->where('hostel_id', $hostelId)
                    ->where(function ($q) use ($blockName) {
                        $q->orwhere('block_name', $blockName);
                        $q->orwhere('block_group', $blockName);
                    })
                    ->with('reserves')->with('beds')
                    ->whereNotIn('id', array_unique($roomRenters));

            } else {
                $roomArrs = [];
                $roomItems = Room::where('hostel_id', $hostel->id)->get();
                foreach ($roomItems as $roomItem) {
                    $numberRenter = RenterRoom::where('room_id', $roomItem->id)->count();
                    $maxRenter = $roomItem->max_renters;
                    if ($numberRenter < $maxRenter) {
                        $roomArrs[] = $roomItem->id;
                    }
                }
                $rooms = Room::query()->whereIn('id', $roomArrs)->with('reserves')->with('beds');
            }
        } else {
            //dd('không tích phòng trống');
            $rooms = Room::query()->where('hostel_id', $hostelId)
                ->with('reserves')
                ->with('beds')
                ->where(function ($q) use ($blockName) {
                    $q->orwhere('block_name', $blockName);
                    $q->orwhere('block_group', $blockName);

                });

//            $rooms->load(['room_bed' => function($query){
//                $query->whereRaw('room_bed.room_id = room.id');
//            }]);

            //dd($rooms);
        }

        $rooms = $rooms->orderByRaw('LPAD(LOWER(name), 10,0) ASC')->get();
        // $rooms = $rooms->get()->sortBy('name');

        return response([
            'status' => 1,
            'data' => view('admin2.room.rooms', compact('rooms'))->render()
        ]);
    }

    public function addRoomExcelView(Request $request)
    {
        return response([
            'status' => 1,
            'data' => view('admin2.room.add_room_excel')->render()
        ]);
    }

    public function checkEw(Request $request)
    {
        $contractId = $request->input('contract_id');
        $contract = Contract::find($contractId);
        if (!$contract) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        $status = 1;
        $message = 'Thành công';
        $dateEnableCarbon = $contract->date_enable;
        //  $dateEnableCarbon = Carbon::createFromFormat('Y-m-d', $dateEnable);
        while ($dateEnableCarbon->lessThanOrEqualTo(Carbon::now())) {
            $dateEnableCarbon = $dateEnableCarbon->startOfMonth();
            $dateEnableCarbon2 = clone $dateEnableCarbon;
            $dateEnableCarbon3 = clone $dateEnableCarbon;
            $check = ElectricWater::query()->where('contract_id', $contractId)
                ->whereBetween('date_action', [
                    $dateEnableCarbon2->toDateString(),
                    $dateEnableCarbon2->endOfMonth()->toDateString()
                ])->count();
            if ($check == 0) {
                $message = 'Bạn chưa chốt điện nước từ ' . $dateEnableCarbon3->format('d/m/Y') . ' đến ' . $dateEnableCarbon3->endOfMonth()->format('d/m/Y') . ' cho HĐ này. Bạn có muốn chốt điện nước không ?';
                $status = 0;
                break;
            }
            $dateEnableCarbon = $dateEnableCarbon->startOfMonth()->addMonth(1);
        }

        return response([
            'status' => 1,
            'data' => $status,
            'message' => $message
        ]);

    }

    public function importExcel(Request $request)
    {
        $file = $request->file('file');
        $fileName = Functions::uploadFileStorage($file);

        $filepath = storage_path('files/' . $fileName);
        $hostelId = $request->input('hostel_id');
        $count = 0;
        $status = 0;

        $hostel = Hostel::find($hostelId);

        if (!$hostel) {
            return redirect()->back()->with('error', 'Dữ liệu không hợp lệ');
        }

        $userId = auth('backend')->user()->id;
        if (auth('backend')->user()->type == User::STAFF) {
            $userId = auth('backend')->user()->staff_owner_id;
        }

        $hostels = Hostel::query()->where('owner_id', auth('backend')->user()->id)->pluck('id')->toArray();
        $hostelsRentEvery = Hostel::query()
            ->where('type_rent', Hostel::TYPE_RENT_EVERY)
            ->where('owner_id', $userId)->pluck('id')->toArray();
        $hostelRentAll = Hostel::query()
            ->where('type_rent', Hostel::TYPE_RENT_ALL)
            ->where('owner_id', $userId)->pluck('id')->toArray();
        $cntRoomEvery = Room::query()->whereIn('hostel_id', $hostelsRentEvery)->sum('max_renters');
        $cntRoomAll = Room::query()->whereIn('hostel_id', $hostelRentAll)->count();

        //  $cntRoom = Room::query()->whereIn('hostel_id', $hostels)->count();
        $cntRoom = $cntRoomEvery + $cntRoomAll;
        $numberRoom = config('constants.LIMIT_ROOM');


        $userPackage = UserPackage::query()->where('user_id', $userId)->first();
        if ($userPackage) {
            if (Carbon::now()->greaterThan($userPackage->end_date)) {
                return response([
                    'status' => 0,
                    'message' => 'Bạn đã hết hạn sử dụng gói hiện tại. Vui lòng nâng cấp gói để tạo thêm'
                ]);
            }

            $numberRoom = $userPackage->number_rooms;
        }

        \DB::beginTransaction();

        try {
            \Excel::load($filepath, function ($reader) use ($hostelId, &$count, $hostel, &$status, $cntRoom, $numberRoom) {

                $data = $results = $reader->all();

                $items = $data->toArray();
                $items = collect($items)->filter(function ($value, $key) {
                    return !empty($value['ten_phong']);
                });


                $count = $items->count();


                if ($hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                    $cntRenter = 0;
                    foreach ($items as $item) {
                        $cntRenter += $item['so_nguoi_toi_da'];
                    }
                } else {
                    $cntRenter = $items->count();
                }

                if ($cntRoom >= $numberRoom) {
                    $status = 10;

                }

                if ($cntRoom + $cntRenter > $numberRoom) {
                    $status = 11;

                }

                foreach ($items as $row) {

                    $deposit = 0;
                    if (isset($row['dat_coc'])) {
                        $deposit = trim($row['dat_coc']);
                    }
                    $roomName = trim($row['ten_phong']);
                    $block = trim($row['tang_khu_day']);
                    $numberPeople = intval($row['so_nguoi_toi_da']);
                    $price = intval($row['gia']);
                    $size = intval($row['dien_tich']);
                    $blockGroup = strtoupper(trim($block));


                    if (empty($roomName)) {
                        $status = 2;
                        break;
                    }

                    if (empty($block)) {
                        $status = 3;
                        break;
                    }

                    if (empty($price)) {
                        $status = 4;
                        break;
                    }

                    if (empty($size)) {
                        $status = 5;
                        break;
                    }


                    $check = Room::query()
                        ->where('hostel_id', $hostelId)
                        ->where('name', $roomName)
                        ->count();

                    if ($check) {
                        return redirect()->back()->with('error', 'Nhà trọ đã tồn tại phòng có tên ' . $roomName);
                    }

                    if (!is_numeric($price)) {
                        return redirect()->back()->with('error', 'Giá phải là số');
                    }


                    $room = Room::query()->updateOrCreate([
                        'name' => $roomName,
                        'hostel_id' => $hostelId,
                        'block_group' => $blockGroup,
                    ], [
                        'name' => $roomName,
                        'price' => $price,
                        'size' => $size,
                        'max_renters' => $numberPeople,
                        'owner_id' => auth('backend')->user()->id,
                        'hostel_id' => $hostelId,
                        'block_group' => $blockGroup,
                        'block_name' => $block,
                        'deposit' => Functions::filterInputNumber($deposit)
                    ]);

                    if ($room->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                        for ($i = 1; $i <= $room->max_renters; $i++) {
                            RoomBed::create([
                                'name' => 'Giường ' . $i,
                                'hostel_id' => $hostelId,
                                'room_id' => $room->id,
                                'status' => RoomBed::AVAILABLE,
                            ]);
                        }
                    }


                }


            });


//            if ($status == 1) {
//                return redirect()->back()->with('error', 'Không được để trống loại phòng');
//            }

            if ($status == 2) {
                return redirect()->back()->with('error', 'Không được để trống tên phòng');
            }
            if ($status == 10) {
                return redirect()->back()->with('error', 'Bạn đã đạt giới hạn số phòng trọ / giường. Vui lòng nâng cấp gói để tạo thêm');
            }
            if ($status == 11) {
                return redirect()->back()->with('error', 'Bạn chỉ được thêm tối đa ' . $numberRoom . ' phòng / giường. Vui lòng nâng cấp gói để tạo thêm');
            }
            if ($status == 3) {
                return redirect()->back()->with('error', 'Không được để trống tầng / khu / dãy');
            }

            if ($status == 4) {
                return redirect()->back()->with('error', 'Không được để trống giá');
            }

            if ($status == 5) {
                return redirect()->back()->with('error', 'Không được để trống diện tích');
            }

            \DB::commit();

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

            return redirect()->back()->with('error', 'Có lỗi xảy ra vui lòng thử lại sau');
        }

        if (empty($status)) {
            return redirect()->back()->with('success', 'Đã import ' . $count . ' phòng vào nhà trọ ' . $hostel->name);
        }

    }

    public function getPaymentHistory($roomId, Request $request)
    {
        return response([
            'status' => 1,
            'data' => view('admin2.room.payment_history')->render()
        ]);
    }

    public function store(Request $request)
    {
        if (auth('backend')->user()->cannot('add-room')) {
            return response([
                'status' => 0,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }
        $data = $request->except('images');

        $images = $request->input('images');
        $userAmenities = $request->input('user_amenities');
        $types = $request->input('types');
        $imagesInput = $request->file('images');

        $hostelId = $data['hostel_id'];

        $hostel = Hostel::find($hostelId);

        if (!$hostel) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $userId = auth('backend')->user()->id;
        $ownerId = auth('backend')->user()->id;
        if (auth('backend')->user()->type == User::STAFF) {
            $ownerId = auth('backend')->user()->staff_owner_id;
        }

        $hostelsRentEvery = Hostel::query()
            ->where('type_rent', Hostel::TYPE_RENT_EVERY)
            ->where('owner_id', $userId)->pluck('id')->toArray();
        $hostelRentAll = Hostel::query()
            ->where('type_rent', Hostel::TYPE_RENT_ALL)
            ->where('owner_id', $userId)->pluck('id')->toArray();
        $cntRoomEvery = Room::query()->whereIn('hostel_id', $hostelsRentEvery)->sum('max_renters');
        $cntRoomAll = Room::query()->whereIn('hostel_id', $hostelRentAll)->count();

        //  $cntRoom = Room::query()->whereIn('hostel_id', $hostels)->count();
        $cntRoom = $cntRoomEvery + $cntRoomAll;
        $numberRoom = config('constants.LIMIT_ROOM');

        $userPackage = UserPackage::query()->where('user_id', $ownerId)->first();
        if ($userPackage) {
            if (Carbon::now()->greaterThan($userPackage->end_date)) {
                return response([
                    'status' => 2,
                    'message' => 'Bạn đã hết hạn sử dụng gói hiện tại. Vui lòng nâng cấp gói để tạo thêm'
                ]);
            }

            $numberRoom = $userPackage->number_rooms;
        }

        if ($cntRoom >= $numberRoom) {
            return response([
                'status' => 2,
                'message' => 'Bạn đã đạt giới hạn số phòng trọ. Vui lòng nâng cấp gói để tạo thêm'
            ]);
        }

        $maxRenter = 1;
        if ($hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
            if (isset($data['max_renters'])) {
                $maxRenter = $data['max_renters'];
            }
        }

        $newRoom = $cntRoom + $maxRenter;
        if ($newRoom > $numberRoom) {
            return response([
                'status' => 2,
                'message' => 'Bạn chỉ được thêm tối đa: ' . $numberRoom . ' phòng, giường. Vui lòng nâng cấp gói để tạo thêm'
            ]);
        }

        $images = [];
        if (isset($imagesInput)) {
            foreach ($imagesInput as $imageItem) {
                $images[] = Functions::uploadImage($imageItem);
            }
        }
        $dateAvailable = $request->input('date_available');
        if (!empty($dateAvailable)) {

            $availableObject = Carbon::createFromFormat('d/m/Y', $dateAvailable);

            if (Carbon::now()->greaterThan($availableObject)) {
                return response([
                    'status' => 0,
                    'message' => 'Ngày trống phòng không được nhỏ hơn ngày hiện tại'
                ]);
            }

            $data['date_available'] = Carbon::createFromFormat('d/m/Y', $dateAvailable)->toDateString();
        }

        if (empty($data['deposit'])) {
            $data['deposit'] = 0;
        }

        try {

            \DB::beginTransaction();

            $data['block_group'] = strtoupper(trim($data['block_name']));
            $data['lat'] = $hostel->lat;
            $data['lng'] = $hostel->lng;
            $data['price'] = Functions::filterInputNumber($data['price']);

            $check = Room::where('block_group', $data['block_group'])
                ->where('hostel_id', $data['hostel_id'])->where('name', trim($data['name']))->count();

            if ($check) {
                return response([
                    'status' => 0,
                    'message' => 'Tầng / khu / dãy này đã tồn tại phòng có tên ' . $data['name'],
                ]);
            }

            if (!is_numeric($data['price'])) {
                return response([
                    'status' => 0,
                    'message' => 'Giá phải là số'
                ]);
            }

            $room = Room::create($data);

            if (is_array($images)) {
                foreach ($images as $key => $image) {
                    \DB::table('room_images')->insert([
                        'type' => $types[$key],
                        'room_id' => $room->id,
                        'image' => $image,
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'updated_at' => Carbon::now()->toDateTimeString(),
                    ]);
                }
            }

            $amenityArr = [];

            if (is_array($userAmenities)) {
                foreach ($userAmenities as $amenity) {
                    if (!empty($amenity)) {
                        $createdAmenity = Amenity::create([
                            'user_id' => auth('backend')->user()->id,
                            'type' => Amenity::AMENITY,
                            'name' => $amenity,
                        ]);

                        $amenityArr[] = $createdAmenity->id;
                    }
                }
            }

            $amenities = $request->input('amenities', []);

            $amenities = array_merge($amenities, $amenityArr);

            // dd($amenities);

            $room->amenities()->sync($amenities);

            $currentNumberRoom = auth('backend')->user()->number_rooms;
            auth('backend')->user()->number_rooms = $currentNumberRoom + 1;
            auth('backend')->user()->save();
            //add 8 giường to room_bed
            if ($hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                if (!empty($room->id)) {
                    for ($i = 1; $i <= $room->max_renters; $i++) {
                        RoomBed::create([
                            'name' => 'Giường ' . $i,
                            'hostel_id' => $data['hostel_id'],
                            'room_id' => $room->id,
                            'status' => RoomBed::AVAILABLE,
                        ]);
                    }
                }
            }

            \DB::commit();

            dispatch(new CreateRoomConservation($room->id, auth('backend')->user()->id));
            dispatch(new CreateRoomConservationV2($room->id, auth('backend')->user()->id));
        } catch (\Exception $exception) {
            \DB::rollBack();
            \Log::error($exception->getMessage() . $exception->getTraceAsString());

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

        return response([
            'status' => 1,
            'hostel_id' => $room->hostel_id,
            'message' => 'Thành công'
        ]);
    }

    public function createFee(Request $request)
    {
        if (auth('backend')->user()->cannot('add-hostel-fee')) {
            return response([
                'status' => 2,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }
        $hostelId = $request->input('hostel_id');

        return response([
            'status' => 1,
            'data' => view('admin2.room.create_fee', compact('hostelId'))->render()
        ]);
    }


    public function getEditRoomType(Request $request)
    {
        if (auth('backend')->user()->cannot('edit-room-type')) {
            return response([
                'status' => 2,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }

        $id = $request->input('id');
        $item = RoomType::find($id);
        if (!$item) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $hostelId = $item->hostel_id;

        return response([
            'status' => 1,
            'data' => view('admin2.room.edit_room_type', compact('item', 'hostelId'))->render()
        ]);
    }

    public function getEditFee(Request $request)
    {
        if (auth('backend')->user()->cannot('edit-hostel-fee')) {
            return response([
                'status' => 2,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }

        $id = $request->input('id');
        $item = HostelFee::find($id);
        if (!$item) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $hostelId = $item->hostel_id;

        return response([
            'status' => 1,
            'data' => view('admin2.room.edit_fee', compact('item', 'hostelId'))->render()
        ]);
    }


    public function deleteRoomType(Request $request)
    {
        if (auth('backend')->user()->cannot('delete-room-type')) {
            return response([
                'status' => 2,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }

        $roomType = $request->input('room_type_id');
        $hostelId = $request->input('hostel_id');
        $item = RoomType::find($roomType);
        if ($item) {
            $checkRoom = Room::where('type', $item->id)->count();

            $roomTypes = RoomType::where('hostel_id', $item->hostel_id)->get();
            if ($checkRoom) {
                return response([
                    'status' => 0,
                    'message' => 'Không thể xóa loại phòng có tồn tại phòng trọ',
                    'data' => view('admin2.room.room_types_table', compact('roomTypes'))->render()
                ]);
            }

            $item->delete();
        }

        $roomTypes = RoomType::where('hostel_id', $item->hostel_id)->get();

        return response([
            'status' => 1,
            'message' => 'Thành công',
            'data' => view('admin2.room.room_types_table', compact('roomTypes'))->render()
        ]);
    }

    public function cancelEditPayment(Request $request)
    {
        $transactionId = $request->input('transaction_id');
        $transaction = Transaction::find($transactionId);

        return response([
            'status' => 1,
            'html' => number_format($transaction->amount, 0, '.', '.'),
            'button' => view('admin2.money.button_payment', compact('transaction'))->render(),
        ]);
    }

    public function getAddBike(Request $request)
    {
        return response([
            'status' => 1,
            'data' => view('admin2.room.add_bike')->render()
        ]);
    }

    public function getEditBike(Request $request)
    {
        $id = $request->input('id');

        $item = RenterBike::find($id);
        if ($item) {

            return response([
                'status' => 1,
                'data' => view('admin2.room.edit_bike', compact('item'))->render()
            ]);
        }

        return response([
            'status' => 0,
            'message' => 'Dữ liệu không hợp lệ'
        ]);
    }

    public function deleteBike(Request $request)
    {
        $id = $request->input('id');
        $bike = RenterBike::find($id);

        $renterId = $bike->renter_id;
        $roomId = $bike->room_id;
        if ($bike) {
            $bike->delete();
        }

        $items = RenterBike::where('room_id', $roomId)->where('renter_id', $renterId)->get();

        $renter = User::find($bike->renter_id);
        if ($renter) {
            $user = Functions::getCurrentUser();
            $room = Room::find($bike->room_id);
            $desc = '{' . $user->name . '} xóa xe của khách {' . $renter->name . '} phòng {' . $room->name . '} nhà {' . $room->hostel->name . '}';
            event(new LogAction([
                'type' => 'delete-bike',
                'user_id' => optional($user)->id,
                'object_id' => $bike->id,
                'hostel_id' => $room->hostel_id,
                'room_id' => $room->id,
                'properties' => $bike->toArray(),
                'desc' => $desc
            ]));
        }

        return response([
            'status' => 1,
            'data' => view('admin2.room.bikes', [
                'items' => $items
            ])->render()
        ]);
    }

    public function editBike(Request $request)
    {
        $id = $request->input('id');
        $name = $request->input('name');
        $type = $request->input('type');
        $bks = $request->input('bks');
        $bike = RenterBike::find($id);
        if ($request->file('bike_image') && $request->file('bike_image')->isValid()) {
            $bikeImg = Functions::uploadImage($request->file('bike_image'));
        }
        if ($bike) {
            $bike->update([
                'name' => $name,
                'type' => $type,
                'bks' => $bks,
            ]);
        }
        if (!empty($bikeImg)) {
            $bike->update([
                'image' => $bikeImg,
            ]);
        }

        return response([
            'status' => 1,
            'data' => view('admin2.room.bike', [
                'item' => $bike
            ])->render()
        ]);
    }

    public function updateRenter(Request $request)
    {
        if (auth('backend')->user()->cannot('update-renter')) {
            return response([
                'status' => 2,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }
        $data = $request->all();

        if ($request->file('image') && $request->file('image')->isValid()) {
            $image = Functions::uploadImage($request->file('image'));
            $data['image'] = $image;
        }

//        if (!empty($data['date_join'])) {
//            $data['date_join'] = Carbon::createFromFormat('d/m/Y', $data['date_join'])->toDateString();
//        }

        if (!empty($data['birthday'])) {
            $data['birthday'] = Carbon::createFromFormat('d/m/Y', $data['birthday'])->toDateString();
        }

        $renter = User::find($data['renter_id']);
        $renter2 = Renter::where('user_id', $data['renter_id'])->first();

        try {

            \DB::beginTransaction();

            if ($renter) {
                $renter->update($data);
            }

            if ($renter2) {
                $renter2->name = $data['name'];
                $renter2->address = $data['address'];
                $renter2->phone = $data['phone'];
                if (isset($data['birthday'])) {
                    $renter2->birthday = $data['birthday'];
                }
                if (isset($data['note'])) {
                    $renter2->note = $data['note'];
                }
                //$renter2->date_joined = $data['date_join'];
                $renter2->address = $data['address'];
                $renter2->save();

            }

            $contract = Contract::where('room_id', $data['room_id'])
                ->where('renter_id', $data['renter_id'])
                ->update([
                    'name' => $data['name'],
                    'id_number' => $data['id_number'],
                    'phone' => $data['phone'],
                    // 'date_join' => $data['date_join']
                ]);

            $renterRoom = RenterRoom::where('room_id', $data['room_id'])->where('user_id', $data['renter_id'])->first();
            if ($renterRoom) {
                $renterRoom->date_joined = $data['date_join'];
                $renterRoom->residence_status = $data['residence_status'];

                if ($data['residence_status'] == RenterRoom::RESIDENCE_LIMIT) {
                    if (!empty($data['date_end_residence'])) {
                        $data['date_end_residence'] = Carbon::createFromFormat('d/m/Y', $data['date_end_residence'])->toDateString();
                        $renterRoom->date_end_residence = $data['date_end_residence'];
                    }
                }

                $renterRoom->save();
            }

            $bikeNames = $request->input('bike_names');
            $bikeTypes = $request->input('bike_types');
            $bikeBks = $request->input('bike_bks');

            if (is_array($bikeNames)) {
                foreach ($bikeNames as $key => $bikeName) {
                    $bikeBk = empty($bikeBks[$key]) ? 0 : $bikeBks[$key];
                    $bikeType = empty($bikeTypes[$key]) ? 0 : $bikeTypes[$key];
                    $bikeName = empty($bikeNames[$key]) ? 0 : $bikeNames[$key];


                    RenterBike::create([
                        'name' => $bikeName,
                        'type' => $bikeType,
                        'bks' => $bikeBk,
                        'room_id' => $data['room_id'],
                        'renter_id' => $data['renter_id'],
                    ]);
                }
            }

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

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

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

    }

    public function getDetailRenter(Request $request)
    {
        $roomId = $request->input('room_id');
        $renterId = $request->input('renter_id');

        $renter = User::find($renterId);
        $renterDt = RenterRoom::where('room_id', $roomId)->where('user_id', $renterId)->first();
        $bikes = RenterBike::where('room_id', $roomId)->where('renter_id', $renterId)->get();

        $birthday = $renter->birthday;
        if (!empty($birthday)) {
            try {
                $birthday = Carbon::createFromFormat('Y-m-d', $birthday)->format('d/m/Y');
            } catch (Exception $exception) {
                $birthday = $renter->birthday;
            }
        }

        return response([
            'status' => 1,
            'data' => view('admin2.room.edit_renter', compact('renter', 'renterDt', 'bikes', 'birthday'))->render()
        ]);
    }

    public function updateTransactionCollect(Request $request)
    {
        $transactionId = $request->input('transaction_id');
        $amount = Functions::filterInputNumber($request->input('amount'));

        $transaction = Transaction::find($transactionId);

        if (empty($amount)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống số tiền'
            ]);
        }

        if (!is_numeric($amount)) {
            return response([
                'status' => 0,
                'message' => 'Số tiền phải là số'
            ]);
        }

        if (!$transaction) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        try {

            \DB::beginTransaction();

            $transaction->amount = $amount;
            $transaction->save();

            $collectSpend = CollectSpend::where('transaction_id', $transaction->id)->first();
            if ($collectSpend) {
                $collectSpend->amount = $amount;
                $collectSpend->save();
            }

            $paid = Transaction::where('money_info_id', $transaction->money_info_id)->sum('amount');
            $moneyInfo = MoneyInfo::find($transaction->money_info_id);
            if ($moneyInfo) {
                $moneyInfo->pay = $paid;
                $moneyInfo->remain = $moneyInfo->amount - $moneyInfo->discount - $paid;
                $moneyInfo->save();
            }

            \DB::commit();

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

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

        return response([
            'status' => 1,
            'html' => number_format($transaction->amount, 0, '.', '.'),
            'button' => view('admin2.money.button_payment', compact('transaction'))->render(),
            'message' => 'Thành công'
        ]);
    }

    public function getEditPayment(
        Request $request
    )
    {
        $transactionId = $request->input('transaction_id');
        $transaction = Transaction::find($transactionId);

        if (!$transaction) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        return response([
            'status' => 1,
            'html' => view('admin2.money.edit_payment', compact('transaction'))->render(),
            'button' => view('admin2.money.button_edit_payment', compact('transaction'))->render(),
        ]);
    }

    public function getPaidHistory(Request $request)
    {
        $roomId = $request->input('room_id');
        $moneyInfoId = $request->input('money_info_id');

        $room = Room::find($roomId);

        if ($room) {

            $items = Transaction::select(\DB::raw('transactions.*, collect_spends.payer'))
                ->where('transactions.type', CollectSpend::COLLECT)
                ->leftjoin('collect_spends', 'transactions.id', '=', 'collect_spends.transaction_id')
                ->whereNull('collect_spends.deleted_at')
                ->where('transactions.money_info_id', $moneyInfoId)
                ->orderBy('transactions.id', 'asc')
                ->get();

            return response([
                'status' => 1,
                'data' => view('admin2.room.paid_history', compact('items'))->render()
            ]);
        }

        return response([
            'title' => '',
            'html' => ''
        ]);
    }

    public function getFormPaid(Request $request)
    {
        if (auth('backend')->user()->cannot('add-payment')) {
            return response([
                'status' => 2,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }
        $moneyInfoId = $request->input('money_info_id');
        $moneyInfo = MoneyInfo::find($moneyInfoId);
        if (!$moneyInfo) {
            return response([
                'status' => 0,
                'data' => ''
            ]);
        }


        return response([
            'status' => 1,
            'data' => view('admin2.money.paid_form', compact('moneyInfoId', 'moneyInfo'))->render()
        ]);
    }

    public function spend(Request $request)
    {
        if (auth('backend')->user()->cannot('add-payment')) {
            return response([
                'status' => 2,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }

        $data = $request->all();

        $amount = $data['amount'];
        $moneyInfoId = $data['money_info_id'];
        $payer = $data['payer'];
        $date = $request->input('date');

        if (empty($amount)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống số tiền'
            ]);
        }

        if (empty($payer)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống người nộp tiền'
            ]);
        }

        $amount = Functions::filterInputNumber($amount);

        if (!is_numeric($amount)) {
            return response([
                'status' => 0,
                'message' => 'Số tiền phải là số'
            ]);
        }

        $moneyInfo = MoneyInfo::find($moneyInfoId);

        if (!$moneyInfo) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if ($amount > $moneyInfo->remain) {
            return response([
                'status' => 0,
                'message' => 'Không được thanh toán vượt quá số tiền còn lại'
            ]);
        }


        $hostelId = $moneyInfo->hostel_id;
        $hostel = $moneyInfo->hostel;
        $roomId = $moneyInfo->room_id;

        $type = 'phòng';
        if ($moneyInfo->type == MoneyInfo::VOUCHER_SERVICE) {
            $type = 'dịch vụ';
        }

        if (empty($amount)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống nhà trọ'
            ]);
        }

        try {
            $dateAction = Carbon::createFromFormat('d/m/Y', $date)->toDateString();
        } catch (\Exception $exception) {
            $dateAction = Carbon::now()->toDateString();
        }

        $userId = null;
        if (auth('backend')->check()) {
            $userId = auth('backend')->user()->id;
        }

        try {
            \DB::beginTransaction();

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

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


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

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

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

            if (in_array($moneyInfo->type, [MoneyInfo::VOUCHER_ROOM_PRICE, MoneyInfo::VOUCHER_CONTRACT])) {
                Statistic::create([
                    'money_info_id' => $moneyInfoId,
                    'money_info_code' => !empty($moneyInfo) ? $moneyInfo->name : null,
                    'collect_spend_id' => !empty($collectSpend) ? $collectSpend->id : null,
                    'collect_spend_code' => !empty($collectSpend) ? Carbon::now()->format('dmY') . $collectSpend->id : null,
                    'type_collect_spend' => CollectSpend::COLLECT,
                    'amount' => $amount,
                    'type' => null,
                    'hostel_id' => $hostelId,
                    'room_id' => $roomId,
                    'owner_id' => !empty($hostel) ? $hostel->owner_id : null,
                    'date_action' => Carbon::now()->toDateString(),
                    'month' => Carbon::now()->month,
                    'year' => Carbon::now()->year
                ]);
            }

            $room = Room::find($moneyInfo->room_id);

            if ($room) {
                $room->debt = $remain;
                $room->save();

                $notiDate = $moneyInfo->date_action->format('m/Y');

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

                foreach ($renters as $renter) {

                    if ($remain > 0) {
                        Notification::create([
                            'image' => auth('backend')->user()->image,
                            'to_user' => $renter->user_id,
                            'hostel_id' => $room->hostel->id,
                            'room_id' => $room->id,
                            'title' => 'Thông báo từ itro.vn',
                            'payload' => $payload,
                            'user_id' => auth('backend')->user()->id,
                            'content' => 'Đã đóng ' . number_format($amount, 0, '.', '.') . ' đ tiền ' . $type . ' tháng ' . $notiDate . '. Số tiền còn lại phải đóng là ' . number_format($remain, 0, '.', '.') . 'đ',
                        ]);
                    } else {
                        Notification::create([
                            'image' => auth('backend')->user()->image,
                            'to_user' => $renter->user_id,
                            'hostel_id' => $room->hostel->id,
                            'room_id' => $room->id,
                            'title' => 'Thông báo từ itro.vn',
                            'payload' => $payload,
                            'user_id' => auth('backend')->user()->id,
                            'content' => 'Đã đóng đủ tiền ' . $type . ' tháng ' . $notiDate . '. Số tiền ' . number_format($moneyInfo->pay, 0, '.', '.') . 'đ'
                        ]);
                    }
                }
            }

            \DB::commit();

            $user = Functions::getCurrentUser();
            $desc = '{' . optional($user)->name . '} vừa thu  {' . number_format($collectSpend->amount, 0, '.', '.') . '}, hóa đơn {' . $moneyInfo->name . '} của khách {' . $payer . '} phòng {' . $room->name . '} nhà {' . $hostel->name . '}';
            if (optional($collectSpend->hostel)->type_rent == Hostel::TYPE_RENT_EVERY) {
                $desc = '{' . optional($user)->name . '} vừa thu  {' . number_format($collectSpend->amount, 0, '.', '.') . '}, hóa đơn {' . $moneyInfo->name . '} của khách {' . $payer . '} giường {' . optional(optional($moneyInfo->contract)->bed)->name . '} phòng {' . $room->name . '} nhà {' . $hostel->name . '}';
            }

            event(new LogAction([
                'type' => 'add-payment-collect',
                'user_id' => optional($user)->id,
                'object_id' => $collectSpend->id,
                'hostel_id' => $collectSpend->hostel_id,
                'room_id' => $collectSpend->room_id,
                'properties' => $collectSpend->toArray(),
                'desc' => $desc
            ]));

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

            return response([
                'status' => 1,
                'message' => 'Có lỗi xảy ra'
            ]);
        }

        return response([
            'status' => 1,
            'message' => 'Thanh toán thành công'
        ]);
    }

    public function createRenter(Request $request)
    {
        $roomId = $request->input('room_id');
        $typeRent = $request->input('type_rent');
        $room = Room::find($roomId);
        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $hostel = $room->hostel;
        if (!$hostel) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if ($hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
            return response([
                'status' => 1,
                'data' => view('admin2.room.create_contract', compact('room'))->render()
            ]);
        } else if ($hostel->type_rent == Hostel::TYPE_RENT_ALL) {

            $checkContracts = Contract::where('hostel_id', $hostel->id)
                ->where('status', Contract::VALIDATED)
                ->count();
            if ($checkContracts) {
                return response([
                    'status' => 1,
                    'data' => view('admin2.room.add_renter', compact('typeRent', 'room'))->render()
                ]);
            } else {
                return response([
                    'status' => 1,
                    'data' => view('admin2.room.create_contract', compact('room', 'typeRent'))->render()
                ]);
            }
        }

        return response([
            'status' => 1,
            'data' => null
        ]);
    }

    public function storeEw(Request $request)
    {
        $data = $request->all();

        $roomId = $data['room_id'];
        $dateAction = $data['date_action'];

        $infoRoom = Room::find($roomId);

        if (!$infoRoom) {
            return response([
                'status' => 0,
                'message' => 'Phòng không hợp lệ'
            ]);
        }
        if (empty($data['date_action'])) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if ($data['end_electric'] < $data['start_electric']) {
            return response([
                'status' => 0,
                'message' => 'Số điện cuối không được nhỏ hơn số đầu'
            ]);
        }
        if ($data['end_water'] < $data['start_water']) {
            return response([
                'status' => 0,
                'message' => 'Số nước cuối không được nhỏ hơn số đầu'
            ]);
        }

        $startDateAction = Carbon::createFromFormat('d/m/Y', '01/'.$data['date_action'])->startOfMonth()->toDateTimeString();
        $endDateAction = Carbon::createFromFormat('d/m/Y', '01/'.$data['date_action'])->endOfMonth()->toDateTimeString();
        $data['date_action'] = Carbon::createFromFormat('d/m/Y', '01/'.$data['date_action'])->toDateTimeString();

        $check = ElectricWater::where('room_id', $roomId)->where('date_action', '>=', $startDateAction)->where('date_action', '<=', $endDateAction)->first();

        if ($check) {

            $moneyInfo = MoneyInfo::where('date_action', '>=', $startDateAction)->where('date_action', '<=', $endDateAction)
                ->whereNull('contract_id')->where('pay', '>', 0)->count();

            if ($moneyInfo) {
                return response([
                    'status' => 0,
                    'message' => 'Hóa đơn đã được thanh toán không thể thay đổi số điện nước'
                ]);
            }

            $check->start_electric = $data['start_electric'];
            $check->start_water = $data['start_water'];
            $check->end_electric = $data['end_electric'];
            $check->end_water = $data['end_water'];

            $check->delta_electric = $data['end_electric'] - $data['start_electric'];
            $check->delta_water = $data['end_water'] - $data['start_water'];

            $check->save();
        } else {
            $data['delta_electric'] = $data['end_electric'] - $data['start_electric'];
            $data['delta_water'] = $data['end_water'] - $data['start_water'];

            ElectricWater::create($data);

            $electricPrice = 0;
            $waterPrice = 0;
            $hostelFeeElectricId = null;
            $hostelFeeWaterId = null;

            $hostelFeeElectric = HostelFee::where('hostel_id', $infoRoom->hostel->id)->where('type', HostelFee::ELECTRIC)->first();
            $hostelFeeWater = HostelFee::where('hostel_id', $infoRoom->hostel->id)->where('type', HostelFee::WATER)->first();

            if ($hostelFeeElectric) {
                $hostelFeeElectricId = $hostelFeeElectric->id;
                $electricPrice = $hostelFeeElectric->price;
            }

            if ($hostelFeeWater) {
                $hostelFeeWaterId = $hostelFeeWater->id;
                $waterPrice = $hostelFeeWater->price;
            }

            $amountElectric = Functions::calculateElectricAmount($data['delta_electric'], $infoRoom, HostelFee::ELECTRIC, $hostelFeeElectricId);
            $amountWater = Functions::calculateElectricAmount($data['delta_water'], $infoRoom, HostelFee::WATER, $hostelFeeWaterId);

            $amount = $amountElectric + $amountWater;

            $moneyInfo = MoneyInfo::create([
                'hostel_id' => $infoRoom->hostel->id,
                'room_id' => $infoRoom->id,
                'amount' => $amount,
                'pay' => 0,
                'remain' => $amount,
                'date_action' => Carbon::createFromFormat('d/m/Y', '01/'.$dateAction)->toDateString(),
            ]);

            MoneyDetail::create([
                'hostel_id' => $infoRoom->hostel->id,
                'room_id' => $roomId,
                'name' => 'Tiền điện',
                'is_electric' => true,
                'money_info_id' => $moneyInfo->id,
                'value' => $electricPrice,
                'qty' => json_encode([
                    'start' => $data['start_electric'],
                    'end' => $data['end_electric'],
                    'item_id' => $check->id
                ]),
                'amount' => $data['delta_electric'] * $electricPrice,
            ]);

            MoneyDetail::create([
                'hostel_id' => $infoRoom->hostel->id,
                'room_id' => $roomId,
                'name' => 'Tiền nước',
                'is_water' => true,
                'money_info_id' => $moneyInfo->id,
                'value' => $waterPrice,
                'qty' => json_encode([
                    'start' => $data['start_water'],
                    'end' => $data['end_water'],
                    'item_id' => $check->id
                ]),
                'amount' => $dateAction['delta_water'] * $waterPrice
            ]);
        }


        if ($check) {

            //Cập nhật sang bên phiếu thu chi
            $voucher = MoneyInfo::where('room_id', $roomId)->where('date_action', '>=', $startDateAction)->where('date_action', '<=', $endDateAction)->first();

            if ($voucher) {
                $moneyDetailElectric = MoneyDetail::where('money_info_id', $voucher->id)
                    ->where('is_electric', true)
                    ->first();
                if ($moneyDetailElectric) {
                    $moneyDetailElectric->qty = json_encode([
                        'start' => $data['start_electric'],
                        'end' => $data['end_electric'],
                        'item_id' => $check->id
                    ]);

                    $moneyDetailElectric->amount = ($data['end_electric'] - $data['start_electric']) * $moneyDetailElectric->value;

                    $moneyDetailElectric->save();
                }

                $moneyDetailWater = MoneyDetail::where('money_info_id', $voucher->id)
                    ->where('is_water', true)
                    ->first();

                if ($moneyDetailWater) {
                    $moneyDetailWater->qty = json_encode([
                        'start' => $data['start_water'],
                        'end' => $data['end_water'],
                        'item_id' => $check->id
                    ]);

                    $moneyDetailWater->amount = ($data['end_water'] - $data['start_water']) * $moneyDetailWater->value;

                    $moneyDetailWater->save();
                }

                $amount = MoneyDetail::where('money_info_id', $voucher->id)->sum('amount');

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

        }


        $renters = RenterRoom::where('room_id', $data['room_id'])->get();

        foreach ($renters as $renter) {
            Notification::create([
                'image' => auth('backend')->user()->image,
                'to_user' => $renter->user_id,
                'hostel_id' => $data['hostel_id'],
                'room_id' => $data['room_id'],
                'title' => 'Thông báo từ itro.vn',
                'user_id' => auth('backend')->user()->id,
                'content' => 'Tình hình sử dụng điện, nước tháng ' . $dateAction . '. Phòng ' . $infoRoom->name . ' dùng ' . $data['delta_electric'] . ' kwh điện và ' . $data['delta_water'] . ' m3 nước. Chỉ số cuối là ' . $data['end_electric'] . ' kwh và ' . $data['end_water'] . ' m3',
            ]);

        }


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

    }


    public function getItems($id, Request $request)
    {
        $room = Room::find($id);

        return response([
            'status' => 1,
            'data' => view('admin2.room.items', [
                'roomId' => $room->id
            ])->render()
        ]);
    }

    public function getBreaks($id, Request $request)
    {
        $room = Room::find($id);

        return response([
            'status' => 1,
            'data' => view('admin2.room.break_history', [
                'roomId' => $room->id
            ])->render()
        ]);

    }

    public function getItemsByAttribute(Request $request)
    {
        $id = $request->input('room_id');
        $room = Room::find($id);

        $items = $room->items;

        return Datatables::of($items)
            ->addIndexColumn()
            ->editColumn('mover', function ($item) {
                return $item->pivot->mover;
            })
            ->editColumn('receiver', function ($item) {
                return $item->pivot->receiver;
            })
            ->editColumn('number', function ($item) {
                return $item->pivot->number;
            })
            ->addColumn('action', function ($item) {
                return '<div style="min-width: 150px">' .
                    '<a data-room="' . $item->pivot->room_id . '" data-id="' . $item->pivot->id . '" class="btn btn-sm btn-outline btn-editable btn-delete-room-item dark black"><i class="fa fa-trash"></i> Xóa</a>' .
                    '<a data-room="' . $item->pivot->room_id . '" data-id="' . $item->id . '" class="btn btn-sm btn-outline btn-editable btn-move-room-item dark black"><i class="fa fa-trash"></i> Chuyển</a></div>';
            })
            ->make(true);
    }

    public function uploadImageBreak(Request $request)
    {
        $file = $request->file('file');
        $image = Functions::uploadImage($file);

        return response([
            'status' => 1,
            'data' => $image
        ]);
    }

    public function moveItemView(Request $request)
    {
        $id = $request->input('id');
        $roomId = $request->input('room_id');
        $ownerId = auth('backend')->user()->id;
        if (auth('backend')->user()->type == User::STAFF) {
            $ownerId = auth('backend')->user()->staff_owner_id;
        }
        $item = Item::query()->find($id);
        $room = Room::find($roomId);

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

        return response([
            'status' => 1,
            'data' => view('admin2.room.move_item', compact('hostels', 'item', 'room'))->render()
        ]);
    }

    public function storeBreakHistory(Request $request)
    {
        $data = $request->all();
        $content = $data['content'];
        $status = $data['status'];
        $roomId = $data['room_id'];
        $itemId = $data['item_id'];
        $userRepair = $data['user_repair'];
        $dayRepair = $data['day_repair'];
        $cost = $data['cost'];

        $room = Room::find($roomId);

        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if (!empty($dayRepair)) {
            $data['day_repair'] = Carbon::createFromFormat('d/m/Y', $data['day_repair'])->toDateString();
        } else {
            $data['day_repair'] = Carbon::now()->toDateString();
        }

        $hostelId = $room->hostel->id;
        $item = BreakHistory::create([
            'content' => $content,
            'status' => $status,
            'room_id' => $roomId,
            'hostel_id' => $hostelId,
            'user_id' => auth('backend')->user()->id,
            'item_id' => $itemId,
            'user_repair' => $userRepair,
            'cost' => $cost,
            'day_repair' => $data['day_repair']
        ]);

        if (!empty($request->input('images'))) {
            $images = $request->input('images');
            if (is_array($images)) {
                foreach ($images as $image) {
                    \DB::table('break_images')->insert([
                        'image' => $image,
                        'break_id' => $item->id,
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'updated_at' => Carbon::now()->toDateTimeString()
                    ]);
                }
            }
        }

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

    public function updateBreakHistory(Request $request)
    {
        $data = $request->all();
        $item = BreakHistory::find($data['id']);

        if (!$item) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if (!empty($data['day_repair'])) {
            $data['day_repair'] = Carbon::createFromFormat('d/m/Y', $data['day_repair'])->toDateString();
        }

        $item->update($data);

        if (!empty($request->input('images'))) {
            $images = $request->input('images');
            if (is_array($images)) {
                foreach ($images as $image) {
                    \DB::table('break_images')->insert([
                        'image' => $image,
                        'break_id' => $item->id,
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'updated_at' => Carbon::now()->toDateTimeString()
                    ]);
                }
            }
        }

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

    public function deleteBreak(Request $request)
    {
        $id = $request->input('id');
        BreakHistory::where('id', $id)->delete();

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

    public function createBreakHistory(Request $request)
    {
        $roomId = $request->input('room_id');

        return response([
            'status' => 1,
            'data' => view('admin2.room.create_break_history', compact('roomId'))->render()
        ]);
    }

    public function editBreakHistory(Request $request)
    {
        $id = $request->input('id');
        $breakHistory = BreakHistory::find($id);
        if (!$breakHistory) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        return response([
            'status' => 1,
            'data' => view('admin2.room.edit_break_history', compact('breakHistory'))->render()
        ]);
    }


    public function deleteBreakImage(Request $request)
    {
        $id = $request->input('id');

        $item = \DB::table('break_images')->where('id', $id)->first();

        if ($item) {
            $breakId = $item->break_id;
            \DB::table('break_images')->where('id', $id)->delete();
            $images = \DB::table('break_images')->where('break_id', $breakId)->get();

            return response([
                'status' => 1,
                'data' => view('admin2.room.edit_break_images', compact('images', 'hostelId'))->render()
            ]);
        }
    }

    public function getBreaksByAttribute(Request $request)
    {
        $id = $request->input('room_id');
        //$room = Room::find($id);

        $items = BreakHistory::where('room_id', $id)
            ->selectRaw('breaks.*, CONCAT(items.name, " / ", items.code, " / ", items.reference) as item_name')
            ->leftJoin('items', 'breaks.item_id', '=', 'items.id')
            ->orderBy('id', 'desc');

        return Datatables::of($items)
            ->addIndexColumn()
            ->editColumn('status', function ($item) {
                return $item->status_text;
            })
            ->editColumn('day_repair', function ($item) {
                if (!empty($item->day_repair)) {
                    return Carbon::createFromFormat('Y-m-d', $item->day_repair)->format('d/m/Y');
                }
            })
            ->editColumn('cost', function ($item) {
                return number_format($item->cost, 0, '.', '.');
            })
            ->editColumn('images', function ($item) {
                $retVal = '';
                $clickContent = '';
                $cnt = \DB::table('break_images')->where('break_id', $item->id)->count();
                if ($cnt > 0) {

                    $images = \DB::table('break_images')->where('break_id', $item->id)->get();
                    $imageContent = $images->first();
                    $clickContent = '<a href="https://itro.vn/files/' . $imageContent->image . '" data-toggle-2="lightbox" data-gallery-2="hidden-images-' . $item->id . '">Bấm để xem ảnh</a>';
                    foreach ($images as $key => $image) {
                        if ($key != 0) {
                            $retVal .= '<div data-toggle-2="lightbox" data-gallery-2="hidden-images-' . $item->id . '" data-remote="https://itro.vn/files/' . $image->image . '"></div>';
                        }
                    }
                }

                return $clickContent . $retVal;

            })
            ->addColumn('action', function ($item) {
                return
                    '<a href="#edit-break" data-room="' . $item->room_id . '" data-id="' . $item->id . '" data-toggle="modal" class="btn btn-sm btn-outline btn-editable btn-edit-room-break purple"><i class="fa fa-edit"></i> Sửa</a>' .
                    '<a data-room="' . $item->room_id . '" data-id="' . $item->id . '" class="btn btn-sm btn-outline btn-editable btn-delete-room-break dark black"><i class="fa fa-trash"></i> Xóa</a>';
            })
            ->make(true);
    }

    public function deleteItemRoom(Request $request)
    {
        $id = $request->input('id');
        $item = \DB::table('room_items')->where('id', $id)->first();
        $warehouseId = null;
        $itemId = null;
        $roomId = null;
        $hostelId = null;
        $itemTypeId = null;
        $number = 1;
        if ($item) {
            $itemId = $item->item_id;
            $itemModel = Item::find($itemId);
            if ($itemModel) {
                $itemTypeId = $itemModel->item_type_id;
            }
            $warehouseId = $item->warehouse_id;
            $roomId = $item->room_id;
            $room = Room::find($roomId);
            if ($room) {
                $hostelId = $room->hostel->id;
            }
        }

        try {
            \DB::beginTransaction();

            \DB::table('room_items')->where('id', $id)->delete();

            if ($item) {
                \DB::table('item_warehouses')
                    ->where('warehouse_id', $warehouseId)
                    ->where('item_id', $itemId)
                    ->increment('amount', $number, [
                        'updated_at' => Carbon::now()->toDateTimeString()
                    ]);

//                $item = Item::find($itemId);
//                if ($item) {
//                    $item->remain = $item->remain + $number;
//                    $item->save();
//                }

                $warehouseItem = Warehouse::find($warehouseId);
                if ($warehouseItem) {
                    $warehouseItem->remain = $warehouseItem->remain + $number;
                    $warehouseItem->save();
                }

                $ie = ImportExport::create([
                    'item_id' => $itemId,
                    'item_type_id' => $itemTypeId,
                    'warehouse_id' => $warehouseId,
                    'import' => $number,
                    'export' => 0,
                    'type' => Warehouse::IMPORT,
                    'user_id' => auth('backend')->user()->id,
                    'room_id' => $roomId,
                    'hostel_id' => $hostelId
                ]);

                ImportExportItem::create([
                    'item_type_id' => $itemTypeId,
                    'item_id' => $itemId,
                    'import_export_id' => $ie->id,
                ]);
            }

            \DB::commit();

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

            return response([
                'status' => 0,
                'message' => 'Có lỗi xảy ra'
            ]);
        }

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

    public function selectItem(Request $request)
    {
        $itemType = $request->input('item_type');
        $roomId = $request->input('room_id');
        $warehouseId = $request->input('warehouse_id');
        $itemsSelected = \DB::table('room_items')->pluck('item_id')->toArray();
        $itemIds = [];
        if (!empty($warehouseId)) {
            $itemIds = \DB::table('item_warehouses')
                ->where('warehouse_id', $warehouseId)
                ->where('item_type_id', $itemType)
                ->pluck('item_id')->toArray();
        }


        $items = Item::where('item_type_id', $itemType)->whereNotIn('id', $itemsSelected)->whereIn('id', $itemIds);

        $items = $items->get();

        return response([
            'status' => 1,
            'data' => view('admin2.room.select_item', compact('items'))->render()
        ]);
    }

    public function storeRenter(Request $request)
    {
        $data = $request->all();
        $data['image'] = null;
        if ($request->file('image') && $request->file('image')->isValid()) {
            $image = Functions::uploadImage($request->file('image'));
            $data['image'] = $image;
        }

        $data['date_join'] = Carbon::now()->toDateString();

//        if (!empty($data['date_join'])) {
//            $data['date_join'] = Carbon::createFromFormat('d/m/Y', $data['date_join'])->toDateString();
//        }

        if (!empty($data['birthday'])) {
            $data['birthday'] = Carbon::createFromFormat('d/m/Y', $data['birthday'])->toDateString();
        }

        if (!empty($data['id_number_date'])) {
            $data['id_number_date'] = Carbon::createFromFormat('d/m/Y', $data['id_number_date'])->toDateString();
        }

        if ($request->file('id_number_front') && $request->file('id_number_front')->isValid()) {
            $idNumberFront = Functions::uploadImage($request->file('id_number_front'));
            $data['id_number_front'] = $idNumberFront;
        }

        if ($request->file('id_number_back') && $request->file('id_number_back')->isValid()) {
            $idNumberBack = Functions::uploadImage($request->file('id_number_back'));
            $data['id_number_back'] = $idNumberBack;
        }


        if (isset($data['residence_status'])) {
            if ($data['residence_status'] == RenterRoom::RESIDENCE_LIMIT) {
                if (!empty($data['date_end_residence'])) {
                    $data['date_end_residence'] = Carbon::createFromFormat('d/m/Y', $data['date_end_residence'])->toDateString();
                } else {
                    $data['date_end_residence'] = null;
                }
            } else {
                $data['date_end_residence'] = null;
            }
        } else {
            $data['date_end_residence'] = null;
        }

        $data['type'] = User::RENTER;

        $room = Room::find($data['room_id']);

        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $hostel = $room->hostel;

        try {
            \DB::beginTransaction();


            $renter = User::where('phone', $data['phone'])->where('type', User::RENTER)->first();

            if (!$renter) {
                $data['password'] = \Hash::make('123456');
                $renter = User::create($data);
            }

            if ($renter) {
                if (empty($renter->password)) {
                    $data['password'] = \Hash::make(123456);

                }
                $renter->update($data);
                unset($data['password']);
            }

            $roomContract = null;
            if ($hostel) {
                if ($hostel->type_rent == Hostel::TYPE_RENT_ALL) {
                    $roomContractItem = RenterRoom::query()->where('room_id', $room->id)
                        ->whereNotNull('contract_id')
                        ->first();
                    if ($roomContractItem) {
                        $roomContract = $roomContractItem->contract_id;
                    }
                }
            }

            $checkRenterRoom = RenterRoom::query()->where('user_id', $renter->id)->latest()->first();
            if ($checkRenterRoom) {
                $hostel = Hostel::find($checkRenterRoom->hostel_id);
                if ($hostel) {
                    $ownerId = $hostel->owner_id;
                    $owner = User::find($ownerId);
                    if ($owner) {
                        return response([
                            'status' => 0,
                            'message' => 'Người trọ này đã được thêm với nhà trọ khác'
                        ]);
                    } else {
                        $checkRenterRoom->delete();
                        RenterRoom::create([
                            'hostel_id' => $room->hostel->id,
                            'room_id' => $data['room_id'],
                            'user_id' => $renter->id,
                            'residence_status' => $data['residence_status'],
                            'date_joined' => $data['date_join'],
                            'date_end_residence' => $data['date_end_residence'],
                            'room_contract_id' => $roomContract
                        ]);

                        Renter::create([
                            'image' => $data['image'],
                            'name' => $renter->name,
                            'room_id' => $data['room_id'],
                            'hostel_id' => $room->hostel->id,
                            'room_name' => $room->name,
                            'hostel_name' => $room->hostel->name,
                            'note' => isset($data['note']) ? $data['note'] : null,
                            'address' => isset($data['address']) ? $data['address'] : '',
                            'province_id' => isset($data['province_id']) ? $data['province_id'] : '',
                            'district_id' => isset($data['district_id']) ? $data['district_id'] : '',
                            '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_date' => isset($data['id_number_date']) ? $data['id_number_date'] : null,
                            'id_number_location' => isset($data['id_number_location']) ? $data['id_number_location'] : null,
                            'ward_id' => isset($data['ward_id']) ? $data['ward_id'] : '',
                            'phone' => $data['phone'],
                            'date_joined' => $data['date_join'],
                            'status' => Renter::LIVING,
                            'user_id' => $renter->id,
                            'birthday' => $data['birthday']
                        ]);
                    }
                } else {
                    $checkRenterRoom->delete();
                    RenterRoom::create([
                        'hostel_id' => $room->hostel->id,
                        'room_id' => $data['room_id'],
                        'user_id' => $renter->id,
                        'residence_status' => $data['residence_status'],
                        'date_joined' => $data['date_join'],
                        'date_end_residence' => $data['date_end_residence'],
                        'room_contract_id' => $roomContract
                    ]);

                    Renter::create([
                        'image' => $data['image'],
                        'name' => $renter->name,
                        'room_id' => $data['room_id'],
                        'hostel_id' => $room->hostel->id,
                        'room_name' => $room->name,
                        'hostel_name' => $room->hostel->name,
                        'address' => isset($data['address']) ? $data['address'] : '',
                        'note' => isset($data['note']) ? $data['note'] : null,
                        'province_id' => isset($data['province_id']) ? $data['province_id'] : '',
                        'district_id' => isset($data['district_id']) ? $data['district_id'] : '',
                        '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_date' => isset($data['id_number_date']) ? $data['id_number_date'] : null,
                        'id_number_location' => isset($data['id_number_location']) ? $data['id_number_location'] : null,
                        'ward_id' => isset($data['ward_id']) ? $data['ward_id'] : '',
                        'phone' => $data['phone'],
                        'date_joined' => $data['date_join'],
                        'status' => Renter::LIVING,
                        'user_id' => $renter->id,
                        'birthday' => $data['birthday']
                    ]);
                }
            } else {

                RenterRoom::create([
                    'hostel_id' => $room->hostel->id,
                    'room_id' => $data['room_id'],
                    'user_id' => $renter->id,
                    'residence_status' => $data['residence_status'],
                    'date_joined' => $data['date_join'],
                    'date_end_residence' => $data['date_end_residence'],
                    'room_contract_id' => $roomContract

                ]);

                Renter::create([
                    'image' => $data['image'],
                    'name' => $renter->name,
                    'room_id' => $data['room_id'],
                    'hostel_id' => $room->hostel->id,
                    'room_name' => $room->name,
                    'hostel_name' => $room->hostel->name,
                    'note' => isset($data['note']) ? $data['note'] : null,
                    'address' => isset($data['address']) ? $data['address'] : '',
                    'province_id' => isset($data['province_id']) ? $data['province_id'] : '',
                    'district_id' => isset($data['district_id']) ? $data['district_id'] : '',
                    '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_date' => isset($data['id_number_date']) ? $data['id_number_date'] : null,
                    'id_number_location' => isset($data['id_number_location']) ? $data['id_number_location'] : null,
                    'ward_id' => isset($data['ward_id']) ? $data['ward_id'] : '',
                    'phone' => $data['phone'],
                    'date_joined' => $data['date_join'],
                    'status' => Renter::LIVING,
                    'user_id' => $renter->id,
                    'birthday' => $data['birthday']
                ]);
            }

            if (!empty($data['id_number']) && empty($renter->id_number)) {
                $renter->id_number = $data['id_number'];
            }

            if (!empty($data['email']) && empty($renter->email)) {
                $renter->email = $data['email'];
            }

            $renter->save();

            $bikeNames = $request->input('bike_names');
            $bikeTypes = $request->input('bike_types');
            $bikeBks = $request->input('bike_bks');
            $bikeImg = $request->file('bike_image');

            if (is_array($bikeNames)) {
                foreach ($bikeNames as $key => $bikeName) {
                    $bikeBk = empty($bikeBks[$key]) ? 0 : $bikeBks[$key];
                    $bikeType = empty($bikeTypes[$key]) ? 0 : $bikeTypes[$key];
                    $bikeName = empty($bikeNames[$key]) ? 0 : $bikeNames[$key];
                    $bikeImage = empty($bikeImg[$key]) ? 0 : Functions::uploadImage($bikeImg[$key]);
                    RenterBike::create([
                        'name' => $bikeName,
                        'type' => $bikeType,
                        'bks' => $bikeBk,
                        'image' => $bikeImage,
                        'room_id' => $data['room_id'],
                        'renter_id' => $renter->id,
                    ]);
                }
            }

            Functions::updateIsEmptyRoom($room);

            \DB::commit();

            $user = Functions::getCurrentUser();
            $desc = '{' . $user->name . '} thêm khách {' . $request->input('name') . '} vào phòng {' . $room->name . '} nhà {' . $room->hostel->name . '}';
            event(new LogAction([
                'type' => 'create-renter',
                'user_id' => optional($user)->id,
                'object_id' => $renter->id,
                'hostel_id' => $room->hostel_id,
                'room_id' => $room->id,
                'properties' => $renter->toArray(),
                'desc' => $desc
            ]));
        } 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 response([
            'status' => 1,
            'message' => 'Thành công'
        ]);

    }

    public function createVoucher(Request $request)
    {
        if (auth('backend')->user()->cannot('add-voucher')) {
            return response([
                'status' => 2,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }

        $roomId = $request->input('room_id');
        $room = Room::find($roomId);

        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        return response([
            'status' => 1,
            'data' => view('admin2.room.voucher', compact('room'))->render()
        ]);
    }

    public function createVoucherAll(Request $request)
    {
        if (auth('backend')->user()->cannot('add-voucher')) {
            return response([
                'status' => 2,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }
        $roomId = $request->input('room_id');
        $month = $request->input('month');
        $room = Room::find($roomId);

        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if (empty($month)) {
            $month = Carbon::now()->format('m/Y');
        }

        $contract = Contract::query()
            ->where('room_id', $roomId)
            ->where('status', '<>', Contract::LIQUIDATED)
            ->first();
        if ($contract) {

            try {
                $startTime = Carbon::createFromFormat('d/m/Y', '01/' . $month)->startOfMonth()->startOfDay()->toDateString();
                $endTime = Carbon::createFromFormat('d/m/Y', '01/' . $month)->endOfMonth()->endOfDay()->toDateString();
            } catch (\Exception $exception) {
                return response([
                    'status' => 0,
                    'message' => 'Dữ liệu ngày tháng phải có định dạng tháng / năm. Ví dụ: 06/2018'
                ]);
            }

            $currentMonth = Carbon::createFromFormat('d/m/Y', '01/' . $month)->startOfMonth()->startOfDay();
            $dateEnable = $contract->date_contract->startOfMonth()->startOfDay();


//			if ( $currentMonth->lessThan( $dateEnable ) ) {
//
//				return response( [
//					'status'  => 0,
//					'message' => 'Bạn không thể lập hóa đơn trước thời điểm khách vào'
//				] );
//			}

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


            if ($item) {
                $fees = MoneyDetail::query()
                    ->where('money_info_id', $item->id)
                    ->pluck('hostel_fee_id')
                    ->toArray();

                return response([
                    'status' => 1,
                    'data' => view('admin2.room.edit_voucher_all', compact('room', 'contract', 'fees', 'item', 'month'))->render()
                ]);
            } else {
                $fees = ContractFee::query()
                    ->where('contract_id', $contract->id)->pluck('fee_id')->toArray();
            }

            return response([
                'status' => 1,
                'data' => view('admin2.room.voucher_all', compact('room', 'contract', 'fees', 'month'))->render()
            ]);
        }

        return response([
            'status' => 0,
            'message' => 'Phòng trống không thể tạo hóa đơn dịch vụ'
        ]);
    }

    public function createVoucherAllEdit(Request $request)
    {

        $roomId = $request->input('room_id');
        $month = $request->input('month');
        $room = Room::find($roomId);

        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if (empty($month)) {
            return response([
                'status' => 1,
                'message' => ''
            ]);
        }

        $carbonMonth = Carbon::createFromFormat('d/m/Y', '01/' . $month);

//        if ($carbonMonth->month > Carbon::now()->month && $carbonMonth->year >= Carbon::now()->year) {
//
//            return response([
//                'status' => 0,
//                'message' => 'Bạn không thể lập hóa đơn tương lai'
//            ]);
//
//        } else {
        $contract = Contract::query()->where('room_id', $roomId)->where('status', '<>', Contract::LIQUIDATED)->first();
        if ($contract) {

            try {
                $startTime = Carbon::createFromFormat('d/m/Y', '01/' . $month)->startOfMonth()->startOfDay()->toDateString();
                $endTime = Carbon::createFromFormat('d/m/Y', '01/' . $month)->endOfMonth()->endOfDay()->toDateString();
            } catch (\Exception $exception) {
                return response([
                    'status' => 0,
                    'message' => 'Dữ liệu ngày tháng phải có định dạng tháng / năm. Ví dụ: 06/2018'
                ]);
            }

            $currentMonth = Carbon::createFromFormat('d/m/Y', '01/' . $month)->startOfMonth()->startOfDay();
            $dateEnable = $contract->date_contract->startOfMonth()->startOfDay();


//			if ( $currentMonth->lessThan( $dateEnable ) ) {
//
//				return response( [
//					'status'  => 0,
//					'message' => 'Bạn không thể lập hóa đơn trước thời điểm khách vào'
//				] );
//			}

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

            if ($item) {


                if ($item->pay > 0 && ($carbonMonth->month < Carbon::now()->month && $carbonMonth->year <= Carbon::now()->year)) {
                    return response([
                        'status' => 0,
                        'message' => 'Hóa đơn đã được thanh toán không thể thay đổi'
                    ]);
                }


                $fees = MoneyDetail::query()->where('money_info_id', $item->id)->pluck('hostel_fee_id')->toArray();

                return response([
                    'status' => 1,
                    'data' => view('admin2.room.voucher_all_table', compact('room', 'contract', 'fees', 'item', 'month'))->render()
                ]);
            } else {


                $fees = ContractFee::query()->where('contract_id', $contract->id)->pluck('fee_id')->toArray();
            }


            return response([
                'status' => 1,
                'data' => view('admin2.room.voucher_all_table', compact('room', 'contract', 'fees', 'month', 'item'))->render()
            ]);
        }


        return response([
            'status' => 0,
            'message' => 'Phòng trống không thể tạo hóa đơn dịch vụ'
        ]);
    }

    public function getRenterFee(Request $request)
    {
        $renterId = $request->input('renter_id');
        $roomId = $request->input('room_id');
        $month = $request->input('month');

        if (empty($renterId)) {
            return response([
                'status' => 1,
                'data' => ''
            ]);
        }

        if (empty($roomId)) {
            return response([
                'status' => 1,
                'data' => ''
            ]);
        }

        if (empty($month)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống tháng',
                'data' => ''
            ]);
        }

        if (!empty($month)) {
            $monthCarbon = Carbon::createFromFormat('d/m/Y', '01/' . $month);
        }


        $contract = Contract::query()->where('renter_id', $renterId)
            ->where('room_id', $roomId)
            ->where('status', '<>', Contract::LIQUIDATED)
            ->first();

        if ($contract) {

            if (!empty($month)) {
                $currentMonth = Carbon::createFromFormat('d/m/Y', '01/' . $month)->startOfMonth()->startOfDay();
                $dateEnable = $contract->date_contract->startOfMonth()->startOfDay();


//				if ( $currentMonth->lessThan( $dateEnable ) ) {
//
//					return response( [
//						'status'  => 0,
//						'message' => 'Bạn không thể lập hóa đơn trước thời điểm khách vào'
//					] );
//				}
            }

            $startTime = Carbon::createFromFormat('d/m/Y', '01/' . $month)->startOfMonth()->startOfDay()->toDateString();
            $endTime = Carbon::createFromFormat('d/m/Y', '01/' . $month)->endOfMonth()->endOfDay()->toDateString();
            $item = MoneyInfo::where('contract_status', '<>', Contract::LIQUIDATED)->where('user_id', $renterId)->where('room_id', $roomId)
                ->where('type', MoneyInfo::VOUCHER_SERVICE)
                ->whereBetween('date_action', [
                    $startTime,
                    $endTime
                ])->first();


            if ($item) {
                return response([
                    'status' => 1,
                    'data' => view('admin2.room.voucher_table_edit', compact('contract', 'renterId', 'item', 'month'))->render()
                ]);
            }

            return response([
                'status' => 1,
                'data' => view('admin2.room.voucher_table', compact('contract', 'renterId', 'month'))->render()
            ]);
        }
    }

    public function calculateVoucher(Request $request)
    {
        $qty = $request->input('qty');
        $feeContracts = $request->input('fee-contracts');
        $contractId = $request->input('contract_id');
        $discount = $request->input('discount', 0);
        $feeDynamics = $request->input('fee-dynamics');
        $month = $request->input('month');
        $ewStart = $request->input('ew-start');
        $ewEnd = $request->input('ew-end');

        $contract = Contract::find($contractId);
        $room = $contract->room;
        $sum = 0;

        if (is_array($feeContracts)) {
            foreach ($feeContracts as $feeContract) {
                if (isset($qty[$feeContract])) {
                    $qtyItem = $qty[$feeContract];
                } else {
                    $qtyItem = 1;
                }

                $feeItem = HostelFee::find($feeContract);
                if ($feeItem) {
                    if ($feeItem->type == HostelFee::ELECTRIC || $feeItem->type == HostelFee::WATER) {
                        if (isset($ewStart[$feeItem->id])) {
                            $start = $ewStart[$feeItem->id];
                        }

                        if (isset($ewEnd[$feeItem->id])) {
                            $end = $ewEnd[$feeItem->id];
                        }

                        $amount = Functions::calculateElectricAmount($end - $start, $room, $feeItem->type, $feeItem->id);
                        $sum += $amount;
                    } else if ($feeItem->type == HostelFee::ELECTRIC_BY_CLOCK || $feeItem->type == HostelFee::WATER_BY_CLOCK) {
                        if (isset($feeDynamics[$feeContract])) {
                            $fee = Functions::filterInputNumber($feeDynamics[$feeContract]);
                            $amount = $qtyItem * $fee;
                            $sum += $amount;

                        }
                    } else if ($feeItem->type == HostelFee::DYNAMIC || $feeItem->type == HostelFee::WATER_DYNAMIC || $feeItem->type == HostelFee::ELECTRIC_DYNAMIC) {
                        if (isset($feeDynamics[$feeContract])) {
                            $fee = Functions::filterInputNumber($feeDynamics[$feeContract]);
                            $amount = $qtyItem * $fee;
                            $sum += $amount;

                        }
                    } else {
                        $amount = $qtyItem * $feeItem->fee;
                        $sum += $amount;
                    }
                }
            }
        }

        return response([
            'status' => 1,
            'data' => view('admin2.room.voucher_calculated', [
                'sum' => $sum,
                'fees' => $feeContracts,
                'contract' => $contract,
                'discount' => $discount,
                'qtys' => $qty,
                'ewStart' => $ewStart,
                'ewEnd' => $ewEnd,
                'feeDynamics' => $feeDynamics,
                'month' => $month,
                'note' => $request->input('note')
            ])->render()
        ]);
    }

    public function calculateVoucherAll(Request $request)
    {
        $qty = $request->input('qty');
        $feeContracts = $request->input('fee-contracts');
        $contractId = $request->input('contract_id');
        $discount = $request->input('discount', 0);
        $ewStart = $request->input('ew-start');
        $ewEnd = $request->input('ew-end');

        $contract = Contract::find($contractId);
        if (!$contract) {
            return response([
                'status' => 0,
                'message' => 'Không tìm thấy hợp đồng'
            ]);
        }
        $room = $contract->room;
        $feeDynamics = $request->input('fee-dynamics');

        $sum = 0;

        if (is_array($feeContracts)) {
            foreach ($feeContracts as $feeContract) {
                $start = 0;
                $end = 0;
                if (isset($qty[$feeContract])) {
                    $qtyItem = $qty[$feeContract];
                } else {
                    $qtyItem = 1;
                }

                $feeItem = HostelFee::find($feeContract);
                if ($feeItem) {
                    if ($feeItem->type == HostelFee::ELECTRIC || $feeItem->type == HostelFee::WATER) {
                        if (isset($ewStart[$feeItem->id])) {
                            $start = $ewStart[$feeItem->id];
                        }

                        if (isset($ewEnd[$feeItem->id])) {
                            $end = $ewEnd[$feeItem->id];
                        }

                        $amount = Functions::calculateElectricAmount($end - $start, $room, $feeItem->type, $feeItem->id);
                        $sum += $amount;
                    }
                    if ($feeItem->type == HostelFee::ELECTRIC_BY_CLOCK || $feeItem->type == HostelFee::WATER_BY_CLOCK) {
                        if (isset($ewStart[$feeItem->id])) {
                            $start = $ewStart[$feeItem->id];
                        }

                        if (isset($ewEnd[$feeItem->id])) {
                            $end = $ewEnd[$feeItem->id];
                        }

                        $amount = ($end - $start) * $feeItem->fee;
                        $sum += $amount;
                    } else if ($feeItem->type == HostelFee::DYNAMIC || $feeItem->type == HostelFee::WATER_DYNAMIC || $feeItem->type == HostelFee::ELECTRIC_DYNAMIC) {
                        if (isset($feeDynamics[$feeContract])) {
                            $fee = Functions::filterInputNumber($feeDynamics[$feeContract]);
                            $amount = $qtyItem * $fee;
                            $sum += $amount;
                        }
                    } else {
                        $amount = $qtyItem * $feeItem->fee;
                        $sum += $amount;
                    }

                }

            }
        }

        return response([
            'status' => 1,
            'data' => view('admin2.room.voucher_all_calculated', [
                'sum2' => $sum,
                'fees' => $feeContracts,
                'contract' => $contract,
                'discount' => $discount,
                'qtys' => $qty,
                'ewStart' => $ewStart,
                'ewEnd' => $ewEnd,
                'feeDynamics' => $feeDynamics
            ])->render()
        ]);
    }

    public function storeVoucher(Request $request)
    {
        $data = $request->all();
        $qty = $request->input('qty');
        $feeContracts = $request->input('fee-contracts');
        $contractId = $request->input('contract_id');
        $discount = $request->input('discount', 0);
        $userId = $request->input('user_id');
        $month = $request->input('month');
        $feeDynamics = $request->input('fee-dynamics');
        $ewStart = $request->input('ew-start');
        $ewEnd = $request->input('ew-end');
        $note = $request->input('note');

        $contract = Contract::find($contractId);


        if (!$contract) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if ($contract->status == Contract::LIQUIDATED) {
            return response([
                'status' => 0,
                'message' => 'Hợp đồng đã được thanh lý'
            ]);
        }

        if (empty($month)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống tháng'
            ]);
        }

        if (empty($userId)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống người thuê'
            ]);
        }

        $sum = 0;
        $room = $contract->room;
        if (is_array($feeContracts)) {
            foreach ($feeContracts as $feeContract) {
                if (isset($qty[$feeContract])) {
                    $qtyItem = $qty[$feeContract];
                } else {
                    $qtyItem = 1;
                }

                $feeItem = HostelFee::find($feeContract);
                if ($feeItem) {
                    if ($feeItem->type == HostelFee::ELECTRIC || $feeItem->type == HostelFee::WATER) {
                        if (isset($ewStart[$feeItem->id])) {
                            $start = $ewStart[$feeItem->id];
                        }

                        if (isset($ewEnd[$feeItem->id])) {
                            $end = $ewEnd[$feeItem->id];
                        }

                        $amount = Functions::calculateElectricAmount($end - $start, $room, $feeItem->type, $feeItem->id);
                        $sum += $amount;
                    } else if ($feeItem->type == HostelFee::ELECTRIC_BY_CLOCK || $feeItem->type == HostelFee::WATER_BY_CLOCK) {

                        if (isset($ewStart[$feeItem->id])) {
                            $start = $ewStart[$feeItem->id];
                        }

                        if (isset($ewEnd[$feeItem->id])) {
                            $end = $ewEnd[$feeItem->id];
                        }

                        $amount = ($end - $start) * $feeItem->fee;
                        $sum += $amount;

                    } else if ($feeItem->type == HostelFee::DYNAMIC || $feeItem->type == HostelFee::WATER_DYNAMIC || $feeItem->type == HostelFee::ELECTRIC_DYNAMIC) {
                        if (isset($feeDynamics[$feeContract])) {
                            $fee = Functions::filterInputNumber($feeDynamics[$feeContract]);
                            $amount = $qtyItem * $fee;
                            $sum += $amount;
                        }
                    } else {
                        $amount = $qtyItem * $feeItem->fee;
                        $sum += $amount;
                    }
                }
            }
        }

        try {

            \DB::beginTransaction();

            try {
                $startTime = Carbon::createFromFormat('d/m/Y', '01/' . $month)->startOfMonth()->startOfDay()->toDateTimeString();
                $endTime = Carbon::createFromFormat('d/m/Y', '01/' . $month)->endOfMonth()->endOfDay()->toDateTimeString();
                $monthCarbon = Carbon::createFromFormat('d/m/Y', '01/' . $month);
            } catch (\Exception $exception) {
                return response([
                    'status' => 0,
                    'message' => 'Dữ liệu ngày tháng phải có định dạng tháng / năm. Ví dụ: 06/2018'
                ]);
            }

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

            $dateAction = Carbon::createFromFormat('d/m/Y', '01/' . $month)->toDateString();

            $pay = 0;
            $itemId = null;
            if ($item) {
                $itemId = $item->id;
                if ($item->pay > 0) {
//                    return response([
//                        'status' => 0,
//                        'message' => 'Hóa đơn này đã được thanh toán một phần, bạn không thể cập nhật'
//                    ]);
                    $pay = $item->pay;

                }
                $dateAction = $item->date_action->toDateString();
                MoneyDetail::where('money_info_id', $item->id)->delete();
                MoneyInfo::find($item->id)->delete();

                $user = Functions::getCurrentUser();

                $desc = '{' . $user->name . '} vừa sửa hóa đơn dịch vụ tháng {' . $monthCarbon->copy()->format('m/Y') . '} cho khách {' . $contract->name . '} phòng {' . $contract->room->name . '} nhà {' . $contract->hostel->name . '}';
                if ($contract->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                    $desc = '{' . $user->name . '} vừa sửa hóa đơn dịch vụ tháng {' . $monthCarbon->copy()->format('m/Y') . '} cho khách {' . $contract->name . '} giường {' . optional($contract->bed)->name . '} phòng {' . $contract->room->name . '} nhà {' . $contract->hostel->name . '}';
                }
                event(new LogAction([
                    'type' => 'update-money-info-service',
                    'user_id' => optional($user)->id,
                    'object_id' => $item->id,
                    'hostel_id' => $contract->hostel_id,
                    'room_id' => $contract->room_id,
                    'desc' => $desc
                ]));
            }


            $moneyInfo = MoneyInfo::create([
                'hostel_id' => $contract->room->hostel->id,
                'room_id' => $contract->room->id,
                'bed_id' => $contract->bed_id,
                'amount' => $sum,
                'discount' => $discount,
                'pay' => $pay,
                'remain' => $sum - $discount - $pay,
                'date_action' => $dateAction,
                'user_id' => $userId,
                'type' => MoneyInfo::VOUCHER_SERVICE,
                'contract_id' => $contract->id,
                'note' => $note
            ]);
            if (!$item) {
                $user = Functions::getCurrentUser();
                $desc = '{' . optional($user)->name . '}' . ' vừa lập hóa đơn dịch vụ tháng {' . $moneyInfo->date_action->format('m/Y') . '} 
                cho khách {' . $moneyInfo->contract->name . '} phòng {' . $moneyInfo->room->name . '} nhà {' . $moneyInfo->hostel->name . '}';
                if ($moneyInfo->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                    $desc = '{' . optional($user)->name . '}' . ' vừa lập hóa đơn dịch vụ tháng {' . $moneyInfo->date_action->format('m/Y') . '} 
                cho khách {' . $moneyInfo->contract->name . '} giường {' . optional($moneyInfo->contract->bed)->name . '} phòng {' . $moneyInfo->room->name . '} nhà {' . $moneyInfo->hostel->name . '}';
                }

                event(new LogAction([
                    'type' => 'create-money-info-service',
                    'user_id' => optional($user)->id,
                    'object_id' => $moneyInfo->id,
                    'hostel_id' => $moneyInfo->hostel_id,
                    'room_id' => $moneyInfo->room_id,
                    'properties' => $moneyInfo->toArray(),
                    'desc' => $desc
                ]));
            }

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

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

            foreach ($feeContracts as $feeContract) {

                if (isset($qty[$feeContract])) {
                    $qtyItem = $qty[$feeContract];
                } else {
                    $qtyItem = 1;
                }

                $feeItem = HostelFee::find($feeContract);

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


                if ($feeItem) {
                    $feeValue = $feeItem->fee;
                    $amount = $feeValue * $qtyItem;
                    if ($feeItem->type == HostelFee::ELECTRIC || $feeItem->type == HostelFee::ELECTRIC_BY_CLOCK) {
                        $isElectric = 1;
                        if ($ewEnd[$feeItem->id] < $ewStart[$feeItem->id]) {
                            return response([
                                'status' => 0,
                                'message' => 'Chỉ số cuối không được nhỏ hơn chỉ số đầu'
                            ]);
                        }
                        $qtyItem = json_encode([
                            'start' => $ewStart[$feeItem->id],
                            'end' => $ewEnd[$feeItem->id]
                        ]);


                        $ew['end_electric'] = $ewEnd[$feeItem->id];
                        $ew['start_electric'] = $ewStart[$feeItem->id];
                        $ew['delta_electric'] = $ew['end_electric'] - $ew['start_electric'];
                        $ew['date_action'] = Carbon::createFromFormat('d/m/Y', '01/' . $month)->toDateString();
                        $ew['room_id'] = $room->id;
                        $ew['hostel_id'] = $room->hostel->id;
                        $ew['contract_id'] = $contractId;
                        $feeValue = 1;

                        if ($feeItem->type == HostelFee::ELECTRIC) {
                            $amount = Functions::calculateElectricAmount($ewEnd[$feeItem->id] - $ewStart[$feeItem->id], $room, HostelFee::ELECTRIC, $feeItem->id);
                        } else {
                            $amount = ($ewEnd[$feeItem->id] - $ewStart[$feeItem->id]) * $feeItem->fee;
                        }

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

                    if ($feeItem->type == HostelFee::WATER || $feeItem->type == HostelFee::WATER_BY_CLOCK) {
                        $isWater = 1;

                        if ($ewEnd[$feeItem->id] < $ewStart[$feeItem->id]) {
                            return response([
                                'status' => 0,
                                'message' => 'Chỉ số cuối không được nhỏ hơn chỉ số đầu'
                            ]);
                        }
                        $qtyItem = json_encode([
                            'start' => $ewStart[$feeItem->id],
                            'end' => $ewEnd[$feeItem->id]
                        ]);

                        $ew['end_water'] = $ewEnd[$feeItem->id];
                        $ew['start_water'] = $ewStart[$feeItem->id];
                        $ew['delta_water'] = $ew['end_water'] - $ew['start_water'];
                        $ew['date_action'] = Carbon::createFromFormat('d/m/Y', '01/' . $month)->toDateString();
                        $ew['room_id'] = $room->id;
                        $ew['hostel_id'] = $room->hostel->id;
                        $ew['contract_id'] = $contractId;

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

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

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

                        if (isset($feeDynamics[$feeItem->id])) {
                            $feeValue = Functions::filterInputNumber($feeDynamics[$feeItem->id]);
                            $amount = $feeValue * $qtyItem;
                        }
                    }


                    $name = $feeItem->name;
                    $feeId = $feeItem->id;

                } else {
                    $name = 'Khác';
                }

                MoneyDetail::create([
                    'hostel_id' => $contract->room->hostel->id,
                    'room_id' => $contract->room->id,
                    'name' => $name,
                    'is_electric' => $isElectric,
                    'is_water' => $isWater,
                    'money_info_id' => $moneyInfo->id,
                    'value' => $feeValue,
                    'qty' => $qtyItem,
                    'amount' => $amount,
                    'hostel_fee_id' => $feeId,
                    //'sum_amount'=> $amount,
                    'start_date' => $startTime,
                    'end_date' => $endTime,
                ]);
            }

//            $payload = json_encode([
//                'id' => null,
//                'type' => null
//            ]);
//
//
//            $renters = RenterRoom::join('users', 'renter_rooms.user_id', '=', 'renters.id')
//                ->where('room_id', $contract->room->id)
//                ->get();
//
//            foreach ($renters as $renter)
//            {
//                Notification::create([
//                    'to_user' => $renter->id,
//                    'title' => 'Thông báo từ itro.vn',
//                    'user_id' => auth('backend')->user()->id,
//                    'content' => 'Đã có một hóa đơn mới cho tháng '.Carbon::createFromFormat('d/m/Y', '01/'.$month)->format('m/Y').', phòng '.$contract->room->name,
//                    'payload' => $payload,
//                ]);
//            }

            \DB::commit();

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

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

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

//        if(em)
    }

    public function storeVoucherAll(Request $request)
    {
        $data = $request->all();
        $qty = $request->input('qty');
        $contractId = $request->input('contract_id');
        $discount = $request->input('discount', 0);
        $month = $request->input('month');
        $note = $request->input('note');


        $contract = Contract::find($contractId);

        if (!$contract) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if ($contract->status == Contract::LIQUIDATED) {
            return response([
                'status' => 0,
                'message' => 'Hợp đồng đã được thanh lý'
            ]);
        }

        if (empty($month)) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $sum = 0;
        $qty = $request->input('qty');
        $feeContracts = $request->input('fee-contracts');
        $contractId = $request->input('contract_id');
        $discount = $request->input('discount', 0);
        $ewStart = $request->input('ew-start');
        $ewEnd = $request->input('ew-end');
        $feeDynamics = $request->input('fee-dynamics');

        if (empty($discount)) {
            $discount = 0;
        }

        $contract = Contract::find($contractId);
        $room = $contract->room;

        $sum = 0;

        if (empty($feeContracts)) {
            return response([
                'status' => 0,
                'message' => 'Bạn chưa chọn dịch vụ'
            ]);
        }
        if (is_array($feeContracts)) {
            foreach ($feeContracts as $feeContract) {
                $start = 0;
                $end = 0;
                if (isset($qty[$feeContract])) {
                    $qtyItem = $qty[$feeContract];
                } else {
                    $qtyItem = 1;
                }

                $feeItem = HostelFee::find($feeContract);
                if ($feeItem) {
                    if ($feeItem->type == HostelFee::ELECTRIC || $feeItem->type == HostelFee::WATER) {
                        if (isset($ewStart[$feeItem->id])) {
                            $start = $ewStart[$feeItem->id];
                        }

                        if (isset($ewEnd[$feeItem->id])) {
                            $end = $ewEnd[$feeItem->id];
                        }

                        $amount = Functions::calculateElectricAmount($end - $start, $room, $feeItem->type, $feeItem->id);
                        $sum += $amount;
                    } else if ($feeItem->type == HostelFee::DYNAMIC || $feeItem->type == HostelFee::WATER_DYNAMIC || $feeItem->type == HostelFee::ELECTRIC_DYNAMIC) {
                        if (isset($feeDynamics[$feeItem->id])) {
                            $amount = $qtyItem * Functions::filterInputNumber($feeDynamics[$feeItem->id]);
                            $sum += $amount;
                        }
                    } else if ($feeItem->type == HostelFee::ELECTRIC_BY_CLOCK || $feeItem->type == HostelFee::WATER_BY_CLOCK) {
                        if (isset($ewStart[$feeItem->id])) {
                            $start = $ewStart[$feeItem->id];
                        }

                        if (isset($ewEnd[$feeItem->id])) {
                            $end = $ewEnd[$feeItem->id];
                        }

                        $amount = ($end - $start) * $feeItem->fee;
                        $sum += $amount;
                    } else {
                        $amount = $qtyItem * $feeItem->fee;
                        $sum += $amount;
                    }
                }
            }
        }

        try {

            \DB::beginTransaction();
            try {
                $startTime = Carbon::createFromFormat('d/m/Y', '01/' . $month)->startOfMonth()->startOfDay()->toDateTimeString();
                $endTime = Carbon::createFromFormat('d/m/Y', '01/' . $month)->endOfMonth()->endOfDay()->toDateTimeString();
                $monthCarbon = Carbon::createFromFormat('d/m/Y', '01/' . $month);
            } catch (\Exception $exception) {
                return response([
                    'status' => 0,
                    'message' => 'Dữ liệu ngày tháng phải có định dạng tháng / năm. Ví dụ: 06/2018'
                ]);
            }


//            if ($monthCarbon->month > Carbon::now()->month && $monthCarbon->year >= Carbon::now()->year) {
//
//                return response([
//                    'status' => 0,
//                    'message' => 'Bạn không thể lập kỳ hóa đơn tương lai'
//                ]);
//
//            }

            $item = MoneyInfo::query()->where('room_id', $room->id)
                ->where('type', MoneyInfo::VOUCHER_SERVICE)
                ->validate($contract->id)->whereBetween(
                    'date_action', [$startTime, $endTime]
                )->first();
            $pay = 0;
            $itemId = null;
            $dateAction = Carbon::createFromFormat('d/m/Y', '01/' . $month)->toDateString();
            //dd($item);
            if ($item) {

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

                if ($cntCollectSpend) {
                    return response([
                        'status' => 0,
                        'message' => 'Đã tồn tại hóa đơn được thanh toán trước đó cho tháng ' . $monthCarbon->copy()->format('m/Y') . '. Mã hóa đơn: ' . $item->name . ', mã phiếu thu chi: ' . $cntCollectSpend->code
                    ]);
                }

                $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)->delete();
                MoneyInfo::find($item->id)->delete();
                ElectricWater::query()->whereBetween('date_action', [
                    $startTime,
                    $endTime
                ])
                    ->where('contract_id', $contractId)
                    ->where('room_id', $room->id)->delete();

                $user = Functions::getCurrentUser();

                $desc = '{' . $user->name . '} vừa sửa hóa đơn dịch vụ tháng {' . $monthCarbon->copy()->format('m/Y') . '} cho khách {' . $contract->name . '} phòng {' . $contract->room->name . '} nhà {' . $contract->hostel->name . '}';
                if ($contract->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                    $desc = '{' . $user->name . '} vừa sửa hóa đơn dịch vụ tháng {' . $monthCarbon->copy()->format('m/Y') . '} cho khách {' . $contract->name . '} giường {' . optional($contract->bed)->name . '} phòng {' . $contract->room->name . '} nhà {' . $contract->hostel->name . '}';
                }
                event(new LogAction([
                    'type' => 'update-money-info-service',
                    'user_id' => optional($user)->id,
                    'object_id' => $item->id,
                    'hostel_id' => $contract->hostel_id,
                    'room_id' => $contract->room_id,
                    'desc' => $desc
                ]));

            } else {

            }

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

            if ($sum - $discount - $pay < 0) {
                return response([
                    'status' => 0,
                    'message' => 'Giảm giá không thể vượt quá tổng tiền'
                ]);
            }
            $moneyInfo = MoneyInfo::create([
                'hostel_id' => $contract->room->hostel->id,
                'user_id' => auth('backend')->user()->id,
                'room_id' => $contract->room->id,
                'amount' => $sum,
                'discount' => $discount,
                'pay' => $pay,
                'remain' => $sum - $discount - $pay,
                'date_action' => $dateAction,
                'type' => MoneyInfo::VOUCHER_SERVICE,
                'contract_id' => $contract->id,
                'note' => $note
            ]);

            if (!$item) {
                $user = Functions::getCurrentUser();
                $desc = '{' . optional($user)->name . '}' . ' vừa lập hóa đơn dịch vụ tháng {' . $moneyInfo->date_action->format('m/Y') . '} 
                cho khách {' . $moneyInfo->contract->name . '} phòng {' . $moneyInfo->room->name . '} nhà {' . $moneyInfo->hostel->name . '}';
                if ($moneyInfo->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                    $desc = '{' . optional($user)->name . '}' . ' vừa lập hóa đơn dịch vụ tháng {' . $moneyInfo->date_action->format('m/Y') . '} 
                cho khách {' . $moneyInfo->contract->name . '} giường {' . optional($moneyInfo->contract->bed)->name . '} phòng {' . $moneyInfo->room->name . '} nhà {' . $moneyInfo->hostel->name . '}';
                }

                event(new LogAction([
                    'type' => 'create-money-info-service',
                    'user_id' => optional($user)->id,
                    'object_id' => $moneyInfo->id,
                    'hostel_id' => $moneyInfo->hostel_id,
                    'room_id' => $moneyInfo->room_id,
                    'properties' => $moneyInfo->toArray(),
                    'desc' => $desc
                ]));
            }

            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
                ]);
            }

            if (is_array($feeContracts)) {
                foreach ($feeContracts as $feeContract) {

                    if (isset($qty[$feeContract])) {
                        $qtyItem = $qty[$feeContract];
                    } else {
                        $qtyItem = 1;
                    }

                    $feeItem = HostelFee::find($feeContract);

                    $isElectric = 0;
                    $isWater = 0;
                    $feeValue = 1;
                    $feeId = 0;
                    if ($feeItem) {
                        $feeValue = $feeItem->fee;
                        $amount = $feeValue * $qtyItem;
                        if ($feeItem->type == HostelFee::ELECTRIC || $feeItem->type == HostelFee::ELECTRIC_BY_CLOCK) {
                            $isElectric = 1;
                            if (isset($ewEnd[$feeItem->id]) && isset($ewStart[$feeItem->id])) {
                                if ($ewEnd[$feeItem->id] < $ewStart[$feeItem->id]) {
                                    return response([
                                        'status' => 0,
                                        'message' => 'Chỉ số cuối không được nhỏ hơn chỉ số đầu'
                                    ]);
                                }
                            }
                            $qtyItem = json_encode([
                                'start' => $ewStart[$feeItem->id],
                                'end' => $ewEnd[$feeItem->id]
                            ]);


                            $ew['end_electric'] = $ewEnd[$feeItem->id];
                            $ew['start_electric'] = $ewStart[$feeItem->id];
                            $ew['delta_electric'] = $ew['end_electric'] - $ew['start_electric'];
                            $ew['date_action'] = Carbon::createFromFormat('d/m/Y', '01/' . $month)->toDateString();
                            $ew['room_id'] = $room->id;
                            $ew['hostel_id'] = $room->hostel->id;
                            $ew['contract_id'] = $contractId;
                            $feeValue = 1;
                            if ($feeItem->type == HostelFee::ELECTRIC) {
                                $amount = Functions::calculateElectricAmount($ewEnd[$feeItem->id] - $ewStart[$feeItem->id], $room, HostelFee::ELECTRIC, $feeItem->id);
                            } else {
                                $amount = ($ewEnd[$feeItem->id] - $ewStart[$feeItem->id]) * $feeItem->fee;
                            }

                            $itemEw = ElectricWater::query()->whereBetween('date_action', [
                                $startTime,
                                $endTime
                            ])
                                ->where('contract_id', $contractId)
                                ->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;

                            if ($ewEnd[$feeItem->id] < $ewStart[$feeItem->id]) {
                                return response([
                                    'status' => 0,
                                    'message' => 'Chỉ số cuối không được nhỏ hơn chỉ số đầu'
                                ]);
                            }
                            $qtyItem = json_encode([
                                'start' => $ewStart[$feeItem->id],
                                'end' => $ewEnd[$feeItem->id]
                            ]);

                            $ew['end_water'] = $ewEnd[$feeItem->id];
                            $ew['start_water'] = $ewStart[$feeItem->id];
                            $ew['delta_water'] = $ew['end_water'] - $ew['start_water'];
                            $ew['date_action'] = Carbon::createFromFormat('d/m/Y', '01/' . $month)->toDateString();
                            $ew['room_id'] = $room->id;
                            $ew['hostel_id'] = $room->hostel->id;
                            $ew['contract_id'] = $contractId;

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

                            $itemEw = ElectricWater::query()->whereBetween('date_action', [
                                $startTime,
                                $endTime
                            ])
                                ->where('contract_id', $contractId)
                                ->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) {

                            if (isset($feeDynamics[$feeItem->id])) {
                                $feeValue = Functions::filterInputNumber($feeDynamics[$feeItem->id]);
                                $amount = $feeValue * $qtyItem;
                            }
                        }


                        $name = $feeItem->name;
                        $feeId = $feeItem->id;

                    } else {
                        $name = 'Khác';
                    }

                    MoneyDetail::create([
                        'hostel_id' => $contract->room->hostel->id,
                        'room_id' => $contract->room->id,
                        'name' => $name,
                        'is_electric' => $isElectric,
                        'is_water' => $isWater,
                        'money_info_id' => $moneyInfo->id,
                        'value' => $feeValue,
                        'qty' => $qtyItem,
                        'amount' => $amount,
                        'hostel_fee_id' => $feeId,
                        'start_date' => $startTime,
                        'end_date' => $endTime,
                    ]);
                }
            }


            $payload = json_encode([
                'id' => null,
                'type' => null
            ]);


            $renters = RenterRoom::query()->join('users', 'renter_rooms.user_id', '=', 'users.id')
                ->where('room_id', $contract->room->id)
                ->get();

//            foreach ($renters as $renter) {
//                Notification::create([
//                    'to_user' => $renter->id,
//                    'title' => 'Thông báo từ itro.vn',
//                    'user_id' => auth('backend')->user()->id,
//                    'content' => 'Đã có một hóa đơn mới cho tháng ' . Carbon::createFromFormat('d/m/Y', '01/' . $month)->format('m/Y') . ', phòng ' . $contract->room->name,
//                    'payload' => $payload,
//                ]);
//            }

            \DB::commit();

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

            dd($exception->getMessage() . '|' . $exception->getLine());

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

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

//        if(em)
    }

    public function leave(Request $request)
    {
        if (auth('backend')->user()->cannot('delete-renter')) {
            return response([
                'status' => 2,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }

        $roomId = $request->input('room_id');
        $renterId = $request->input('renter_id');

        $room = Room::find($roomId);


        $checkContract = Contract::query()->where('room_id', $roomId)
            ->where('renter_id', $renterId)
            ->where('status', Contract::VALIDATED)
            ->first();

        if ($checkContract) {
            return response([
                'status' => 2,
                'contract_id' => $checkContract->id
            ]);
        }

        RenterRoom::query()->where('user_id', $renterId)->where('room_id', $roomId)->delete();

        $renter = Renter::query()->where('user_id', $renterId)->where('room_id', $roomId)
            ->latest()
            ->first();
        if ($renter) {
            $renter->update([
                'status' => Renter::LEFT
            ]);
        }

        $isDeleteContract = true;

        if ($room->hostel->type_rent == Hostel::TYPE_RENT_ALL) {
            $changeContractAlready = RenterRoom::query()
                ->where('room_id', $roomId)
                ->whereNotNull('contract_id')
                ->count();
            if ($changeContractAlready) {
                $isDeleteContract = false;
            }
        }

        if ($isDeleteContract) {
            Contract::query()->where('renter_id', $renterId)
                ->where('room_id', $roomId)
                ->delete();
        }

        dispatch(new DeleteRenterConversation($renterId, $roomId));


        $user = Functions::getCurrentUser();
        $desc = '{' . $user->name . '} tác động rời phòng {' . optional($renter)->name . '} khỏi phòng {' . $room->name . '} nhà {' . $room->hostel->name . '}';

        event(new LogAction([
            'type' => 'leave-room',
            'user_id' => optional($user)->id,
            'object_id' => optional($renter)->id,
            'hostel_id' => $room->hostel_id,
            'room_id' => $room->id,
            'properties' => optional($renter)->toArray(),
            'desc' => $desc
        ]));

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

    }

    public function getRemain(Request $request)
    {
        $moneyInfoId = $request->input('money_info_id');
        $moneyInfo = MoneyInfo::find($moneyInfoId);
        if (!$moneyInfo) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        return response([
            'status' => 1,
            'data' => [
                'remain' => number_format($moneyInfo->amount - $moneyInfo->pay - $moneyInfo->discount, 0, '.', '.')
            ]
        ]);
    }

    public function getEmptyRooms(Request $request)
    {
        $hostelId = $request->input('hostel_id');

        if (empty($hostelId)) {
            $ownerId = auth('backend')->user()->id;
            if (auth('backend')->user()->type == User::STAFF) {
                $ownerId = auth('backend')->user()->staff_owner_id;
            }

            $hostelArrs = Hostel::query()->where('owner_id', $ownerId)->pluck('id')->toArray();
        } else {
            $hostelArrs = Hostel::query()->where('id', $hostelId)->pluck('id')->toArray();
        }

        $isShowHostel = true;

        $usedRooms = RenterRoom::query()->whereIn('hostel_id', $hostelArrs)->whereNotNull('user_id')->pluck('room_id')->toArray();
        $rooms = Room::query()->whereIn('hostel_id', $hostelArrs)
            ->whereNotIn('id', array_unique($usedRooms))
            ->with('reserves')
            ->with('beds')
            ->get();
        $roomBeds = Room::query()->select('rooms.*')
            ->whereHas('beds', function ($q) {
                $q->where('room_bed.status', '=', RoomBed::AVAILABLE);
            })
            ->whereIn('rooms.hostel_id', $hostelArrs)
            ->get();

        $rooms = $rooms->merge($roomBeds);

        return response([
            'status' => 1,
            'data' => view('admin2.room.rooms', compact('rooms', 'isShowHostel'))->render(),
            'title' => 'Danh sách phòng trống'
        ]);
    }

    public function getNearEmptyRooms(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $dayRemind = auth('backend')->user()->day_remind_empty_room;

        $ownerId = auth('backend')->user()->id;

        if (auth('backend')->user()->type == User::STAFF) {
            $ownerId = auth('backend')->user()->staff_owner_id;
            $owner = User::find($ownerId);
            $dayRemind = $owner->day_remind_empty_room;
        }

        $isShowHostel = true;

        if (empty($hostelId)) {
            $hostelArrs = Hostel::where('owner_id', $ownerId)->pluck('id')->toArray();
        } else {
            $hostelArrs = Hostel::where('id', $hostelId)->pluck('id')->toArray();
        }

        $roomIds = Contract::query()
            ->whereIn('hostel_id', $hostelArrs)
            ->where('leave_day',  '>=', Carbon::now()->subDay($dayRemind))
            ->where('status', '<>', Contract::LIQUIDATED)
            ->pluck('room_id')
            ->unique()
            ->toArray();

        $rooms = Room::query()->whereIn('id', $roomIds)->get();

        foreach ($rooms as $room) {

            $contracts = Contract::query()
                ->where('room_id', $room->id)
                ->whereNotNull('bed_id')
                ->where('status', '<>', Contract::LIQUIDATED)
                ->where('leave_day',  '>=', Carbon::now()->subDay($dayRemind))
                ->get();

            $room->beds = RoomBed::query()->whereIn('id', $contracts->pluck('bed_id'))->get();
        }

        $isNearEmpty = true;

        return response([
            'status' => 1,
            'data' => view('admin2.room.rooms_near', compact('rooms', 'isNearEmpty', 'isShowHostel'))->render(),
            'title' => 'Danh sách phòng sắp trống'
        ]);
    }

    public function updateRoomBed(Request $request)
    {
        $data = $request->all();
        if (!empty($data['date_available'])) {
            $data['date_available'] = Carbon::createFromFormat('d/m/Y', $data['date_available'])->toDateString();
        }
        $item = RoomBed::find($request->id);
        if ($item) {
            $item->update($data);
            $user = Functions::getCurrentUser();
            $desc = '{' . $user->name . '} đã sửa thông tin giường {' . $item->name . '}, phòng {' . $item->room->name . '}, nhà {' . $item->hostel->name . '}';
            event(new LogAction([
                'type' => 'update-room-bed',
                'user_id' => optional($user)->id,
                'object_id' => $request->id,
                'hostel_id' => $item->hostel_id,
                'room_id' => $item->room_id,
                'properties' => $item->toArray(),
                'desc' => $desc
            ]));
        }
        return response([
            'status' => 1,
            'message' => 'Thành công',
        ]);
    }

    public function deleteRoomBed(Request $request)
    {
        $id = $request->input('id');
        $item = Contract::query()
            ->where('bed_id', $id)
            ->first();
        if ($item) {

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

            $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();
                }

                $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();
                }
            }

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

            if ($hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                RoomBed::query()->where('id', $item->bed_id)->update([
                    'status' => RoomBed::AVAILABLE,
                ]);
            }

            dispatch(new DeleteRenterConversation($item->renter_id, $item->room_id));

            $item->delete();
        }

        $roomBed = RoomBed::find($id);
        if ($roomBed) {

            $user = Functions::getCurrentUser();
            $desc = '{' . optional($user)->name . '} đã xóa giường {' . $roomBed->name . '}, phòng {' . optional($roomBed->room)->name . '}, nhà {' . optional($roomBed->hostel)->name . '}';

            event(new LogAction([
                'type' => 'delete-room-bed',
                'user_id' => optional($user)->id,
                'object_id' => $roomBed->id,
                'hostel_id' => $roomBed->hostel_id,
                'room_id' => $roomBed->room_id,
                'properties' => $roomBed->toArray(),
                'desc' => $desc
            ]));
            $roomBed->delete();
        }

        return response([
            'status' => 1
        ]);
    }

//    public function createBed()
//    {
//        $rooms = Room::query()
//            ->select('*', 'rooms.id as room_id')
//            ->join('hostels', 'rooms.hostel_id', 'hostels.id')
//            ->join('users', 'users.id', 'hostels.owner_id')
//            ->where('hostels.type_rent', Hostel::TYPE_RENT_EVERY)
//            ->whereNull('rooms.deleted_at')
//            ->whereNull('hostels.deleted_at')
//            ->whereNull('users.deleted_at')
//            ->get();
//        $data = $rooms->count();
//        $count = 0;
//        foreach ($rooms as $room) {
//            $count = $count + $room->max_renters;
//            if ($room->max_renters > 0) {
//                for ($i = 1; $i <= $room->max_renters; $i++) {
//                    RoomBed::create([
//                        'name' => 'Giường ' . $i,
//                        'hostel_id' => $room->hostel_id,
//                        'room_id' => $room->room_id,
//                    ]);
//                }
//            }
//        }
//
//        return response([
//            'status' => 1,
//            'message' => 'Thêm dữ liệu giường thành công',
//            'data' => $data,
//            'count_record' => $count,
//        ]);
//
//    }
//
//    public function updateRoomReservations()
//    {
//
//        $rooms = Room::query()
//            ->select('*', 'rooms.id as room_id')
//            ->join('hostels', 'rooms.hostel_id', 'hostels.id')
//            ->join('users', 'users.id', 'hostels.owner_id')
//            ->where('hostels.type_rent', Hostel::TYPE_RENT_EVERY)
//            ->whereNull('rooms.deleted_at')
//            ->whereNull('hostels.deleted_at')
//            ->whereNull('users.deleted_at')
//            ->get();
//
//        $data = [];
//        foreach ($rooms as $room) {
//            $beds = RoomBed::where('room_id', $room->room_id)->get();
//
//            $reservations = RoomReservation::where('room_id', $room->room_id)->get();
//            if ($reservations->count() > 0) {
//                $data[] = $reservations;
//                for ($i = 1; $i <= $reservations->count(); $i++) {
//                    $bed_id = $beds[$i-1]->id;
//                    RoomReservation::where('id', $reservations[$i-1]->id)->update([
//                        'bed_id' => $bed_id,
//                    ]);
//                    RoomBed::find($bed_id)->update([
//                        'status'=> RoomBed::DEPOSIT,
//                    ]);
//                }
//            }
//        }
//
//        return $data;
//    }
//
//    public function updateContracts()
//    {
//        $rooms = Room::query()
//            ->select('*', 'rooms.id as room_id')
//            ->join('hostels', 'rooms.hostel_id', 'hostels.id')
//            ->join('users', 'users.id', 'hostels.owner_id')
//            ->where('hostels.type_rent', Hostel::TYPE_RENT_EVERY)
//            ->whereNull('rooms.deleted_at')
//            ->whereNull('hostels.deleted_at')
//            ->whereNull('users.deleted_at')
//            ->get();
//
//        $data = [];
//        foreach ($rooms as $room) {
//            $beds = RoomBed::where('room_id', $room->room_id)->get();
//
//            $contracts = Contract::where('room_id', $room->room_id)
//                ->where('status','!=', Contract::LIQUIDATED)
//                ->get();
//            if ($contracts->count() > 0) {
//
//                for ($i = 1; $i <= $contracts->count(); $i++) {
//                    $bed_id = $beds[$i-1]->id;
//                    Contract::where('id', $contracts[$i-1]->id)->update([
//                        'bed_id' => $bed_id,
//                    ]);
//                    RoomBed::find($bed_id)->update([
//                        'status'=> RoomBed::UNAVAILABLE,
//                    ]);
//
//                    MoneyInfo::where('contract_id', $contracts[$i-1]->id)->update([
//                        'bed_id' => $bed_id,
//                    ]);
//
//                    $money_infos = MoneyInfo::where('contract_id', $contracts[$i-1]->id)->get();
//                    foreach ($money_infos as $money_info){
//                        Transaction::where('money_info_id', $money_info->id)->update([
//                            'bed_id' =>$bed_id,
//                        ]);
//                    }
//                }
//            }
//        }
//
//        return $data;
//    }

//    public function updateInvoice()
//    {
//        $moneyInfo = MoneyInfo::select('money_infos.*')
//            ->join('hostels', 'hostels.id', '=','money_infos.hostel_id')
//            ->join('contracts','money_infos.contract_id','=','contracts.id')
//            ->where('hostels.type_rent', 0)
//            ->whereNotNull('contracts.bed_id')
//            ->whereNull('money_infos.bed_id')
//            ->whereIn('money_infos.type',[0,1])
//            ->get();
//        foreach ($moneyInfo as $item) {
//
//                $contracts = Contract::find($item->contract_id);
//                if ($contracts) {
//                    $item->update([
//                        'bed_id' => $contracts->bed_id,
//                    ]);
//                }
//
//        }
//        return $moneyInfo->count();
//
//    }

//    public function updateElectricWaterStatitic()
//    {
//        $moneyElectricDetails = MoneyDetail::query()->select('money_details.*','hostel_fees.type')
//        ->leftJoin('hostel_fees', 'money_details.hostel_fee_id', '=', 'hostel_fees.id')
//        ->whereIn('hostel_fees.type',[1,8,9,10])->where('money_details.is_electric',0)
//        ->get();
//        foreach ($moneyElectricDetails as $moneyEDetail){
//            $moneyEDetail->update([
//                'is_electric'=>1,
//            ]);
//        }
//
//        $moneyWaterDetails = MoneyDetail::query()->select('money_details.*','hostel_fees.type')
//            ->leftJoin('hostel_fees', 'money_details.hostel_fee_id', '=', 'hostel_fees.id')
//            ->whereIn('hostel_fees.type',[2,11,12,13])->where('money_details.is_water',0)
//            ->get();
//        foreach ($moneyWaterDetails as $moneyWDetail){
//            $moneyWDetail->update([
//                'is_water'=>1,
//            ]);
//        }
//
//        return 'Updated!';
//
//    }
    public function updateElectricWaterStatitic()
    {
        $moneyElectricDetails = MoneyDetail::query()->select('money_details.*', 'hostel_fees.type')
            ->leftJoin('hostel_fees', 'money_details.hostel_fee_id', '=', 'hostel_fees.id')
            ->whereIn('hostel_fees.type', [
                1,
                8,
                9,
                10
            ])->where('money_details.is_electric', 1)
            ->whereNull('money_details.start_date')
            ->whereNull('money_details.end_date')
            ->get();
        foreach ($moneyElectricDetails as $moneyEDetail) {
            $start_date = Carbon::parse($moneyEDetail->created_at)->startOfMonth()->toDateTimeString();
            $end_date = Carbon::parse($moneyEDetail->created_at)->endOfMonth()->toDateTimeString();
            $moneyEDetail->update([
                'start_date' => $start_date,
                'end_date' => $end_date,
            ]);
        }

        $moneyWaterDetails = MoneyDetail::query()->select('money_details.*', 'hostel_fees.type')
            ->leftJoin('hostel_fees', 'money_details.hostel_fee_id', '=', 'hostel_fees.id')
            ->whereIn('hostel_fees.type', [
                2,
                11,
                12,
                13
            ])->where('money_details.is_water', 1)
            ->whereNull('money_details.start_date')
            ->whereNull('money_details.end_date')
            ->get();
        foreach ($moneyWaterDetails as $moneyWDetail) {
            $start_date = Carbon::parse($moneyWDetail->created_at)->startOfMonth()->toDateTimeString();
            $end_date = Carbon::parse($moneyWDetail->created_at)->endOfMonth()->toDateTimeString();
            $moneyWDetail->update([
                'start_date' => $start_date,
                'end_date' => $end_date,
            ]);
        }

        return 'update tiền điện: ' . $moneyElectricDetails->count() . ' Bản ghi' . '<br>' . 'update tiền nước: ' . $moneyWaterDetails->count() . ' Bản ghi';

    }

    public function editMoneyInfo(Request $request)
    {
        $moneyInfoId = $request->input('money_info_id');
        $item = MoneyInfo::find($moneyInfoId);

        if (!$item) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        $room = $item->room;
        $moneyInfo = clone $item;

        if (in_array($item->type, [MoneyInfo::VOUCHER_CONTRACT, MoneyInfo::VOUCHER_ROOM_PRICE])) {
            $detail = $item->details->first();
            $startDate = Carbon::createFromFormat('Y-m-d', $detail->start_date);
            $endDate = Carbon::createFromFormat('Y-m-d', $detail->end_date);

            return response([
                'status' => 1,
                'data' => view('admin2.room.update_money_info_room', compact('moneyInfo', 'startDate', 'endDate'))->render(),
                'type' => 'room'
            ]);
        } else {
            $isNote = true;

            if ($item->pay > 0) {
                return response([
                    'status' => 0,
                    'message' => 'Hóa đơn đã được thanh toán không thể thay đổi'
                ]);
            }

            $fees = \DB::table('money_details')->where('money_info_id', $item->id)->pluck('hostel_fee_id')->toArray();
            $contract = $item->contract;
            $month = $item->date_action->format('m/Y');

            if ($item->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                $renterId = $contract->renter_id;
                return response([
                    'status' => 1,
                    'data' => view('admin2.room.voucher_table_edit', compact('contract', 'renterId', 'item', 'month', 'isNote'))->render(),
                    'type' => 'service-every'
                ]);
            }

            return response([
                'status' => 1,
                'data' => view('admin2.room.voucher_all_table', compact('room', 'contract', 'fees', 'item', 'month', 'isNote'))->render(),
                'type' => 'service-all'
            ]);
        }
    }

    public function calMoneyInfo(Request $request)
    {
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');
        $moneyInfoId = $request->input('money_info_id');
        $discount = $request->input('discount');
        $valueMoneyInfo = $request->input('value_money_info');
        $discount = Functions::filterInputNumber($discount);
        $valueMoneyInfo = Functions::filterInputNumber($valueMoneyInfo);
        $moneyInfo = MoneyInfo::find($moneyInfoId);
        if (!$moneyInfo) {
            return response([
                'stautus' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        if (empty($startDate) || empty($endDate)) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }


        $startDate = Carbon::createFromFormat('d/m/Y', $startDate);
        $endDate = Carbon::createFromFormat('d/m/Y', $endDate);
        $dayCollect = $moneyInfo->contract->day_collect;
        $cost = $moneyInfo->contract->room_price;

        if (is_numeric($valueMoneyInfo)) {
            $cost = $valueMoneyInfo;
        }
        $oldStartDate = $moneyInfo->details->first()->start_date;
        $oldEndDate = $moneyInfo->details->first()->end_date;
        $currentValue = $moneyInfo->details->first()->value;
        $cal = Functions::calculateMoneyInRange4($startDate->copy(), $endDate->copy(), $cost, $dayCollect, true);
        if ($startDate->copy()->toDateString() == $oldStartDate
            && $endDate->copy()->toDateString() == $oldEndDate
            && $cost == $currentValue) {
            $cal = $moneyInfo->amount;
        }

        if (is_numeric($discount)) {
            $cal -= $discount;
        }

        return response([
            'status' => 1,
            'data' => number_format($cal, 0, '.', '.')
        ]);
    }

    public function updateMoneyInfoRoom(Request $request)
    {
        $data = $request->all();
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');
        $moneyInfoId = $request->input('money_info_id');
        $discount = $request->input('discount');
        $valueMoneyInfo = $request->input('value_money_info');
        $discount = Functions::filterInputNumber($discount);
        $valueMoneyInfo = Functions::filterInputNumber($valueMoneyInfo);
        $note = $request->input('note');
        $moneyInfo = MoneyInfo::find($moneyInfoId);

        if (!$moneyInfo) {
            return response([
                'stautus' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        if ($moneyInfo->pay > 0) {
            return response([
                'status' => 0,
                'message' => 'Hóa đơn đã được thanh toán toàn bộ hoặc một phần. Bạn vui lòng xóa các phiếu thu trước khi cập nhật hóa đơn'
            ]);
        }
        if (empty($startDate) || empty($endDate)) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $startDate = Carbon::createFromFormat('d/m/Y', $startDate);
        $endDate = Carbon::createFromFormat('d/m/Y', $endDate);
        $dayCollect = $moneyInfo->contract->day_collect;
        $cost = $moneyInfo->contract->room_price;
        if (is_numeric($valueMoneyInfo)) {
            $cost = $valueMoneyInfo;
        }
        $oldStartDate = $moneyInfo->details->first()->start_date;
        $oldEndDate = $moneyInfo->details->first()->end_date;
        $currentValue = $moneyInfo->details->first()->value;
        $cal = Functions::calculateMoneyInRange4($startDate->copy(), $endDate->copy(), $cost, $dayCollect, true);
        if ($startDate->copy()->toDateString() == $oldStartDate
            && $endDate->copy()->toDateString() == $oldEndDate
            && $cost == $currentValue) {

            $cal = $moneyInfo->amount;
        }
        $moneyInfo->amount = $cal;
        $moneyInfo->remain = $cal;
        if (is_numeric($discount)) {
            $moneyInfo->discount = $discount;
            $moneyInfo->remain = $cal - $discount;
        }
        $moneyInfo->note = $note;
        $moneyInfo->save();

        $moneyDetail = $moneyInfo->details->first();
        if ($moneyDetail) {
            $name = 'Thu tiền phòng từ ' . $startDate->copy()->format('d/m/Y') . ' đến ' . $endDate->copy()->format('d/m/Y');
            $qty = round($cal / $cost, 2);
            $moneyDetail->start_date = $startDate->copy()->toDateString();
            $moneyDetail->end_date = $endDate->copy()->toDateString();
            if (!empty($moneyDetail->amount)) {
                $moneyDetail->amount = $cal;
            }

            if (is_numeric($cost)) {
                $moneyDetail->value = $cost;
            }

            if (!empty($moneyDetail->sum_amount)) {
                $moneyDetail->sum_amount = $cal;
            }
            $moneyDetail->qty = $qty;
            $moneyDetail->name = $name;
            $moneyDetail->save();

            $moneyInfo->money_info_name = $name;
            $moneyInfo->date_action = $startDate->copy()->toDateString();
            $moneyInfo->save();
        }

        return response([
            'status' => 1
        ]);

    }

    public function checkPaymentStatusMoneyInfo(Request $request)
    {
        $moneyInfoId = $request->input('money_info_id');
        $moneyInfo = MoneyInfo::find($moneyInfoId);
        if (!$moneyInfo) {
            return response([
                'stautus' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        if ($moneyInfo->pay > 0) {
            return response([
                'status' => 0,
                'message' => 'Hóa đơn đã được thanh toán toàn bộ hoặc một phần. Bạn vui lòng xóa các phiếu thu trước khi cập nhật hóa đơn'
            ]);
        }

        return response([
            'status' => 1
        ]);
    }

    public function processMoveItem(Request $request)
    {
        $itemId = $request->input('item_id');
        $hostelId = $request->input('hostel_id');
        $roomId = $request->input('room_id');
        $roomExportId = $request->input('room_export_id');
        $roomExport = Room::find($roomExportId);
        $receiver = $request->input('receiver');
        $mover = $request->input('mover');

        $room = Room::find($roomId);

        $item = Item::find($itemId);

        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if (!$item) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $export = ImportExport::create([
            'item_id' => $item->id,
            'item_type_id' => $item->item_type_id,
            'warehouse_id' => null,
            'import' => 0,
            'export' => 1,
            'type' => Warehouse::EXPORT,
            'user_id' => auth('backend')->user()->id,
            'hostel_id' => $roomExport->hostel->id,
            'room_id' => $roomExportId,
            'receiver' => $receiver,
            'mover' => $mover,
        ]);

        ImportExportItem::create([
            'item_type_id' => $item->item_type_id,
            'item_id' => $itemId,
            'import_export_id' => $export->id,
        ]);

        $import = ImportExport::create([
            'item_id' => $item->id,
            'item_type_id' => $item->item_type_id,
            'warehouse_id' => null,
            'import' => 1,
            'export' => 0,
            'type' => Warehouse::IMPORT,
            'user_id' => auth('backend')->user()->id,
            'hostel_id' => $room->hostel->id,
            'room_id' => $roomId,
            'receiver' => $receiver,
            'mover' => $mover,
        ]);

        ImportExportItem::create([
            'item_type_id' => $item->item_type_id,
            'item_id' => $itemId,
            'import_export_id' => $import->id,
        ]);
        $roomExport->items()->detach($item->id, [
            'mover' => $mover,
            'receiver' => $receiver
        ]);
        $room->items()->attach($item->id, [
            'mover' => $mover,
            'receiver' => $receiver
        ]);

        return response([
            'status' => 1
        ]);
    }


    public function getBedsByRoom(Request $request)
    {
        $roomId = $request->input('room_id');
        $beds = RoomBed::query()
            ->where('room_id', $roomId)
            ->where('status', RoomBed::AVAILABLE)
            ->get();
        return response([
            'status' => 1,
            'data' => view('admin2.contract.select_bed', compact('beds'))->render()
        ]);
    }
}