<?php

namespace App\Http\Controllers\Api\v1;

use App\Components\Functions;
use App\Console\Commands\ReGenerateMoneyInfo;
use App\Events\LogAction;
use App\Http\Middleware\RedirectIfNotAdmin;
use App\Jobs\AddDiscountHostel;
use App\Jobs\CreateHostelConservation;
use App\Jobs\CreateHostelConservationV2;
use App\Jobs\CreateHostelPostCrawl;
use App\Jobs\DeleteHostelConversation;
use App\Jobs\GenerateDynamicLinkHostel;
use App\Jobs\GenerateNextContractInvoice;
use App\Models\Amenity;
use App\Models\CollectSpend;
use App\Models\Contract;
use App\Models\DiscountHostel;
use App\Models\ElectricQuota;
use App\Models\ElectricWater;
use App\Models\Hostel;
use App\Models\HostelFee;
use App\Models\HostelPromotion;
use App\Models\HostelRating;
use App\Models\HostelSchedule;
use App\Models\HostelType;
use App\Models\MoneyInfo;
use App\Models\Policy;
use App\Models\Promotion;
use App\Models\Renter;
use App\Models\RenterBike;
use App\Models\RenterRoom;
use App\Models\Room;
use App\Models\RoomBed;
use App\Models\RoomEw;
use App\Models\RoomFee;
use App\Models\RoomReservation;
use App\Models\RoomType;
use App\Models\StatisticLog;
use App\Models\Transaction;
use App\Models\UserPackage;
use App\Models\UserPackageFindHostel;
use App\Models\WaterQuota;
use App\Models\Wishlist;
use App\Notifications\RemindOwnerWhenRenterRate;
use App\Notifications\SendTextMessage;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use phpDocumentor\Reflection\DocBlock\Description;

class HostelController extends BaseController
{
    //
    public function getByAttribute(Request $request)
    {
        $userId = $this->user->id;
        $limit = $request->input('limit', 5);
        $lastId = $request->input('last_id');
        $items = Hostel::publish()->orderBy('id', 'desc');

        if (!empty($lastId)) {
            $items = $items->where('id', '<', $lastId);
        }

        $items = $items->limit($limit)->get();

        $arr = [];

        foreach ($items as $item) {
            $id = $item->id;
            $name = $item->name;
            $address = $item->address;
            $verified = $item->status_confirm;
            $favorite = Functions::checkFavourite($userId, $item->id);
            $price = Functions::getPriceHostelFrontend3($item);
            $minPrice = $price['smallest'];
            $maxPrice = $price['greatest'];
            $totalRoom = Room::where('hostel_id', $item->id)->count();
            $emptyRoom = Functions::getEmptyRoomHostel($item);
            $area = Functions::getAreaHostelFrontend3($item);
            $minArea = $area['smallest'];
            $maxArea = $area['greatest'];
            $lat = $item->lat;
            $lng = $item->lng;
            $highlightAmenities = Functions::getAmenitiesHostel($item);


            $arr[] = [
                'id' => $id,
                'name' => $name,
                'address' => $address,
                'verified' => $verified,
                'favorite' => $favorite,
                'min_price' => $minPrice,
                'max_price' => $maxPrice,
                'empty_room_count' => $emptyRoom,
                'total_room' => $totalRoom,
                'min_area' => $minArea,
                'max_area' => $maxArea,
                'lat' => $lat,
                'lng' => $lng,
                'highlight_amenities' => $highlightAmenities,
                'background_image' => $item->image
            ];


        }

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

    }

    /**
     * @api {get} /contracts Lấy danh sách HĐ
     * @apiName contracts
     * @apiGroup Hostel
     * @apiDescription Lấy danh sách HĐ
     * @apiParam {String} hostel_id
     * @apiParam {String} room_id
     * @apiParam {String} status
     * @apiParam {String} start_date Gửi lên dạng m/Y
     * @apiParam {String} end_date Gửi lên dạng m/Y
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getContracts(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $roomId = $request->input('room_id');
        $status = $request->input('status');
        $startTime = $request->input('start_date');
        $endTime = $request->input('end_date');
        $limit = $request->input('limit', 10);
        $offset = $request->input('offset', 0);
        $user = $this->user;

        $contracts = Contract::query()
            ->has('renter')
            ->when(!empty($hostelId), function ($q) use ($hostelId) {
                $q->where('hostel_id', $hostelId);
            }, function ($q) use ($user) {
                if ($user->type == User::STAFF) {
                    $hostelArr = Functions::getHostelArrStaffApi($this->user);
                } else {
                    $hostelArr = Hostel::query()
                        ->where('owner_id', $user->id)
                        ->pluck('id')
                        ->toArray();
                }

                $q->whereIn('hostel_id', $hostelArr);
            })
            ->when(!empty($roomId), function ($q) use ($roomId) {

                $q->where('room_id', $roomId);
            });

        if (isset($status)) {
            if ($status == Contract::EXPIRE) {
                $contracts = $contracts->where('end_date', '<', Carbon::now())
                    ->where('status', '<>', Contract::LIQUIDATED);
            } else {
                $contracts = $contracts->where('status', $status);
            }
        }

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

        if (empty($startTime) && !empty($endTime)) {
            $endTime = Carbon::createFromFormat('d/m/Y', '01/' . $endTime)->endOfMonth()->toDateString();
            $contracts = $contracts->where('end_date', '>=', $endTime);
        }

        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();
            $contracts = $contracts->where(function ($q) use ($startTime, $endTime) {
                $q->orWhereBetween('start_date', [
                    $startTime,
                    $endTime
                ])
                    ->orWhereBetween('end_date', [
                        $startTime,
                        $endTime
                    ])
                    ->orWhere('start_date', '<=', $startTime)
                    ->orWhere('end_date', '>=', $endTime);
            });
        }
        $contracts = $contracts->orderBy('contracts.created_at', 'desc');
        $totalContracts = clone $contracts;
        $total = $totalContracts->count();
        $contracts = $contracts->limit($limit)->offset($offset)->get()
            ->map(function ($contract) {
                $renters = RenterRoom::has('account')
                    ->where(function ($q) use ($contract) {
                        $q->orWhere('contract_id', $contract->id);
                        $q->orWhere('room_contract_id', $contract->id);
                    })
                    ->get();

                $users = $renters->map(function ($renter) {
                    return [
                        'name' => $renter->account->name,
                        'phone' => $renter->account->phone,
                        'image' => $renter->account->image
                    ];
                });

                $bed = null;
                if ($contract->bed) {
                    $bed = [
                        'id' => $contract->bed->id,
                        'name' => $contract->bed->name
                    ];
                }
                return [
                    'code' => $contract->code,
                    'name' => $contract->name,
                    'room' => $contract->room->name,
                    'hostel' => $contract->room->hostel->name,
                    'start_date' => optional($contract->start_date)->format('d/m/Y'),
                    'end_date' => optional($contract->end_date)->format('d/m/Y'),
                    'status' => $contract->status,
                    'id' => $contract->id,
                    'room_price' => $contract->room_price,
                    'deposit' => $contract->deposit,
                    'period' => $contract->period,
                    'users' => $users,
                    'bed' => $bed,

                ];
            });

        return response([
            'status' => 1,
            'data' => [
                'total' => $total,
                'values' => $contracts
            ]
        ]);


    }


    /**
     * @api {post} /delete Xóa nhà trọ
     * @apiName delete
     * @apiGroup Hostel
     * @apiParam {String} id
     * @apiDescription Api Xóa nhà trọ
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function destroy(Request $request)
    {
        $id = $request->input('id');
        $hostel = Hostel::find($id);
        if ($hostel) {

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

            dispatch(new DeleteHostelConversation($hostel->id));

            $rooms = Room::where('hostel_id', $hostel->id)->get();
            foreach ($rooms as $room) {
                Contract::where('room_id', $room->id)->delete();
                $moneyInfos = MoneyInfo::where('room_id', $room->id)->get();
                foreach ($moneyInfos as $moneyInfo) {
                    Transaction::where('money_info_id', $moneyInfo->id)->delete();
                    MoneyInfo::where('id', $moneyInfo->id)->delete();
                    $moneyInfo->delete();
                }

                $room->delete();
            }
            CollectSpend::where('hostel_id', $hostel->id)->delete();
            StatisticLog::where('hostel_id', $hostel->id)->delete();

            $hostel->delete();
        }

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

    public function removeWishlist(Request $request)
    {
        $userId = $this->user->id;
        $hostelId = $request->input('hostel_id');

        Wishlist::where('user_id', $userId)
            ->where('hostel_id', $hostelId)
            ->delete();

        return response([
            'status' => 1,
            'message' => 'Xóa thành công'
        ]);

    }

    public function addWishlist(Request $request)
    {
        if (!$this->user) {
            return response([
                'status' => 0,
                'message' => 'Bạn cần đăng nhập trước'
            ]);
        }
        $userId = $this->user->id;
        $hostelId = $request->input('hostel_id');

        $cnt = Wishlist::where('user_id', $userId)
            ->where('hostel_id', $hostelId)->count();

        if ($cnt == 0) {

            Wishlist::create([
                'user_id' => $userId,
                'hostel_id' => $hostelId
            ]);
        }

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

    public function getWishlist(Request $request)
    {
        $userId = $this->user->id;

        $items = Hostel::select('hostels.*')
            ->join('wishlists', 'hostels.id', '=', 'wishlists.hostel_id')
            ->where('wishlists.user_id', $userId)
            ->get();

        $arr = [];

        foreach ($items as $item) {
            $id = $item->id;
            $name = $item->name;
            $address = $item->address;
            $verified = $item->status_confirm;
            $favorite = Functions::checkFavourite($userId, $item->id);
            $price = Functions::getPriceHostelFrontend3($item);
            $minPrice = $price['smallest'];
            $maxPrice = $price['greatest'];
            $totalRoom = Room::where('hostel_id', $item->id)->count();
            $emptyRoom = Functions::getEmptyRoomHostel($item);
            $area = Functions::getAreaHostelFrontend3($item);
            $minArea = $area['smallest'];
            $maxArea = $area['greatest'];
            $lat = $item->lat;
            $lng = $item->lng;
            $highlightAmenities = Functions::getAmenitiesHostel($item);


            $arr[] = [
                'id' => $id,
                'name' => $name,
                'address' => $address,
                'verified' => $verified,
                'favorite' => $favorite,
                'min_price' => $minPrice,
                'max_price' => $maxPrice,
                'empty_room_count' => $emptyRoom,
                'total_room' => $totalRoom,
                'min_area' => $minArea,
                'max_area' => $maxArea,
                'lat' => $lat,
                'lng' => $lng,
                'highlight_amenities' => $highlightAmenities,
                'background_image' => $item->image
            ];


        }

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

    public function getHostelsByUser(Request $request)
    {
        $userId = $this->user->id;
        //$userId = 3;
        $provinceId = $request->input('province_id');
        $districtId = $request->input('district_id');
        $hostels = Hostel::query()->where('owner_id', $userId);

        if ($this->user->type == User::STAFF) {
            $hostels = Hostel::query()->where('owner_id', $this->user->staff_owner_id);
            $hostelArrs = Functions::getHostelArrStaffApi($this->user);
            $hostels = $hostels->whereIn('id', $hostelArrs);
        }

        $phone = $this->user->phone;


        if ($this->user->is_agent == true) {
            $owners = UserPackageFindHostel::query()
                ->where('package_id', 3)
                ->pluck('user_id')
                ->toArray();

            if (!empty($owners)) {
                $hostels = Hostel::query()
                    ->whereIn('owner_id', $owners);
            }

            $agentDistricts = $this->user->agentDistricts->pluck('districtid')->toArray();
            if (!empty($agentDistricts)) {
                $hostels = $hostels->whereIn('district_id', $agentDistricts);
            }
        }

        $hostels = $hostels->when(!empty($provinceId), function ($q) use ($provinceId) {
            $q->where('province_id', $provinceId);
        })->when(!empty($districtId), function ($q) use ($districtId) {
            $q->whereIn('district_id', $districtId);
        });

        $hostels = $hostels->get();

        foreach ($hostels as $hostel) {
            $numberRenter = 0;
            $numberRooms = Room::where('hostel_id', $hostel->id)->count();
            $numberRenter = RenterRoom::where('hostel_id', $hostel->id)->count();
            $hostel->number_renter = $numberRenter;
            unset($hostel->number_room);
            $hostel->number_room = $numberRooms;
            $hostel->number_rooms = $numberRooms;
            $numberRooms = Room::where('hostel_id', $hostel->id)->count();

            $usedRooms = RenterRoom::query()->where('hostel_id', $hostel->id)
                ->whereNotNull('user_id')->groupBy('room_id')
                ->get()
                ->count();

            if ($hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                $numberBeds = Room::where('hostel_id', $hostel->id)->sum('max_renters');
                $usedBeds = RenterRoom::where('hostel_id', $hostel->id)
                    ->count();
                $hostel->number_empty_bed = $numberBeds - $usedBeds;

            }

            $numberEmptyRooms = $numberRooms - $usedRooms;

            $hostel->number_empty_room = $numberEmptyRooms;
            $hostel->number_empty_rooms = $numberEmptyRooms;
            $hostel->number_fees = HostelFee::query()
                ->where('hostel_id', $hostel->id)
                ->count();
            $hostel->number_contracts = Contract::query()
                ->where('hostel_id', $hostel->id)
                ->where('status', '<>', Contract::LIQUIDATED)
                ->count();
        }

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

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

        $amenities = Amenity::where('type', Amenity::AMENITY)->whereIn('user_id', [0, $this->user->id])->get();

        if (!empty($hostelId)) {
            $hostel = Hostel::find($hostelId);
            $amenities = $hostel->amenities2;
        }

        foreach ($amenities as $amenity) {
            $amenity->mobile_image = '/files/' . $amenity->mobile_image;
            $amenity->web_image = '/files/' . $amenity->web_image;
        }

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

    }

    public function getPolicies()
    {
        $amenities = Amenity::where('type', Amenity::POLICY)->whereIn('user_id', [0, $this->user->id])->get();
        foreach ($amenities as $amenity) {
            $amenity->mobile_image = '/files/' . $amenity->mobile_image;
            $amenity->web_image = '/files/' . $amenity->web_image;
        }

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

    }

    /**
     * @api {get} /type Lấy loại nhà trọ
     * @apiName type
     * @apiGroup Hostel
     * @apiDescription Lấy loại nhà trọ
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getHostelType()
    {
        $roomTypes = HostelType::all();

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

    public function contacts(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $owner = null;
        $hostel = null;

        $users = User::select(\DB::raw('users.id, users.type, users.name, users.image, 
        users.phone, users.address, hostels.name as hostel_name, rooms.name as room_name'))
            ->join('renter_rooms', 'users.id', '=', 'renter_rooms.user_id')
            ->join('rooms', 'renter_rooms.room_id', '=', 'rooms.id')
            ->join('hostels', 'rooms.hostel_id', '=', 'hostels.id')
            ->where('users.id', '<>', $this->user->id);

        if ($this->user->type == User::OWNER) {
            $users = $users->where('users.type', '<>', User::OWNER);
        }

        if (!empty($hostelId)) {
            $users = $users->where('rooms.hostel_id', $hostelId);
            $hostel = Hostel::find($hostelId);
        } else {
            $hostels = Hostel::where('owner_id', $this->user->id)->pluck('id')->toArray();
            $users = $users->whereIn('rooms.hostel_id', $hostels);
        }

        $users = $users->get();

        if (!empty($hostelId)) {
            $hostel = Hostel::find($hostelId);
            if ($hostel->owner) {
                $owner = $hostel->owner;

            }
        } else {
            $owner = $this->user;
        }

        if (!empty($owner) && !empty($hostel)) {

            if ($this->user->type != User::OWNER) {
                $users->push([
                    'id' => $owner->id,
                    'type' => $owner->type,
                    'name' => $owner->first_name . ' ' . $owner->last_name,
                    'image' => $owner->image,
                    'phone' => $owner->phone,
                    'address' => $owner->address,
                    'hostel_name' => $hostel->name,
                    'room_name' => null

                ]);
            }
        }

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

    /**
     * @api {get} /fees Lấy phí nhà trọ
     * @apiName fees
     * @apiGroup Hostel
     * @apiDescription Lấy danh sách phí nhà trọ. Các loại type: 1 là điện, 2 là nước, 3 là phương tiện, 4 là vệ sinh, 5 là quản lý, 6 là khác, 7 là biến động
     * @apiParam {String} hostel_id
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */


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

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

