<?php

namespace App\Http\Controllers\Api\v1;

use App\Components\Functions;
use App\Events\LogAction;
use App\Jobs\CreateRoomConservation;
use App\Jobs\CreateRoomConservationV2;
use App\Jobs\DeleteRenterConversation;
use App\Jobs\DeleteRoomConversation;
use App\Jobs\GenerateNextContractInvoice;
use App\Jobs\RemindRating;
use App\Jobs\RemoveUserConversationV2;
use App\Jobs\SendMailContract;
use App\Models\Amenity;
use App\Models\BreakHistory;
use App\Models\CollectSpend;
use App\Models\CollectSpendFile;
use App\Models\Config;
use App\Models\ConfigHostel;
use App\Models\Contract;
use App\Models\ContractAttachment;
use App\Models\ContractFee;
use App\Models\Deposit;
use App\Models\ElectricWater;
use App\Models\Hostel;
use App\Models\HostelFee;
use App\Models\HostelSchedule;
use App\Models\MoneyDetail;
use App\Models\MoneyInfo;
use App\Models\Notification;
use App\Models\Renter;
use App\Models\RenterBike;
use App\Models\RenterRoom;
use App\Models\Report;
use App\Models\ReportBreak;
use App\Models\ReportBreakRating;
use App\Models\ReserveFiles;
use App\Models\Room;
use App\Models\RoomBed;
use App\Models\RoomEw;
use App\Models\RoomFee;
use App\Models\RoomNote;
use App\Models\RoomReservation;
use App\Models\RoomType;
use App\Models\Statistic;
use App\Models\StatisticLog;
use App\Models\StatisticMonth;
use App\Models\Transaction;
use App\Models\TypeSpend;
use App\Models\UserPackage;
use App\Notifications\ExtendContract;
use App\User;
use Carbon\Carbon;
use Dompdf\Exception;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Mpdf\Tag\U;

class RoomController extends BaseController
{
    /**
     * @api {get} /history-contract Lấy danh sách lịch sử HĐ của 1 phòng
     * @apiName history-contract
     * @apiGroup Room
     * @apiDescription Lấy danh sách lịch sử HĐ của 1 phòng. Status 0 là còn hiệu lực, 2 là đã thanh lý,1  là đã hết hạn
     * @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 historyContract(Request $request)
    {
        $roomId = $request->input('room_id');
        $status = $request->input('status');
        $startTime = $request->input('start_date');
        $endTime = $request->input('end_date');
        $room = Room::find($roomId);
        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $contracts = Contract::query()
            ->with('fees')
            ->where('room_id', $room->id);

        if (isset($status)) {
            $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);
            });
        }

        //  dd($contracts->toSql());
        $contracts = $contracts->orderBy('contracts.created_at', 'desc')->get();

        $returnArr = [];
        foreach ($contracts as $contract) {
            $renters = RenterRoom::withTrashed()
                ->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
                ];
            });
            $returnArr[] = [
                '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' => $contract->end_date->format('d/m/Y'),
                'leave_day' => optional($contract->leave_day)->format('d/m/Y'),
                'status' => $contract->status,
                'id' => $contract->id,
                'users' => $users,
                'services' => $contract->fees->count()
            ];
        }

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


    }

    /**
     * @api {get} /contract-end-by-day Lấy danh sách HD sap het theo ngay
     * @apiName contract-end-by-day
     * @apiGroup Room
     * @apiDescription Lấy danh sách HD sap het theo ngay
     * @apiParam {String} hostel_id
     * @apiParam {String} number_day 30-60-90
     * @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 contractEndByDay(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $numberDay = $request->input('number_day', 30);
        if (empty($hostelId)) {
            $ownerId = $this->user->id;
            if ($this->user->type == User::STAFF) {
                $ownerId = $this->user->staff_owner_id;
            }
            $hostelArrs = Hostel::query()->where('owner_id', $ownerId)->pluck('id')->toArray();
        } else {
            $hostelArrs = Hostel::query()->where('id', $hostelId)->pluck('id')->toArray();
        }

        $contracts = Contract::query()->whereIn('hostel_id', $hostelArrs)
            ->where('status', '<>', Contract::LIQUIDATED)
            ->with(['room'])
            ->where(function ($q) use ($numberDay) {
                $q->orWhere(function ($q) use ($numberDay) {
                    $q->whereNotNull('end_date')->whereBetween('end_date', [
                        Carbon::now()->toDateString(),
                        Carbon::now()->addDay($numberDay)->toDateString()
                    ]);
                });

                $q->orWhere(function ($q) use ($numberDay) {
                    $q->whereNotNull('leave_day')->whereBetween('leave_day', [
                        Carbon::now()->toDateString(),
                        Carbon::now()->addDay($numberDay)->toDateString()
                    ]);
                });

                $q->orWhere(function ($q) {
                    $q->where('end_date', '<=', Carbon::now());
                });
            });

        $contracts = $contracts->orderBy('contracts.end_date', 'asc')->get()
            ->map(function ($contract) {
                $renters = RenterRoom::withTrashed()
                    ->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
                    ];
                });

                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' => $contract->end_date->format('d/m/Y'),
                    'status' => $contract->status,
                    'id' => $contract->id,
                    'users' => $users,
                    'leave_day' => !empty($contract->leave_day) ? $contract->leave_day->format('d/m/Y') : null,
                    'date_end_contract' => !empty($contract->date_end_contract) ? $contract->date_end_contract->format('d/m/Y') : null
                ];
            });


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

    /**
     * @api {post} /reserve Giữ chỗ cho phòng
     * @apiName reserve
     * @apiGroup Room
     * @apiDescription Giữ chố cho phòng.
     * @apiParam {String} room_id
     * @apiParam {String} phone
     * @apiParam {String} name
     * @apiParam {String} id_number
     * @apiParam {String} email
     * @apiParam {String} deposit
     * @apiParam {String} bed_id
     * @apiParam {String} date_join date_join để dạng d/m/Y
     * @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 storeReserve(Request $request)
    {
        $data = $request->except('files');
        $files = $request->file('files');

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

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

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

        if ($room->hostel->type_rent == Hostel::TYPE_RENT_ALL) {
            $check = RoomReservation::where('room_id', $data['room_id'])->count();
            if ($check) {
                return response([
                    'status' => 0,
                    'message' => 'Nhà trọ bao phòng chỉ được phép tạo 1 giữ chỗ'
                ]);
            }
        } else if ($room->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
            $maxRenters = $room->max_renters;
            $numberCurrentRenter = RenterRoom::where('room_id', $roomId)->count();

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

            if (empty($data['bed_id'])) {
                return response([
                    'status' => 0,
                    'message' => 'Không có dữ liệu giường'
                ]);
            }

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

        if (empty($data['deposit'])) {
            $data['deposit'] = 0;
        }
        $reserve = RoomReservation::create($data);

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

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

        $hostelScheduleId = $request->input('hostel_schedule_id');

        $hostelSchedule = HostelSchedule::find($hostelScheduleId);
        if ($hostelSchedule) {
            $hostelSchedule->status = HostelSchedule::STATUS_RESERVED;
            $hostelSchedule->reserve_id = $reserve->id;
            $hostelSchedule->save();
        }

        if (!empty($files)) {
            foreach ($files as $file) {
                $name = time() . $file->getClientOriginalName();
                $filePath = 'reserves/' . $reserve->id . '/files/' . str_slug($name);
                $filePath = $filePath . '.' . $file->getClientOriginalExtension();
                \Storage::disk('s3')->put($filePath, file_get_contents($file), 'public');
                ReserveFiles::create([
                    'reserve_id' => $reserve->id,
                    'file' => 'https://resident.sgp1.digitaloceanspaces.com/' . $filePath
                ]);
            }
        }

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

    /**
     * @api {post} /update-reserve Cập nhật giữ chỗ
     * @apiName update-reserve
     * @apiGroup Room
     * @apiDescription Cập nhật giữ chỗ
     * @apiParam {String} id
     * @apiParam {String} phone
     * @apiParam {String} name
     * @apiParam {String} id_number
     * @apiParam {String} email
     * @apiParam {String} deposit
     * @apiParam {String} bed_id
     * @apiParam {String} date_join date_join để dạng d/m/Y
     * @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 updateReserve(Request $request)
    {
        $reserveId = $request->input('id');
        $reserve = RoomReservation::find($reserveId);
        if (!$reserve) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        $roomId = $reserve->room_id;
        $hostelId = $reserve->hostel_id;
        $data = $request->except('files');

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

        $reserve->update($data);

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

            if ($collectSpend) {

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

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

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

        $files = $request->file('files');
        if (!empty($files)) {
            foreach ($files as $file) {
                $name = time() . $file->getClientOriginalName();
                $filePath = 'reserves/' . $reserve->id . '/files/' . str_slug($name);
                $filePath = $filePath . '.' . $file->getClientOriginalExtension();
                \Storage::disk('s3')->put($filePath, file_get_contents($file), 'public');
                ReserveFiles::create([
                    'reserve_id' => $reserve->id,
                    'file' => 'https://resident.sgp1.digitaloceanspaces.com/' . $filePath
                ]);
            }
        }

        $deletedFiles = $request->input('deleted_files');
        if (is_array($deletedFiles) && !empty($deletedFiles)) {
            ReserveFiles::query()->whereIn('id', $deletedFiles)->delete();
        }

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

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

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


    /**
     * @api {get} /get-reserve Lấy danh sách giữ chỗ
     * @apiName get-reserve
     * @apiGroup Room
     * @apiDescription Lấy danh sách giữ chỗ.
     * @apiParam {String} hostel_id
     * @apiParam {String} room_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 getReserve(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $roomId = $request->input('room_id');
        $bedId = $request->input('bed_id');

        $items = RoomReservation::query()
            ->has('room')
            ->with([
                'bed',
                'room',
                'collectSpends',
                'room.hostel',
                'files'
            ]);

        if (!empty($hostelId)) {
            $items = $items->where('hostel_id', $hostelId);
        } else {
            $hostelArr = Hostel::query()
                ->where('owner_id', $this->user->id)
                ->pluck('id')
                ->toArray();

            if ($this->user->type == User::STAFF) {
                $hostelArr = Functions::getHostelArrStaffApi($this->user);
            }

            $items = $items->whereIn('hostel_id', $hostelArr);
        }
        if (!empty($roomId)) {
            $items = $items->where('room_id', $roomId);
        }
        if (!empty($bedId)) {
            $items = $items->where('bed_id', $bedId);
        }

        $items = $items->get();

        foreach ($items as $item) {
            $bed = $item->bed;
            if (!empty($bed)) {
                $item->bed_name = $bed->name;
            }
            $room = $item->room;
            $createdBy = null;
            $collectSpend = $item->collectSpends->first();
            if ($collectSpend) {
                if ($collectSpend->user) {
                    $createdBy = $collectSpend->user->name_text;
                }
            }
            if ($room) {
                $item->room_name = $room->name;
                $item->room_price = $room->price;
                $item->created_by = $createdBy;
                $item->hostel_name = $room->hostel->name;
                $item->hostel_type_rent = optional($room->hostel)->type_rent;
            }


        }

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

    /**
     * @api {post} /delete-reserve Xóa giữ chỗ
     * @apiName delete-reserve
     * @apiGroup Room
     * @apiDescription Xóa Giữ chố.
     * @apiParam {String} id
     * @apiParam {String} back_deposit
     * @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 deleteReserve(Request $request)
    {
        $id = $request->input('id');
        $backDeposit = $request->input('back_deposit', 0);
        $reserve = RoomReservation::find($id);

        if ($reserve) {
            if ($backDeposit > 0) {

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

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

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

            }

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

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

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

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

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


    /**
     * @api {get} /detail-contract Chi tiết hợp đồng
     * @apiName detail-contract
     * @apiGroup Room
     * @apiDescription Chi tiết hợp đồng
     * @apiParam {String} contract_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 detailContract(Request $request)
    {
        $contractId = $request->input('contract_id');
        $contract = Contract::find($contractId);
        if (!$contract) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $returnArr = $contract->toArray();

        $feeItem = [];
        $fees = HostelFee::query()->where('hostel_id', $contract->hostel->id)->get();
        $qty = ContractFee::query()->where('contract_id', $contract->id)->pluck('qty', 'fee_id')->toArray();
        $feeUsed = ContractFee::query()->where('contract_id', $contract->id)->pluck('fee_id')->toArray();

        foreach ($fees as $fee) {
            $isUsed = false;
            $qtyItem = 0;
            if (in_array($fee->id, $feeUsed)) {
                $isUsed = true;
            }

            if (isset($qty[$fee->id])) {
                $qtyItem = $qty[$fee->id];
            }

            $feeItem[] = [
                'is_used' => $isUsed,
                'id' => $fee->id,
                'name' => $fee->name,
                'qty' => $qtyItem,
                'type' => $fee->type,
                'fee' => $fee->fee
            ];
        }

        $returnArr['fee_items'] = $feeItem;
        $returnArr['date_contract'] = optional($contract->date_contract)->format('d/m/Y');
        $returnArr['end_date'] = $contract->end_date->format('d/m/Y');
        $returnArr['start_date'] = optional($contract->start_date)->format('d/m/Y');
        $returnArr['date_enable'] = optional($contract->date_enable)->format('d/m/Y');
        $returnArr['next_invoice_date'] = $contract->last_invoice_at_text;
        $returnArr['hostel_name'] = optional($contract->hostel)->name;
        $returnArr['room_name'] = optional($contract->room)->name;
        $returnArr['hostel_type_rent'] = optional($contract->hostel)->type_rent;

        $bedId = null;
        $bedName = null;
        if ($contract->bed) {
            $bedId = $contract->bed->id;
            $bedName = $contract->bed->name;
        }
        $returnArr['bed_id'] = $bedId;
        $returnArr['bed_name'] = $bedName;


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

    }

    /**
     * @api {get} /info Chi tiết thông tin phòng trọ
     * @apiName info
     * @apiGroup Room
     * @apiDescription Chi tiết thông tin phòng trọ
     * @apiParam {String} room_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 roomInfo(Request $request)
    {
        $roomId = $request->input('room_id');
        $room = Room::find($roomId);
        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        $imageArr = [];

        $images = \DB::table('room_images')->where('room_id', $room->id)->get();
        foreach ($images as $image) {
            $imageArr[] = [
                'url' => '/files/' . $image->image,
                'type' => $image->type,
                'id' => $image->id
            ];
        }
        $hostelAmenities = Amenity::where('type', Amenity::AMENITY)->whereIn('user_id', [
            0,
            $this->user->id
        ])->get();
        $roomAmenities = $room->amenities->pluck('id')->toArray();

        if ($hostelAmenities) {
            foreach ($hostelAmenities as $hostelAmenity) {
                if (in_array($hostelAmenity->id, $roomAmenities)) {
                    $hostelAmenity->is_check = true;
                } else {
                    $hostelAmenity->is_check = false;
                }
            }
        }
        $numberBike = RenterBike::query()->where('room_id', $roomId)->count();
        $isReserve = false;
        $reserveData = null;
        $isEmpty = Functions::ifEmptyRoom($room);
        if (!$isEmpty) {
            $isReserveC = Functions::checkReserve($room);
            if ($isReserveC) {
                $isReserve = true;
                $reserveData = RoomReservation::where('room_id', $room->id)->first();
            }
        }
        $returnArr = [
            'id' => $room->id,
            'hostel_id' => $room->hostel_id,
            'hostel_type_rent' => optional($room->hostel)->type_rent,
            'type' => ($room->roomType) ? $room->roomType->id : null,
            'type_name' => ($room->roomType) ? $room->roomType->name : null,
            'size' => $room->size,
            'block_name' => $room->block_name,
            'price' => $room->price,
            'max_renters' => $room->max_renters,
            'number_current_renters' => \App\Models\RenterRoom::where('room_id', $room->id)->count(),
            'is_empty' => $room->is_empty,
            'type_rent' => $room->hostel->type_rent_text,
            'images' => $imageArr,
            'room_name' => $room->name,
            'hostel_name' => $room->hostel->name,
            'amenities' => $hostelAmenities,
            'hostel_amenities' => $hostelAmenities,
            'date_available' => $room->date_available,
            'deposit' => $room->deposit,
            'number_bike' => $numberBike,
            'is_reserve' => $isReserve,
            'reserve_data' => $reserveData
        ];

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

    }


    /**
     * @api {post} /create-renter Lưu người phụ thuộc (hoặc thêm người ở trọ)
     * @apiName create-renter
     * @apiGroup Room
     * @apiDescription Lưu người phụ thuộc (hoặc thêm người ở trọ)
     * @apiParam {String} name
     * @apiParam {String} phone
     * @apiParam {String} id_number
     * @apiParam {String} email
     * @apiParam {String} residence_status Trạng thái khai báo tạm trú
     * @apiParam {String} date_end_residence Thời hạn tạm trú
     * @apiParam {String} room_id
     * @apiParam {String} address
     * @apiParam {String} province_id
     * @apiParam {String} district_id
     * @apiParam {String} ward_id
     * @apiParam {String} birthday
     * @apiParam {String} note Ghi chú khách hàng
     *
     * @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 storeRenter(Request $request)
    {
        $data = $request->all();

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

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

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

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

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

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


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

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

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

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

//        $checkRenter = Renter::query()
//            ->where('phone', $data['phone'])
//            ->first();
//        if ($checkRenter) {
//            return response([
//                'status' => 0,
//                'message' => 'SĐT này hiện đang gắn với một HĐ khác'
//            ]);
//        }

        $hostel = $room->hostel;
        try {
            \DB::beginTransaction();
            $renter = User::where('phone', $data['phone'])->where('type', User::RENTER)->first();

            if (!$renter) {
                $userRenter = Renter::query()->where('phone', $data['phone'])->first();
                if ($userRenter) {
                    $renter = $userRenter->user;
                }
            }
            if (!$renter) {
                $data['password'] = \Hash::make('123456');
                $renter = User::create($data);
            }

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

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


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

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

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


                    ]);

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

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

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

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

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

            $renter->save();

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

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

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

            Functions::updateIsEmptyRoom($room);

            \DB::commit();

            $user = Functions::getCurrentUser();
            $desc = '{' . $user->name . '} thêm khách {' . $request->input('name') . '} vào phòng {' . $room->name . '} nhà {' . $room->hostel->name . '}';
            event(new LogAction([
                'type' => 'create-renter',
                'user_id' => optional($user)->id,
                'object_id' => $renter->id,
                'hostel_id' => $room->hostel_id,
                'room_id' => $room->id,
                'properties' => $renter->toArray(),
                'desc' => $desc
            ]));
        } catch (\Exception $exception) {
            \DB::rollBack();

            \Log::info($exception->getTraceAsString());

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

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

    }

    /**
     * @api {get} /edit-renter Cập nhật người phụ thuộc (hoặc người ở trọ)
     * @apiName edit-renter
     * @apiGroup Room
     * @apiDescription Cập nhật người phụ thuộc (hoặc thêm người ở trọ)
     * @apiParam {String} name
     * @apiParam {String} phone
     * @apiParam {String} id_number
     * @apiParam {String} email
     * @apiParam {String} residence_status Trạng thái khai báo tạm trú
     * @apiParam {String} date_end_residence Thời hạn tạm trú
     * @apiParam {String} room_id
     * @apiParam {String} birthday
     * @apiParam {String} note
     * @apiParam {String} renter_id id của người muốn được cập nhật
     * @apiParam {File} image
     * @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 updateRenter(Request $request)
    {
        $data = $request->all();
        $roomId = $request->input('room_id');

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

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

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

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

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

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

        $renter = User::find($data['renter_id']);

        if (!empty($data['phone'])) {
            $checkPhone = Renter::query()->where('phone', $data['phone'])
                ->where('user_id', '<>', $data['renter_id'])
                ->count();

            if ($checkPhone > 0) {

                $contract = Contract::query()
                    ->where('phone', $data['phone'])
                    ->where('room_id', $roomId)
                    ->first();
                if ($contract) {
                    return response([
                        'status' => 0,
                        'message' => 'SĐT đã tồn tại'
                    ]);
                }
            }
        }

        try {

            \DB::beginTransaction();

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

                $user = $renter->user;
                if ($user) {
                    $user->phone = $data['phone'];
                    //$user->address = $data['address'];
                    $user->save();
                }
            }

            $contract = Contract::where('room_id', $data['room_id'])
                ->where('renter_id', $data['renter_id'])->first();

            if ($contract) {
                if (isset($data['name'])) {
                    $contract->name = $data['name'];
                }

                if (isset($data['id_number'])) {
                    $contract->id_number = $data['id_number'];
                }

                if (isset($data['phone'])) {
                    $contract->phone = $data['phone'];
                }

                if (isset($data['date_join'])) {
                    $contract->date_join = $data['date_join'];
                }

                $contract->save();
            }

            //$user = User::find( $data['renter_id'] );

            $renter = Renter::query()->where('user_id', $data['renter_id'])
                ->where('room_id', $roomId)
                ->orderBy('id', 'desc')
                ->first();


//			if ( $user ) {
//				$user->name    = $data['name'];
//				$user->address = $data['address'];
//				if ( isset( $data['birthday'] ) ) {
//					$user->birthday = $data['birthday'];
//				}
//				$user->save();
//			}
            if ($renter) {
                if (isset($data['id_number_front'])) {
                    $renter->id_number_front = $data['id_number_front'];
                }
                if (isset($data['work_place_id'])) {
                    $renter->work_place_id = $data['work_place_id'];
                }
                if (isset($data['id_number_location'])) {
                    $renter->id_number_location = $data['id_number_location'];
                }
                if (isset($data['id_number_date'])) {
                    $renter->id_number_date = $data['id_number_date'];
                }

                if (isset($data['id_number_back'])) {
                    $renter->id_number_back = $data['id_number_back'];
                }

                if (isset($data['note'])) {
                    $renter->note = $data['note'];
                }
                if (isset($data['birthday'])) {
                    $renter->birthday = $data['birthday'];
                }
                if (isset($data['phone'])) {
                    $renter->phone = $data['phone'];
                }
                $renter->name = $data['name'];
                if (isset($data['image'])) {
                    $renter->image = $data['image'];
                }

                $renter->address = $data['address'];

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

//                if(isset($data['id_number'])) {
//                    $renterRoom->id_number = isset($data['id_number']) ? $data['id_number'] : null;
//                }

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

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

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

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

            \DB::commit();

            if ($renter) {
                $roomId = $renter->room_id;
                $room = Room::find($roomId);
                $user = Functions::getCurrentUser();
                $desc = '{' . $user->name . '} sửa thông tin khách {' . $request->input('name') . '} phòng {' . $room->name . '} nhà {' . $room->hostel->name . '}';
                event(new LogAction([
                    'type' => 'update-renter',
                    'user_id' => optional($user)->id,
                    'object_id' => $renter->id,
                    'hostel_id' => $room->hostel_id,
                    'room_id' => $room->id,
                    'properties' => $renter->toArray(),
                    'desc' => $desc
                ]));
            }
        } catch (\Exception $exception) {
            \DB::rollBack();

            dd($exception->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'
        ]);

    }


    /**
     * @api {post} /end-contract Kết thúc hợp đồng
     * @apiName end-contract
     * @apiGroup Room
     * @apiDescription Kết thúc hợp đồng
     * @apiParam {String} contract_id
     * @apiParam {String} date_end_contract dạng d/m/Y
     * @apiParam {String} is_return_deposit 1 là có, 0 là không trả lại nợ
     * @apiParam {String} is_return_money_info 1 là có, 0 là không trả lại số tiền thừa tiền phòng
     *
     * @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 endContract(Request $request)
    {
        $contractId = $request->input('contract_id');
        $isReturnDeposit = $request->input('is_return_deposit');
        $amountReturnDeposit = $request->input('amount_return_deposit');
        $isReturnMoneyInfo = $request->input('is_return_money_info');
        $dateEndContract = $request->input('date_end_contract');
        $contract = Contract::find($contractId);
        if (!$contract) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $roomId = $contract->room_id;
        $room = $contract->room;
        $hostel = $contract->room->hostel;
        $userId = $contract->renter_id;
        if (empty($dateEndContract)) {
            $dateEndContract = Carbon::now();
        } else {
            $dateEndContract = Carbon::createFromFormat('d/m/Y', $dateEndContract);
        }

        try {
            \DB::beginTransaction();

            $itemsRoomPrice = MoneyInfo::where('room_id', $roomId)
                ->where(function ($q) use ($contract) {

                    $q->orwhere('user_id', $contract->renter_id);
                    $q->orWhere('contract_id', $contract->id);

                })->whereIn('type', [
                    MoneyInfo::VOUCHER_ROOM_PRICE,
                    MoneyInfo::VOUCHER_CONTRACT
                ])->pluck('id')->toArray();

            $moneyDetails = MoneyDetail::whereIn('money_info_id', $itemsRoomPrice)
                ->orderBy('end_date', 'desc')->first();


            $itemsToPaids = MoneyInfo::where('room_id', $roomId)
                ->where(function ($q) use ($contract) {

                    $q->orwhere('user_id', $contract->renter_id);
                    $q->orWhere('contract_id', $contract->id);

                })
                ->where('remain', '>', 0)
                ->get();

            foreach ($itemsToPaids as $itemToPaid) {
                $transaction = Transaction::create([
                    'money_info_id' => $itemToPaid->id,
                    'amount' => $itemToPaid->remain,
                    'note' => 'Thanh toán thanh lý hợp đồng',
                    'room_id' => $roomId,
                    'hostel_id' => $hostel->id,
                    'date_action' => Carbon::now()->toDateString(),
                    'type' => CollectSpend::COLLECT
                ]);

                CollectSpend::create([
                    'amount' => $itemToPaid->remain,
                    'hostel_id' => $hostel->id,
                    'room_id' => $roomId,
                    'name' => 'Thanh toán thanh lý hợp đồng',
                    'note' => 'Thanh toán thanh lý hợp đồng',
                    'payment_method' => CollectSpend::MONEY,
                    'date_action' => Carbon::now()->toDateString(),
                    'user_id' => $contract->renter_id,
                    'money_info_id' => $itemToPaid->id,
                    'type' => CollectSpend::COLLECT,
                    'transaction_id' => $transaction->id
                ]);

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

            }


            if ($isReturnDeposit == 1) {

                $amountDeposit = $contract->deposit;
                if (!empty($amountReturnDeposit)) {
                    $amountDeposit = $amountReturnDeposit;
                }

                if ($amountReturnDeposit > $contract->deposit) {
                    return response([
                        'status' => 0,
                        'message' => 'Số cọc trả lại không được vượt quá cọc Hợp đồng'
                    ]);
                }

                $transaction = Transaction::create([
                    'money_info_id' => null,
                    'amount' => $amountDeposit,
                    'note' => 'Thanh toán tiền cọc HĐ ' . $contract->code,
                    'room_id' => $roomId,
                    'hostel_id' => $hostel->id,
                    'date_action' => Carbon::now()->toDateString(),
                    'type' => CollectSpend::SPEND
                ]);

                CollectSpend::create([
                    'amount' => $amountDeposit,
                    'hostel_id' => $hostel->id,
                    'room_id' => $roomId,
                    'note' => 'Thanh toán tiền cọc HĐ ' . $contract->code,
                    'name' => 'Thanh toán tiền cọc HĐ ' . $contract->code,
                    'payment_method' => CollectSpend::MONEY,
                    'date_action' => Carbon::now()->toDateString(),
                    'user_id' => $contract->renter_id,
                    'money_info_id' => null,
                    'type' => CollectSpend::SPEND,
                    'transaction_id' => $transaction->id,
                    'contract_id' => $contract->id,
                    'is_deposit' => true,
                    'receiver' => $contract->name,
                    'is_return_deposit' => true
                ]);
                $contract->is_return_deposit = true;
                $contract->save();

                CollectSpend::where('contract_id', $contract->id)
                    ->where('is_deposit', true)
                    ->where('type', CollectSpend::COLLECT)
                    ->where('name', 'LIKE', '%Thu tiền đặt cọc%')
                    ->update([
                        'is_return_deposit' => true
                    ]);


                if ($contract->deposit - $amountDeposit > 0) {
                    $statMonth = StatisticMonth::create([
                        'month' => Carbon::now()->month,
                        'year' => Carbon::now()->year,
                        'amount' => $contract->deposit - $amountDeposit,
                        'current_paid' => $amountDeposit,
                        'hostel_id' => $hostel->id,
                        'room_id' => $roomId,
                        'contract_id' => $contract->id,
                    ]);
                    StatisticLog::create([
                        'amount' => $contract->deposit - $amountDeposit,
                        'month' => Carbon::now()->month,
                        'year' => Carbon::now()->year,
                        'type' => CollectSpend::COLLECT,
                        'hostel_id' => $hostel->id,
                        'room_id' => $roomId,
                        'contract_id' => $contract->id,
                        'statistic_month_id' => $statMonth->id,
                        'note' => 'Thu tiền đặt cọc HĐ: ' . $contract->code
                    ]);
                }

            } else {

                $cp = CollectSpend::query()->where('contract_id', $contract->id)
                    ->where('is_deposit', true)
                    ->where('type', CollectSpend::COLLECT)
                    ->where('name', 'LIKE', '%Thu tiền đặt cọc%')
                    ->first();
                if ($cp) {
                    $cp->is_return_deposit = 2;
                    $cp->save();
                }

                Deposit::query()->where('contract_id', $contract->id)->delete();


                $statMonth = StatisticMonth::create([
                    'month' => Carbon::now()->month,
                    'year' => Carbon::now()->year,
                    'amount' => $contract->deposit,
                    'current_paid' => $contract->deposit,
                    'hostel_id' => $hostel->id,
                    'room_id' => $roomId,
                    'contract_id' => $contract->id,
                ]);

                StatisticLog::query()->updateOrCreate([
                    'collect_spend_id' => optional($cp)->id,
                ], [
                    'amount' => $contract->deposit,
                    'month' => Carbon::now()->month,
                    'year' => Carbon::now()->year,
                    'type' => CollectSpend::COLLECT,
                    'hostel_id' => $hostel->id,
                    'room_id' => $roomId,
                    'contract_id' => $contract->id,
                    'statistic_month_id' => $statMonth->id,
                    'collect_spend_id' => optional($cp)->id,
                    'note' => 'Thu tiền đặt cọc HĐ: ' . $contract->code
                ]);
            }

            $latestEndDate = null;
            if ($moneyDetails) {
                $latestEndDate = $moneyDetails->end_date;
            }
            $endDate = null;
            $amountReturned = 0;
            $messageReturned = null;
            if (!empty($latestEndDate)) {
                $endDateCarbon = Carbon::createFromFormat('Y-m-d', $latestEndDate);
                $startDate = $dateEndContract->copy()->addDay(1)->startOfDay();
                if ($startDate->lessThanOrEqualTo($endDateCarbon)) {
                    //$amountReturned  = Functions::calculateMoneyInRange( $contract, $startDate, $endDateCarbon );
                    //$messageReturned = 'Trả lại tiền phòng từ ' . $startDate->copy()->format( 'd/m/Y' ) . ' đến ' . $endDateCarbon->copy()->format( 'd/m/Y' );

                    $amountReturned = Functions::calculateMoneyInRange4($startDate->copy(), $endDateCarbon->copy(), $contract->room_price, $contract->day_collect, true);
                    $messageReturned = 'Trả lại tiền phòng từ ' . $startDate->copy()->format('d/m/Y') . ' đến ' . $endDateCarbon->copy()->format('d/m/Y');
                }
            }

//            if($isReturnMoneyInfo)
//            {
//                $amountReturnUser = $amountRemain - $amountReturned;
//            }
//
//            if($isReturnDeposit)
//            {
//                $amountReturnUser = $amountReturnUser - $contract->deposit;
//            }


            if ($amountReturned > 0) {
                if ($isReturnMoneyInfo == 1) {
                    $contract->is_return_money_info = true;
                    $contract->save();
                    $ownerId = $this->user->id;
                    if ($this->user->type == User::STAFF) {
                        $ownerId = $this->user->staff_owner_id;
                    }
                    $typeSpend = TypeSpend::query()
                        ->where('owner_id', $ownerId)
                        ->where('is_default', 1)
                        ->first();
                    $transaction = Transaction::create([
                        'money_info_id' => null,
                        'amount' => $amountReturned,
                        'note' => $messageReturned . ', HĐ: ' . $contract->code,
                        'room_id' => $roomId,
                        'hostel_id' => $hostel->id,
                        'date_action' => !empty($dateEndContract) ? $dateEndContract->copy()->toDateString() : Carbon::now()->toDateString(),
                        'type' => CollectSpend::SPEND
                    ]);
                    CollectSpend::create([
                        'amount' => $amountReturned,
                        'hostel_id' => $hostel->id,
                        'room_id' => $roomId,
                        'note' => $messageReturned . ', HĐ: ' . $contract->code,
                        'name' => $messageReturned . ', HĐ: ' . $contract->code,
                        'payment_method' => CollectSpend::MONEY,
                        'date_action' => !empty($dateEndContract) ? $dateEndContract->copy()->toDateString() : Carbon::now()->toDateString(),
                        'user_id' => $contract->renter_id,
                        'money_info_id' => null,
                        'type' => CollectSpend::SPEND,
                        'transaction_id' => $transaction->id,
                        'contract_id' => $contract->id,
                        'type_purpose' => optional($typeSpend)->id
                    ]);
                }
            }

            $contract->status = Contract::LIQUIDATED;
            if (isset($dateEndContract)) {
                $contract->date_end_contract = $dateEndContract->toDateString();
            }
            $contract->save();
            $hostelTypeRent = $hostel->type_rent;
            if ($hostelTypeRent == Hostel::TYPE_RENT_EVERY) {
                //change status of bed
                $bed = RoomBed::find($contract->bed_id);
                if ($bed) {
                    $bed->status = RoomBed::AVAILABLE;
                    $bed->save();
                }
            }

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

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

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

            Renter::query()->where('user_id', $contract->renter_id)->where('room_id', $roomId)->update([
                'status' => Renter::LEFT
            ]);

            $moneyInfoArrs = MoneyInfo::query()->where(function ($q) use ($contract) {
                $q->orwhere('user_id', $contract->renter_id);
                $q->orWhere('contract_id', $contract->id);
            })->pluck('id')->toArray();

            MoneyInfo::query()->where(function ($q) use ($contract) {
                $q->orwhere('user_id', $contract->renter_id);
                $q->orWhere('contract_id', $contract->id);
            })->update([
                'contract_status' => Contract::LIQUIDATED
            ]);

            MoneyDetail::query()->whereIn('money_info_id', $moneyInfoArrs)->update([
                'contract_status' => Contract::LIQUIDATED
            ]);

            \DB::table('contract_logs')->insert([
                'contract_id' => $contract->id,
                'status' => Contract::LIQUIDATED,
                'created_at' => Carbon::now()->toDateTimeString(),
                'updated_at' => Carbon::now()->toDateTimeString(),
                'date_end_contract' => isset($dateEndContract) ? $dateEndContract->toDateString() : null
            ]);

            \DB::commit();

            dispatch(new DeleteRenterConversation($contract->renter_id, $contract->room_id));
        } catch (\Exception $exception) {
            \DB::rollBack();

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

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


    /**
     * @api {post} /leave Rời phòng
     * @apiName leave
     * @apiGroup Room
     * @apiDescription Rời phòng
     * @apiParam {String} room_id
     * @apiParam {String} renter_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 leave(Request $request)
    {
        $roomId = $request->input('room_id');
        $renterId = $request->input('renter_id');
        $room = Room::find($roomId);

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

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

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

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

        if ($room) {
            $contract = Contract::query()->where('room_id', $roomId)
                ->where('renter_id', $renterId)
                ->first();

            if ($contract) {
                $bedId = $contract->bed_id;
                $bed = RoomBed::find($bedId);
                $bed->status = RoomBed::AVAILABLE;
                $bed->save();
            }

        }

        $this->dispatch(new DeleteRenterConversation($renterId, $roomId));

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

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


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

    }

    /**
     * @api {post} /create Lưu phòng trọ
     * @apiName /create
     * @apiGroup Room
     * @apiParam {String} amenities Mảng id các tiện ích. Kiểu amenities[] = 1, amenities[] = 2
     * @apiParam {String} user_amenities Mảng tên các tiện ích của user.
     * @apiParam {String} images Mảng các ảnh.
     * @apiParam {String} types Mảng các type ảnh.
     * @apiParam {String} block_name Tầng / khu /dãy
     * @apiParam {String} hostel_id Id nhà trọ
     * @apiParam {String} name
     * @apiParam {String} price
     * @apiParam {String} deposit
     * @apiParam {String} size Diện tích
     * @apiParam {String} max_renters Số người phù hợp
     * @apiParam {String} user_amenities Các tiện ích do user tự thêm
     * @apiParam {String} amenities Các tiện ích được chọn trong danh sách
     * @apiParam {String} types Mảng các loại ảnh phòng
     * @apiParam {String} date_available Ngày trống phòng dạng d/m/Y
     *
     *
     *
     * @apiDescription Api Lưu phòng 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 create(Request $request)
    {
        $data = $request->except('images');

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

        $hostelId = $data['hostel_id'];

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

        if (!$hostel) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        $ownerId = $this->user->id;
        if ($this->user->type == User::STAFF) {
            $ownerId = $this->user->staff_owner_id;
        }
        $hostels = Hostel::query()->where('owner_id', $ownerId)->pluck('id')->toArray();

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

        $cntRoom = $cntRoomEvery + $cntRoomAll;
        $numberRoom = config('constants.LIMIT_ROOM');

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

            $numberRoom = $userPackage->number_rooms;
        }

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

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

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

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

        $dateAvailable = $request->input('date_available');
        if (!empty($dateAvailable)) {

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

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

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

        try {

            \DB::beginTransaction();

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

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

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

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

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

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

            $amenityArr = [];

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

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

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

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

            // dd($amenities);

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

            $currentNumberRoom = $this->user->number_rooms;
            $this->user->number_rooms = $currentNumberRoom + 1;
            $this->user->save();

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

            \DB::commit();

            dispatch(new CreateRoomConservation($room->id, $this->user->id));
            dispatch(new CreateRoomConservationV2($room->id, $this->user->id));
        } catch (\Exception $exception) {
            \DB::rollBack();
            dump($exception->getLine());

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

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

    public function getRoomType()
    {
        $userId = $this->user->id;

        $roomTypes = RoomType::where('owner_id', $userId)->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;

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

            $featureArr = [];
            if (is_array($features)) {
                foreach ($features as $feature) {
                    $item = Amenity::find($feature);
                    if ($item) {
                        $featureArr[] = [
                            'id' => $item->id,
                            'name' => $item->name,
                        ];
                    }
                }
            }

            $roomType->features = $featureArr;
        }

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

    public function getRoomLog(Request $request)
    {
        $id = $request->input('room_id');
        $logs = \DB::table('room_logs')->where('room_id', $id)->orderBy('id', 'desc')->get();

        foreach ($logs as $log) {
            $log->created_at = Carbon::createFromFormat('Y-m-d H:i:s', $log->created_at)->format('d/m/Y H:i');
            $log->updated_at = Carbon::createFromFormat('Y-m-d H:i:s', $log->updated_at)->format('d/m/Y H:i');
        }

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

    public function addRenterByCode(Request $request)
    {
        $data = $request->all();
        $code = $request->input('code');
        $type = $request->input('type');
        $user = User::where('code', $code)->where('type', '<>', User::OWNER)->first();
        if (!$user) {
            return response([
                'status' => 0,
                'message' => 'Mã code không tồn tại, vui lòng kiểm tra lại'
            ]);
        }

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

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

        $checkRenter = RenterRoom::where('user_id', $user->id)->first();

        if ($checkRenter) {
            if ($checkRenter->room_id == $room->id) {
                return response([
                    'status' => 0,
                    'message' => 'Người trọ này đã được thêm vào phòng này rồi'
                ]);
            }
        }

        $hostel = $room->hostel;

        RenterRoom::where('user_id', $user->id)->delete();

        RenterRoom::create([
            'user_id' => $user->id,
            'room_id' => $data['room_id'],
            'hostel_id' => $hostel->id
        ]);

        if ($room) {
            $currentRenter = Functions::getUserForRoom($room);
            $room->current_renter = $currentRenter->id;
            $room->date_available = null;
            $room->is_start_remind = false;
            $room->save();
        }

        \DB::table('room_logs')->insert([
            'content' => 'Thêm người ở trọ ' . $user->name,
            'room_id' => $data['room_id'],
            'created_at' => Carbon::now()->toDateTimeString(),
            'updated_at' => Carbon::now()->toDateTimeString()
        ]);

        Notification::create([
            'to_user' => $user->id,
            'hostel_id' => $hostel->id,
            'room_id' => $data['room_id'],
            'title' => 'Thông báo từ itro.vn',
            'image' => $this->user->image,
            'user_id' => $this->user->id,
            'content' => 'Bạn vừa được chủ trọ thêm vào nhà trọ  ' . $hostel->name . ', phòng ' . $room->name . '. Nếu thông tin không đúng, vui lòng liên hệ với chúng tôi để xoá bỏ sự liên kết này'
        ]);

        Notification::create([
            'to_user' => $this->user->id,
            'hostel_id' => $hostel->id,
            'room_id' => $data['room_id'],
            'title' => 'Thông báo từ itro.vn',
            'image' => $user->image,
            'user_id' => $this->user->id,
            'content' => 'Bạn vừa thêm thành công ' . $user->name . ' vào phòng ' . $room->name . '. Hãy nhờ người trọ đánh giá về nhà trọ của bạn trên itro để tăng độ xếp hạng nhà trọ của bạn'
        ]);

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

        if (empty($type)) {
            $hostels = Hostel::where('owner_id', $this->user->id)->get();
            $rooms = Room::whereIn('hostel_id', $hostels->pluck('id')->toArray())->pluck('id')->toArray();

            // $renters = RenterRoom::whereIn('renter_rooms.room_id', $rooms)->orderBy('id', 'desc')->get();
        }

        Functions::updateNumberEmptyRoom($hostel);

        $remindRating = (new RemindRating($user->id, $hostel->id))->delay(Carbon::now()->addMonth(1));

        dispatch($remindRating);

        return response([
            'status' => 1,
            'message' => 'Thêm người vào phòng trọ thành công',
        ]);
    }


    /**
     * @api {post} /delete Xóa HĐ
     * @apiName delete
     * @apiGroup Contract
     * @apiParam {String} id
     * @apiDescription Api Xóa HĐ
     * @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 destroyContract(Request $request)
    {
        $id = $request->input('id');

        if ($this->user->cannot('delete-contract')) {
            return response([
                'status' => 0,
                'message' => 'Bạn không có quyền thao tác'
            ]);
        }
        $item = Contract::find($id);
        if (!$item) {
            return response([
                'status' => 0,
                'message' => 'Hợp đồng không tồn tại'
            ]);
        }

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

        $ownerId = $this->user->id;
        if ($this->user->type == User::STAFF) {
            $ownerId = $this->user->staff_owner_id;
        }
        if ($hostel) {
            if ($hostel->owner_id != $ownerId) {
                return response([
                    'status' => 0,
                    'message' => 'Bạn không phải chủ nhà trọ này'
                ]);
            }
        }

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

        try {
            \DB::beginTransaction();

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

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

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

            foreach ($moneyInfos as $moneyInfo) {
                MoneyDetail::query()->where('money_info_id', $moneyInfo->id)->delete();
                CollectSpend::query()->where('money_info_id', $moneyInfo->id)->delete();
                Statistic::query()->where('money_info_id', $moneyInfo->id)->delete();
            }
            $room = $item->room;
            MoneyInfo::query()->where('contract_id', $contractId)->delete();
            if ($item->status != Contract::LIQUIDATED) {
//				RenterRoom::query()->where( 'user_id', $item->renter_id )->where( 'room_id', $roomId )->delete();
//				RenterBike::query()->where( 'renter_id', $item->renter_id )->where( 'room_id', $roomId )->delete();
//				Renter::query()->where( 'user_id', $item->renter_id )->where( 'room_id', $roomId )->delete();

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

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

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

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

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

            $item->delete();

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

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

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

        }

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


    }

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

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

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

        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Phòng không tồn tại',
            ]);
        }

        $hostelId = $room->hostel->id;
        $user = null;

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

        if (!$hostel) {
            return response([
                'status' => 0,
                'message' => 'Nhà trọ không tồn tại',
            ]);
        }

        $checkEmail = null;
        $check = User::where('phone', $data['phone'])->first();

        if (!empty($data['email'])) {
            $checkEmail = User::where('email', $data['email'])->first();
        }


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

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

        if (!empty($data['birthday'])) {
            try {
                $birthday = Carbon::createFromFormat('d/m/Y', $data['birthday'])->format('d/m/Y');
            } catch (\Exception $ex) {
                $birthday = null;
            }

            $data['birthday'] = $birthday;
        }

        if ($check) {

            if ($check->first_add_renter) {
                $user = $check;
            } else {

                return response([
                    'status' => 0,
                    'message' => 'SĐT đã tồn tại trên hệ thống. Bạn vui lòng thêm người ở trọ bằng mã'
                ]);
            }
        } else if (!empty($checkEmail)) {

            if ($checkEmail->first_add_renter) {
                $user = $checkEmail;
            } else {
                return response([
                    'status' => 0,
                    'message' => 'Email đã tồn tại trên hệ thống. Bạn vui lòng thêm người ở trọ bằng mã'
                ]);
            }
        } else {

            $user = User::create($data);
        }

        $checkRenter = RenterRoom::where('user_id', $user->id)->where('room_id', $data['room_id'])->count();

        if ($checkRenter == 0) {
            RenterRoom::create([
                'user_id' => $user->id,
                'room_id' => $data['room_id'],
                'hostel_id' => $hostelId
            ]);
        }

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

        if ($room) {
            $currentRenter = Functions::getUserForRoom($room);
            $room->date_available = null;
            $room->is_start_remind = false;
            $room->current_renter = $currentRenter->id;
            $room->save();
        }

        \DB::table('room_logs')->insert([
            'content' => 'Thêm người ở trọ ' . $user->first_name . ' ' . $user->last_name,
            'room_id' => $data['room_id'],
            'created_at' => Carbon::now()->toDateTimeString(),
            'updated_at' => Carbon::now()->toDateTimeString()
        ]);

        Notification::create([
            'to_user' => $user->id,
            'hostel_id' => $hostelId,
            'room_id' => $data['room_id'],
            'title' => 'Thông báo từ itro.vn',
            'user_id' => $this->user->id,
            'content' => 'Chủ trọ ' . $this->user->name . ' đã thêm bạn vào phòng ' . $room->name . ' nhà trọ ' . $room->hostel->name
        ]);

        Functions::updateNumberEmptyRoom($hostel);

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

        return response([
            'status' => 1,
            'message' => 'Thêm người vào phòng trọ thành công',
        ]);
    }

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

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

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

        $user = User::find($data['user_id']);

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

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

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

        $hostelId = $room->hostel->id;

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

        if ($cntRenterRoom <= 1) {
            $remain = MoneyInfo::where('room_id', $data['room_id'])->sum('remain');
            if ($remain > 0) {
                return response([
                    'status' => 0,
                    'message' => 'Người trọ phải thanh toán khoản nợ: ' . number_format($remain, 0, '.', '.') . ' mới có thể xóa khỏi phòng trọ'
                ]);
            }


        }

        RenterRoom::query()->where('room_id', $data['room_id'])->where('user_id', $data['user_id'])->delete();
        Contract::query()->where('renter_id', $data['user_id'])
            ->where('room_id', $data['room_id'])
            ->delete();

        \DB::table('room_logs')->insert([
            'content' => 'Xóa người ở trọ ' . $user->name,
            'room_id' => $data['room_id'],
            'created_at' => Carbon::now()->toDateTimeString(),
            'updated_at' => Carbon::now()->toDateTimeString()
        ]);

        Notification::create([
            'to_user' => $user->id,
            'hostel_id' => $hostelId,
            'room_id' => $data['room_id'],
            'title' => 'Thông báo từ itro.vn',
            'user_id' => $this->user->id,
            'content' => 'Chủ trọ ' . $this->user->name . ' đã xóa bạn khỏi phòng ' . $room->name . ' nhà trọ ' . $room->hostel->name
        ]);

        if ($user->first_add_renter) {
            $user->delete();
        }

        dispatch(new DeleteRenterConversation($user->id, $room->id));

        return response([
            'status' => 1,
            'message' => 'Xóa người ở trợ thành công'
        ]);
    }

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

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

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

        $renters = RenterRoom::select(\DB::raw('users.first_name, users.last_name, renter_rooms.room_id, users.name,users.id, users.id_number, users.id as user_id,
         users.address, users.phone, users.birthday, renter_rooms.date_joined as date_joined, users.email,
        renter_rooms.residence_status, renter_rooms.contract_id, renter_rooms.date_end_residence, renter_rooms.user_id as renter_id, users.id_number'))
            ->join('users', 'renter_rooms.user_id', '=', 'users.id')
            ->whereNull('renter_rooms.deleted_at')
            ->where('renter_rooms.room_id', $id);

        if ($room->hostel->type_rent == Hostel::TYPE_RENT_ALL) {
            $renters = $renters->orderBy('renter_rooms.contract_id', 'desc');
        } else {
            $renters = $renters->orderBy('renter_rooms.created_at', 'desc');
        }

        $renters = $renters->get();

        $returnArr = [];
        foreach ($renters as $renter) {

            $isRepresent = false;
            if ($room->hostel->type_rent == Hostel::TYPE_RENT_ALL) {
                if (!empty($renter->contract_id)) {
                    $isRepresent = true;
                }
            }

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


            $returnArr[] = [
                'is_represent' => $isRepresent,
                'first_name' => $renter->first_name,
                'last_name' => $renter->last_name,
                'name' => $renter->name,
                'id' => $renter->id,
                'image' => optional($renter2)->image,
                'address' => optional($renter2)->address,
                'phone' => $renter->phone,
                'birthday' => $birthday,
                'email' => $renter->email,
                'date_joined' => empty($renter->date_joined) ? null : Carbon::createFromFormat('Y-m-d H:i:s', $renter->date_joined)->format('d/m/Y'),
                'id_number' => $renter->id_number,
                'date_end_residence' => empty($renter->date_end_residence) ? null : $renter->date_end_residence->format('d/m/Y'),
                'residence_status' => $renter->residence_status,
                'room_id' => $renter->room_id,
                'note' => !empty($renter2) ? $renter2->note : null,
                'renter_id' => $renter->renter_id,
                'contract_id' => $renter->contract_id
            ];
        }

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


    public function getRentersByContract(Request $request)
    {
        $contractId = $request->input('contract_id');
        $contract = Contract::withTrashed()->find($contractId);

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

        $room = $contract->room;

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

        $hostel = $room->hostel;

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

        if ($hostel->type_rent == Hostel::TYPE_RENT_ALL) {

            $renters = RenterRoom::query()->select(\DB::raw('users.first_name, users.last_name, renter_rooms.room_id, users.name,users.id, users.id_number, users.id as user_id,
         users.address, users.phone, users.birthday, renter_rooms.date_joined as date_joined, users.email,
        renter_rooms.residence_status, renter_rooms.contract_id, renter_rooms.date_end_residence, renter_rooms.user_id as renter_id, users.id_number'))
                ->join('users', 'renter_rooms.user_id', '=', 'users.id')
                ->where(function ($q) use ($contractId) {
                    $q->orWhere('renter_rooms.room_contract_id', $contractId);
                    $q->orWhere('renter_rooms.contract_id', $contractId);
                });
        } else {

            $renters = RenterRoom::query()->select(\DB::raw('users.first_name, users.last_name, renter_rooms.room_id, users.name,users.id, users.id_number, users.id as user_id,
         users.address, users.phone, users.birthday, renter_rooms.date_joined as date_joined, users.email,
        renter_rooms.residence_status, renter_rooms.contract_id, renter_rooms.date_end_residence, renter_rooms.user_id as renter_id, users.id_number'))
                ->join('users', 'renter_rooms.user_id', '=', 'users.id')
                ->where('renter_rooms.contract_id', $contractId);
        }
        // return response([
        //     'status' => 1,
        //     'data' => $renters
        // ]);
        if ($hostel->type_rent == Hostel::TYPE_RENT_ALL) {
            $renters = $renters->orderBy('renter_rooms.contract_id', 'desc');
        } else {
            $renters = $renters->orderBy('renter_rooms.created_at', 'desc');
        }
        $renters = $renters->get();
        

        
        $returnArr = [];
        foreach ($renters as $renter) {
            $user = User::find($renter->user_id);
            $isRepresent = false;
            if ($room->hostel->type_rent == Hostel::TYPE_RENT_ALL) {
                if (!empty($renter->contract_id)) {
                    $isRepresent = true;
                }
            }

            $renter2 = Renter::query()->where('user_id', $renter->user_id)->first();
            $image = $user->image;
            $birthday = $user->birthday;
            if ($renter2) {
                if ($renter2->image) {
                    $image = $renter2->image;
                }

                if ($renter2->birthday) {
                    $birthday = $renter2->birthday;
                }
            }

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

            $returnArr[] = [
                'is_represent' => $isRepresent,
                'first_name' => $renter->first_name,
                'last_name' => $renter->last_name,
                'name' => $renter->name,
                'id' => $renter->id,
                'image' => $image,
                'address' => optional($renter2)->address,
                'phone' => $renter->phone,
                'birthday' => $birthday,
                'email' => $renter->email,
                'date_joined' => empty($renter->date_joined) ? null : Carbon::createFromFormat('Y-m-d H:i:s', $renter->date_joined)->format('d/m/Y'),
                'id_number' => $renter->id_number,
                'date_end_residence' => empty($renter->date_end_residence) ? null : $renter->date_end_residence->format('d/m/Y'),
                'residence_status' => $renter->residence_status,
                'room_id' => $renter->room_id,
                'note' => !empty($renter2) ? $renter2->note : null,
                'renter_id' => $renter->renter_id
            ];
        }

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


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

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

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

    /**
     * @api {post} /create-room-type Tạo loại phòng
     * @apiName create-room-type
     * @apiGroup Room
     * @apiDescription Api Tạo loại phòng
     * @apiParam {String} name
     * @apiParam {String} price
     * @apiParam {String} size
     * @apiParam {String} max_peoples
     * @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 createRoomType(Request $request)
    {
        $data = $request->all();
        $data['owner_id'] = $this->user->id;

        RoomType::create($data);

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

    /**
     * @api {post} /update-room-type Cập nhật loại phòng
     * @apiName update-room-type
     * @apiGroup Room
     * @apiDescription Api Cập nhật loại phòng
     * @apiParam {String} id
     * @apiParam {String} name
     * @apiParam {String} price
     * @apiParam {String} size
     * @apiParam {String} max_peoples
     *
     * @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 updateRoomType(Request $request)
    {
        $data = $request->except('id');
        $id = $request->input('id');
        $data['owner_id'] = $this->user->id;

        RoomType::where('id', $id)->update($data);

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

    /**
     * @api {post} /create-room-note Tạo ghi chú phòng
     * @apiName create-room-note
     * @apiGroup Room
     * @apiDescription Api Tạo ghi chú phòng
     * @apiParam {String} room_id
     * @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 createRoomNote(Request $request)
    {
        $data = $request->all();
        $data['user_id'] = $this->user->id;

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

        $data['hostel_id'] = $room->hostel_id;
        RoomNote::create($data);

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

    /**
     * @api {post} /update-room-note Cập nhật ghi chú phòng
     * @apiName update-room-note
     * @apiGroup Room
     * @apiDescription Api Cập nhật ghi chú phòng
     * @apiParam {String} id
     * @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 updateRoomNote(Request $request)
    {
        $data = $request->all();

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

        $item->update($data);

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

    /**
     * @api {post} /delete-room-note Xóa ghi chú phòng
     * @apiName delete-room-note
     * @apiGroup Room
     * @apiDescription Api Xóa ghi chú phòng
     * @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 deleteRoomNote(Request $request)
    {
        $data = $request->all();

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

        $item->delete();

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


    }

    /**
     * @api {get} /get-room-note Danh sách ghi chú phòng
     * @apiName get-room-note
     * @apiGroup Room
     * @apiDescription Api Danh sách ghi chú phòng
     * @apiParam {String} room_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 getRoomNote(Request $request)
    {
        $items = RoomNote::where('room_id', $request->input('room_id'))
            ->get();

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

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

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

        if ($room) {
            $type = $room->type;
            if (!empty($type)) {
                $rt = RoomType::find($type);
                if ($rt) {
                    $room->room_type_name = $rt->name;
                }
            }

            return response([

                'status' => 1,
                'data' => $room,
                'message' => 'Thành công'
            ]);
        }

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

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

        if ($room) {

            $data['fees'] = Functions::getFeeRoom($room);

            return response([

                'status' => 1,
                'data' => $data,
                'message' => 'Thành công'
            ]);
        }

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

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

        $roomId = $data['room_id'];

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

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

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

        $fee = $data['fee'];
        $name = $data['name'];

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

        if (!is_numeric($fee)) {

            return response([
                'status' => 0,
                'message' => 'Giá trị phải là số'
            ]);
        }

        $fee = RoomFee::create($data);


        return response([
            'status' => 1,
            'message' => 'Tạo thành công',
            'data' => [
                'id' => $fee->id,
                'value' => $fee->fee,
                'name' => $fee->name,
                'type' => 'FEE'
            ]
        ]);


    }

    public function deleteFee(Request $request)
    {
        $id = $request->input('fee_id');
        $item = RoomFee::find($id);
        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 {post} /delete-room-type Xóa loại phòng
     * @apiName delete-room-type
     * @apiGroup Room
     * @apiParam {String} id
     * @apiDescription  Xóa loại phòng
     * @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 deleteRoomType(Request $request)
    {
        $roomType = $request->input('id');
        $item = RoomType::find($roomType);
        if ($item) {
            $checkRoom = Room::where('type', $item->id)->count();

            if ($checkRoom) {
                return response([
                    'status' => 0,
                    'message' => 'Không thể xóa loại phòng có tồn tại phòng trọ',
                ]);
            }

            $item->delete();
        }


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

    /**
     * @api {post} /update Cập nhật phòng trọ
     * @apiName update
     * @apiGroup Room
     * @apiDescription Api Cập nhật phòng trọ
     *
     * @apiParam {String} room_id
     * @apiParam {String} amenities Mảng id các tiện ích. Kiểu amenities[] = 1, amenities[] = 2
     * @apiParam {String} user_amenities Mảng tên các tiện ích của user.
     * @apiParam {String} images Mảng các ảnh.
     * @apiParam {String} deleted_images Mảng id các ảnh xóa đi. Dạng json [1,2,3]
     * @apiParam {String} types Mảng các type ảnh.
     * @apiParam {String} block_name Tầng / khu /dãy
     * @apiParam {String} hostel_id Id nhà trọ
     * @apiParam {String} name
     * @apiParam {String} price
     * @apiParam {String} deposit
     * @apiParam {String} size Diện tích
     * @apiParam {String} max_renters Số người phù hợp
     * @apiParam {String} user_amenities Các tiện ích do user tự thêm
     * @apiParam {String} amenities Các tiện ích được chọn trong danh sách
     * @apiParam {String} types Mảng các loại ảnh phòng
     * @apiParam {String} date_available Ngày trống phòng dạng d/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 update(Request $request)
    {
        $id = $request->input('room_id');
        $room = Room::find($id);
        if (!$room) {
            return response([
                'status' => 0,
                'data' => null
            ]);
        }

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

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

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

        $dateAvailable = $request->input('date_available');
        if (!empty($dateAvailable)) {

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

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

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

        try {

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

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

            $room->update($data);

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

            if (!empty($deletedImages)) {
                if (is_array($deletedImages)) {
                    foreach ($deletedImages as $imageDelete) {
                        \DB::table('room_images')->where('id', $imageDelete)->delete();
                    }
                }
            }

            $amenityArr = [];

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

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


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

            \DB::commit();

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

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

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

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

    }


    public function getFeeByHostel(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $fees = HostelFee::where('hostel_id', $hostelId)->get();

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

    /**
     * @api {post} /delete Xóa phòng
     * @apiName delete
     * @apiGroup Room
     * @apiDescription Xóa phòng
     * @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 destroy(Request $request)
    {
        $id = $request->input('id');
        $room = Room::find($id);

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


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

        dispatch(new DeleteRoomConversation($room->id, $room->hostel->id, $userCreate, $this->user));

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

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

        $room->delete();


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

    /**
     * @api {post} /create-contract Tạo hợp đồng
     * @apiName create-contract
     * @apiGroup Room
     * @apiDescription Tạo hợp đồng
     * @apiParam {String} date_contract Ngày hợp đồng
     * @apiParam {String} date_enable Ngày hiệu lực
     * @apiParam {String} start_date Thuê từ ngày (dạng d/m/Y)
     * @apiParam {String} end_date Thuê đến ngày (dạng d/m/Y)
     * @apiParam {String} room_price Tiền phòng
     * @apiParam {String} deposit Đặt cọc
     * @apiParam {String} period Chu kỳ trả (truyền 1 2 3 6 12)
     * @apiParam {String} type_rent Hình thức thuê (1 là đầu kỳ 2 là cuối kỳ)
     * @apiParam {String} is_collected Đã thu tiền phòng hay chưa ('on' là có)
     * @apiParam {String} collect_to Đã thu tiền đến tháng (dạng 'm/Y')
     * @apiParam {String} note Ghi chú khách hàng
     * @apiParam {String} phone SĐT khách
     * @apiParam {String} name Tên khách
     * @apiParam {File} image Ảnh khách
     * @apiParam {String} email Email khách
     * @apiParam {String} address Địa chỉ khách
     * @apiParam {String} id_number CMND khách
     * @apiParam {String} date_join Ngày vào (dạng 'd/m/Y')
     * @apiParam {String} residence_status Trạng thái tạm trú (0 là chưa khai báo, 1 là có thời hạn, 2 là không thời hạn)
     * @apiParam {String} date_end_residence Hạn tạm trú
     * @apiParam {String} fee_contracts Id của cái fee ["10", "11"]
     * @apiParam {String} qty Số lượng hoặc chỉ số đầu của fee
     * @apiParam {String} province_id
     * @apiParam {String} district_id
     * @apiParam {String} ward_id
     * @apiParam {String} birthday
     *
     *
     *
     * @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 storeContract(Request $request)
    {
        $data = $request->all();
        $feeContracts = $request->input('fee_contracts');
        //$feeContracts = json_decode( $feeContracts, true );

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

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

        $hostel = $room->hostel;

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

        $hostelId = $hostel->id;

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


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


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

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

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

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

        $checkContract = Contract::where('phone', $data['phone'])
            ->where('status', Contract::VALIDATED)->count();

        if ($checkContract) {
            return response([
                'status' => 0,
                'message' => 'SĐT đang có Hợp đồng hoạt động nên không thể thêm'
            ]);
        }

        try {
            \DB::beginTransaction();
            $data['hostel_id'] = $hostelId;
            $hostelTypeRent = $hostel->type_rent;
            if ($hostelTypeRent == Hostel::TYPE_RENT_ALL) {
                $checkContractValidated = Contract::where('status', '<>', Contract::LIQUIDATED)
                    ->where('room_id', $roomId)
                    ->count();

                if ($checkContractValidated) {
                    return response([
                        'status' => 0,
                        'message' => 'Bạn cần thanh lý HĐ trước khi tạo HĐ mới'
                    ]);
                }
            }
            if ($hostelTypeRent == Hostel::TYPE_RENT_EVERY) {
                $checkContractValidated = Contract::where('status', '<>', Contract::LIQUIDATED)
                    ->where('bed_id', $bedId)
                    ->count();
                if ($checkContractValidated) {
                    return response([
                        'status' => 0,
                        'message' => 'Bạn cần thanh lý HĐ trước khi tạo HĐ mới'
                    ]);
                }
            }

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

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

            $contract = Contract::create($data);


            $reserveId = $request->input('reserve_id');

            $reserveDeposit = 0;
            $reserve = null;

            if (!empty($reserveId)) {
                $reserve = RoomReservation::find($reserveId);
                if ($reserve) {

                    CollectSpend::where('reserve_id', $reserve->id)
                        ->update([
                            'contract_id' => $contract->id,
                            'is_return_deposit' => true,
                        ]);

                    $reserveDeposit = $reserve->deposit;
                    $reserve->delete();
                }

                if ($room->hostel->type_rent == Hostel::TYPE_RENT_ALL) {
                    $reserve = RoomReservation::query()->where('room_id', $reserveId)->first();
                    if ($reserve) {
                        CollectSpend::query()->where('reserve_id', $reserve->id)
                            ->update([
                                'contract_id' => $contract->id,
                                'is_return_deposit' => true,
                            ]);
                        $reserveDeposit = $reserve->deposit;
                        $reserve->delete();
                    }
                }

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

                    CollectSpend::create([
                        'amount' => $reserveDeposit,
                        'hostel_id' => $hostel->id,
                        'room_id' => $roomId,
                        'note' => 'Thanh toán tiền cọc giữ chỗ HĐ ' . 'HD' . $contract->id . Carbon::now()->format('dmY'),
                        'name' => 'Thanh toán tiền cọc giữ chỗ HĐ ' . 'HD' . $contract->id . Carbon::now()->format('dmY'),
                        'payment_method' => CollectSpend::MONEY,
                        'date_action' => Carbon::now()->toDateString(),
                        'user_id' => $contract->renter_id,
                        'money_info_id' => null,
                        'type' => CollectSpend::SPEND,
                        'transaction_id' => $transaction->id,
                        'contract_id' => $contract->id,
                        'is_deposit' => true,
                        'is_return_deposit' => true
                    ]);
                }
            }

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

            if ($data['deposit'] > 0) {

                $transaction = Transaction::create([
                    'amount' => $data['deposit'],
                    'hostel_id' => $hostelId,
                    'room_id' => $roomId,
                    'date_action' => Carbon::now()->toDateString(),
                    'type' => CollectSpend::COLLECT,
                    'note' => 'Thu tiền đặt cọc Hợp đồng ' . $contract->code,
                ]);

                CollectSpend::create([
                    'amount' => $data['deposit'],
                    'hostel_id' => $hostelId,
                    'room_id' => $roomId,
                    'note' => 'Thu tiền đặt cọc Hợp đồng ' . $contract->code,
                    'payment_method' => CollectSpend::MONEY,
                    'date_action' => Carbon::now()->toDateString(),
                    'type' => CollectSpend::COLLECT,
                    'name' => 'Thu tiền đặt cọc Hợp đồng ' . $contract->code,
                    'transaction_id' => $transaction->id,
                    'contract_id' => $contract->id,
                    'is_deposit' => true,
                ]);

//                if (!empty($reserveDeposit)) {
//                    if ($data['deposit'] > $reserveDeposit) {
//
//                        $transaction = Transaction::create([
//                            'amount' => $data['deposit'] - $reserveDeposit,
//                            'hostel_id' => $hostelId,
//                            'room_id' => $roomId,
//                            'date_action' => Carbon::now()->toDateString(),
//                            'type' => CollectSpend::COLLECT,
//                            'note' => 'Thu tiền đặt cọc Hợp đồng ' . $contract->code . ' đã trừ đặt cọc giữ chỗ' . number_format($reserveDeposit, 0, '.', '.')
//                        ]);
//
//                        CollectSpend::create([
//                            'amount' => $data['deposit'] - $reserveDeposit,
//                            'hostel_id' => $hostelId,
//                            'room_id' => $roomId,
//                            'note' => 'Thu tiền đặt cọc Hợp đồng ' . $contract->code . ' đã trừ đặt cọc giữ chỗ' . number_format($reserveDeposit, 0, '.', '.'),
//                            'payment_method' => CollectSpend::MONEY,
//                            'date_action' => Carbon::now()->toDateString(),
//                            'type' => CollectSpend::COLLECT,
//                            //'note' => 'Thu tiền đặt cọc Hợp đồng ' . $contract->code . ' đã trừ đặt cọc giữ chỗ' . number_format($reserveDeposit, 0, '.', '.'),
//                            'transaction_id' => $transaction->id,
//                            'contract_id' => $contract->id,
//                            'is_deposit' => true,
//                            'payer' => $data['name'],
//                            'reserve_id' => !empty($reserve) ? $reserve->id : null,
//                        ]);
//                    } else if ($data['deposit'] < $reserveDeposit) {
//                        $transaction = Transaction::create([
//                            'amount' => $reserveDeposit - $data['deposit'],
//                            'hostel_id' => $hostelId,
//                            'room_id' => $roomId,
//                            'date_action' => Carbon::now()->toDateString(),
//                            'type' => CollectSpend::SPEND,
//                        ]);
//
//                        CollectSpend::create([
//                            'amount' => $reserveDeposit - $data['deposit'],
//                            'hostel_id' => $hostelId,
//                            'room_id' => $roomId,
//                            'note' => 'Thanh toán thừa đặt cọc Hợp đồng ' . $contract->code . ' do đã thu ' . number_format($reserveDeposit, 0, '.', '.') . ' đặt cọc giữ chỗ trước đó',
//                            'payment_method' => CollectSpend::MONEY,
//                            'date_action' => Carbon::now()->toDateString(),
//                            'type' => CollectSpend::SPEND,
//                            'receiver' => $data['name'],
//                            'name' => 'Thanh toán thừa đặt cọc Hợp đồng ' . $contract->code . ' do đã thu ' . number_format($reserveDeposit, 0, '.', '.') . ' đặt cọc giữ chỗ trước đó',
//                            'transaction_id' => $transaction->id,
//                            'is_deposit' => true,
//                            'payer' => $data['name'],
//                            'reserve_id' => !empty($reserve) ? $reserve->id : null,
//                        ]);
//                    }
//                } else {
//                    $transaction = Transaction::create([
//                        'amount' => $data['deposit'],
//                        'hostel_id' => $hostelId,
//                        'room_id' => $roomId,
//                        'date_action' => Carbon::now()->toDateString(),
//                        'type' => CollectSpend::COLLECT,
//                        'note' => 'Thu tiền đặt cọc Hợp đồng ' . $contract->code,
//                    ]);
//
//                    CollectSpend::create([
//                        'amount' => $data['deposit'] - $reserveDeposit,
//                        'hostel_id' => $hostelId,
//                        'room_id' => $roomId,
//                        'note' => 'Thu tiền đặt cọc Hợp đồng ' . $contract->code,
//                        'payment_method' => CollectSpend::MONEY,
//                        'date_action' => Carbon::now()->toDateString(),
//                        'type' => CollectSpend::COLLECT,
//                        'name' => 'Thu tiền đặt cọc Hợp đồng ' . $contract->code,
//                        'transaction_id' => $transaction->id,
//                        'contract_id' => $contract->id,
//                        'payer' => $data['name'],
//                        'is_deposit' => true,
//                    ]);
//                }
            }

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


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

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


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

                $data['birthday'] = $birthday;
            }


            if ($check) {
                if (empty($check->id_number)) {
                    $check->id_number = $data['id_number'];
                    $check->save();
                }
                $user = $check;
            } else {
                if (isset($data['customer_image'])) {
                    $data['image'] = $data['customer_image'];
                    unset($data['customer_image']);
                }

                $data['password'] = \Hash::make('123456');
                $user = User::create($data);
                unset($data['password']);
            }

            $checkRenter = RenterRoom::where('user_id', $user->id)->where('room_id', $data['room_id'])->count();

            if ($checkRenter == 0) {
                RenterRoom::create([
                    'user_id' => $user->id,
                    'room_id' => $data['room_id'],
                    'hostel_id' => $hostelId,
                    'type_rent' => $hostel->type_rent,
                    'contract_id' => $contract->id,
                    'date_joined' => $data['date_join'],
                    'residence_status' => $data['residence_status'],
                    'date_end_residence' => $data['date_end_residence'],
                ]);

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

//                    'residence_status' => $data['residence_status'],
//                    ''
                ]);
            }


            $contract->update([
                'renter_id' => $user->id
            ]);

            if ($room) {
                $currentRenter = Functions::getUserForRoom($room);
                $room->date_available = null;
                $room->is_start_remind = false;
                $room->current_renter = $currentRenter->id;
                $room->save();
            }

            \DB::table('room_logs')->insert([
                'content' => 'Thêm người ở trọ ' . $user->name,
                'room_id' => $data['room_id'],
                'created_at' => Carbon::now()->toDateTimeString(),
                'updated_at' => Carbon::now()->toDateTimeString()
            ]);

            Functions::updateNumberEmptyRoom($hostel);
            $period = Functions::getPeriodNumber($data['period']);
            $from = Carbon::createFromFormat('Y-m-d', $data['date_enable']);
            $fromChange = clone $from;
            if (isset($data['is_collected']) && ($data['is_collected'] == 'on')) {

                if ($data['is_collected'] == 'on') {
                    $collectTo = $data['collect_to'];
                    if (empty($collectTo)) {
                        return response([
                            'status' => 0,
                            'message' => 'Bạn phải chọn tháng đã thu đến'
                        ]);
                    }
                    $to = Carbon::createFromFormat('d/m/Y', '01/' . $collectTo);
                    $contract->update([
                        'is_collected' => true,
                        'collect_to' => $to->toDateString()
                    ]);
                    while ($fromChange->lessThanOrEqualTo(Carbon::now())) {
                        $startDate = clone $fromChange;
                        $endDate = clone $fromChange;

                        if ($period > 1) {

                            $endDate->addMonth($period - 1)->lastOfMonth();

                            $name = 'Thu tiền phòng từ ' . $fromChange->format('d/m/Y') . ' đến ' .
                                $fromChange->addMonth($period - 1)->lastOfMonth()->format('d/m/Y');

                        } else {
                            $endDate->lastOfMonth();

                            $name = 'Thu tiền phòng từ ' . $fromChange->format('d/m/Y') . ' đến ' . $fromChange->lastOfMonth()->format('d/m/Y');
                        }
                        if ($startDate->day != 1) {
                            $range = Functions::calculatePeriod2($startDate, $endDate);
                        } else {
                            $range = $period;
                        }
                        $fromChange->addDay(1);
                        $money = intval(round($contract->room_price * $range));
                        $rangePaid = 0;
                        $paidMoney = 0;

                        if ($to->lastOfMonth()->lessThanOrEqualTo($endDate) && $to->lastOfMonth()->greaterThanOrEqualTo($startDate)) {
                            //	dump('wow');
                            if ($endDate->month == $to->month && $endDate->year == $to->year) {
                                $paidMoney = $money;
                            } else {

                                if ($startDate->day != 1) {
                                    $rangePaid = Functions::calculatePeriod2($startDate, $to->lastOfMonth());
                                } else {
                                    $rangePaid = $to->diffInMonths($startDate);
                                }
                                if ($rangePaid == 0) {
                                    $rangePaid++;
                                }
                                $paidMoney = $rangePaid * $contract->room_price;
                            }


                        } else if ($to->lastOfMonth()->greaterThanOrEqualTo($endDate)) {
                            //dump('wow2');
                            $paidMoney = $money;
                        } else if ($to->lastOfMonth()->lessThanOrEqualTo($startDate)) {
                            //dump('wow3');
                            $paidMoney = 0;
                        }

                        $check = Functions::checkExistDate($hostel, $startDate, $endDate, $contract, $roomId, $hostelId);
                        // dump($name);
                        if ($check == 0) {
//							dump($name);
//							dump($range);
//							dump($paidMoney);
//							dump($money);
                            $moneyInfo = MoneyInfo::create([
                                'hostel_id' => $hostelId,
                                'room_id' => $roomId,
                                'date_action' => $startDate->toDateString(),
                                'contract_id' => $contract->id,
                                'user_id' => $user->id,
                                'type' => MoneyInfo::VOUCHER_CONTRACT,
                                'amount' => $money,
                                'pay' => $paidMoney,
                                'remain' => $money - $paidMoney,
                                'money_info_name' => $name
                            ]);

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

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

                            if ($paidMoney > 0) {

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

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

                    }

                    $fromChange = clone $from;
                    $to2 = clone $to;
                    if ($to->month == $fromChange->month) {
                        $to2->lastOfMonth();
                    }

                    while ($fromChange->lessThanOrEqualTo($to2)) {
                        $startDate = clone $fromChange;
                        $endDate = clone $fromChange;

                        if ($period > 1) {

                            $endDate->addMonth($period - 1)->lastOfMonth();

                            $name = 'Thu tiền phòng từ ' . $fromChange->format('d/m/Y') . ' đến ' .
                                $fromChange->addMonth($period - 1)->lastOfMonth()->format('d/m/Y');

                        } else {
                            $endDate->lastOfMonth();

                            $name = 'Thu tiền phòng từ ' . $fromChange->format('d/m/Y') . ' đến ' . $fromChange->lastOfMonth()->format('d/m/Y');
                        }
                        if ($startDate->day != 1) {
                            $range = Functions::calculatePeriod2($startDate, $endDate);
                        } else {
                            $range = $period;
                        }
                        $fromChange->addDay(1);
                        $money = intval(round($contract->room_price * $range));
                        $rangePaid = 0;
                        $paidMoney = 0;

                        if ($to->lessThanOrEqualTo($endDate) && $to->greaterThanOrEqualTo($startDate)) {
                            //	dump('wow');
                            if ($endDate->month == $to->month && $endDate->year == $to->year) {
                                $paidMoney = $money;
                            } else {
                                if ($startDate->day != 1) {
                                    $rangePaid = Functions::calculatePeriod2($startDate, $to->lastOfMonth());
                                } else {
                                    $rangePaid = $to->diffInMonths($startDate);
                                }
                                if ($rangePaid == 0) {
                                    $rangePaid++;
                                }
                                $paidMoney = $rangePaid * $contract->room_price;
                            }


                        } else if ($to->greaterThanOrEqualTo($endDate)) {
                            //dump('wow2');
                            $paidMoney = $money;
                        } else if ($to->lessThanOrEqualTo($startDate)) {
                            //dump('wow3');
                            $paidMoney = 0;
                        }

                        $check = Functions::checkExistDate($hostel, $startDate, $endDate, $contract, $roomId, $hostelId);
                        // dump($name);
                        if ($check == 0) {
//                            dump($name);
//							dump($range);
//							dump($paidMoney);
//							dump($money);
                            $moneyInfo = MoneyInfo::create([
                                'hostel_id' => $hostelId,
                                'room_id' => $roomId,
                                'date_action' => $startDate->toDateString(),
                                'contract_id' => $contract->id,
                                'user_id' => $user->id,
                                'type' => MoneyInfo::VOUCHER_CONTRACT,
                                'amount' => $money,
                                'pay' => $paidMoney,
                                'remain' => $money - $paidMoney,
                                'money_info_name' => $name
                            ]);

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

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

                            if ($paidMoney > 0) {

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

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

                }
            } else {

                while ($fromChange->startOfDay()->lessThanOrEqualTo(Carbon::now())) {
                    $startDate = clone $fromChange;
                    $endDate = clone $fromChange;

                    if ($period > 1) {

                        $endDate->addMonth($period - 1)->lastOfMonth();
                        $name = 'Thu tiền phòng từ ' . $fromChange->format('d/m/Y') . ' đến ' .
                            $fromChange->addMonth($period - 1)->lastOfMonth()->format('d/m/Y');

                    } else {
                        $endDate->lastOfMonth();
                        $name = 'Thu tiền phòng từ ' . $fromChange->format('d/m/Y') . ' đến ' . $fromChange->lastOfMonth()->format('d/m/Y');
                    }
                    if ($startDate->day != 1) {
                        $range = Functions::calculatePeriod2($startDate, $endDate);
                    } else {
                        $range = $period;
                    }
                    $fromChange->addDay(1);
                    $money = intval(round($contract->room_price * $range));
                    $rangePaid = 0;
                    $paidMoney = 0;


                    $check = Functions::checkExistDate($hostel, $startDate, $endDate, $contract, $roomId, $hostelId);


                    if ($check == 0) {
//						dump($name);
//						dump($range);
//						dump($paidMoney);
//						dump($money);

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

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

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


                        if ($paidMoney > 0) {
                            $transaction = Transaction::create([
                                'money_info_id' => $moneyInfo->id,
                                'amount' => $paidMoney,
                                'note' => $name,
                                'room_id' => $roomId,
                                'hostel_id' => $hostelId,
                                'date_action' => $startDate->toDateString(),
                                'type' => CollectSpend::COLLECT
                            ]);

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

            $from2 = clone $from;
            if (Carbon::now()->greaterThanOrEqualTo($from2->startOfDay())) {

                $startDate = Carbon::now()->firstOfMonth()->format('d/m/Y');
                if ($period > 1) {
                    $endDate = Carbon::now()->addMonth($period - 1)->lastOfMonth()->format('d/m/Y');
                } else {
                    $endDate = Carbon::now()->lastOfMonth()->format('d/m/Y');
                }

                $name = 'Thu tiền phòng từ ' . $startDate . ' đến ' . $endDate;

                $startDate = Carbon::now()->firstOfMonth();

                if ($period > 1) {
                    $endDate = Carbon::now()->addMonth($period - 1)->lastOfMonth();
                } else {
                    $endDate = Carbon::now()->lastOfMonth();
                }
                $range = $period;

                $money = $contract->room_price * $period;
                $paidMoney = 0;
                if (isset($to)) {
                    if ($to->lessThanOrEqualTo($endDate) && $to->greaterThanOrEqualTo($startDate)) {
                        if ($endDate->month == $to->month && $endDate->year == $to->year) {
                            $paidMoney = $money;
                        } else {
                            if ($startDate->day != 1) {
                                $rangePaid = Functions::calculatePeriod2($startDate, $to->lastOfMonth());
                            } else {
                                $rangePaid = $to->diffInMonths($startDate);
                            }
                            if ($rangePaid == 0) {
                                $rangePaid++;
                            }
                            $paidMoney = $rangePaid * $contract->room_price;
                        }


                    } else if ($to->greaterThanOrEqualTo($endDate)) {
                        $paidMoney = $money;
                    } else if ($to->lessThanOrEqualTo($startDate)) {
                        $paidMoney = 0;
                    }
                }

                $check = Functions::checkExistDate($hostel, $startDate, $endDate, $contract, $roomId, $hostelId);

                if ($check == 0) {
//                                	dump($name);
//				dump($range);
//				dump($paidMoney);
//				dump($money);
                    $moneyInfo = MoneyInfo::create([
                        'hostel_id' => $hostelId,
                        'room_id' => $roomId,
                        'date_action' => $startDate->toDateString(),
                        'contract_id' => $contract->id,
                        'user_id' => $user->id,
                        'type' => MoneyInfo::VOUCHER_CONTRACT,
                        'amount' => $money,
                        'pay' => $paidMoney,
                        'remain' => $money - $paidMoney,
                        'money_info_name' => $name
                    ]);

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

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

                    if ($paidMoney > 0) {

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

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

                }
            }


            if (is_array($feeContracts)) {
                $qty = $request->input('qty');
                //	$qty  = json_decode( $qty, true );
                $fees = [];
                foreach ($feeContracts as $key => $feeContract) {
                    $fees[$feeContract] = ['qty' => $qty[$key]];
                }

                $contract->fees()->sync($fees);
            }

            Functions::updateIsEmptyRoom($room);

            RoomBed::find($bedId)->update([
                'status' => RoomBed::UNAVAILABLE,
            ]);

            \DB::commit();

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

            //    dd( $exception->getTraceAsString() );
            \Log::info(($exception->getTraceAsString()));
            \Log::info(($exception->getMessage() . '|' . $exception->getLine()));


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

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

    /**
     * @api {post} /create-contract-2 Tạo hợp đồng moi
     * @apiName create-contract
     * @apiGroup Room
     * @apiDescription Tạo hợp đồng
     * @apiParam {String} date_contract Thuê từ ngày
     * @apiParam {String} end_date Thuê đến ngày (dạng d/m/Y)
     * @apiParam {String} room_price Tiền phòng
     * @apiParam {String} deposit Đặt cọc
     * @apiParam {String} period Chu kỳ trả (truyền 1 2 3 6 12)
     * @apiParam {String} is_collected Đã thu tiền phòng hay chưa ('on' là có)
     * @apiParam {String} collect_to Đã thu tiền đến tháng (dạng 'd/m/Y')
     * @apiParam {String} note Ghi chú khách hàng
     * @apiParam {String} phone SĐT khách
     * @apiParam {String} name Tên khách
     * @apiParam {File} image Ảnh khách
     * @apiParam {File} renter_signature Ảnh chữ ký khách
     * @apiParam {String} email Email khách
     * @apiParam {String} address Địa chỉ khách
     * @apiParam {String} id_number CMND khách
     * @apiParam {String} id_number_date ngày cấp cmnd
     * @apiParam {String} id_number_location nơi cấp
     * @apiParam {String} residence_status Trạng thái tạm trú (0 là chưa khai báo, 1 là có thời hạn, 2 là không thời hạn)
     * @apiParam {String} date_end_residence Hạn tạm trú
     * @apiParam {String} fee_contracts Id của cái fee ["10", "11"]
     * @apiParam {String} qty Số lượng hoặc chỉ số đầu của fee
     * @apiParam {String} province_id
     * @apiParam {String} district_id
     * @apiParam {String} ward_id
     * @apiParam {String} birthday
     * @apiParam {String} reserve_id Id cua giu cho
     * @apiParam {String} day_collect Ngay thu (tu 1 den 31)
     * @apiParam {int} bed_id id giường
     *
     *
     * @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 storeContract2(Request $request)
    {
        if ($this->user->cannot('add-contract')) {
            return response([
                'status' => 0,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }
//        $keyCache = 'processing-contract-mobile-' . $this->user->id;
//
//        if (cache()->has($keyCache)) {
//            return response([
//                'status' => 0,
//                'message' => 'Hệ thống đang xử lý thêm HĐ, bạn vui lòng đợi trong giây lát'
//            ]);
//        }
//        cache()->put($keyCache, time(), 5);
        $data = $request->all();
        $bed = $request->input('bed_id');
        if (!isset($data['bed_id'])) {
            $data['bed_id'] = null;
        }
        $feeContracts = $request->input('fee_contracts');
        $data['type_rent'] = 1;

        $roomId = $data['room_id'];

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

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

        if ($data['period'] == 4) {
            $data['period'] = Room::FOUR_MONTH_PERIOD;
        }

        $hostel = $room->hostel;

        if (!$hostel) {
//            cache()->forget($keyCache);
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        if ($hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
            if (empty($bed)) {
//                cache()->forget($keyCache);
                return response([
                    'status' => 0,
                    'message' => 'Không được để trống giường trong mô hình ký túc xá.'
                ]);
            }
        }
        $hostelId = $hostel->id;
        $dateContractCarbon = null;
        if (!empty($data['date_contract'])) {
            $dateContractCarbon = Carbon::createFromFormat('d/m/Y', $data['date_contract']);
            $data['date_contract'] = Carbon::createFromFormat('d/m/Y', $data['date_contract'])->toDateString();
            $data['date_enable'] = $data['date_contract'];
            $data['start_date'] = $data['date_contract'];
            $data['date_join'] = $data['date_contract'];
        }
        



        if ($request->file('image') && $request->file('image')->isValid()) {
            // return response([
            //         'status' => 0,
            //         'message' => $request->file('image')->getRealPath()
            //     ]);
            $avatarImage = Functions::uploadImage($request->file('image'));
            if (is_null($avatarImage)) {
                return response([
                    'status' => 0,
                    'message' => 'Có lỗi khi xử lý ảnh đại diện khách hàng'
                ]);
            } else {
                $data['customer_image'] = $avatarImage;
            }
            
        }
        
        
        

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


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

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

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

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

        if ($request->file('id_number_front')  && $request->file('id_number_front')->isValid()) {
            $idNumberFront = Functions::uploadImage($request->file('id_number_front'));
            if (is_null($idNumberFront)) {
                return response([
                    'status' => 0,
                    'message' => 'Có lỗi khi xử lý ảnh'
                ]);
            } else {
                $data['id_number_front'] = $idNumberFront;
            }

        }

        if ($request->file('id_number_back')  && $request->file('id_number_back')->isValid()) {
            $idNumberBack = Functions::uploadImage($request->file('id_number_back'));
            if (is_null($idNumberBack)) {
                return response([
                    'status' => 0,
                    'message' => 'Có lỗi khi xử lý ảnh CMND mat sau'
                ]);
            } else {
                $data['id_number_back'] = $idNumberBack;
            }
        }
        
        

        
        $hostelArr = Hostel::query()
            ->where('owner_id', $this->user->id)
            ->pluck('id')
            ->toArray();
        if ($this->user->type == User::STAFF) {
            $hostelArr = Functions::getHostelArrStaffApi($this->user);
        }

        $checkContract = Contract::query()
            ->where('phone', $data['phone'])
            ->where('status', Contract::VALIDATED)
            ->whereIn('hostel_id', $hostelArr)
            ->count();

        if ($checkContract > 0) {
//            cache()->forget($keyCache);
            return response([
                'status' => 0,
                'message' => 'SĐT đang có Hợp đồng hoạt động nên không thể thêm'
            ]);
        }

        try {

            \DB::beginTransaction();


            $data['hostel_id'] = $hostelId;

            $hostelTypeRent = $hostel->type_rent;
            if ($hostelTypeRent == Hostel::TYPE_RENT_ALL) {
                $bed = null;
            }

            if ($hostelTypeRent == Hostel::TYPE_RENT_EVERY) {
                $maxRenters = $room->max_renters;
                $currentNumberRenter = RenterRoom::where('room_id', $room->id)->count();
                if ($maxRenters == $currentNumberRenter) {
//                    cache()->forget($keyCache);
                    return response([
                        'status' => 0,
                        'message' => 'Bạn không thể thêm quá số người tối đa'
                    ]);
                }
            }

            if ($hostelTypeRent == Hostel::TYPE_RENT_ALL) {
                $checkContractValidated = Contract::where('status', '<>', Contract::LIQUIDATED)
                    ->where('room_id', $roomId)
                    ->count();


                if ($checkContractValidated) {
//                    cache()->forget($keyCache);
                    return response([
                        'status' => 0,
                        'message' => 'Bạn cần thanh lý HĐ trước khi tạo HĐ mới'
                    ]);
                }
            }

            if ($hostelTypeRent == Hostel::TYPE_RENT_EVERY) {
                $checkContractValidated = Contract::where('status', '<>', Contract::LIQUIDATED)
                    ->where('bed_id', $bed)
                    ->count();


                if ($checkContractValidated) {
//                    cache()->forget($keyCache);
                    return response([
                        'status' => 0,
                        'message' => 'Bạn cần thanh lý HĐ trước khi tạo HĐ mới'
                    ]);
                }
            }

            $contract = Contract::create($data);
            $roomBed = RoomBed::find($bed);
            if ($roomBed) {
                $roomBed->update([
                    'status' => RoomBed::UNAVAILABLE,
                ]);
            }
            $reserveId = $request->input('reserve_id');
            $reserveDeposit = 0;
            $reserve = null;

            if (!empty($reserveId)) {
                $reserve = RoomReservation::find($reserveId);
                if ($reserve) {
                    if ($data['phone'] != $reserve->phone) {
//                        cache()->forget($keyCache);
                        return response([
                            'status' => 0,
                            'message' => 'Bạn không thể tạo hợp đồng với số điện thoại: ' . $data['phone'] . ' vì đang có đặt cọc của số điện thoại: ' . $reserve->phone
                        ]);
                    }
                    CollectSpend::query()->where('reserve_id', $reserve->id)
                        ->update([
                            'contract_id' => $contract->id,
                            'is_return_deposit' => true,
                        ]);
                    $reserveDeposit = $reserve->deposit;
                    $reserve->delete();
                }

                if ($room->hostel->type_rent == Hostel::TYPE_RENT_ALL) {
                    $reserve = RoomReservation::query()->where('room_id', $reserveId)->first();
                    if ($reserve) {
                        CollectSpend::query()->where('reserve_id', $reserve->id)
                            ->update([
                                'contract_id' => $contract->id,
                                'is_return_deposit' => true,
                            ]);
                        $reserveDeposit = $reserve->deposit;
                        $reserve->delete();
                    }
                }

//                cache()->forget($keyCache);
//                dd($reserveDeposit);

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

                    CollectSpend::create([
                        'amount' => $reserveDeposit,
                        'hostel_id' => $hostel->id,
                        'room_id' => $roomId,
                        'note' => 'Thanh toán tiền cọc giữ chỗ HĐ ' . 'HD' . $contract->id . Carbon::now()->format('dmY'),
                        'name' => 'Thanh toán tiền cọc giữ chỗ HĐ ' . 'HD' . $contract->id . Carbon::now()->format('dmY'),
                        'payment_method' => CollectSpend::MONEY,
                        'date_action' => Carbon::now()->toDateString(),
                        'user_id' => $contract->renter_id,
                        'money_info_id' => null,
                        'type' => CollectSpend::SPEND,
                        'transaction_id' => $transaction->id,
                        'contract_id' => $contract->id,
                        'is_deposit' => true,
                        'is_return_deposit' => true
                    ]);
                }
            }

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

            if ($data['deposit'] > 0) {

                $transaction = Transaction::create([
                    'amount' => $data['deposit'],
                    'hostel_id' => $hostelId,
                    'room_id' => $roomId,
                    'date_action' => !empty($dateContractCarbon) ? $dateContractCarbon->copy()->toDateString() : Carbon::now()->toDateString(),
                    'type' => CollectSpend::COLLECT,
                    'note' => 'Thu tiền đặt cọc Hợp đồng ' . $contract->code,
                ]);

                CollectSpend::create([
                    'amount' => $data['deposit'],
                    'hostel_id' => $hostelId,
                    'room_id' => $roomId,
                    'note' => 'Thu tiền đặt cọc Hợp đồng ' . $contract->code,
                    'payment_method' => CollectSpend::MONEY,
                    'date_action' => !empty($dateContractCarbon) ? $dateContractCarbon->copy()->toDateString() : Carbon::now()->toDateString(),
                    'type' => CollectSpend::COLLECT,
                    'name' => 'Thu tiền đặt cọc Hợp đồng ' . $contract->code,
                    'transaction_id' => $transaction->id,
                    'contract_id' => $contract->id,
                    'is_deposit' => true,
                ]);
            }

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


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

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

            $birthday = null;
            if (!empty($data['birthday'])) {
                try {
                    $birthday = Carbon::createFromFormat('d/m/Y', $data['birthday'])->toDateString();
                } catch (\Exception $ex) {
                    $birthday = null;
                    \Log::info($ex->getMessage());
                    \Log::info($ex->getTraceAsString());
                }

                $data['birthday'] = $birthday;
            }


            if (isset($data['customer_image'])) {
                $data['image'] = $data['customer_image'];
                unset($data['customer_image']);
            }

            if ($check) {
                $check->update($data);
                $user = $check;
            } else {
                $data['password'] = \Hash::make('123456');
                $user = User::create($data);
                unset($data['password']);
            }

            $checkRenter = RenterRoom::where('user_id', $user->id)->where('room_id', $data['room_id'])->count();

            if ($checkRenter == 0) {
                RenterRoom::create([
                    'user_id' => $user->id,
                    'room_id' => $data['room_id'],
                    'hostel_id' => $hostelId,
                    'type_rent' => $hostel->type_rent,
                    'contract_id' => $contract->id,
                    'date_joined' => $data['date_join'],
                    'residence_status' => $data['residence_status'],
                    'date_end_residence' => !empty($data['date_end_residence']) ?  $data['date_end_residence'] : null,
                ]);

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


            $contract->update([
                'renter_id' => $user->id
            ]);

            if ($room) {
                $currentRenter = Functions::getUserForRoom($room);
                $room->date_available = null;
                $room->is_start_remind = false;
                $room->current_renter = $currentRenter->id;
                $room->save();
            }

            \DB::table('room_logs')->insert([
                'content' => 'Thêm người ở trọ ' . $user->name,
                'room_id' => $data['room_id'],
                'created_at' => Carbon::now()->toDateTimeString(),
                'updated_at' => Carbon::now()->toDateTimeString()
            ]);

            Functions::updateNumberEmptyRoom($hostel);
            $period = Functions::getPeriodNumber($data['period']);
            //Sinh hoa don
            $dayCollect = $data['day_collect'];
            $lastEnd = null;

            $from = Carbon::createFromFormat('Y-m-d', $data['date_enable']);


            $target = Carbon::now();
            $cost = $data['room_price'];
            $periodMoney = $period;
            $collectToCarbon = null;
            $qty = $request->input('qty');
            if (is_array($feeContracts)) {
                $qty = $request->input('qty');
                //	$qty  = json_decode( $qty, true );
                $fees = [];
                foreach ($feeContracts as $key => $feeContract) {
                    $fees[$feeContract] = ['qty' => $qty[$key]];
                }

                $contract->fees()->sync($fees);
            }
            Functions::updateIsEmptyRoom($room);
            if ($data['room_price'] <= 0) {
                \DB::commit();

                return response([
                    'status' => 1,
                    'message' => 'Thành công'
                ]);
            }
            if (isset($data['is_collected'])) {
                if ($data['is_collected'] == 'on') {
                    $collectTo = $data['collect_to'];
                    if (!empty($collectTo)) {

                        $collectToCarbon = Carbon::createFromFormat('d/m/Y', $collectTo);
                        if ($target->lessThan($collectToCarbon)) {
                            $target = $collectToCarbon->copy();
                        }

                        $contract->update([
                            'is_collected' => true,
                            'collect_to' => $collectToCarbon->toDateString()
                        ]);
                    }
                }
            }
            if (!empty($target)) {
                while ($from->lessThanOrEqualTo($target)) {
                    if ($period > 1) {
                        $month = $from->copy()->firstOfMonth()->addMonth($period - 1)->month;
                        $year = $from->copy()->firstOfMonth()->addMonth($period - 1)->year;
                        if ($dayCollect <= $from->copy()->day) {
                            $month = $from->copy()->firstOfMonth()->addMonth($period)->month;
                            $year = $from->copy()->firstOfMonth()->addMonth($period)->year;
                        }
                    } else {
                        $month = $from->copy()->month;
                        $year = $from->copy()->year;
                        if ($dayCollect <= $from->copy()->day) {
                            $month = $from->copy()->firstOfMonth()->addMonth()->month;
                            $year = $from->copy()->firstOfMonth()->addMonth()->year;
                        }
                    }

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

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

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

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

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

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

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

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

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

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

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


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

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

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


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

                                        if ($period > 1) {

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

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

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

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

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

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

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

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

                    $moneyInfo = MoneyInfo::create([
                        'hostel_id' => $hostelId,
                        'room_id' => $roomId,
                        'bed_id' => isset($data['bed_id']) ? $data['bed_id'] : null,
                        'date_action' => $from->copy()->toDateString(),
                        'contract_id' => $contract->id,
                        'user_id' => $user->id,
                        'type' => MoneyInfo::VOUCHER_CONTRACT,
                        'amount' => $sumMoney,
                        'pay' => $money,
                        'remain' => $sumMoney - $money,
                        'money_info_name' => $name
                    ]);

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

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

                    if ($isCollect == true) {

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

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


                    //}

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

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

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

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

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

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

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


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

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

                    MoneyDetail::create([
                        'hostel_id' => $hostelId,
                        'room_id' => $roomId,
                        'name' => $name,
                        'value' => $contract->room_price,
                        'money_info_id' => $moneyInfo->id,
                        'amount' => 0,
                        'note' => $name,
                        'start_date' => $lastEnd->copy()->toDateString(),
                        'end_date' => $to2->copy()->toDateString(),
                        'qty' => $period,
                        'renter_id' => $contract->renter_id,
                        'sum_amount' => $period * $cost
                    ]);

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

            //xử lý case tương lai
            $from2 = Carbon::createFromFormat('Y-m-d', $data['date_enable']);
            if ($from2->copy()->startOfDay()->greaterThan($target->copy()->startOfDay())) {
                if ($period > 1) {
                    $month = $from2->copy()->firstOfMonth()->addMonth($period - 1)->month;
                    $year = $from2->copy()->firstOfMonth()->addMonth($period - 1)->year;
                    if ($dayCollect <= $from2->copy()->day) {
                        $month = $from2->copy()->firstOfMonth()->addMonth($period)->month;
                        $year = $from2->copy()->firstOfMonth()->addMonth($period)->year;
                    }
                } else {
                    $month = $from2->copy()->month;
                    $year = $from2->copy()->year;
                    if ($dayCollect <= $from2->copy()->day) {
                        $month = $from2->copy()->firstOfMonth()->addMonth()->month;
                        $year = $from2->copy()->firstOfMonth()->addMonth()->year;
                    }
                }
                if (checkdate($month, $dayCollect, $year)) {

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

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

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

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

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

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

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

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

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

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

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

        } catch (\Exception $exception) {
            \DB::rollBack();
//            cache()->forget($keyCache);
            dump($exception->getMessage() . '|' . $exception->getLine());
            dd($exception->getTraceAsString());

            //var_dump($exception->getMessage() . '|' . $exception->getLine()); die();
            \Log::info($exception->getMessage());
            \Log::error($exception->getTraceAsString());

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

//        cache()->forget($keyCache);

        $hostelScheduleId = $request->input('hostel_schedule_id');
        $hostelSchedule = HostelSchedule::find($hostelScheduleId);
        if ($hostelSchedule) {
            $hostelSchedule->status = HostelSchedule::STATUS_CONTRACTED;
            $hostelSchedule->contract_id = $contract->id;
            $hostelSchedule->save();
        }
        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);
    }

    /**
     * @api {post} /update-contract  Cập nhật hợp đồng
     * @apiName update-contract
     * @apiGroup Room
     * @apiDescription Cập nhật hợp đồng
     * @apiParam {String} id id của hợp đồng
     * @apiParam {String} room_price Tiền phòng
     * @apiParam {String} deposit Đặt cọc
     * @apiParam {String} period Chu kỳ trả (truyền 1 2 3 6 12)
     * @apiParam {String} reference Mã HĐ tham chiếu
     * @apiParam {String} end_date Ngày kết thúc HĐ. Format d/m/Y
     * @apiParam {String} note Ghi chú
     * @apiParam {String} fee_contracts Id của cái fee dạng fee_contracts[]
     * @apiParam {String} qty Số lượng. Gửi lên dưới dạng qty[{fee_id}][]. Ví dụ qty[11][]
     *
     *
     *
     * @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 updateContract(Request $request)
    {
        //\Log::info(json_encode($request->all()));
        $data = $request->except([
            'note',
            'end_date'
        ]);
        $feeContracts = $request->input('fee_contracts');
        $qty = $request->input('qty');

        $endDate = $request->input('end_date');
        $leaveDay = $request->input('leave_day');
        if (!empty($endDate)) {
            $data['end_date'] = Carbon::createFromFormat('d/m/Y', $endDate)->toDateString();
        }

        if (!empty($leaveDay)) {
            $data['leave_day'] = Carbon::createFromFormat('d/m/Y', $leaveDay)->toDateString();
        }
        $contract = Contract::find($data['id']);

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

        try {
            \DB::beginTransaction();


            $deposit = $data['deposit'];
            if (empty($deposit)) {
                $deposit = 0;
            }
            $currentDeposit = $contract->deposit;
            $type = null;
            $note = null;
            $name = null;

            if ($currentDeposit == 0) {
                if ($deposit > $currentDeposit) {
                    $type = CollectSpend::COLLECT;
                    $note = $name = 'Thu tiền đặt cọc Hợp đồng ' . $contract->code;
                    $name = $name = 'Thu tiền đặt cọc Hợp đồng ' . $contract->code;
                    $amount = abs($deposit - $currentDeposit);

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

                    $transaction = Transaction::create([
                        'money_info_id' => null,
                        'amount' => $amount,
                        'note' => $note,
                        'room_id' => $roomId,
                        'hostel_id' => $hostelId,
                        'date_action' => Carbon::now()->toDateString(),
                        'type' => $type
                    ]);

                    CollectSpend::create([
                        'amount' => $amount,
                        'hostel_id' => $hostelId,
                        'room_id' => $roomId,
                        'note' => $note,
                        'name' => $name,
                        'payment_method' => CollectSpend::MONEY,
                        'date_action' => Carbon::now()->toDateString(),
                        'user_id' => $contract->renter_id,
                        'money_info_id' => null,
                        'type' => $type,
                        'transaction_id' => $transaction->id,
                        'contract_id' => $contract->id,
                        'is_deposit' => true
                    ]);
                }
            }

            $renter = Renter::where('user_id', $contract->renter_id)->first();
            if ($renter) {
                $renter->note = $request->input('note');
                $renter->save();
            }

            $contract->update($data);


            if (is_array($feeContracts)) {
                $fees = [];
                foreach ($feeContracts as $key => $feeContract) {

                    $feeItem = HostelFee::find($feeContract);
                    if ($feeItem) {
                        if ($feeItem->type = HostelFee::ELECTRIC) {

                        }
                    }
                    $qtyValue = $qty[$feeContract];
                    $fees[$feeContract] = ['qty' => $qtyValue];
                }

                //    dump($fees);

                $contract->fees()->sync($fees);
            }

            \DB::commit();
//            $contract->updated_at = Carbon::now();
//            $contract->save();


            $user = Functions::getCurrentUser();

            $desc = '{' . optional($user)->name . '}' . ' đã cập nhật hợp đồng khách {' . $contract->name . '}, phòng {' . $contract->room->name . '}, nhà {' . $contract->hostel->name . '}';
            if ($contract->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                $desc = '{' . optional($user)->name . '} đã cập nhật hợp đồng khách {' . $contract->name . '}, giường {' . optional($contract->bed)->name .
                    '} phòng {' . optional($contract->room)->name . '}, nhà {' . optional($contract->hostel)->name . '}';
            }
            event(new LogAction([
                'type' => 'update-contract',
                'user_id' => optional($user)->id,
                'object_id' => $contract->id,
                'hostel_id' => $contract->hostel->id,
                'room_id' => $contract->room->id,
                'properties' => $contract->toArray(),
                'desc' => $desc
            ]));
        } catch (\Exception $exception) {
            \DB::rollBack();

            \Log::info($exception->getTraceAsString());

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

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

    /**
     * @api {get} /amenities Lấy danh sách tiện ích phòng
     * @apiName amenities
     * @apiGroup Room
     * @apiDescription  Lấy danh sách tiện ích phòng
     * @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 getAmenityRoom()
    {
        $amenities = Amenity::where('type', Amenity::AMENITY)->whereIn('user_id', [
            0,
            $this->user->id
        ])->get();

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

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

    }

    /**
     * @api {post} /create-bike Thêm phương tiện
     * @apiName create-bike
     * @apiGroup Room
     * @apiParam {String} bike_names Danh sách tên xe dạng mảng
     * @apiParam {String} bike_types Danh sách loại xe dạng mảng. 0 là xe đạp, 1 là xe máy, 2 là xe điện, 3 là ô tô
     * @apiParam {String} bike_bks Danh sách biển số xe dạng mảng
     * @apiParam {File} bike_image Hình ảnh xe dạng mảng file
     * @apiParam {String} room_id
     * @apiParam {String} renter_id
     *
     *
     * @apiDescription  Thêm phương tiện vào phòng
     * @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 addBike(Request $request)
    {
        $bikeNames = $request->input('bike_names');
        $bikeTypes = $request->input('bike_types');
        $bikeBks = $request->input('bike_bks');
        $bikeImg = $request->file('bike_image');
        $data = $request->all();

        $user = Functions::getCurrentUser();


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

                $renter = User::find($data['renter_id']);
                $item = RenterBike::create([
                    'name' => $bikeName,
                    'type' => $bikeType,
                    'bks' => $bikeBk,
                    'image' => $bikeImage,
                    'room_id' => $data['room_id'],
                    'renter_id' => $data['renter_id'],
                ]);

                if ($renter) {
                    $room = Room::find($data['room_id']);
                    $desc = '{' . $user->name . '} thêm xe cho khách {' . optional($renter)->name . '} phòng {' . $room->name . '} nhà {' . $room->hostel->name . '}';
                    event(new LogAction([
                        'type' => 'create-bike',
                        'user_id' => optional($user)->id,
                        'object_id' => $item->id,
                        'hostel_id' => $room->hostel_id,
                        'room_id' => $room->id,
                        'properties' => $item->toArray(),
                        'desc' => $desc
                    ]));
                }
            }
        }

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

    /**
     * @api {post} /update-bike Cập nhật phương tiện
     * @apiName update-bike
     * @apiGroup Room
     * @apiParam {String} bike_name Tên xe
     * @apiParam {String} bike_type Loại xe. 0 là xe đạp, 1 là xe máy, 2 là xe điện, 3 là ô tô
     * @apiParam {String} bike_bks Biển số xe
     * @apiParam {File} bike_image Hình ảnh xe
     * @apiParam {String} room_id
     * @apiParam {String} renter_id
     * @apiParam {String} delete_vehicle_image
     *
     * @apiParam {String} id
     *
     *
     * @apiDescription Cập nhật phương tiện
     * @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 updateBike(Request $request)
    {
        $id = $request->input('id');
        $deleteImage = $request->input('delete_vehicle_image');
        $item = RenterBike::find($id);
        if ($item) {
            $item->update([
                'name' => $request->input('bike_name'),
                'type' => $request->input('bike_type'),
                'bks' => $request->input('bike_bks'),
                'image' => !empty($request->file('bike_image')) ? Functions::uploadImage($request->file('bike_image')) : $item->image,
                'room_id' => $request->input('room_id'),
                'renter_id' => $request->input('renter_id'),
            ]);

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

        if ($deleteImage) {
            $item->image = null;
            $item->save();
        }

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

    /**
     * @api {post} /delete-bike Xóa phương tiện
     * @apiName delete-bike
     * @apiGroup Room
     * @apiParam {String} id
     *
     *
     * @apiDescription  Xóa phương tiện
     * @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 deleteBike(Request $request)
    {
        $id = $request->input('id');
        $bike = RenterBike::query()->find($id);
        if ($bike) {
            $bike->delete();
        }

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

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


    /**
     * @api {get} /bikes Danh sách phương tiện
     * @apiName bikes
     * @apiGroup Room
     * @apiParam {String} hostel_id
     * @apiParam {String} room_id
     * @apiParam {String} renter_id
     *
     *
     * @apiDescription  Danh sách phương tiện
     * @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 getBikes(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $roomId = $request->input('room_id');
        $userId = $request->input('renter_id');


        $roomArrs = [];

        if (!empty($roomId)) {
            $roomArrs = [$roomId];
        } else if (!empty($hostelId)) {
            $roomArrs = Room::query()->where('hostel_id', $hostelId)->pluck('id')->toArray();
        } else {

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

            $roomArrs = Room::query()->whereIn('hostel_id', $hostelArrs)->pluck('id')->toArray();
        }

        $bikes = RenterBike::query()
            ->with('room')
            ->with('room.hostel')
            ->whereIn('room_id', $roomArrs);
        if (!empty($userId)) {
            $bikes = $bikes->where('renter_id', $userId);
        }

        $bikes = $bikes->get();

        foreach ($bikes as $bike) {
            $bike->room_name = $bike->room->name;
            $bike->hostel_id = optional($bike->room->hostel)->id;
            $bike->hostel_name = optional($bike->room->hostel)->name;

            unset($bike->room);
            $bike->type_name = $bike->type_text;
            $bike->renter_name = $bike->renter->name_text;
            $bike->image = !empty($bike->image) ? '/files/' . $bike->image : null;

            unset($bike->renter);
        }

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

    /**
     * @api {get} /bike-type Danh sách loại phương tiện
     * @apiName bike-type
     * @apiGroup Room
     *
     * @apiDescription  Danh sách loại phương tiện
     * @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 getBikeType(Request $request)
    {
        $bikeType = [
            [
                'id' => RenterRoom::MOTORBIKE,
                'name' => 'Xe máy'
            ],
            [
                'id' => RenterRoom::ELECTRIC_BIKE,
                'name' => 'Xe điện'
            ],
            [
                'id' => RenterRoom::BICYCLE,
                'name' => 'Xe đạp'
            ],
            [
                'id' => RenterRoom::CAR,
                'name' => 'Ô tô'
            ]
        ];

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

    /**
     * @api {post} /create-report-break Tạo một yêu cầu báo hỏng
     * @apiName create-report-break
     * @apiGroup Room
     *
     * @apiParam {String} hostel_id
     * @apiParam {String} [room_id]
     * @apiParam {String} content
     * @apiParam {String} images
     * @apiParam {String} title
     *
     *
     * @apiDescription  Tạo một yêu cầu báo hỏng
     * @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 storeReportBreak(Request $request)
    {
        $roomId = $request->input('room_id');
        $hostelId = $request->input('hostel_id');
        $content = $request->input('content');
        $images = $request->file('images');
        $title = $request->input('title');

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

        $room = Room::find($roomId);
        $owner = $hostel->owner;
        if (!$owner) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        $userReportRoomId = null;
        if ($this->user->type == User::RENTER) {
            $userReportRenter = RenterRoom::query()
                ->where('user_id', $this->user->id)
                ->orderBy('id', 'desc')
                ->first();
            if ($userReportRenter) {
                $userReportRoomId = $userReportRenter->room_id;
            }
        }

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

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

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

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


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

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

        if (!empty($images)) {

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

        }

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

    public function countReportBreak(Request $request)
    {
        $hostelArr = [];
        if ($this->user->type == User::OWNER) {
            $hostelArr = Hostel::query()
                ->where('owner_id', $this->user->id)
                ->pluck('id')
                ->toArray();
        } else if ($this->user->type == User::RENTER) {
            $hostelArr = Functions::getHostelArrStaffApi($this->user);
        }

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

        $cnt = ReportBreak::query()
            ->whereIn('hostel_id', $hostelArr)
            ->where('status', ReportBreak::NOT_PROCESS)
            ->count();

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

    /**
     * @api {get} /get-report-break Lấy danh sách báo hỏng
     * @apiName get-report-break
     * @apiGroup Room
     *
     * @apiParam {String} room_id
     * @apiParam {String} hostel_id
     * @apiParam {String} start_date d/m/Y
     * @apiParam {String} end_date d/m/Y
     * @apiParam {String} status Status 0 la chua xu ly, 1 la dang xu ly, 2 la da xu ly
     *
     * @apiDescription  Lấy danh sách báo hỏng. Status 0 la chua xu ly, 1 la dang xu ly, 2 la da xu ly
     * @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 getReportBreak(Request $request)
    {
        $roomId = $request->input('room_id');
        $hostelId = $request->input('hostel_id');
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');
        $status = $request->input('status');

        $items = ReportBreak::query()->with([
            'room',
            'hostel',
            'userReport',
            'userTakeCare',
            'rating'
        ])->orderBy('id', 'desc');

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

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

        if ($this->user->type == User::STAFF) {
            $hostelArrs = Functions::getHostelArrStaffApi($this->user);
        }

        if ($this->user->type == User::RENTER) {
            $items = $items->where('user_report', $this->user->id);
        }

        if (!empty($roomId)) {
            $items = $items->where('room_id', $roomId);
        }

        if (!empty($startDate)) {
            $startDate = Carbon::createFromFormat('d/m/Y', $startDate)->startOfDay()->toDateTimeString();
            $items = $items->where('created_at', '>=', $startDate);
        }

        if (!empty($endDate)) {
            $endDate = Carbon::createFromFormat('d/m/Y', $endDate)->endOfDay()->toDateTimeString();
            $items = $items->where('created_at', '<=', $endDate);
        }

        if (is_numeric($status)) {
            $items = $items->where('status', $status);
        }

        if (!empty($hostelId)) {

            $items = $items->where('hostel_id', $hostelId)->get();
        } else {
            $items = $items->whereIn('hostel_id', $hostelArrs)->get();
        }

        $retVal = [];
        foreach ($items as $item) {
            $images = \DB::table('report_break_images')
                ->where('report_break_id', $item->id)
                ->get();
            $imageArr = [];
            $imageFixedArr = [];
            foreach ($images as $image) {
                $imageArr[] = [
                    'id' => $image->id,
                    'image' => '/files/' . $image->image
                ];
            }

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

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

            $userReport = null;
            $userTakeCare = null;
            if (!empty($item->userReport)) {
                $userReportItem = $item->userReport;
                $userReport = [
                    'id' => $userReportItem->id,
                    'name' => $userReportItem->name_text,
                    'type' => $userReportItem->type
                ];
            }

            if (!empty($item->userTakeCare)) {
                $userTakeCareItem = $item->userTakeCare;
                $userTakeCare = [
                    'id' => $userTakeCareItem->id,
                    'name' => $userTakeCareItem->name_text,
                    'type' => $userReportItem->type
                ];
            }

            $isRate = false;
            $rate = null;
            $contentRate = null;
            if (!empty($item->rating)) {
                $isRate = true;
                $rate = $item->rating->rate;
                $contentRate = $item->rating->content;
            }

            $retVal[] = [
                'id' => $item->id,
                'content' => $item->content,
                'room_id' => $item->room_id,
                'hostel_id' => $item->hostel_id,
                'response_content' => $item->response_content,
                'title' => $item->title,
                'room_name' => optional($item->room)->name,
                'hostel_name' => optional($item->hostel)->name,
                'images' => $imageArr,
                'images_fixed' => $imageFixedArr,
                'status' => $item->status,
                'user_report' => $userReport,
                'user_take_care' => $userTakeCare,
                'processing_date' => !empty($item->processing_date) ? Carbon::createFromFormat('Y-m-d H:i:s', $item->processing_date)->format('d/m/Y H:i') : null,
                'processed_date' => !empty($item->processed_date) ? Carbon::createFromFormat('Y-m-d H:i:s', $item->processed_date)->format('d/m/Y H:i') : null,
                'created_at' => $item->created_at->format('d/m/Y H:i'),
                'user_report_room_id' => $item->user_report_room_id,
                'is_rate' => $isRate,
                'rate' => $rate,
                'content_rate' => $contentRate,
                'date_finish' => !empty($item->date_finish) ? $item->date_finish->format('d/m/Y H:i') : null,
            ];
        }

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

    }

    /**
     * @api {post} /rate-report-break Đánh giá báo hỏng
     * @apiName rate-report-break
     * @apiGroup Room
     *
     * @apiParam {String} report_break_id
     * @apiParam {String} content
     * @apiParam {String} rate
     *
     * @apiDescription  Đánh giá báo hỏng
     * @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 rateReportBreak(Request $request)
    {
        $reportBreakId = $request->input('report_break_id');
        $rate = $request->input('rate');
        $content = $request->input('content');

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

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

        $check = ReportBreakRating::query()
            ->where('report_break_id', $reportBreakId)
            ->count();
        if ($check) {
            return response([
                'status' => 0,
                'message' => 'Sự vụ đã được đánh giá trước đó'
            ]);
        }

        if ($this->user->id != $item->user_report) {
            return response([
                'status' => 0,
                'message' => 'Bạn phải là người báo cáo'
            ]);
        }

        ReportBreakRating::create([
            'user_id' => $this->user->id,
            'content' => $content,
            'rate' => $rate,
            'report_break_id' => $reportBreakId
        ]);

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

    }

    /**
     * @api {get} /detail-report-break Lấy chi tiet báo hỏng
     * @apiName detail-report-break
     * @apiGroup Room
     *
     * @apiParam {String} id
     *
     * @apiDescription  Lấy chi tiet báo hỏng
     * @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 detailReportBreak(Request $request)
    {
        $item = ReportBreak::find($request->input('id'));
        if (!$item) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ',
            ]);
        }

        $images = \DB::table('report_break_images')
            ->where('report_break_id', $item->id)
            ->get();
        $imageArr = [];
        $imageFixedArr = [];
        foreach ($images as $image) {
            $imageArr[] = [
                'id' => $image->id,
                'image' => '/files/' . $image->image
            ];
        }

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

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

        $userReport = null;
        $userTakeCare = null;
        if (!empty($item->userReport)) {
            $userReportItem = $item->userReport;
            $userReport = [
                'id' => $userReportItem->id,
                'name' => $userReportItem->name_text
            ];
        }

        if (!empty($item->userTakeCare)) {
            $userTakeCareItem = $item->userTakeCare;
            $userTakeCare = [
                'id' => $userTakeCareItem->id,
                'name' => $userTakeCareItem->name_text
            ];
        }

        $isRate = false;
        $rate = null;
        $contentRate = null;
        if (!empty($item->rating)) {
            $isRate = true;
            $rate = $item->rating->rate;
            $contentRate = $item->rating->content;
        }

        $retVal = [
            'id' => $item->id,
            'content' => $item->content,
            'room_id' => $item->room_id,
            'hostel_id' => $item->hostel_id,
            'response_content' => $item->response_content,
            'title' => $item->title,
            'room_name' => optional($item->room)->name,
            'hostel_name' => optional($item->hostel)->name,
            'images' => $imageArr,
            'images_fixed' => $imageFixedArr,
            'status' => $item->status,
            'user_report' => $userReport,
            'user_take_care' => $userTakeCare,
            'is_rate' => $isRate,
            'rate' => $rate,
            'content_rate' => $contentRate,
            'processing_date' => !empty($item->processing_date) ? Carbon::createFromFormat('Y-m-d H:i:s', $item->processing_date)->format('d/m/Y H:i') : null,
            'processed_date' => !empty($item->processed_date) ? Carbon::createFromFormat('Y-m-d H:i:s', $item->processed_date)->format('d/m/Y H:i') : null,
            'created_at' => $item->created_at->format('d/m/Y H:i')
        ];


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

    }

    /**
     * @api {post} /update-report-break Cập nhật báo hỏng
     * @apiName update-report-break
     * @apiGroup Room
     *
     * @apiParam {String} id
     * @apiParam {String} content
     * @apiParam {String} response_content phản hồi của người sửa
     * @apiParam {String} status Status 0 la chua xu ly, 1 la dang xu ly, 2 la da xu ly
     * @apiParam {String} title
     * @apiParam {String} images-fixed Anh ket qua
     * @apiParam {String} images Anh bo sung tu nguoi tro
     * @apiParam {String} images-deleted Anh xoa
     *
     * @apiDescription  Cập nhật báo hỏng. Status 0 la chua xu ly, 1 la dang xu ly, 2 la da xu ly
     * @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 updateReportBreak(Request $request)
    {
        $id = $request->input('id');
        $status = $request->input('status');
        $images = $request->file('images-fixed');
        $title = $request->input('title');
        $content = $request->input('content');
        $responseContent = $request->input('response_content');
        $imagesDeleted = $request->input('images-deleted');
        $imageAdds = $request->file('images');
        $dateFinish = $request->input('date_finish');
        $item = ReportBreak::find($id);
        if (!$item) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

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

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

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

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

        if (!empty($dateFinish)) {
            $item->date_finish = Carbon::createFromFormat('d/m/Y H:i', $dateFinish);
        }


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

        if (!empty($images)) {

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

        }

        if (!empty($imageAdds)) {

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

        }

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

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

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

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

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

        }

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

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

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

        $item->save();

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


    }

    /**
     * @api {post} /delete-report-break Xoa báo hỏng
     * @apiName delete-report-break
     * @apiGroup Room
     *
     * @apiParam {String} id
     *
     * @apiDescription  Xoa báo hỏng.
     * @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 deleteReportBreak(Request $request)
    {
        $id = $request->input('id');
        $item = ReportBreak::find($id);
        if (!$item) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $item->delete();

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


    }

    public function storeContractTest(Request $request)
    {
        $dateEnable = $request->input('date_enable');
        $collectTo = $request->input('collect_to');
        $dayCollect = $request->input('day_collect');
        $period = $request->input('period');
        $cost = 1000000;

        $returnArr = [];

        $from = Carbon::createFromFormat('d/m/Y', $dateEnable);
        $target = Carbon::now();
        $collectToCarbon = null;
        if (!empty($collectTo)) {
            $collectToCarbon = Carbon::createFromFormat('d/m/Y', $collectTo);
            if ($target->lessThan($collectToCarbon)) {
                $target = $collectToCarbon->copy();
            }
        }

//		if($period > 1)
//		{
//			$period--;
//		}


        $periodMoney = $request->input('period');

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


                $isValid = true;
                if (checkdate($month, $dayCollect, $year)) {


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

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

                $money = $periodMoney * $cost;
                $sumMoney = $money;

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


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

                            if ($period > 1) {


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

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

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

                                        $money = intval($cost / ($numberDays + 1) * ($diffDays + 1));
                                    }
                                }
                            }

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

                            if ($period > 1) {

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

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

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

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

                    if ($collectToCarbon->greaterThan($to->copy())) {
                        if ($period > 1) {

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

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

                            }
                        } else {
                            if (Functions::checkFullPeriod($from->copy(), $to->copy(), $dayCollect)) {
                                $money = $periodMoney * $cost;
                            } else {


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

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

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

                        } else {


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

                                if ($period > 1) {

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

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


//                if($to->copy()->lessThanOrEqualTo(Carbon::now())) {
//
//                    if ($from->copy()->day == $to->copy()->day) {
//                        $money = $periodMoney * $cost;
//                    } else {
//
//                        if ($from->copy()->day != $to->copy()->addDay()->day) {
//                            $diffDays2 = $from->copy()->diffInDays($to->copy());
//                            $sumDays2 = $to->copy()->diffInDays($to->copy()->subMonth($period));
//                            $money = intval($cost / ($sumDays2) * ($diffDays2 + 1));
//                        }
//                    }
//                }

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

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

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

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

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

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

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

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

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

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

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


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

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

        $from2 = Carbon::createFromFormat('d/m/Y', $dateEnable);
        if ($from2->copy()->greaterThan($target)) {
            if ($period > 1) {
                $month = $from2->copy()->firstOfMonth()->addMonth($period - 1)->month;
                $year = $from2->copy()->firstOfMonth()->addMonth($period - 1)->year;
                if ($dayCollect <= $from2->copy()->day) {
                    $month = $from2->copy()->firstOfMonth()->addMonth($period)->month;
                    $year = $from2->copy()->firstOfMonth()->addMonth($period)->year;
                }
            } else {
                $month = $from2->copy()->month;
                $year = $from2->copy()->year;
                if ($dayCollect <= $from2->copy()->day) {
                    $month = $from2->copy()->firstOfMonth()->addMonth()->month;
                    $year = $from2->copy()->firstOfMonth()->addMonth()->year;
                }
            }
            if (checkdate($month, $dayCollect, $year)) {

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

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

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

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

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

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


        return response($returnArr);

    }

    /**
     * @api {get} /empty-recently Phong trong gan day
     * @apiName empty-recently
     * @apiGroup Room
     * @apiDescription Api Phong trong gan day
     * @apiParam {String} hostel_id
     * @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 getRoomsEmptyRecently(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $limit = $request->input('limit', 8);
        $offset = $request->input('offset', 0);
        $ownerId = $this->user->id;
        if ($this->user->type == User::STAFF) {
            $ownerId = $this->user->staff_owner_id;
        }

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

        $rooms = Room::whereIn('hostel_id', $hostelArrs);

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

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

    }

    /**
     * @api {post} /extend-contract Gia han HD
     * @apiName extend-contract
     * @apiGroup Room
     * @apiDescription Api Gia han HD
     * @apiParam {String} contract_id
     * @apiParam {String} end_date dang d/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 extendContract(Request $request)
    {
        if ($this->user->cannot('extend-contract')) {
            return response([
                'status' => 0,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }

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

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

        try {

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

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

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


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

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

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

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


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

    /**
     * @api {get} /get-list-room-bed Danh sách giường
     * @apiName get-list-room-bed
     * @apiGroup Room
     * @apiDescription Api Danh sách giường
     * @apiParam {String} room_id
     * @apiParam {int} status 0 Trống, 1 Đang cọc, 2 Đ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 getListRoomBed(Request $request)
    {
        $roomId = $request->input('room_id');
        $statuses = $request->input('status');
        $roomBeds = RoomBed::query()
            ->with('reservation')
            ->with('contractValid')
            ->where('room_id', $roomId)
            ->when(!empty($statuses) && is_array($statuses), function ($q) use ($statuses) {
                $q->where(function ($q) use ($statuses) {
                    foreach ($statuses as $status) {
                        if ($status == 0) {
                            $q->orDoesntHave('contractValid');
                        }
                        if ($status == 2) {
                            $q->orHas('contract');
                        }
                        if ($status == 1) {
                            $q->orHas('reservation');
                        }
                    }
                });

            });

        if (empty($roomBeds->count())) {
            return response([
                'status' => 0,
                'message' => 'Không có giường trong phòng',
            ]);
        }

        $roomBeds = $roomBeds->get();

        return response([
            'status' => 1,
            'message' => 'Danh sách giường',
            'data' => $roomBeds,
        ]);
    }

    /**
     * @api {post} /edit-room-bed Cập nhật giường
     * @apiName edit-room-bed
     * @apiGroup Room
     * @apiDescription Api Cập nhật giường mô hình ktx
     * @apiParam {String} bed_id
     * @apiParam {String} bed_name
     * @apiParam {String} bed_available
     *
     * @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 updateRoomBed(Request $request)
    {
        $data = $request->all();
        $roombed = RoomBed::find($data['bed_id']);
        if (empty($roombed)) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ',
            ]);
        }

        if (!empty($data['bed_available'])) {
            $data['bed_available'] = Carbon::createFromFormat('d/m/Y', $data['bed_available'])->toDateString();
        }
        $roombed->update([
            'id' => $data['bed_id'],
            'name' => $data['bed_name'],
            'date_available' => $data['bed_available'],
        ]);

        $user = Functions::getCurrentUser();
        $desc = '{' . $user->name . '} đã sửa thông tin giường {' . $roombed->name . '}, phòng {' . $roombed->room->name . '}, nhà {' . $roombed->hostel->name . '}';
        event(new LogAction([
            'type' => 'update-room-bed',
            'user_id' => optional($user)->id,
            'object_id' => $request->id,
            'hostel_id' => $roombed->hostel_id,
            'room_id' => $roombed->room_id,
            'properties' => $roombed->toArray(),
            'desc' => $desc
        ]));


        return response([
            'status' => 1,
            'message' => 'Sửa giường thành công',
        ]);
    }

    /**
     * @api {post} /calculate-update-money-info Lấy thông tin số tiền cập nhật hóa đơn
     * @apiName calculate-update-money-info
     * @apiGroup Room
     * @apiDescription Api Lấy thông tin số tiền cập nhật hóa đơn
     * @apiParam {String} start_date
     * @apiParam {String} end_date
     * @apiParam {String} money_info_id
     * @apiParam {String} discount
     * @apiParam {String} value_money_info đơn 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 calMoneyInfo(Request $request)
    {
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');
        $moneyInfoId = $request->input('money_info_id');
        $discount = $request->input('discount');
        $valueMoneyInfo = $request->input('value_money_info');
        $moneyInfo = MoneyInfo::find($moneyInfoId);
        if (!$moneyInfo) {
            return response([
                'stautus' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        if (empty($startDate) || empty($endDate)) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }


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

        if (is_numeric($valueMoneyInfo)) {
            $cost = $valueMoneyInfo;
        }

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

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


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

    /**
     * @api {post} /update-money-info Cập nhật hóa đơn
     * @apiName update-money-info
     * @apiGroup Room
     * @apiDescription Api Cập nhật hóa đơn
     * @apiParam {String} start_date
     * @apiParam {String} end_date
     * @apiParam {String} money_info_id
     * @apiParam {String} discount giảm giá
     * @apiParam {String} value_money_info Đơn giá nhà mới
     *
     * @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 updateMoneyInfoRoom(Request $request)
    {
        $data = $request->all();
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');
        $moneyInfoId = $request->input('money_info_id');
        $discount = $request->input('discount');
        $valueMoneyInfo = $request->input('value_money_info');
        $moneyInfo = MoneyInfo::find($moneyInfoId);

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

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

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

            $moneyDetail->qty = $qty;
            $moneyDetail->name = $name;
            $moneyDetail->save();


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

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

    }

    /**
     * @api {post} /send-custom-mail-contract Gửi HĐ đến mail
     * @apiName send-custom-mail-contract
     * @apiGroup Room
     * @apiDescription Api Gửi HĐ đến mail
     * @apiParam {String} contract_id
     * @apiParam {String} email
     *
     * @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 sendMailContract(Request $request)
    {
        $contractId = $request->input('contract_id');
        $email = $request->input('email');

        $contract = Contract::find($contractId);
        if (!$contract) {
            return response([
                'status' => 0,
                'message' => 'Không tồn tại HĐ'
            ]);
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return response([
                'status' => 0,
                'message' => 'Email không hợp lệ'
            ]);
        }


        dispatch_now(new SendMailContract($contract->id, $email));

        $user = Functions::getCurrentUser();

        $desc = '{' . $user->name . '} đã gửi mail hợp đồng cho khách {' . $contract->name . '} phòng {' . $contract->room->name . '} nhà {' . $contract->hostel->name . '}';
        if ($contract->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
            $desc = '{' . $user->name . '} đã gửi mail hợp đồng cho khách {' . $contract->name . '} giường {' . optional($contract->bed)->name . '} phòng {' . $contract->room->name . '} nhà {' . $contract->hostel->name . '}';
        }
        event(new LogAction([
            'type' => 'send-contract-email',
            'user_id' => optional($user)->id,
            'object_id' => $contract->id,
            'hostel_id' => $contract->hostel_id,
            'room_id' => $contract->room_id,
            'desc' => $desc
        ]));

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

    /**
     * @api {post} /gen-next-invoice Sinh hóa đơn kỳ tiếp theo
     * @apiName gen-next-invoice
     * @apiGroup Room
     * @apiDescription Api Sinh hóa đơn kỳ tiếp theo
     * @apiParam {String} contract_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 generateNextInvoice(Request $request)
    {
        $contractId = $request->input('contract_id');
        $contract = Contract::find($contractId);
        if (!$contract) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $user = Functions::getCurrentUser();
        dispatch_now(new GenerateNextContractInvoice($contractId, null, $user));

        $reContract = Contract::find($contractId);
        $nextInvoiceDate = $reContract->last_invoice_at_text;

        return response([
            'status' => 1,
            'message' => 'Hệ thống đã xử lý hóa đơn mới',
            'data' => $nextInvoiceDate
        ]);
    }

    /**
     * @api {post} /contract-attach Thêm file vào HĐ
     * @apiName contract-attach
     * @apiGroup Room
     * @apiDescription Api Thêm file vào HĐ
     * @apiParam {String} contract_id
     * @apiParam {Files} files
     *
     * @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 contractAttach(Request $request)
    {
        $user = Functions::getCurrentUser();
        $files = $request->file('files');
        $contractId = $request->input('contract_id');
        $contract = Contract::find($contractId);
        if ($request->hasFile('files')) {
            foreach ($files as $file) {
                $fileName = str_slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));
                $mime = $file->getMimeType();

                $filePath = Functions::uploadFile($file);

                if (str_contains($mime, 'image')) {
                    $thumbnailUrl = '/files/' . $filePath;
                } else {
                    $thumbnailUrl = 'https://s3-ap-southeast-1.amazonaws.com/ishopgo/folder.jpg';
                }

                $fileId = ContractAttachment::create([
                    'name' => $fileName,
                    'file' => $filePath,
                    'contract_id' => $contractId,
                    'preview' => $thumbnailUrl
                ]);


                $desc = '{' . $user->name . '} đã đính kèm file hợp đồng khách {' . $contract->name . '} phòng {' . $contract->room->name . '} nhà {' . $contract->hostel->name . '}';
                if ($contract->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                    $desc = '{' . $user->name . '} đã đính kèm file hợp đồng khách {' . $contract->name . '} giường {' . optional($contract->bed)->name . '} phòng {' . $contract->room->name . '} nhà {' . $contract->hostel->name . '}';
                }
                event(new LogAction([
                    'type' => 'create-contract-attachment',
                    'user_id' => optional($user)->id,
                    'object_id' => $fileId->id,
                    'hostel_id' => $contract->hostel_id,
                    'room_id' => $contract->room_id,
                    'desc' => $desc
                ]));

            }

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


    }


    /**
     * @api {get} /get-contract-attach Lấy file HĐ
     * @apiName get-contract-attach
     * @apiGroup Room
     * @apiDescription Api Lấy file HĐ
     * @apiParam {String} contract_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 getContractAttach(Request $request)
    {
        $contractId = $request->input('contract_id');
        $items = ContractAttachment::query()
            ->where('contract_id', $contractId)
            ->get()
            ->map(function ($item) {
                $arr = $item->toArray();
                $arr['file'] = '/files/' . $arr['file'];
                $path = public_path($arr['file']);
                $arr['file_size'] = Functions::convertFileSize(\File::size($path));
                $arr['file_extension'] = \File::extension($path);

                return $arr;
            });

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

    /**
     * @api {post} /change-contract Chuyển HĐ
     * @apiName change-contract
     * @apiGroup Room
     * @apiDescription Api Chuyển HĐ
     * @apiParam {String} room_id
     * @apiParam {String} renter_id ID của người thuê
     *
     * @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 changeContract(Request $request)
    {
        $roomId = $request->input('room_id');
        $renterId = $request->input('renter_id');

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

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

        $rep = RenterRoom::query()
            ->where('room_id', $roomId)
            ->whereNotNull('contract_id')
            ->first();

        if (!$rep) {
            return response([
                'status' => 0,
                'message' => 'Không tìm được đại diện phòng'
            ]);
        }

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

        $renter = Renter::query()->where('user_id', $renterId)->first();
        if (!$renter) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $contract->update([
            'name' => $renter->name,
            'phone' => $renter->phone,
            'email' => $renter->email,
            'id_number_front' => $renter->id_number_front,
            'id_number_back' => $renter->id_number_back,
            'renter_id' => optional($renter->user)->id,
        ]);

        RenterRoom::query()
            ->where('room_id', $contract->room_id)
            ->where('user_id', $renter->user_id)
            ->update([
                'contract_id' => $contract->id,
                'room_contract_id' => null
            ]);

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

    /**
     * @api {post} /delete-room-bed Xoa giuong
     * @apiName delete-room-bed
     * @apiGroup Room
     * @apiDescription Api Xoa giuong
     * @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 deleteRoomBed(Request $request)
    {
        $id = $request->input('id');
        $item = Contract::query()
            ->where('bed_id', $id)
            ->first();
        if ($item) {

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

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

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

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

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

            $room = $item->room;

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

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

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

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

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

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

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

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

            $item->delete();
        }

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

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

        }

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

    /**
     * @api {get} /get-renter-by-code Tìm thông tin khách thuê theo sđt
     * @apiName get-renter-by-code
     * @apiGroup Room
     * @apiDescription Tìm thông tin khách thuê theo sđt
     * @apiParam {String} phone
     *
     * @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 getRenterByCode(Request $request)
    {
        $phone = $request->input('phone');

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

        $data = User::query()
            ->where('phone', $phone)
            ->with([
                'province',
                'district',
                'ward'
            ])
            ->where('type', User::RENTER)->first();

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

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

        $renter = Renter::withTrashed()->where('user_id', $data->id)->first();


        if (!empty($data->province_id)) {
            $data->province_name = optional(Functions::getProvinceName($data->province_id))->name;
        } else {
            $data->province_name = null;
        }

        if (!empty($data->district_id)) {
            $data->district_name = optional(Functions::getDistrictName($data->district_id))->name;
        } else {
            $data->district_name = null;
        }

        if (!empty($data->ward_id)) {
            $data->ward_name = optional(Functions::getWardName($data->ward_id))->name;
        } else {
            $data->ward_name = null;
        }

        $data->name = $data->name_text;
        $data->id_number_front = null;
        $data->id_number_back = null;
        if ($renter) {
            $data->id_number_front = '/files/' . $renter->id_number_front;
            $data->id_number_back = '/files/' . $renter->id_number_back;
        }

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

    public function getLatestEw(Request $request)
    {
        $roomId = $request->input('room_id');
        $item = ElectricWater::query()
            ->where('room_id', $roomId)
            ->orderBy('date_action', 'desc')
            ->first();
        $e = 1;
        $w = 1;
        if ($item) {
            $e = $item->end_electric;
            $w = $item->end_water;
        }
        return response([
            'status' => 1,
            'data' => [
                'e' => $e,
                'w' => $w
            ]
        ]);
    }
}