        if (!$hostel) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        $userId = $this->user->id;
        $items = HostelFee::orderBy('id', 'desc');
        $items = $items->where('hostel_id', $hostelId)->orderBy('id', 'desc')->get();

        $retVal = [];
        foreach ($items as $item) {
            if ($item->type == HostelFee::ELECTRIC) {
                $retVal[] = [
                    'id' => $item->id,
                    'fee' => 0,
                    'name' => $item->name,
                    'type' => 'electric',
                    'unit' => $item->unit,
                    'new_type' => $item->type
                ];
            } else if ($item->type == HostelFee::WATER) {
                $retVal[] = [
                    'id' => $item->id,
                    'fee' => 0,
                    'name' => $item->name,
                    'type' => 'water',
                    'unit' => $item->unit,
                    'new_type' => $item->type
                ];
            } else {
                $retVal[] = [
                    'id' => $item->id,
                    'fee' => $item->fee,
                    'name' => $item->name,
                    'type' => 'other',
                    'unit' => $item->unit,
                    'new_type' => $item->type
                ];
            }
        }

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

    }


    /**
     * @api {post} /update-fee  Cập nhật phí dịch vụ
     * @apiName update-fee
     * @apiGroup Hostel
     * @apiDescription Api Cập nhật phí dịch vụ
     * @apiParam {String} type
     * @apiParam {String} fee Số tiền dịch vụ
     * @apiParam {String} hostel_id
     * @apiParam {String} name
     * @apiParam {String} fee_id
     *
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function updateFee(Request $request)
    {
        $feeId = $request->input('fee_id');
        $type = $request->input('type');
        $fee = $request->input('fee');
        $hostelId = $request->input('hostel_id');
        $feeName = $request->input('name');

        if ($type == HostelFee::ELECTRIC) {
            $unit = 'Đồng/Kwh';
        } else if ($type == HostelFee::WATER) {
            $unit = 'Đồng/Khối';
        } else if ($type == HostelFee::VEHICLE) {
            $unit = 'Đồng/Chiếc/Tháng';
        } else if ($type == HostelFee::WATER_BY_CLOCK) {
            $unit = 'Đồng/Khối';
        } else if ($type == HostelFee::WATER_BY_PEOPLE) {
            $unit = 'Đồng/Người';
        } else if ($type == HostelFee::ELECTRIC_BY_CLOCK) {
            $unit = 'Đồng/KwH';
        } else if ($type == HostelFee::ELECTRIC_BY_PEOPLE) {
            $unit = 'Đồng/Người';
        } else {
            $unit = 'Đồng/Tháng';
        }

//        if ($type == HostelFee::WATER || $type == HostelFee::ELECTRIC) {
//            $check = HostelFee::query()
//                ->where('type', $type)
//                ->where('hostel_id', $hostelId)
//                ->count();
//            if ($check) {
//                return response([
//                    'status' => 0,
//                    'message' => 'Bạn không thể thiết lập 2 giá điện nước'
//                ]);
//            }
//        }

        if ($type != HostelFee::DYNAMIC && $type != HostelFee::ELECTRIC && $type != HostelFee::WATER
            && $type != HostelFee::ELECTRIC_DYNAMIC && $type != HostelFee::WATER_DYNAMIC
        ) {
            if (empty($fee)) {
                return response([
                    'status' => 0,
                    'message' => 'Không được bỏ trống đơn giá'
                ]);
            }
        }

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

        $item = HostelFee::find($feeId);
        if($item) {
            $item->name = $feeName;
            $item->unit = $unit;
            $item->fee = $fee;
            $item->type = $type;
            $item->hostel_id = $hostelId;
            $item->save();
        }
        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);

    }

    /**
     * @api {post} /delete-fee Xóa dịch vụ
     * @apiName delete-fee
     * @apiGroup Hostel
     * @apiDescription Api Xóa dịch vụ
     * @apiParam {String} fee_id
     *
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function deleteFee(Request $request)
    {
        $feeId = $request->input('fee_id');

        $item = HostelFee::find($feeId);

        if ($item) {
            $item->delete();

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

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

    /**
     * @api {get} /room-types Lấy loại phòng nhà trọ
     * @apiName room-types
     * @apiGroup Hostel
     * @apiDescription Lấy loại phòng nhà trọ
     * @apiParam {String} hostel_id
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function getRoomType(Request $request)
    {
        $userId = $this->user->id;
        $hostelId = $request->input('hostel_id');

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

        foreach ($roomTypes as $roomType) {
            $images = json_decode($roomType->images, true);
            if (is_array($images)) {
                foreach ($images as $key => $image) {
                    $images[$key] = '/files/' . $image;
                }
                $roomType->images = $images;
                $roomType->features = json_decode($roomType->features, true);
            }
        }

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

    public function getRenters(Request $request)
    {
        $id = $request->input('hostel_id');
        $renters = RenterRoom::select(\DB::raw('users.first_name, users.last_name, renter_rooms.room_id, users.name,users.id, users.id_number,
        users.image, users.address, users.phone, users.birthday, renter_rooms.date_joined as date_joined,
        renter_rooms.residence_status, renter_rooms.date_end_residence, renter_rooms.user_id as renter_id'))
            ->join('users', 'renter_rooms.user_id', '=', 'users.id')
            ->where('renter_rooms.hostel_id', $id)->orderBy('renter_rooms.created_at', 'desc')->get();

        foreach ($renters as $renter) {
            if (!empty($renter->image)) {
                $renter->image = '/files/' . $renter->image;
            }

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

            if (empty($renter->name)) {
                $renter->name = $renter->first_name . ' ' . $renter->last_name;
            }
            if (!empty($renter->date_joined)) {
                $renter->date_joined->format('d/m/Y');
            }
            if (!empty($renter->date_end_residence)) {
                $renter->date_end_residence->format('d/m/Y');
            }

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

            if ($room) {
                $renter->room_name = $room->name;
                $renter->room_id = $room->id;
            }
        }

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

    /**
     * @api {get} /room-not-ew Lấy phòng chưa chốt điện nước
     * @apiName room-not-ew
     * @apiGroup Hostel
     * @apiDescription Lấy phòng chưa chốt điện nước
     * @apiParam {String} hostel_id
     * @apiParam {String} month
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getRoomsNotEw(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $month = $request->input('month');

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

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

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

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

        $rooms = Room::query()->where('hostel_id', $hostelId);

        $month = '01/' . $month;

        $startDate = Carbon::createFromFormat('d/m/Y', $month)->startOfMonth()->toDateTimeString();
        $endDate = Carbon::createFromFormat('d/m/Y', $month)->endOfMonth()->toDateTimeString();

        $contractEws = ElectricWater::query()
            ->whereBetween('date_action', [
                $startDate,
                $endDate
            ])
            ->where('hostel_id', $hostelId)
            ->pluck('contract_id')
            ->unique()
            ->toArray();
        //dd($contractEws);
        $roomsAllow = Contract::query()
            ->when(!empty($contractEws), function ($q) use ($contractEws) {
                $q->whereNotIn('id', $contractEws);
            })
            ->where('hostel_id', $hostelId)
            ->where('status', '<>', Contract::LIQUIDATED)
            ->pluck('room_id')
            ->unique()
            ->toArray();
        $roomUser = RenterRoom::query()
            ->where('hostel_id', $hostelId)
            ->whereNotNull('user_id')
            ->pluck('room_id')
            ->toArray();

        $roomUser = array_unique($roomUser);
        $rooms = $rooms->whereIn('id', $roomsAllow);
        if (!empty($roomUser)) {
            $rooms = $rooms->whereIn('id', $roomUser);
        }

        $rooms = $rooms->get()
            ->map(function ($item) {
                $arr = $item->toArray();
                $arr['hostel_name'] = $item->hostel->name;

                return $arr;
            });

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

    /**
     * @api {get} /room-not-payment Lấy phòng chưa thanh toán hết
     * @apiName room-not-payment
     * @apiGroup Hostel
     * @apiDescription Lấy phòng chưa thanh toán hết
     * @apiParam {String} hostel_id
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getRoomsNotPayment(Request $request)
    {
        $hostelId = $request->input('hostel_id');

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

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

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

        $roomsNotPayment = MoneyInfo::select(\DB::raw('SUM(Remaining) AS remain_check, room_id'))
            ->having('remain_check', '>', 0)
            ->where('hostel_id', $hostelId)
            ->groupBy('room_id')->pluck('room_id')->toArray();

        $rooms = Room::where('hostel_id', $hostelId)->whereIn('id', $roomsNotPayment);

        $rooms = $rooms->get();

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

    /**
     * @api {get} /room-by-block Lấy phòng theo block
     * @apiName room-by-block
     * @apiGroup Hostel
     * @apiDescription Lấy phòng theo block
     * @apiParam {String} hostel_id
     * @apiParam {String} month
     * @apiParam {String} type
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

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

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

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

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

        $blockNames = Room::query()
            ->where('hostel_id', $hostelId)
            ->groupBy('block_group')
            ->pluck('block_group')
            ->toArray();

        $retVal = [];

        foreach ($blockNames as $blockName) {
            $roomItems = Room::query()
                ->where('block_group', $blockName)
                ->where('hostel_id', $hostelId)
                ->get();

            if ($isEmptyInput == 1) {
                $roomRenters = RenterRoom::query()
                    ->whereIn('room_id', $roomItems->pluck('id')->toArray())
                    ->pluck('room_id')
                    ->toArray();

                $roomRenters = array_unique($roomRenters);
                $rooms = Room::query()
                    ->where('block_group', $blockName)
                    ->whereIn('id', $roomRenters)
                    ->with('hostel')
                    ->get();

            } else if ($isEmptyInput == 2) {
                $rooms = collect([]);
                $hostelId = $hostel->id;
                if ($hostel->type_rent == Hostel::TYPE_RENT_ALL) {

                    $roomRenters = RenterRoom::query()
                        ->where('hostel_id', $hostelId)
                        ->pluck('room_id')->toArray();
                    $roomRenters = array_unique($roomRenters);
                    $rooms = $rooms->merge(Room::where('hostel_id', $hostelId)
                        ->where('block_group', $blockName)
                        ->whereNotIn('id', $roomRenters)
                        ->with('hostel')
                        ->get());

                } else {
                    $roomArrs = [];
                    $roomItems = Room::query()
                        ->where('hostel_id', $hostel->id)
                        ->where('block_group', $blockName)
                        ->get();
                    foreach ($roomItems as $roomItem) {
                        $numberRenter = RenterRoom::where('room_id', $roomItem->id)->count();
                        $maxRenter = $roomItem->max_renters;
                        if ($numberRenter < $maxRenter) {
                            $roomArrs[] = $roomItem->id;
                        }
                    }
                    $rooms = $rooms->merge(Room::query()
                        ->whereIn('id', $roomArrs)
                        ->where('hostel_id', $hostelId)
                        ->where('block_group', $blockName)
                        ->with('hostel')
                        ->get());
                }


            } else if ($isEmptyInput == 4) {
                $rooms = Room::query()
                    ->where('hostel_id', $hostelId)
                    ->with('hostel')
                    ->where('block_group', $blockName)
                    ->has('reserves')
                    ->get();

            } else {
                $rooms = Room::query()
                    ->where('block_group', $blockName)
                    ->where('hostel_id', $hostelId)
                    ->get();
            }
            foreach ($rooms as $room) {
                $imageArr = [];
                $currentRenter = Functions::getCurrentRenter($room);
                $room->status_text = $room->status;
                $room->type_text = $room->type;
                if ($currentRenter) {
                    $room->current_renter = $currentRenter->name;
                    $room->current_renter_phone = $currentRenter->phone;
                }
                $room->number_renters = Functions::getNumberRenter($room->id);
                $isEmpty = Functions::ifEmptyRoom($room);
                $room->empty = ($isEmpty > 0) ? false : true;
                $isReserve = false;
                $reserveData = null;
                if (!$isEmpty) {
                    $isReserveC = Functions::checkReserve($room);
                    if ($isReserveC) {
                        $isReserve = true;
                        $reserveData = RoomReservation::where('room_id', $room->id)->first();
                    }
                }

                $room->is_reserve = $isReserve;
                $room->reserve_data = $reserveData;
                $room->can_add = Functions::checkAddRenter($room);

                $room->number_bike = RenterBike::where('room_id', $room->id)->count();
                $images = \DB::table('room_images')->where('room_id', $room->id)->get();
                foreach ($images as $image) {
                    $imageArr[] = '/files/' . $image->image;
                }
                $room->images = $imageArr;

                $dayLeave = null;
                $dateEndContract = null;
                if ($room->hostel->type_rent == Hostel::TYPE_RENT_ALL) {
                    $contract = Contract::query()->where('room_id', $room->id)
                        ->latest()
                        ->first();
                    if ($contract) {
                        if ($contract->leave_day) {
                            $dayLeave = $contract->leave_day->format('d/m/Y');
                        }

                        if ($contract->date_end_contract) {
                            $dateEndContract = Carbon::createFromFormat('Y-m-d', $contract->date_end_contract)->format('d/m/Y');
                        }
                    }
                }

                $room->leave_day = $dayLeave;
                $room->date_end_contract = $dateEndContract;

            }

            if (empty($blockName)) {
                $blockName .= ' ';
            }
            $retVal[$blockName] = $rooms;
        }

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

    /**
     * @api {get} /room-not-voucher Lấy phòng chưa lập hóa đơn dịch vụ
     * @apiName room-not-voucher
     * @apiGroup Hostel
     * @apiDescription Lấy phòng chưa lập hóa đơn dịch vụ
     * @apiParam {String} hostel_id
     * @apiParam {String} month
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getRoomNotVoucher(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $month = $request->input('month');

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

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

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

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

        $startDate = Carbon::createFromFormat('d/m/Y', '01/' . $month)->startOfDay()->startOfMonth()->toDateTimeString();
        $endDate = Carbon::createFromFormat('d/m/Y', '01/' . $month)->endOfDay()->endOfMonth()->toDateTimeString();

        if ($hostel->type_rent == Hostel::TYPE_RENT_ALL) {
            $roomVoucher = MoneyInfo::query()->where('hostel_id', $hostelId)->where('type', MoneyInfo::VOUCHER_SERVICE)
                ->whereHas('contract', function ($q) {
                    $q->where('status', '<>', Contract::LIQUIDATED);
                })
                ->whereBetween('date_action', [$startDate, $endDate])
                ->pluck('room_id')
                ->toArray();
        } else {
            $roomVoucher = Room::query()->select(\DB::raw('rooms.id,
	(
		SELECT
			count(*)
		FROM
			`contracts`
		WHERE
			`contracts`.`status` <> ' . Contract::LIQUIDATED . '
		AND `rooms`.`id` = `contracts`.`room_id`
	) AS `cnt_contracts`,
	(
		SELECT
			count(*)
		FROM
			`money_infos`
		WHERE
			`rooms`.`id` = `money_infos`.`room_id`
		AND `money_infos`.`date_action` BETWEEN "' . $startDate . '"
		AND "' . $endDate . '"
		AND `money_infos`.`deleted_at` IS NULL
		AND `money_infos`.`type` = ' . MoneyInfo::VOUCHER_SERVICE . '
	) AS `cnt_money_infos`'))->where('rooms.hostel_id', $hostelId)->having(\DB::raw('`cnt_money_infos` >= `cnt_contracts`'))
                ->pluck('id')->toArray();
        }


        $roomRenters = RenterRoom::query()->where('hostel_id', $hostelId)->pluck('room_id')->toArray();
        $roomRenters = array_unique($roomRenters);

        $rooms = Room::query()->where('hostel_id', $hostelId)->whereNotIn('id', array_unique($roomVoucher))->whereIn('id', $roomRenters)->get();

        foreach ($rooms as $room) {
            $currentRenter = Functions::getCurrentRenter($room);
            $room->status_text = $room->status;
            $room->type_text = $room->type;
            if ($currentRenter) {
                $room->current_renter = $currentRenter->name;
                $room->current_renter_phone = $currentRenter->phone;
            }
            $room->number_renters = Functions::getNumberRenter($room->id);
            $isEmpty = Functions::ifEmptyRoom($room);
            $room->is_empty = ($isEmpty > 0) ? true : false;
            $isReserve = false;
            if (!$isEmpty) {
                $isReserveC = Functions::checkReserve($room);
                if ($isReserveC) {
                    $isReserve = true;
                }
            }

            $room->is_reserve = $isReserve;
            $room->can_add = Functions::checkAddRenter($room);

        }

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

    /**
     * @api {get} /room-near-empty Lấy phòng sắp trống
     * @apiName room-near-empty
     * @apiGroup Hostel
     * @apiDescription Lấy phòng sắp trống
     * @apiParam {String} hostel_id
     * @apiParam {String} start_date
     * @apiParam {String} end_date
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getRoomNearEmpty(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');

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

        if (!empty($startDate)) {
            $startDate = Carbon::createFromFormat('d/m/Y', $startDate);
        }

        if (!empty($endDate)) {
            $endDate = Carbon::createFromFormat('d/m/Y', $endDate);
        }

        if (!empty($hostelId)) {
            $rooms = Room::where('hostel_id', $hostelId);
        } else {
            $hostelArrs = Hostel::where('owner_id', $owner->id)->pluck('id')->toArray();
            $rooms = Room::whereIn('hostel_id', $hostelArrs);

        }

        if (empty($startDate) && empty($endDate)) {
            $rooms = $rooms->where('date_available', '>=', Carbon::now()->subDay($dayRemind));
        } else {
            if (!empty($startDate)) {
                $rooms = $rooms->where('date_available', '>=', $startDate->copy()->toDateString());
            }

            if (!empty($endDate)) {
                $rooms = $rooms->where('date_available', '<=', $endDate->copy()->toDateString());
            }
        }

        $rooms = $rooms->get();

        foreach ($rooms as $room) {
            $currentRenter = Functions::getCurrentRenter($room);
            $room->status_text = $room->status;
            $room->type_text = $room->type;
            if ($currentRenter) {
                $room->current_renter = $currentRenter->name;
                $room->current_renter_phone = $currentRenter->phone;
            }
            $room->number_renters = Functions::getNumberRenter($room->id);
            $isEmpty = Functions::ifEmptyRoom($room);
            $room->is_empty = ($isEmpty > 0) ? true : false;
            $isReserve = false;
            if (!$isEmpty) {
                $isReserveC = Functions::checkReserve($room);
                if ($isReserveC) {
                    $isReserve = true;
                }
            }

            $room->is_reserve = $isReserve;
            $room->can_add = Functions::checkAddRenter($room);

        }

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

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

        $cntBed = 0;

        if (!empty($hostelId)) {
            $hostels = Hostel::query()->where('id', $hostelId);
        } else {
            $ownerId = $this->user->id;
            if ($this->user->type == User::STAFF) {
                $ownerId = $this->user->staff_owner_id;
                $hostelArr = Functions::getHostelArrStaffApi($this->user);
                $hostels = Hostel::query()->where('owner_id', $ownerId)->whereIn('id', $hostelArr);
            } else {
                $hostels = Hostel::query()->where('owner_id', $ownerId);
            }
        }

        $hostelArrs = $hostels->pluck('id')->toArray();

        $numberEmptyBed = 0;


        if ($isEmpty == 1) {
            $roomRenters = RenterRoom::query()->whereIn('hostel_id', $hostelArrs)->pluck('room_id')->toArray();
            $roomRenters = array_unique($roomRenters);
            $rooms = Room::query()
                ->whereIn('hostel_id', $hostelArrs)
                ->whereIn('id', $roomRenters)
                ->with('hostel')
                ->get();

        } else if ($isEmpty == 2) {
            $rooms = collect([]);
            foreach ($hostels->get() as $hostel) {
                $hostelId = $hostel->id;
                if ($hostel->type_rent == Hostel::TYPE_RENT_ALL) {

                    $roomRenters = RenterRoom::where('hostel_id', $hostelId)->pluck('room_id')->toArray();
                    $roomRenters = array_unique($roomRenters);
                    $rooms = $rooms->merge(Room::where('hostel_id', $hostelId)->whereNotIn('id', $roomRenters)->with('hostel')->get());

                } 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 = $rooms->merge(Room::whereIn('id', $roomArrs)->with('hostel')->get());
                }

            }

        } else if ($isEmpty == 4) {
            $rooms = Room::query()
                ->whereIn('hostel_id', $hostelArrs)
                ->with('hostel')
                ->has('reserves')
                ->get();


        } else if ($isEmpty == 5) {
            $rooms = collect([]);
            foreach ($hostels->get() as $hostel) {
                $hostelId = $hostel->id;
                if ($hostel->type_rent == Hostel::TYPE_RENT_ALL) {

                    $rooms = $rooms->merge(
                        Room::query()->where('hostel_id', $hostelId)
                            ->doesntHave('reserves')
                            ->with('hostel')
                            ->get());

                } else {
                    $roomArrs = [];
                    $roomItems = Room::query()->where('hostel_id', $hostel->id)
                        ->withCount('reserves')
                        ->get();
                    foreach ($roomItems as $roomItem) {
                        $maxRenter = $roomItem->max_renters;
                        if ($roomItem->reserves_count < $maxRenter) {
                            $roomArrs[] = $roomItem->id;
                        }
                    }
                    $rooms = $rooms->merge(Room::whereIn('id', $roomArrs)->with('hostel')->get());
                }

            }

        } else {
            $rooms = Room::whereIn('hostel_id', $hostelArrs)->with('hostel')->get();
        }


        foreach ($rooms as $room) {

            if (!$room->hostel) {
                continue;
            }
            $currentRenter = Functions::getCurrentRenter($room);
            $room->status_text = $room->status;
            $room->type_text = $room->type;
            if ($currentRenter) {
                $room->current_renter = $currentRenter->name;
                $room->current_renter_phone = $currentRenter->phone;
            }
            $room->number_renters = Functions::getNumberRenter($room->id);
            $isEmpty = Functions::ifEmptyRoom($room);
            $room->empty = ($isEmpty > 0) ? false : true;
            $isReserve = false;
            $reserveData = null;
            if (!$isEmpty) {
                $isReserveC = Functions::checkReserve($room);
                if ($isReserveC) {
                    $isReserve = true;
                    $reserveData = RoomReservation::where('room_id', $room->id)->first();
                }
            }

            $room->is_reserve = $isReserve;
            $room->reserve_data = $reserveData;
            $room->can_add = Functions::checkAddRenter($room);
            $room->number_bike = RenterBike::where('room_id', $room->id)->count();
            $imageArr = [];
            $images = \DB::table('room_images')->where('room_id', $room->id)->get();


            $dayLeave = null;
            $dateEndContract = null;
            if ($room->hostel->type_rent == Hostel::TYPE_RENT_ALL) {
                $contract = Contract::query()->where('room_id', $room->id)
                    ->latest()
                    ->first();
                if ($contract) {
                    if ($contract->leave_day) {
                        $dayLeave = $contract->leave_day->format('d/m/Y');
                    }

                    if ($contract->date_end_contract) {
                        $dateEndContract = Carbon::createFromFormat('Y-m-d', $contract->date_end_contract)->format('d/m/Y');
                    }
                }
            }

            $room->leave_day = $dayLeave;
            $room->date_end_contract = $dateEndContract;

            foreach ($images as $image) {
                $imageArr[] = '/files/' . $image->image;
            }
            $room->images = $imageArr;
            if ($room->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                $cntBed = RoomBed::query()
                    ->where('room_id', $room->id)
                    ->has('reserve')
                    ->count();

            } else {
                $cntBed = RoomReservation::query()->where('room_id', $room->id)->count();
            }
            $room->number_deposit = $cntBed;
        }

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


    /**
     * @api {post} /ratings Danh sách đánh giá nhà trọ
     * @apiName /ratings
     * @apiGroup Hostel
     * @apiParam {String} hostel_id
     * @apiParam {String} limit Nội dung
     * @apiParam {String} offset
     *
     *
     *
     * @apiDescription Danh sách đánh giá nhà trọ
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getRating(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $limit = $request->input('limit', 10);
        $offset = $request->input('offset', 0);
        $items = HostelRating::query()
            ->with('user')
            ->where('hostel_id', $hostelId);

        $items = $items
            ->limit($limit)
            ->offset($offset)
            ->get()
            ->map(function ($item) {
                $imageArr = \DB::table('hostel_rating_images')
                    ->where('hostel_rating_id', $item->id)
                    ->get()
                    ->map(function ($item) {
                        return [
                            'id' => $item->id,
                            'url' => '/files/' . $item->image
                        ];
                    });

                return [
                    'id' => $item->id,
                    'images' => $imageArr,
                    'rating' => $item->rating,
                    'comment' => $item->comment,
                    'created_at' => $item->created_at->format('d/m/Y'),
                    'user' => [
                        'id' => $item->user->id,
                        'name' => $item->user->name_text,
                        'image' => $item->user->image
                    ]
                ];
            });

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

    /**
     * @api {post} /create-rating Đánh giá nhà trọ
     * @apiName /create-rating
     * @apiGroup Hostel
     * @apiParam {String} rating Điểm. Cho phép điểm lẻ dạng 4.5
     * @apiParam {String} comment Nội dung
     * @apiParam {String} hostel_id
     * @apiParam {String} images Danh sách ảnh
     *
     *
     *
     * @apiDescription Đánh giá nhà trọ
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function createRating(Request $request)
    {
        $data = $request->all();
        $hostelId = $request->input('hostel_id');
        $ratingPoint = $request->input('rating');
        $images = $request->file('images');
        $comment = $request->input('comment');
        if (empty($hostelId) || empty($ratingPoint)) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $hostel = Hostel::find($hostelId);
        if (!$hostel) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        $data['user_id'] = $this->user->id;
        $check = HostelRating::query()
            ->where('hostel_id', $data['hostel_id'])
            ->where('user_id', $this->user->id)
            ->first();
        if ($check) {
            return response([
                'status' => 1,
                'message' => 'Bạn đã đánh giá nhà trọ này trước đó'
            ]);
        }
        $rating = HostelRating::create($data);
        if (!empty($images)) {
            foreach ($images as $image) {
                $imageItem = Functions::uploadImage($image);
                \DB::table('hostel_rating_images')
                    ->insert([
                        'hostel_rating_id' => $rating->id,
                        'image' => $imageItem
                    ]);

            }
        }

        $owner = $hostel->owner;
        if ($owner) {
            \Notification::send($owner, new RemindOwnerWhenRenterRate(
                $hostel, $this->user, $ratingPoint, $comment
            ));
        }

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

    //sử dụng hàm này để lưu

    /**
     * @api {post} /create Lưu nhà trọ
     * @apiName /create
     * @apiGroup Hostel
     * @apiParam {String} amenities Mảng id các tiện ích. Kiểu amenities[] = 1, amenities[] = 2
     * @apiParam {String} policies Mảng id các quy định. Kiểu policies[] = 1, policies[] = 2
     * @apiParam {String} images Mảng các ảnh.
     * @apiParam {String} types Mảng các loại ảnh
     * @apiParam {String} date_ew Ngày check điện nước.
     * @apiParam {String} date_money Ngày thu tiền.
     * @apiParam {String} name
     * @apiParam {String} type Loại nhà trọ. 2 là nhà tầng, 3 là chung cư mini, 4 là dãy trọ, 5 là nhà cấp 4
     * @apiParam {String} address
     * @apiParam {String} type_rent Hình thức thuê. 1 là bao phòng, 0 là từng người
     * @apiParam {String} province_id
     * @apiParam {String} district_id
     * @apiParam {String} ward_id
     * @apiParam {String} owner_name Tên chủ sở hữu
     * @apiParam {String} owner_id_number CMND chủ sở hữu
     * @apiParam {String} owner_phone SĐT chủ sở hữu
     * @apiParam {String} owner_email Email chủ sở hữu
     * @apiParam {String} desc
     * @apiParam {String} lat
     * @apiParam {String} lng
     * @apiParam {String} electric_price
     * @apiParam {String} water_price
     * @apiParam {String} min_price Giá tối thiểu
     * @apiParam {String} max_price Giá tối đa
     * @apiParam {String} user_amenities Mảng tên các tiện ích do user thêm
     * @apiParam {String} amenities Mảng tiện ích chọn từ sẵn có
     * @apiParam {String} user_policies Mảng tên các quy định do user thêm
     * @apiParam {String} policies Mảng quy định chọn từ sẵn có
     *
     *
     *
     * @apiDescription Api Lưu nhà trọ.  Loại ảnh: 1 là phòng khách, 2 là phòng ngủ, 3 là bếp, 4 là khác
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function store(Request $request)
    {
        $data = $request->except([
            'images',
            'min_price',
            'max_price'
        ]);

        $amenities = $request->input('amenities', []);
        $userAmenities = $request->input('user_amenities');
        $policies = $request->input('policies', []);
        $userPolicies = $request->input('user_policies');
        $imagesInput = $request->file('images');
        $videos = $request->file('videos');

        $amenityArr = [];
        $policyArr = [];
        $dateEw = $request->input('date_ew');
        $dateMoney = $request->input('date_money');
        $types = $request->input('types');
        $electricPrice = $request->input('electric_price');
        $waterPrice = $request->input('water_price');
        $smallestPrice = $request->input('min_price', 0);
        $greatestPrice = $request->input('max_price', 0);

        $data['smallest_price'] = $smallestPrice;
        $data['greatest_price'] = $greatestPrice;


        $ownerId = $this->user->id;

        if ($this->user->type == User::STAFF) {
            $ownerId = $this->user->staff_owner_id;
        }
        $owner = User::find($ownerId);

        $data['owner_name'] = $owner->name_text;
        $data['owner_id_number'] = $owner->id_number;
        $data['owner_phone'] = $owner->phone;
        $data['owner_email'] = $owner->email;

//		$cntHostel    = Hostel::query()->where( 'owner_id', $ownerId )->count();
//		$numberHostel = config( 'constants.LIMIT_HOSTEL' );;
//
//		$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'
//				] );
//			}
//
//			$numberHostel = $userPackage->number_hostels;
//		}

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

        try {

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

            \DB::beginTransaction();

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

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

            if (is_array($userPolicies)) {
                foreach ($userPolicies as $policy) {
                    if (!empty($policy)) {
                        $createdPolicy = Policy::create([
                            'user_id' => $this->user->id,
                            'type' => Amenity::POLICY,
                            'name' => $policy,
                        ]);

                        $policyArr[] = $createdPolicy->id;
                    }
                }
            }

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

            $data['owner_id'] = $ownerId;
            $data['number_empty_rooms'] = 0;
            $data['number_rooms'] = 0;
            $data['electric_price'] = !empty($electricPrice) ? $electricPrice : 0;
            $data['water_price'] = !empty($waterPrice) ? $waterPrice : 0;

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

            // dd($hostel);

            if (is_array($images)) {
                foreach ($images as $key => $image) {
                    $type = $types[$key];
                    if (empty($type)) {
                        return response([
                            'status' => 0,
                            'message' => 'Bạn phải chọn loại hình ảnh tương ứng với hình'
                        ]);
                    }
                    \DB::table('hostel_images')->insert([
                        'hostel_id' => $hostel->id,
                        'image' => $image,
                        'type' => $type,
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'updated_at' => Carbon::now()->toDateTimeString(),
                    ]);
                }
            }

            if (is_array($videos)) {
                foreach ($videos as $key => $video) {
                    $name = time() . $video->getClientOriginalName();
                    $filePath = $hostel->id . '/videos/' . str_slug($name);
                    $filePath = $filePath . '.' . $video->getClientOriginalExtension();
                    \Storage::disk('s3')->put($filePath, file_get_contents($video), 'public');
                    $previewPath = null;
                    $previews = $request->file('previews');
                    if (is_array($previews)) {
                        if (isset($previews[$key]) && !empty($previews[$key])) {
                            $previewUpload = $previews[$key];
                            $namePreview = time() . $previewUpload->getClientOriginalName();
                            $previewPath = $hostel->id . '/videos/previews/' . str_slug($namePreview);
                            $previewPath = $previewPath . '.' . $previewUpload->getClientOriginalExtension();
                            \Storage::disk('s3')->put($previewPath, file_get_contents($previewUpload), 'public');
                        }
                    }
                    \DB::table('hostel_videos')->insert([
                        'hostel_id' => $hostel->id,
                        'path' => 'https://resident.sgp1.digitaloceanspaces.com/' . $filePath,
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'updated_at' => Carbon::now()->toDateTimeString(),
                        'preview' => 'https://resident.sgp1.digitaloceanspaces.com/' . $previewPath,
                    ]);
                }
            }

            $hostel->amenities2()->sync($amenityArr);
            $hostel->policies()->sync($policyArr);

            if ($this->user) {
                $data['owner_id'] = $this->user->id;

                $currentNumberHostel = $this->user->number_hostels;
                $this->user->number_hostels = $currentNumberHostel + 1;
                $this->user->save();
            }


            if (!empty($electricPrice)) {
                HostelFee::create([
                    'name' => 'Tiền điện theo đồng hồ',
                    'unit' => 'Đồng/Kwh',
                    'fee' => $electricPrice,
                    'type' => HostelFee::ELECTRIC_BY_CLOCK,
                    'hostel_id' => $hostel->id
                ]);
            }


            if (!empty($waterPrice)) {
                HostelFee::create([
                    'name' => 'Tiền nước theo đồng hồ',
                    'unit' => 'Đồng/Khối',
                    'fee' => $waterPrice,
                    'type' => HostelFee::WATER_BY_CLOCK,
                    'hostel_id' => $hostel->id
                ]);
            }

            RoomType::create([
                'name' => 'Phòng loại 1',
                'price' => '1500000',
                'size' => '12',
                'max_peoples' => 3,
                'owner_id' => $this->user->id,
                'hostel_id' => $hostel->id
            ]);

            \DB::commit();
            if ($this->user->type == User::STAFF) {
                $this->user->staffHostel()->attach($hostel->id);
            }

            dispatch(new GenerateDynamicLinkHostel($hostel->id));
            dispatch(new CreateHostelConservation($hostel->id, $this->user->id));
            dispatch(new CreateHostelConservationV2($hostel->id, $this->user->id));
            dispatch_now(new CreateHostelPostCrawl($hostel->id));
        } 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',
            //'data'    => $hostel->id
        ]);
    }

    /**
     * @api {post} /create-by-renter Khai báo nhà trọ cho người trọ
     * @apiName /create-by-renter
     * @apiGroup Hostel
     * @apiParam {String} amenities Mảng id các tiện ích. Kiểu amenities[] = 1, amenities[] = 2
     * @apiParam {String} policies Mảng id các quy định. Kiểu policies[] = 1, policies[] = 2
     * @apiParam {String} images Mảng các ảnh.
     * @apiParam {String} types Mảng các loại ảnh
     * @apiParam {String} date_ew Ngày check điện nước.
     * @apiParam {String} date_money Ngày thu tiền.
     * @apiParam {String} name
     * @apiParam {String} type Loại nhà trọ. 2 là nhà tầng, 3 là chung cư mini, 4 là dãy trọ, 5 là nhà cấp 4
     * @apiParam {String} address
     * @apiParam {String} type_rent Hình thức thuê. 1 là bao phòng, 0 là từng người
     * @apiParam {String} province_id
     * @apiParam {String} district_id
     * @apiParam {String} ward_id
     * @apiParam {String} owner_name Tên chủ sở hữu
     * @apiParam {String} owner_id_number CMND chủ sở hữu
     * @apiParam {String} owner_phone SĐT chủ sở hữu
     * @apiParam {String} owner_email Email chủ sở hữu
     * @apiParam {String} desc
     * @apiParam {String} lat
     * @apiParam {String} lng
     * @apiParam {String} electric_price
     * @apiParam {String} water_price
     * @apiParam {String} min_price Giá tối thiểu
     * @apiParam {String} max_price Giá tối đa
     * @apiParam {String} user_amenities Mảng tên các tiện ích do user thêm
     * @apiParam {String} amenities Mảng tiện ích chọn từ sẵn có
     * @apiParam {String} user_policies Mảng tên các quy định do user thêm
     * @apiParam {String} policies Mảng quy định chọn từ sẵn có
     *
     *
     *
     * @apiDescription Api Khai báo nhà trọ cho người trọ.  Loại ảnh: 1 là phòng khách, 2 là phòng ngủ, 3 là bếp, 4 là khác
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function storeByRenter(Request $request)
    {
        $data = $request->except([
            'images',
            'min_price',
            'max_price'
        ]);

        $amenities = $request->input('amenities', []);
        $userAmenities = $request->input('user_amenities');
        $policies = $request->input('policies', []);
        $userPolicies = $request->input('user_policies');
        $imagesInput = $request->file('images');
        $videos = $request->file('videos');

        $amenityArr = [];
        $policyArr = [];
        $dateEw = $request->input('date_ew');
        $dateMoney = $request->input('date_money');
        $types = $request->input('types');
        $electricPrice = $request->input('electric_price');
        $waterPrice = $request->input('water_price');
        $smallestPrice = $request->input('min_price', 0);
        $greatestPrice = $request->input('max_price', 0);

        $data['smallest_price'] = $smallestPrice;
        $data['greatest_price'] = $greatestPrice;


        $ownerId = $this->user->id;

        try {

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

            \DB::beginTransaction();

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

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

            if (is_array($userPolicies)) {
                foreach ($userPolicies as $policy) {
                    if (!empty($policy)) {
                        $createdPolicy = Policy::create([
                            'user_id' => $this->user->id,
                            'type' => Amenity::POLICY,
                            'name' => $policy,
                        ]);

                        $policyArr[] = $createdPolicy->id;
                    }
                }
            }

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

            $data['owner_id'] = $ownerId;
            $data['number_empty_rooms'] = 0;
            $data['number_rooms'] = 0;
            $data['electric_price'] = !empty($electricPrice) ? $electricPrice : 0;
            $data['water_price'] = !empty($waterPrice) ? $waterPrice : 0;

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

            // dd($hostel);

            if (is_array($images)) {
                foreach ($images as $key => $image) {
                    $type = $types[$key];
                    if (empty($type)) {
                        return response([
                            'status' => 0,
                            'message' => 'Bạn phải chọn loại hình ảnh tương ứng với hình'
                        ]);
                    }
                    \DB::table('hostel_images')->insert([
                        'hostel_id' => $hostel->id,
                        'image' => $image,
                        'type' => $type,
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'updated_at' => Carbon::now()->toDateTimeString(),
                    ]);
                }
            }

            if (is_array($videos)) {
                foreach ($videos as $key => $video) {
                    $name = time() . $video->getClientOriginalName();
                    $filePath = $hostel->id . '/videos/' . str_slug($name);
                    $filePath = $filePath . '.' . $video->getClientOriginalExtension();
                    \Storage::disk('s3')->put($filePath, file_get_contents($video), 'public');
                    $previewPath = null;
                    $previews = $request->file('previews');
                    if (is_array($previews)) {
                        if (isset($previews[$key]) && !empty($previews[$key])) {
                            $previewUpload = $previews[$key];
                            $namePreview = time() . $previewUpload->getClientOriginalName();
                            $previewPath = $hostel->id . '/videos/previews/' . str_slug($namePreview);
                            $previewPath = $previewPath . '.' . $previewUpload->getClientOriginalExtension();
                            \Storage::disk('s3')->put($previewPath, file_get_contents($previewUpload), 'public');
                        }
                    }
                    \DB::table('hostel_videos')->insert([
                        'hostel_id' => $hostel->id,
                        'path' => 'https://resident.sgp1.digitaloceanspaces.com/' . $filePath,
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'updated_at' => Carbon::now()->toDateTimeString(),
                        'preview' => 'https://resident.sgp1.digitaloceanspaces.com/' . $previewPath,
                    ]);
                }
            }

            $hostel->amenities2()->sync($amenityArr);
            $hostel->policies()->sync($policyArr);

            if ($this->user) {
                $data['owner_id'] = $this->user->id;

                $currentNumberHostel = $this->user->number_hostels;
                $this->user->number_hostels = $currentNumberHostel + 1;
                $this->user->save();
            }


            if (!empty($electricPrice)) {
                HostelFee::create([
                    'name' => 'Tiền điện theo đồng hồ',
                    'unit' => 'Đồng/Kwh',
                    'fee' => $electricPrice,
                    'type' => HostelFee::ELECTRIC_BY_CLOCK,
                    'hostel_id' => $hostel->id
                ]);
            }


            if (!empty($waterPrice)) {
                HostelFee::create([
                    'name' => 'Tiền nước theo đồng hồ',
                    'unit' => 'Đồng/Khối',
                    'fee' => $waterPrice,
                    'type' => HostelFee::WATER_BY_CLOCK,
                    'hostel_id' => $hostel->id
                ]);
            }

            RoomType::create([
                'name' => 'Phòng loại 1',
                'price' => '1500000',
                'size' => '12',
                'max_peoples' => 3,
                'owner_id' => $this->user->id,
                'hostel_id' => $hostel->id
            ]);

            \DB::commit();
            if ($this->user->type == User::STAFF) {
                $this->user->staffHostel()->attach($hostel->id);
            }

            //dispatch( new CreateHostelConservation( $hostel->id, $this->user->id ) );
        } 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',
            //'data'    => $hostel->id
        ]);
    }


    public function create(Request $request)
    {


        $cntHostel = Hostel::where('owner_id', $this->user->id)->count();
        $numberHostel = config('constants.LIMIT_HOSTEL');

        $userPackage = UserPackage::where('user_id', $this->user->id)->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'
                ]);
            }

            $numberHostel = $userPackage->number_hostels;
        }

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

        $data = $request->all();

        $data['status'] = Hostel::IN_ACTIVE;

        \DB::beginTransaction();
        try {

            $data['owner_id'] = $this->user->id;

//            $owner = User::create([
//                'phone' => $data['phone'],
//                'password' => \Hash::make('123456123456'),
//                'type' => User::OWNER,
//                'name' => $data['name'],
//            ]);
//
//            $data['owner_id'] = $owner->id;

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

            $images = $request->file('images');

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

            $data['images'] = json_encode($imageData);

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

            $roomCnt = 0;

            if (!empty($data['rooms'])) {
                $data['rooms'] = preg_replace('/\s+/', '', $data['rooms']);
                $rooms = json_decode($data['rooms'], true);


                if (is_array($rooms)) {

                    foreach ($rooms as $room) {
                        $roomCnt++;
                        $type = $room['type'];
                        $dtType = RoomType::find($type);
                        $roomPrice = 0;
                        $roomSize = 0;
                        if ($dtType) {
                            $roomPrice = $dtType->price;
                            $roomSize = $dtType->size;
                        }

                        Room::create([
                            'floor' => $room['floor'],
                            'type' => $room['type'],
                            'name' => $room['name'],
                            'size' => $roomSize,
                            'price' => $roomPrice,
                            'hostel_id' => $hostel->id
                        ]);
                    }
                }
            }

            $hostel->number_rooms = $roomCnt;
            $hostel->number_empty_room = $roomCnt;
            $hostel->number_empty_rooms = $roomCnt;
            $hostel->save();

            $user = User::find($this->user->id);

            if ($user) {
                $currentNumberHostel = $user->number_hostels;
                $user->number_hostels = $currentNumberHostel + 1;
                $user->is_owner_first = false;
                $user->save();
            }
            \DB::commit();
        } catch (\Exception $ex) {
            \DB::rollBack();

            return response([
                'status' => 0,
                'message' => $ex->getMessage()
            ]);

        }

        return response([
            'status' => 1,
            'message' => 'Tạo thành công'
        ]);

    }


    /**
     * @api {post} /create-fee  Tạo phí dịch vụ
     * @apiName create-fee
     * @apiGroup Hostel
     * @apiDescription Api Tạo phí dịch vụ.
     * @apiParam {String} type
     * @apiParam {String} fee Số tiền dịch vụ
     * @apiParam {String} hostel_id
     * @apiParam {String} name
     *
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function createFee(Request $request)
    {
        $type = $request->input('type');
        $fee = $request->input('fee');
        $hostelId = $request->input('hostel_id');
        $feeName = $request->input('name');

        if ($type == HostelFee::ELECTRIC) {
            $unit = 'Đồng/Kwh';
        } else if ($type == HostelFee::WATER) {
            $unit = 'Đồng/Khối';
        } else if ($type == HostelFee::VEHICLE) {
            $unit = 'Đồng/Chiếc/Tháng';
        } else if ($type == HostelFee::WATER_BY_CLOCK) {
            $unit = 'Đồng/Khối';
        } else if ($type == HostelFee::WATER_BY_PEOPLE) {
            $unit = 'Đồng/Người';
        } else if ($type == HostelFee::ELECTRIC_BY_CLOCK) {
            $unit = 'Đồng/KwH';
        } else if ($type == HostelFee::ELECTRIC_BY_PEOPLE) {
            $unit = 'Đồng/Người';
        } else {
            $unit = 'Đồng/Tháng';
        }

        if ($type == HostelFee::WATER || $type == HostelFee::ELECTRIC) {
            $check = HostelFee::where('type', $type)->where('hostel_id', $hostelId)->count();
            if ($check) {
                return response([
                    'status' => 0,
                    'message' => 'Bạn không thể thiết lập 2 giá điện nước'
                ]);
            }
        }

        if ($type != HostelFee::DYNAMIC && $type != HostelFee::ELECTRIC && $type != HostelFee::WATER
            && $type != HostelFee::ELECTRIC_DYNAMIC && $type != HostelFee::WATER_DYNAMIC
        ) {
            if (empty($fee)) {
                return response([
                    'status' => 0,
                    'message' => 'Không được bỏ trống đơn giá'
                ]);
            }
        }

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

        $item = HostelFee::create([
            'name' => $feeName,
            'unit' => $unit,
            'fee' => $fee,
            'type' => $type,
            'hostel_id' => $hostelId
        ]);

        $user = Functions::getCurrentUser();
        $desc = '{' . $user->name . '}  đã tạo dịch vụ mới {' . $item->name . '} của nhà {' . optional($item->hostelItem)->name . '}';
        event(new LogAction([
            'type' => 'create-hostel-fee',
            'user_id' => optional($user)->id,
            'object_id' => $item->id,
            'hostel_id' => $item->hostel_id,
            'properties' => $item->toArray(),
            'desc' => $desc
        ]));

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

    }


    /**
     * @api {post} /create-fee-multiple-hostel  Tạo phí dịch vụ nhiều nhà trọ cùng lúc
     * @apiName create-fee-multiple-hostel
     * @apiGroup Hostel
     * @apiDescription Api Tạo phí dịch vụ.
     * @apiParam {String} type
     * @apiParam {String} fee Số tiền dịch vụ
     * @apiParam {String} hostel_ids[]
     * @apiParam {String} name
     *
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function createFeeMultipleHostel(Request $request)
    {
        $type = $request->input('type');
        $fee = $request->input('fee');
        $hostelIds = $request->input('hostel_ids');
        $feeName = $request->input('name');
        $user = Functions::getCurrentUser();

        if (!is_array($hostelIds) || empty($hostelIds)) {
            return response([
                'status' => 0,
                'message' => 'Không được để trống danh sách nhà trọ'
            ]);
        }

        if ($type == HostelFee::ELECTRIC) {
            $unit = 'Đồng/Kwh';
        } else if ($type == HostelFee::WATER) {
            $unit = 'Đồng/Khối';
        } else if ($type == HostelFee::VEHICLE) {
            $unit = 'Đồng/Chiếc/Tháng';
        } else if ($type == HostelFee::WATER_BY_CLOCK) {
            $unit = 'Đồng/Khối';
        } else if ($type == HostelFee::WATER_BY_PEOPLE) {
            $unit = 'Đồng/Người';
        } else if ($type == HostelFee::ELECTRIC_BY_CLOCK) {
            $unit = 'Đồng/KwH';
        } else if ($type == HostelFee::ELECTRIC_BY_PEOPLE) {
            $unit = 'Đồng/Người';
        } else {
            $unit = 'Đồng/Tháng';
        }

        foreach ($hostelIds as $hostelId) {

            if ($type == HostelFee::WATER || $type == HostelFee::ELECTRIC) {
                $check = HostelFee::query()->where('type', $type)->where('hostel_id', $hostelId)->count();
                if ($check) {
                    return response([
                        'status' => 0,
                        'message' => 'Bạn không thể thiết lập 2 giá điện nước'
                    ]);
                }
            }

            if ($type != HostelFee::DYNAMIC && $type != HostelFee::ELECTRIC && $type != HostelFee::WATER
                && $type != HostelFee::ELECTRIC_DYNAMIC && $type != HostelFee::WATER_DYNAMIC
            ) {
                if (empty($fee)) {
                    return response([
                        'status' => 0,
                        'message' => 'Không được bỏ trống đơn giá'
                    ]);
                }
            }

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

            $item = HostelFee::create([
                'name' => $feeName,
                'unit' => $unit,
                'fee' => $fee,
                'type' => $type,
                'hostel_id' => $hostelId
            ]);

            $desc = '{' . $user->name . '}  đã tạo dịch vụ mới {' . $item->name . '} của nhà {' . optional($item->hostelItem)->name . '}';
            event(new LogAction([
                'type' => 'create-hostel-fee',
                'user_id' => optional($user)->id,
                'object_id' => $item->id,
                'hostel_id' => $item->hostel_id,
                'properties' => $item->toArray(),
                'desc' => $desc
            ]));
        }

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

    }

    /**
     * @api {post} /update Cập nhật nhà
     * @apiName /update
     * @apiGroup Hostel
     * @apiParam {String} hostel_id id của nhà trọ cần cập nhật
     * @apiParam {String} amenities Mảng id các tiện ích. Kiểu amenities[] = 1, amenities[] = 2
     * @apiParam {String} policies Mảng id các quy định. Kiểu policies[] = 1, policies[] = 2
     * @apiParam {String} images Mảng các ảnh.
     * @apiParam {String} videos Mảng các video.
     * @apiParam {String} types Mảng các loại ảnh
     * @apiParam {String} date_ew Ngày check điện nước.
     * @apiParam {String} date_money Ngày thu tiền.
     * @apiParam {String} name
     * @apiParam {String} type Loại nhà trọ. 2 là nhà tầng, 3 là chung cư mini, 4 là dãy trọ, 5 là nhà cấp 4
     * @apiParam {String} address
     * @apiParam {String} type_rent Hình thức thuê. 1 là bao phòng, 0 là từng người
     * @apiParam {String} province_id
     * @apiParam {String} district_id
     * @apiParam {String} ward_id
     * @apiParam {String} owner_name Tên chủ sở hữu
     * @apiParam {String} owner_id_number CMND chủ sở hữu
     * @apiParam {String} owner_phone SĐT chủ sở hữu
     * @apiParam {String} owner_email Email chủ sở hữu
     * @apiParam {String} desc
     * @apiParam {String} lat
     * @apiParam {String} lng
     * @apiParam {String} min_price
     * @apiParam {String} max_price
     * @apiParam {String} user_amenities Mảng tên các tiện ích do user thêm
     * @apiParam {String} amenities Mảng tiện ích chọn từ sẵn có
     * @apiParam {String} user_policies Mảng tên các quy định do user thêm
     * @apiParam {String} policies Mảng quy định chọn từ sẵn có
     *
     *
     *
     * @apiDescription Api Lưu nhà trọ.  Loại ảnh: 1 là phòng khách, 2 là phòng ngủ, 3 là bếp, 4 là khác
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function update(Request $request)
    {
        $id = $request->input('hostel_id');
        $hostel = Hostel::find($id);

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

        $data = $request->except([
            'images',
            'min_price',
            'max_price'
        ]);

        $amenities = $request->input('amenities', []);
        $userAmenities = $request->input('user_amenities');
        $policies = $request->input('policies', []);
        $userPolicies = $request->input('user_policies');
        $imagesInput = $request->file('images');
        $imageTypes = $request->input('image-types');
        $deletedImages = $request->input('deleted_images');
        $deletedVideos = $request->input('deleted_videos');
        $types = $request->input('types');

        $videos = $request->file('videos');


        $smallestPrice = $request->input('min_price', 0);
        $greatestPrice = $request->input('max_price', 0);

        $data['smallest_price'] = $smallestPrice;
        $data['greatest_price'] = $greatestPrice;

        $amenityArr = [];
        $policyArr = [];

        $images = [];
        if (isset($imagesInput)) {
            foreach ($imagesInput as $imageItem) {
                $images[] = Functions::uploadImage($imageItem);
            }
        }
        $data['status_confirm'] = Hostel::WAIT_CONFIRM;

        try {
            \DB::beginTransaction();

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

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

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

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

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

            if (is_array($userPolicies)) {
                foreach ($userPolicies as $policy) {
                    if (!empty($policy)) {
                        $createdPolicy = Amenity::create([
                            'user_id' => $this->user->id,
                            'type' => Amenity::POLICY,
                            'name' => $policy,
                        ]);

                        $policyArr[] = $createdPolicy->id;
                    }
                }
            }

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

            $hostel->update($data);

            if (is_array($images)) {
                foreach ($images as $key => $image) {
                    $type = $types[$key];
                    if (empty($type)) {
                        return response([
                            'status' => 0,
                            'message' => 'Bạn phải chọn loại hình ảnh tương ứng với hình'
                        ]);
                    }
                    \DB::table('hostel_images')->insert([
                        'hostel_id' => $hostel->id,
                        'image' => $image,
                        'type' => $type,
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'updated_at' => Carbon::now()->toDateTimeString(),
                    ]);
                }
            }

            if (is_array($videos)) {
                foreach ($videos as $key => $video) {
                    $name = time() . $video->getClientOriginalName();
                    $filePath = $hostel->id . '/videos/' . str_slug($name);
                    $filePath = $filePath . '.' . $video->getClientOriginalExtension();
                    \Storage::disk('s3')->put($filePath, file_get_contents($video), 'public');
                    $previewPath = null;
                    $previews = $request->file('previews');
                    if (is_array($previews)) {
                        if (isset($previews[$key]) && !empty($previews[$key])) {
                            $previewUpload = $previews[$key];
                            $namePreview = time() . $previewUpload->getClientOriginalName();
                            $previewPath = $hostel->id . '/videos/previews/' . str_slug($namePreview);
                            $previewPath = $previewPath . '.' . $previewUpload->getClientOriginalExtension();
                            \Storage::disk('s3')->put($previewPath, file_get_contents($previewUpload), 'public');
                        }
                    }
                    \DB::table('hostel_videos')->insert([
                        'hostel_id' => $hostel->id,
                        'path' => 'https://resident.sgp1.digitaloceanspaces.com/' . $filePath,
                        'created_at' => Carbon::now()->toDateTimeString(),
                        'updated_at' => Carbon::now()->toDateTimeString(),
                        'preview' => 'https://resident.sgp1.digitaloceanspaces.com/' . $previewPath,
                    ]);
                }
            }

            $hostel->amenities2()->sync($amenityArr);
            $hostel->policies()->sync($policyArr);

            if ($this->user) {
                $data['owner_id'] = $this->user->id;

                $currentNumberHostel = $this->user->number_hostels;
                $this->user->number_hostels = $currentNumberHostel + 1;
                $this->user->save();
            }

            if (isset($data['lat']) && isset($data['lng'])) {
                Room::query()->where('hostel_id', $hostel->id)->update([
                    'lat' => $data['lat'],
                    'lng' => $data['lng']
                ]);
            }

            \DB::commit();
            dispatch_now(new CreateHostelPostCrawl($hostel->id));
            $user = Functions::getCurrentUser();
            event(new LogAction([
                'type' => 'update-hostel',
                'user_id' => optional($user)->id,
                'object_id' => $hostel->id,
                'hostel_id' => $hostel->id,
                'properties' => $hostel->toArray(),
                'desc' => '{'.$user->name.'} đã sửa nhà {'.$hostel->name.'}'
            ]));
        } 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',
        ]);
    }

    /**
     * @api {get} /detail Lấy chi tiết nhà trọ
     * @apiName detail
     * @apiGroup Hostel
     * @apiDescription Api Lấy chi tiết nhà trọ
     * @apiParam {String} hostel_id
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function detail(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $hostel = Hostel::find($hostelId);

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

        $images = \DB::table('hostel_images')
            ->where('hostel_id', $hostel->id)
            ->get();

        $videos = \DB::table('hostel_videos')
            ->where('hostel_id', $hostel->id)
            ->get();
        $imgArr = [];
        $videoArr = [];

        foreach ($images as $image) {
            $imgArr[] = ['id' => $image->id, 'type' => $image->type, 'url' => '/files/' . $image->image];
        }

        foreach ($videos as $video) {
            $videoArr[] = ['id' => $video->id, 'url' => $video->path, 'preview' => $video->preview];
        }

        $hostel->images = $imgArr;
        $hostel->videos = $videoArr;

        if (!empty($hostel->province_id)) {
            $province = Functions::getProvinceName($hostel->province_id);
            if ($province) {
                $hostel->province_name = $province->name;
            }
        }

        if (!empty($hostel->district_id)) {
            $district = Functions::getDistrictName($hostel->district_id);

            if ($district) {
                $hostel->district_name = $district->name;
            }
        }

        if (!empty($hostel->ward_id)) {
            $ward = Functions::getWardName($hostel->ward_id);
            if ($ward) {
                $hostel->ward_name = $ward->name;
            }
        }

        $hostel->desc = nl2br($hostel->desc);

        $amenities = Functions::getAmenitiesHostel($hostel);
        $policies = Functions::getPoliciesHostel($hostel);

        $hostel->amenities = $amenities;
        $hostel->policies = $policies;

        $relatesArr = [];
        $userId = null;
        if ($this->user) {
            $userId = $this->user->id;
        }

        if (!empty($hostel->lat) && !empty($hostel->lng)) {
            $relates = Hostel::isWithinMaxDistance([
                'lat' => $hostel->lat,
                'lng' => $hostel->lng
            ])->where('id', '<>', $hostel->id)->orderBy('id', 'desc')->take(4)->get();


            $relatesArr = Functions::listHostelTransformer($relates, $userId);
        }

        $hostel->relates = $relatesArr;

        $ownerName = null;
        $ownerAge = null;
        $ownerId = null;
        $ownerImage = null;
        $ownerStatusEmail = null;
        $ownerStatusPhone = null;
        $ownerPhone = null;

        if ($hostel->owner) {
            $owner = $hostel->owner;
            $ownerName = $owner->name;
            $ownerAge = Functions::getOld($owner);
            $ownerId = $owner->id;
            $ownerImage = $owner->image;
            $ownerStatusEmail = $owner->status_email ? true : false;
            $ownerStatusPhone = $owner->status_phone ? true : false;
            $ownerPhone = $owner->phone;
        }

        if ($this->user) {

            $hostel->is_favourite = Functions::checkFavourite($this->user->id, $hostel->id);
            $hostel->is_rated = Functions::checkRate($this->user->id, $hostel->id);
            $hostel->is_favourite_search_hostel = Functions::checkFavouriteSearchHostel($this->user->id, $hostel->id);
        } else {
            $hostel->is_favourite = false;
            $hostel->is_favourite_search_hostel = false;
            $hostel->is_rated = false;
        }

        $canDelete = false;
        $canEdit = false;

        if ($this->user) {
            if ($this->user->type == User::STAFF) {
                $hostelArr = Functions::getHostelArrStaffApi($this->user);
                if (in_array($hostelId, $hostelArr)) {
                    if ($this->user->can('edit-hostel')) {
                        $canEdit = true;
                    }

                    if ($this->user->can('delete-hostel')) {
                        $canDelete = true;
                    }
                }
            } else if ($this->user->type == User::OWNER) {
                if ($hostel->owner_id == $this->user->id) {
                    $canDelete = true;
                    $canEdit = true;
                }
            }
        }

        $hostel->can_edit = $canEdit;
        $hostel->can_delete = $canDelete;

        unset($hostel->owner);

        $hostel->owner_info = [
            'owner_name' => $ownerName,
            'owner_age' => $ownerAge,
            'owner_id' => $ownerId,
            'owner_image' => $ownerImage,
            'status_email' => $ownerStatusEmail,
            'status_phone' => $ownerStatusPhone,
            'phone' => $ownerPhone
        ];


        if ($this->user) {

            if (cache()->has('last-viewed-' . $this->user->id)) {

                $items = cache()->get('last-viewed-' . $this->user->id);
                $items[] = $hostel->id;
                cache()->put('last-viewed-' . $this->user->id, $items, 3600 * 24 * 180);

            } else {
                $items = [];
                $items[] = $hostel->id;
                cache()->put('last-viewed-' . $this->user->id, $items, 3600 * 24 * 180);
            }

        }

        $hostel->desc = html_entity_decode(strip_tags($hostel->desc));
        $hostel->number_rooms = Room::query()->where('hostel_id', $hostelId)->count();
        $numberRatings = HostelRating::query()->where('hostel_id', $hostelId)->count();
        $ratings = HostelRating::query()->where('hostel_id', $hostelId)->sum('rating');
        $hostel->number_ratings = $numberRatings;
        if (!empty($numberRatings)) {
            $hostel->avg_ratings = round($ratings / $numberRatings, 1);
        } else {
            $hostel->avg_ratings = 0;
        }

        if (empty($hostel->dynamic_link)) {
            $dynamicLink = Functions::generateDynamicLinkHostel($hostel);
            if (!empty($dynamicLink)) {
                Hostel::query()->where('id', $hostelId)
                    ->update([
                        'dynamic_link' => $dynamicLink
                    ]);
            }
        }

        $promotions = $hostel->promotions->map(function ($item) {
            return [
                'start_date' => $item->start_date,
                'end_date' => $item->end_date,
                'title' => $item->title,
                'desc' => $item->desc,
                'from' => $item->from
            ];
        });
        unset($hostel->promotions);
        $hostel->promotions = $promotions;
        $hostel->hostel_count = Hostel::query()->where('owner_id', $hostel->owner_id)->count();
        $hostel->hostel_type_name = optional($hostel->hostelType)->name;

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

    /**
     * @api {get} /get-fee-quota Lấy cấu hình điện nước
     * @apiName get-fee-quota
     * @apiGroup Hostel
     * @apiDescription Api Lấy cấu hình điện nước
     * @apiParam {String} hostel_id
     * @apiParam {String} fee_id
     * @apiParam {String} type 1 là điện 2 là nước
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function getFeeQuota(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $feeId = $request->input('fee_id');
        $hostel = Hostel::find($hostelId);
        if (!$hostel) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $type = $request->input('type');

        $item = null;
        if ($type == HostelFee::ELECTRIC) {

            $item = ElectricQuota::where('hostel_id', $hostelId)->where('fee_id', $feeId)->first();
            if (!$item) {

                $item = ElectricQuota::where('hostel_id', $hostelId)->first();
            }
        } else if ($type == HostelFee::WATER) {
            $item = WaterQuota::where('hostel_id', $hostelId)->where('fee_id', $feeId)->first();
            if (!$item) {
                $item = WaterQuota::where('hostel_id', $hostelId)->first();
            }
        }

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

    /**
     * @api {get} /store-fee-quota Tạo / Cập nhật cấu hình điện nước
     * @apiName store-fee-quota
     * @apiGroup Hostel
     * @apiDescription Api Tạo / cập nhật cấu hình điện nước. Gửi lên hostel_id và các params. Nếu chưa có hệ thống sẽ tự động tạo
     * @apiParam {String} hostel_id
     * @apiParam {String} type 1 là điện 2 là nước
     * @apiParam {String} quota_1 quota_1 đến quota_7 là các mức
     * @apiParam {String} price_quota_1 price_quota_1 đến price_quota_1 là giá các mức
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function storeFeeQuota(Request $request)
    {

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

            WaterQuota::updateOrCreate([
                'hostel_id' => $data['hostel_id']
            ], $data);
        } else if ($type == HostelFee::ELECTRIC) {
            ElectricQuota::updateOrCreate([
                'hostel_id' => $data['hostel_id']
            ], $data);
        }

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


    }

    public function lastViewed(Request $request)
    {
        $userId = $this->user->id;

        if (cache()->has('last-viewed-' . $userId)) {

            $hostelArrs = cache()->get('last-viewed-' . $userId);

            $items = Hostel::whereIn('id', $hostelArrs)->get();

            $arr = [];

            foreach ($items as $item) {
                $id = $item->id;
                $name = $item->name;
                $address = $item->address;
                $verified = $item->status_confirm;
                $favorite = Functions::checkFavourite($userId, $item->id);
                $price = Functions::getPriceHostelFrontend3($item);
                $minPrice = $price['smallest'];
                $maxPrice = $price['greatest'];
                $totalRoom = Room::where('hostel_id', $item->id)->count();
                $emptyRoom = Functions::getEmptyRoomHostel($item);
                $area = Functions::getAreaHostelFrontend3($item);
                $minArea = $area['smallest'];
                $maxArea = $area['greatest'];
                $lat = $item->lat;
                $lng = $item->lng;
                $highlightAmenities = Functions::getAmenitiesHostel($item);


                $arr[] = [
                    'id' => $id,
                    'name' => $name,
                    'address' => $address,
                    'verified' => $verified,
                    'favorite' => $favorite,
                    'min_price' => $minPrice,
                    'max_price' => $maxPrice,
                    'empty_room_count' => $emptyRoom,
                    'total_room' => $totalRoom,
                    'min_area' => $minArea,
                    'max_area' => $maxArea,
                    'lat' => $lat,
                    'lng' => $lng,
                    'highlight_amenities' => $highlightAmenities,
                    'background_image' => $item->image
                ];


            }

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

        }

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

    public function getEmptyRoomHostel(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $hostel = Hostel::find($hostelId);

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

        $usedRoom = RenterRoom::where('hostel_id', $hostelId)->whereNotNull('user_id')->pluck('room_id')->toArray();

        $emptyRooms = Room::where('hostel_id', $hostelId)->whereNotIn('id', $usedRoom)->get();

        foreach ($emptyRooms as $room) {
            $type = $room->type;
            $roomType = RoomType::find($type);
            if ($roomType) {
                $features = json_decode($roomType->features, true);
                if (is_array($features)) {
                    $amenityArr = [];
                    $amenities = Amenity::whereIn('id', $features)->get();
                    foreach ($amenities as $amenity) {
                        $amenityArr[] = [
                            'name' => $amenity->name,
                            'image' => '/files/' . $amenity->mobile_image
                        ];
                    }
                    $room->amenities = $amenityArr;
                }

                $images = json_decode($roomType->images, true);

                if (is_array($images)) {
                    $imageArr = [];
                    foreach ($images as $image) {
                        $imageArr[] = '/files/' . $image;
                    }
                    $room->images = $imageArr;
                }
            }

            $room->status_text = $room->status;
            $room->type_text = $room->type;
        }

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

    }


    /**
     * @api {get} /current-hostel Lấy thông tin nhà trọ đang ở
     * @apiName current-hostel
     * @apiGroup Hostel
     * @apiDescription Api Lấy thông tin nhà trọ đang ở
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getCurrentHostelAndRoom()
    {
        $userId = $this->user->id;

        $currentRent = RenterRoom::where('user_id', $userId)->latest()->first();

        if (!$currentRent) {
            return response([
                'status' => 0,
                'message' => 'Không tìm thấy dữ liệu người thuê',
                'data' => null
            ]);
        }

        $hostelId = $currentRent->hostel_id;
        $roomId = $currentRent->room_id;

        $room = Room::find($roomId);
        $hostel = Hostel::find($hostelId);

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

        $ownerId = $hostel->owner_id;

        $owner = User::find($ownerId);

        if (!$owner) {
            $hostel = null;
            $room = null;
        }
        $roomName = null;
        $roomId = null;
        $hostelName = null;
        $hostelAddress = null;
        $hostelOwnerName = null;
        $hostelOwnerPhone = null;
        $hotline = null;
        $hotLineName = null;
        $hotlineId = null;
        $hotlineImage = null;

        if ($room) {
            $roomName = $room->name;
            $roomId = $room->id;
        }

        if ($hostel) {
            $hostelOwner = $hostel->owner;
            $hotLineName = $hostelOwner->name;
            $hotline = $hostelOwner->phone;
            $hotlineId = $hostelOwner->id;
            $hotlineImage = $hostelOwner->image;

            $hotlineUserId = $hostel->user_hotline;
            if (!empty($hotlineUserId)) {
                $hotlineUser = User::find($hotlineUserId);
                if ($hotlineUser) {
                    $hotLineName = $hotlineUser->name_text;
                    $hotlineImage = $hotlineUser->image;
                    $hotlineId = $hotlineUser->id;
                    $hotline = $hotlineUser->phone;
                }
            }

            $hostelName = $hostel->name;
            $hostelAddress = $hostel->address;
            $hostelOwnerPhone = $hostel->owner_phone;
            $hostelOwnerName = $hostel->owner_name;
            $hostelId = $hostel->id;
        }

        if (empty($hostel)) {
            return response([
                'status' => 1,
                'message' => 'Người trọ không ở nhà trọ nào',
                'data' => null
            ]);
        }


        return response([
            'status' => 1,
            'data' => [
                'hostel_id' => $hostelId,
                'room_id' => $roomId,
                'room_name' => $roomName,
                'hostel_name' => $hostelName,
                'address' => $hostelAddress,
                'owner_name' => $hostelOwnerName,
                'owner_phone' => $hostelOwnerPhone,
                'image' => $hostel->image,
                'allow_renter_momo_payment' => $owner->allow_renter_momo_payment,
                'hotline' => [
                    'phone' => $hotline,
                    'name' => $hotLineName,
                    'id' => $hotlineId,
                    'image' => $hotlineImage
                ],
            ]
        ]);

    }

    /**
     * @api {get} /empty-bed Lấy so giuong trong cua nha tro
     * @apiName empty-bed
     * @apiGroup Hostel
     * @apiParam {String} hostel_id
     * @apiDescription Api Lấy so giuong trong cua nha tro
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getEmptyBedsByHostel(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $hostel = Hostel::find($hostelId);
        if (!$hostel) {
            return response([
                'status' => 0
            ]);
        }

//        if($hostel->type != Hostel::TYPE_RENT_EVERY)
//        {
//            return response([
//                'status' => 0
//            ]);
//        }

        $maxRenters = Room::where('hostel_id', $hostelId)->sum('max_renters');
        $renters = RenterRoom::where('hostel_id', $hostelId)->count();
        $numberEmptyBed = $maxRenters - $renters;
        $numberRooms = Room::where('hostel_id', $hostelId)->count();

        return response([
            'status' => 1,
            'data' => [
                'number_beds' => $numberEmptyBed,
                'number_rooms' => $numberRooms
            ]
        ]);
    }


    /**
     * @api {get} /empty-recently Nha tro trong gan day
     * @apiName empty-recently
     * @apiGroup Hostel
     * @apiDescription Api Nha tro trong gan day
     * @apiParam {String} limit
     * @apiParam {String} offset
     * @apiParam {String} province_id
     *
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function getHostelsEmptyRecently(Request $request)
    {
        $limit = $request->input('limit', 8);
        $offset = $request->input('offset', 0);
        $provinceId = $request->input('province_id');

        $hostels = Hostel::query()->select(\DB::raw('hostels.*'))
            ->join('rooms', 'hostels.id', '=', 'rooms.hostel_id');

        if (!empty($provinceId)) {
            $hostels = $hostels->where('hostels.province_id', $provinceId);
        }

        $hostels = $hostels->where(function ($q) {
            $q->where('rooms.date_available', '<=', Carbon::now()->toDateString());
            $q->orWhere(function ($q2) {
                $q2->whereNull('rooms.date_available');
                $q2->where('rooms.is_empty', true);
            });
        })->orderBy('rooms.date_available', 'desc')
            ->groupBy('hostels.id')
            ->limit($limit)
            ->offset($offset)
            ->get();

        //dd($hostels);

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

    }

    /**
     * @api {get} /outstanding Nha tro noi bat
     * @apiName outstanding
     * @apiGroup Hostel
     * @apiDescription Api Nha tro noi bat
     * @apiParam {String} limit
     * @apiParam {String} offset
     * @apiParam {String} province_id
     *
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getHostelsOutstanding(Request $request)
    {
        $limit = $request->input('limit', 8);
        $offset = $request->input('offset', 0);
        $provinceId = $request->input('province_id');

        $hostels = Hostel::query();

        if (!empty($provinceId)) {
            $hostels = $hostels->where('province_id', $provinceId);
        }

        $hostels = $hostels
            ->limit($limit)
            ->offset($offset)
            ->orderBy('avg_ratings', 'desc')
            ->get();

        //dd($hostels);

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

    }

    /**
     * @api {get} /near Nha tro gan ban
     * @apiName near
     * @apiGroup Hostel
     * @apiDescription Api Nha tro gan ban
     * @apiParam {String} limit
     * @apiParam {String} offset
     * @apiParam {String} lat
     * @apiParam {String} lng
     * @apiParam {String} provinceId
     *
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getHostelsNearYou(Request $request)
    {
        $limit = $request->input('limit', 8);
        $offset = $request->input('offset', 0);
        $lat = $request->input('lat');
        $lng = $request->input('lng');
        $provinceId = $request->input('province_id');

        $hostels = Hostel::query()
            ->isWithinMaxDistance([
                'lat' => $lat,
                'lng' => $lng
            ])
            ->limit($limit)
            ->offset($offset);
        if (!empty($provinceId)) {
            $hostels = $hostels->where('province_id', $provinceId);
        }

        $hostels = $hostels->get();
        //dd($hostels);

        foreach ($hostels as $hostel) {
            $distance = Functions::haversineGreatCircleDistance($lat, $lng, $hostel->lat, $hostel->lng);
            $distance = round($distance / 1000, 2);
            $hostel->distance = $distance;
        }

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

    }


    /**
     * @api {get} /term Nha tro theo tim kiem
     * @apiName term
     * @apiGroup Hostel
     * @apiDescription Api Nha tro theo tim kiem
     * @apiParam {String} limit
     * @apiParam {String} offset
     * @apiParam {String} term noi dung tim kiem
     * @apiParam {String} owner_id
     *
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getHostelsByTerm(Request $request)
    {
        $limit = $request->input('limit', 8);
        $offset = $request->input('offset', 0);
        $term = $request->input('term');
        $ownerId = $request->input('owner_id');


        $hostels = Hostel::query()
            ->when(!empty($q), function ($q) use ($term) {
                $q->where(function ($q) use ($term) {
                    $q->orWhere('name', 'LIKE', '%' . $term . '%');
                    $q->orWhere('address', 'LIKE', '%' . $term . '%');
                });
            })
            ->when(!empty($ownerId), function ($q) use ($ownerId) {
                $q->where('owner_id', $ownerId);
            })
            ->limit($limit)
            ->offset($offset);

        $hostels = $hostels->get();

        //dd($hostels);
        return response([
            'status' => 1,
            'data' => $hostels
        ]);

    }

    /**
     * @api {get} /outstand Nha tro nổi bật
     * @apiName outstand
     * @apiGroup Hostel
     * @apiDescription Api Nha tro nổi bật
     * @apiParam {String} limit
     * @apiParam {String} offset
     *
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getOutStandHostels(Request $request)
    {
        $limit = $request->input('limit', 15);
        $offset = $request->input('offset', 0);

        $owners = UserPackage::where(function ($q) {
            $q->orWhere('end_date', '>', Carbon::now());
            $q->orwhereRaw('end_date > start_date');
        })->pluck('user_id')->unique()->toArray();

        $hostels = Hostel::whereRaw('LENGTH(`desc`) > 100')
            ->whereNotNull('name')
            ->whereNotNull('province_id')
            ->whereNotNull('district_id')
            ->whereNotNull('ward_id')
            ->whereNotNull('address')
            ->where('is_display', true)
            ->where('number_empty_rooms', '>', 1)
            ->has('images')
            ->whereIn('owner_id', $owners)
            ->limit($limit)
            ->offset($offset)
            ->get();

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


    public function getTypeRents(Request $request)
    {
        $limit = $request->input('limit', 15);
        $offset = $request->input('offset', 0);

        $owners = UserPackage::where(function ($q) {
            $q->orWhere('end_date', '>', Carbon::now());
            $q->orwhereRaw('end_date > start_date');
        })->pluck('user_id')->unique()->toArray();

        $hostels = Hostel::whereRaw('LENGTH(`desc`) > 100')
            ->whereNotNull('name')
            ->whereNotNull('province_id')
            ->whereNotNull('district_id')
            ->whereNotNull('ward_id')
            ->whereNotNull('address')
            ->where('is_display', true)
            ->where('number_empty_rooms', '>', 1)
            ->has('images')
            ->whereIn('owner_id', $owners)
            ->limit($limit)
            ->offset($offset)
            ->get();

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

    /**
     * @api {post} /create-discount Tạo giảm giá
     * @apiName create-discount
     * @apiGroup Hostel
     * @apiDescription Api Tạo giảm giá
     * @apiParam {String} hostel_ids[]
     * @apiParam {String} date Dạng m/Y
     * @apiParam {String} discount Số tiền giảm giá
     *
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function storeDiscount(Request $request)
    {
        $data = $request->all();
        $hostelIds = $request->input('hostel_ids');
        if (empty($hostelIds) || !is_array($hostelIds)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống nhà trọ'
            ]);
        }

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

        $date = $request->input('date');
        $discount = Functions::filterInputNumber($request->input('discount'));
        try {
            $dateCarbon = Carbon::createFromFormat('d/m/Y', '01/' . $date);
        } catch (\Exception $exception) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu thời gian không hợp lệ. Format phải là m/Y'
            ]);
        }
        foreach ($hostelIds as $hostelId) {

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

            $checkDiscount = DiscountHostel::query()
                ->where('month', $dateCarbon->copy()->month)
                ->where('year', $dateCarbon->copy()->year)
                ->whereHas('hostels', function ($q) use ($hostelId) {
                    $q->where('hostel_id', $hostelId);
                })
                ->count();

            if ($checkDiscount > 0) {
                return response([
                    'status' => 0,
                    'message' => 'Nhà trọ ' . $hostel->name . ' đã được cài giảm giá cho tháng ' . $dateCarbon->copy()->format('m/Y') . ' trước đó'
                ]);
            }

            $checkMoneyInfo = MoneyInfo::query()
                ->whereIn('type', [
                    MoneyInfo::VOUCHER_CONTRACT,
                    MoneyInfo::VOUCHER_ROOM_PRICE
                ])
                ->where('hostel_id', $hostelId)
                ->whereBetween('date_action', [
                    $dateCarbon->copy()->startOfMonth(),
                    $dateCarbon->copy()->endOfMonth()
                ])
                ->where('pay', '<>', 0)
                ->count();

            if ($checkMoneyInfo) {
                return response([
                    'status' => 0,
                    'message' => 'Nhà trọ ' . $hostel->name . ' tồn tại hóa đơn đã thanh toán hoặc thanh toán một phần'
                ]);
            }
        }

        $discountItem = DiscountHostel::create([
            'month' => $dateCarbon->copy()->month,
            'year' => $dateCarbon->copy()->year,
            'date' => $dateCarbon->copy()->toDateString(),
            'user_id' => $this->user->id,
            'owner_id' => $ownerId,
            'discount' => $discount
        ]);

        $discountItem->hostels()->sync($hostelIds);

        dispatch(new AddDiscountHostel($discountItem->id));


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

    /**
     * @api {post} /delete-discount Xóa giảm giá
     * @apiName delete-discount
     * @apiGroup Hostel
     * @apiDescription Api Xóa giảm giá
     * @apiParam {String} id
     *
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function deleteDiscount(Request $request)
    {
        $id = $request->input('id');
        DiscountHostel::query()
            ->where('id', $id)
            ->delete();

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

    /**
     * @api {post} /update-discount Cập nhật giảm giá
     * @apiName update-discount
     * @apiGroup Hostel
     * @apiDescription Api Cập nhật giảm giá
     * @apiParam {String} hostel_ids[]
     * @apiParam {String} date Dạng m/Y
     * @apiParam {String} discount Số tiền giảm giá
     * @apiParam {String} id
     *
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function updateDiscount(Request $request)
    {
        $data = $request->all();
        $hostelIds = $request->input('hostel_ids');
        if (empty($hostelIds) || !is_array($hostelIds)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống nhà trọ'
            ]);
        }

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

        $date = $request->input('date');
        $discount = Functions::filterInputNumber($request->input('discount'));
        try {
            $dateCarbon = Carbon::createFromFormat('d/m/Y', '01/' . $date);
        } catch (\Exception $exception) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu thời gian không hợp lệ. Format phải là m/Y'
            ]);
        }
        foreach ($hostelIds as $hostelId) {

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

            $checkDiscount = DiscountHostel::query()
                ->where('month', $dateCarbon->copy()->month)
                ->where('year', $dateCarbon->copy()->year)
                ->whereHas('hostels', function ($q) use ($hostelId) {
                    $q->where('hostel_id', $hostelId);
                })
                ->count();

            if ($checkDiscount > 0) {
                return response([
                    'status' => 0,
                    'message' => 'Nhà trọ ' . $hostel->name . ' đã được cài giảm giá cho tháng ' . $dateCarbon->copy()->format('m/Y') . ' trước đó'
                ]);
            }

            $checkMoneyInfo = MoneyInfo::query()
                ->where('hostel_id', $hostelId)
                ->whereIn('type', [
                    MoneyInfo::VOUCHER_CONTRACT,
                    MoneyInfo::VOUCHER_ROOM_PRICE
                ])
                ->whereBetween('date_action', [
                    $dateCarbon->copy()->startOfMonth(),
                    $dateCarbon->copy()->endOfMonth()
                ])
                ->where('pay', '<>', 0)
                ->count();

            if ($checkMoneyInfo) {
                return response([
                    'status' => 0,
                    'message' => 'Nhà trọ ' . $hostel->name . ' tồn tại hóa đơn đã thanh toán hoặc thanh toán một phần'
                ]);
            }
        }

        $discountItem = DiscountHostel::find($request->input('id'));
        if ($discountItem) {
            $discountItem->update([
                'month' => $dateCarbon->copy()->month,
                'year' => $dateCarbon->copy()->year,
                'date' => $dateCarbon->copy()->toDateString(),
                'user_id' => $this->user->id,
                'owner_id' => $ownerId,
                'discount' => $discount
            ]);

            $discountItem->hostels()->sync($hostelIds);
            dispatch(new AddDiscountHostel($discountItem->id));
        }

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

    /**
     * @api {get} /get-discount Lấy danh sách giảm giá
     * @apiName get-discount
     * @apiGroup Hostel
     * @apiDescription Api Lấy danh sách giảm giá
     *
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getDiscount(Request $request)
    {
        $user = $this->user;
        $items = DiscountHostel::query()
            ->with('hostels')
            ->when($this->user->type == User::STAFF, function ($q) use ($user) {
                $q->where('owner_id', $user->staff_owner_id);
            }, function ($q) use ($user) {
                $q->where('owner_id', $user->id);
            })
            ->get();

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

    /**
     * @api {post} /create-schedule-meeting tạo lịch hẹn
     * @apiName create-schedule-meeting
     * @apiGroup Hostel
     * @apiDescription Api tạo lịch hẹn
     * @apiParam {String} hostel_id
     * * @apiParam {String} room_id
     * @apiParam {String} schedule Dạng Y-m-d H:i. Ví dụ 2020-01-19 15:12
     * @apiParam {String} name
     * @apiParam {String} phone
     * @apiParam {String} note
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function storeScheduleMeeting(Request $request)
    {
        $data = $request->all();
        if (empty($request->input('schedule'))) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        if (empty($request->input('hostel_id'))) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $hostel = Hostel::find($data['hostel_id']);
        if (!$hostel) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        $schedule = Carbon::createFromFormat('Y-m-d H:i', $request->input('schedule'));
        $data['schedule'] = $schedule->copy()->toDateTimeString();
        if ($this->user) {
            $data['user_id'] = $this->user->id;

            if (empty($data['name'])) {
                $data['name'] = $this->user->name;
            }

            if (empty($data['phone'])) {
                $data['phone'] = $this->user->phone;
            }
        }

        $item = HostelSchedule::create($data);
        $message = 'Khách ' . $data['name'] . ' vừa đặt hẹn xem nhà ' . $hostel->name . ' vào lúc ' . $schedule->copy()->format('H:i') . ' ngày ' . $schedule->copy()->format('d/m/Y');

        if (!empty($data['room_id'])) {
            $room = Room::find($data['room_id']);
            if ($room) {
                $message = 'Khách ' . $data['name'] . ' vừa đặt hẹn xem nhà ' . $hostel->name . ', phòng ' . $room->name . ' vào lúc ' . $schedule->copy()->format('H:i') . ' ngày ' . $schedule->copy()->format('d/m/Y');
            }
        }


            $owner = $hostel->owner;
            $staffs = User::query()
                ->where('staff_owner_id', $owner->id)
                ->get();
            if($this->user) {
                if ($this->user->type == User::RENTER) {
                    \Notification::send($owner, new SendTextMessage($message, $this->user, $item->id));
                    \Notification::send($staffs, new SendTextMessage($message, $this->user, $item->id));
                } else if ($this->user->type == User::STAFF) {
                    \Notification::send($owner, new SendTextMessage($message, $this->user, $item->id));
                }
            } else {
                \Notification::send($owner, new SendTextMessage($message, $this->user, $item->id));
                \Notification::send($staffs, new SendTextMessage($message, $this->user, $item->id));
            }


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

    }

    /**
     * @api {get} /detail-schedule-meeting chi tiết lịch hẹn
     * @apiName detail-schedule-meeting
     * @apiGroup Hostel
     * @apiDescription Api chi tiết lịch hẹn
     * @apiParam {String} id
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getScheduleMeeting(Request $request)
    {
        $limit = $request->input('limit', 10);
        $offset = $request->input('offset', 0);
        $user = $this->user;
        $ownerId = null;
        if ($user->type == User::OWNER) {
            $ownerId = $user->id;
        } else if ($user->type == User::STAFF) {
            $ownerId = $user->staff_owner_id;
        }
        $items = HostelSchedule::query()
            ->with('hostel')
            ->with('room')
            ->with('user')
            ->whereHas('hostel', function ($q) use ($ownerId) {
                $q->where('owner_id', $ownerId);
            })
            ->where('status', 0)
            ->limit($limit)
            ->offset($offset)
            ->orderBy('schedule', 'asc')
            ->get()
            ->map(function ($item) {
                $room = null;
                if ($item->room) {
                    $room = [
                        'id' => $item->room->id,
                        'name' => $item->room->name
                    ];
                }
                $user = null;
                if ($item->user) {
                    $user = [
                        'id' => $item->user->id,
                        'name' => $item->user->name,
                        'image' => $item->user->image
                    ];
                }
                return [
                    'id' => $item->id,
                    'hostel' => [
                        'id' => $item->hostel->id,
                        'name' => $item->hostel->name
                    ],
                    'room' => $room,
                    'user' => $user,
                    'name' => $item->name,
                    'phone' => $item->phone,
                    'status' => $item->status,
                    'schedule' => $item->schedule->format('d/m/Y H:i'),
                    'note' => $item->note
                ];
            });

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

    }

    public function detailScheduleMeeting(Request $request)
    {
        $id = $request->input('id');
        $item = HostelSchedule::find($id);
        if (!$item) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        return response([
            'status' => 1,
            'data' => [
                'id' => $item->id,
                'hostel' => [
                    'id' => $item->hostel->id,
                    'name' => $item->hostel->name
                ],
                'name' => $item->name,
                'phone' => $item->phone,
                'status' => $item->status,
                'schedule' => $item->schedule->format('d/m/Y H:i'),
                'note' => $item->note
            ]
        ]);
    }

    /**
     * @api {post} /update-schedule-meeting cập nhật lịch hẹn
     * @apiName update-schedule-meeting
     * @apiGroup Hostel
     * @apiDescription Api cập nhật lịch hẹn
     * @apiParam {String} id
     * @apiParam {String} hostel_id
     * @apiParam {String} schedule Dạng Y-m-d H:i. Ví dụ 2020-01-19 15:12
     * @apiParam {String} name
     * @apiParam {String} phone
     * @apiParam {String} note
     * * @apiParam {String} status
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function updateScheduleMeeting(Request $request)
    {
        $id = $request->input('id');
        $data = $request->except(['id']);
        $item = HostelSchedule::find($id);
        if ($item) {
            $item->update($data);
        }
        return response([
            'status' => 1
        ]);

    }

    /**
     * @api {post} /gen-invoice-all Sinh hóa đơn
     * @apiName gen-invoice-all
     * @apiGroup Hostel
     * @apiDescription Sinh hóa đơn
     * @apiParam {String} hostel_id
     * @apiParam {String} date Dạng m/Y
     * * @apiParam {String} status
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function generateNextInvoice(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $date = $request->input('date');
        $user = $this->user;

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

        $contracts = Contract::query()
            ->when(!empty($hostelId), function ($q) use ($hostelId) {
                $q->where('hostel_id', $hostelId);
            }, function ($q) use ($user) {
                if ($user->type == User::STAFF) {
                    $hostelArr = Functions::getHostelArrStaffApi($user);
                } else {
                    $hostelArr = Hostel::query()
                        ->where('owner_id', $user->id)
                        ->pluck('id')
                        ->toArray();
                }

                $q->whereIn('hostel_id', $hostelArr);
            })
            ->where('status', '<>', Contract::LIQUIDATED)
            ->get();
        $user = Functions::getCurrentUser();
        foreach ($contracts as $contract) {
            dispatch(new GenerateNextContractInvoice($contract->id, $date, $user));

        }

        $hostels = Hostel::query()
            ->whereIn('id', $contracts->pluck('hostel_id')->toArray())
            ->get();
        $user = Functions::getCurrentUser();
        foreach ($hostels as $hostel) {
            $desc = '{' . $user->name . '} đã sinh hóa đơn tiền nhà tháng {' . $date . '} cho nhà {' . $hostel->name . '}';
            event(new LogAction([
                'type' => 'gen-hostel-money',
                'user_id' => optional($user)->id,
                'object_id' => $hostelId,
                'hostel_id' => $hostelId,
                'desc' => $desc
            ]));
        }
        return response([
            'status' => 1
        ]);
    }

}
