<?php

namespace App\Http\Controllers\Backend2;

use App\Components\Functions;
use App\Events\LogAction;
use App\Http\Controllers\Backend\AdminController;
use App\Jobs\DeleteRenterConversation;
use App\Jobs\GenerateNextContractInvoice;
use App\Jobs\ImportContract;
use App\Jobs\ImportContractService;
use App\Jobs\SendMailContract;
use App\Models\CollectSpend;
use App\Models\Contract;
use App\Models\ContractAttachment;
use App\Models\Deposit;
use App\Models\ElectricWater;
use App\Models\Hostel;
use App\Models\HostelFee;
use App\Models\MoneyDetail;
use App\Models\MoneyInfo;
use App\Models\Renter;
use App\Models\RenterBike;
use App\Models\RenterRoom;
use App\Models\Room;
use App\Models\RoomBed;
use App\Models\RoomReservation;
use App\Models\Statistic;
use App\Models\StatisticLog;
use App\Models\StatisticMonth;
use App\Models\Transaction;
use App\Models\TypeSpend;
use App\Services\ContractService;
use App\User;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use MongoDB\BSON\Type;

class ContractController extends AdminController
{
    //
    public function getListView(Request $request)
    {
        return view('admin2.renter.contract');
    }

    public function edit(Request $request)
    {
        $id = $request->input('id');
        $contract = Contract::find($id);

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

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

    public function update(Request $request)
    {
        $data = $request->except('note');
        $feeContracts = $request->input('fee-contracts');
        $qty = $request->input('qty');

        $leaveDay = $request->input('leave_day');
        $endDate = $request->input('end_date');
        $contractDate = $request->input('date_contract');

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

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

        $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][0];
                    if (is_null($qtyValue)) {
                        $qtyValue = 0;
                    }
                    $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();

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

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

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

        $roomId = $data['room_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;
        $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();

        }


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

        $checkContract = Contract::query()->where('phone', $data['phone'])
            ->has('room')
            ->has('hostel')
            ->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'
                    ]);
                }
            }

            $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::where('room_id', $reserveId)->first();
                    if ($reserve) {
                        CollectSpend::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' => !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,
                ]);

//                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,
//                            '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,
//                            '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,
//                        '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;
                }

                $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'],
                    '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' => $data['date_end_residence'],
                    'id_number_front' => isset($data['id_number_front']) ? $data['id_number_front'] : null,
                    'id_number_back' => isset($data['id_number_back']) ? $data['id_number_back'] : null,
//                    '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'])) {
                if ($data['is_collected'] == 'on') {
                    $collectTo = $data['collect_to'];
                    $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
                        ]);
                    }

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

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

                        }
                    }

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

                //    dump($fees);

                $contract->fees()->sync($fees);
            }
            Functions::updateIsEmptyRoom($room);
            //   dd();
            \DB::commit();

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

            //dd($exception->getTraceAsString());

            //   var_dump($exception->getMessage() . '|' . $exception->getLine()); die();

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

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

        $keyCache = 'processing-contract-' . auth('backend')->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->except([
            'months'
        ]);
        $feeContracts = $request->input('fee-contracts');

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

        $hostel = $room->hostel;

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

        $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()) {
            $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['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();
//		}

//        $months = $request->input('months');
//        if($dateContractCarbon) {
//            if (!empty($months)) {
//                $data['end_date'] = $dateContractCarbon->copy()->startOfMonth()->startOfDay()->addMonth(intval($months))->format('d/m/Y');
//            } else {
//                $data['end_date'] = $dateContractCarbon->copy()->startOfMonth()->startOfDay()->addMonth(6)->format('d/m/Y');
//            }
//        }

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

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

        $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_EVERY) {
                $maxRenters = $room->max_renters;
                $currentNumberRenter = RenterRoom::query()->where('room_id', $room->id)->count();
                RoomBed::query()->where('id', $data['bed_id'])->update([
                    'status' => RoomBed::UNAVAILABLE,
                ]);
                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::query()->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'
                    ]);
                }
            }
            $data['user_id'] = auth('backend')->user()->id;
            $contract = Contract::create($data);

            $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', $roomId)->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,
                    'bed_id' => $data['bed_id'],
                    '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::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;
            }

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

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


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

            $checkRenter = RenterRoom::query()->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'],
                    'bed_id' => $data['bed_id'],
                ]);

                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' => $data['date_end_residence'],
                    'id_number_front' => isset($data['id_number_front']) ? $data['id_number_front'] : null,
                    'id_number_back' => isset($data['id_number_back']) ? $data['id_number_back'] : null,
                    'id_number_location' => isset($data['id_number_location']) ? $data['id_number_location'] : null,
                    'id_number_date' => isset($data['id_number_date']) ? $data['id_number_date'] : null,
//                    'residence_status' => $data['residence_status'],
//                    ''
                ]);
            } 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');
//            dump($feeContracts);
//            dump($qty);
            if (is_array($feeContracts)) {
                $fees = [];
                foreach ($feeContracts as $key => $feeContract) {

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

                        }
                    }

                    $qtyValue = $qty[$feeContract][0];
                    if (is_null($qtyValue)) {
                        $qtyValue = 0;
                    }
                    $fees[$feeContract] = ['qty' => $qtyValue];
                }

                //    dump($fees);

                $contract->fees()->sync($fees);
            }
            Functions::updateIsEmptyRoom($room);

            if ($data['room_price'] <= 0) {
                \DB::commit();
                cache()->forget($keyCache);

                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()
                        ]);
                    }
                }
            }
            //	var_dump($collectToCarbon->toDateString()); die();
            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' => $data['bed_id'],
                        'date_action' => $from->copy()->toDateString(),
                        'contract_id' => $contract->id,
                        'user_id' => $user->id,
                        'type' => MoneyInfo::VOUCHER_CONTRACT,
                        'amount' => $sumMoney,
                        'pay' => $money,
                        'remain' => $sumMoney - $money,
                        'money_info_name' => $name
                    ]);

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

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

                    if ($isCollect == true) {

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

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


                    //}

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

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

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

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

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

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

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

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


                    $name = 'Thu tiền phòng từ ' . $from->copy()->format('d/m/Y') . ' đến ' . $to2->copy()->format('d/m/Y');
//                    dump('---');
//							dump($name);
//							dump($period);
//							//dump($paidMoney);
//							dump($money);
                    $moneyInfo = MoneyInfo::create([
                        'hostel_id' => $hostelId,
                        'room_id' => $roomId,
                        'bed_id' => $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
//                ];
            }


            //	var_dump($returnArr); die();

            //die();


//              dd();
            \DB::commit();

        } catch (\Exception $exception) {
            \DB::rollBack();
            cache()->forget($keyCache);

            dump($exception->getMessage());

            dd($exception->getTraceAsString());

            //var_dump($exception->getMessage() . '|' . $exception->getLine()); die();

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

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

    public function endContract($id, Request $request)
    {
        $contract = Contract::find($id);
        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;
        $isConfirm = $request->input('is_confirm');
        $isReturnDeposit = $request->input('is_return_deposit');
        $isReturnMoneyInfo = $request->input('is_return_money_info');
        $amountReturnDeposit = $request->input('amount_return_deposit');

        $dateEndContract = $request->input('date_end_contract');

        if (empty($dateEndContract)) {
            $dateEndContract = Carbon::now();
        } else {
            $dateEndContract = Carbon::createFromFormat('d/m/Y', $dateEndContract);
        }

        try {
            \DB::beginTransaction();

            if ($isConfirm != 1) {


                $items = MoneyInfo::query()->select(\DB::raw('id, room_id, remain, user_id, date_action, CONCAT(MONTH(date_action),"/", YEAR(date_action)) as date_action_group'))
                    ->where('room_id', $roomId)
                    // ->where('remain', '>', 0)
                    ->where(function ($q) use ($contract) {

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

                    })
                    ->groupBy(\DB::raw('MONTH(date_action), YEAR(date_action)'))
                    ->orderBy(\DB::raw('date_action', 'asc'))->get();

                $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::query()->whereIn('money_info_id', $itemsRoomPrice)
                    ->orderBy('end_date', 'desc')->first();

                $itemsSum = MoneyInfo::query()->where('room_id', $roomId)
                    // ->where('remain', '>', 0)
                    ->where(function ($q) use ($contract) {

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

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

                $amountRemain = MoneyInfo::query()->where('room_id', $roomId)
                    // ->where('remain', '>', 0)
                    ->where(function ($q) use ($contract) {

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

                    })->sum('remain');
                $amountReturnUser = 0;
                $amountCollected = 0;
                $amountReturned = 0;
                $messageReturnCollected = null;
                $amountSum = $itemsSum->sum('amount');
                $amountPay = $itemsSum->sum('pay');
                $amountDiscount = $itemsSum->sum('discount');

                $amountSum -= $amountDiscount;

                // $endDate = null;


                $latestEndDate = optional($moneyDetails)->end_date;
                $endDate = null;
                $messageReturned = null;
                if (!empty($latestEndDate)) {
                    $endDateCarbon = Carbon::createFromFormat('Y-m-d', $latestEndDate);
                    $endDate = $endDateCarbon->copy()->addDay();
                    $startDate = Carbon::now()->addDay(1)->startOfDay();
                    if ($startDate->lessThanOrEqualTo($endDateCarbon)) {
                        $amountReturned = Functions::calculateMoneyInRange4($startDate, $endDateCarbon, $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');
                    }
                }

                $amountReturnUser = $amountRemain - $amountReturned - $contract->deposit;

                return response([
                    'status' => 2,
                    'data' => view('admin2.room.payment_end_contract', compact('items', 'amountSum', 'amountPay',
                        'roomId', 'room', 'hostel', 'userId', 'contract', 'endDate', 'amountCollected',
                        'messageReturnCollected', 'amountReturned', 'messageReturned', 'amountReturnUser', 'contract'))->render()
                ]);


            } else {
                $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::query()->whereIn('money_info_id', $itemsRoomPrice)
                    ->orderBy('end_date', 'desc')->first();

                $itemsToPaids = MoneyInfo::query()->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,
                        '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) {

                $amountReturnDeposit = Functions::filterInputNumber($amountReturnDeposit);
                if ($amountReturnDeposit <= 0) {
                    return response([
                        'status' => 0,
                        'message' => 'Số tiền trả cọc phải lớn hơn 0'
                    ]);
                }

                if ($amountReturnDeposit > $contract->deposit) {
                    return response([
                        'status' => 0,
                        'message' => 'Số tiền trả cọc không được vượt quá cọc Hợp đồng'
                    ]);
                }
                $transaction = Transaction::create([
                    'money_info_id' => null,
                    'amount' => $amountReturnDeposit,
                    'note' => 'Thanh toán tiền cọc HĐ ' . $contract->code,
                    'room_id' => $roomId,
                    'hostel_id' => $hostel->id,
                    'date_action' => Carbon::now()->toDateString(),
                    'type' => CollectSpend::SPEND,
                    'is_statistic' => false
                ]);

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

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

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

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

                $statMonth = StatisticMonth::create([
                    'month' => $dateEndContract->copy()->month,
                    'year' => $dateEndContract->copy()->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' => $dateEndContract->copy()->month,
                    'year' => $dateEndContract->copy()->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,
                    'collect_spend_id' => optional($cp)->id,
                ]);
            }


            $latestEndDate = optional($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::calculateMoneyInRange4($startDate, $endDateCarbon, $contract->room_price, $contract->day_collect, true);
                    //	$amountReturned  = Functions::calculateMoneyInRange3( $startDate, $endDateCarbon, $contract->room_price, $contract->day_collect );
                    $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 = auth('backend')->user()->id;
                    if (auth('backend')->user()->type == User::STAFF) {
                        $ownerId = auth('backend')->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
                RoomBed::query()->where('id', $contract->bed_id)->update([
                    'status' => RoomBed::AVAILABLE,
                ]);
            }

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

            //dd($contract->renter_id, $roomId);

            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, $room->id));
        } catch (\Exception $exception) {
            \DB::rollBack();

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

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

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

    }

    public function printEndContract($id, Request $request)
    {
        $contract = Contract::find($id);
        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;
        $isConfirm = $request->input('is_confirm');
        $isReturnDeposit = $request->input('is_return_deposit');
        $isReturnMoneyInfo = $request->input('is_return_money_info');
        $amountReturnDeposit = $request->input('amount_return_deposit');
        if (!empty($amountReturnDeposit)) {
            $amountReturnDeposit = Functions::filterInputNumber($amountReturnDeposit);
        }

        $dateEndContract = $request->input('date_end_contract');

        if (empty($dateEndContract)) {
            $dateEndContract = Carbon::now();
        } else {
            $dateEndContract = Carbon::createFromFormat('d/m/Y', $dateEndContract);
        }


        $items = MoneyInfo::query()
            ->where('room_id', $roomId)
            ->where('remain', '>', 0)
            ->where(function ($q) use ($contract) {

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

            })
            ->orderBy('id', 'desc')->get();

        $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::query()->whereIn('money_info_id', $itemsRoomPrice)
            ->orderBy('end_date', 'desc')->first();

        $itemsSum = MoneyInfo::query()->where('room_id', $roomId)
            // ->where('remain', '>', 0)
            ->where(function ($q) use ($contract) {

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

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

        $amountRemain = MoneyInfo::where('room_id', $roomId)
            // ->where('remain', '>', 0)
            ->where(function ($q) use ($contract) {

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

            })->sum('remain');
        $amountReturnUser = 0;
        $amountCollected = 0;
        $amountReturned = 0;
        $messageReturnCollected = null;
        $amountSum = $itemsSum->sum('amount');
        $amountPay = $itemsSum->sum('pay');
        $amountDiscount = $itemsSum->sum('discount');

        $amountSum -= $amountDiscount;

        // $endDate = null;


        $latestEndDate = optional($moneyDetails)->end_date;
        $endDate = null;
        $messageReturned = null;
        if (!empty($latestEndDate)) {
            $endDateCarbon = Carbon::createFromFormat('Y-m-d', $latestEndDate);
            $endDate = $endDateCarbon->copy()->addDay();
            $startDate = $dateEndContract->copy()->addDay(1)->startOfDay();
            if ($startDate->lessThanOrEqualTo($endDateCarbon)) {
                $amountReturned = Functions::calculateMoneyInRange4($startDate, $endDateCarbon, $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');
            }
        }

        //	$amountReturnUser = $amountRemain - $amountReturned - $contract->deposit;

        $amountReturnUser = $amountSum;

        if ($isReturnMoneyInfo) {
            $amountReturnUser = $amountReturnUser - $amountReturned;
        }

        if ($isReturnDeposit) {
            if (!empty($amountReturnDeposit)) {
                $amountReturnUser = $amountReturnUser - $amountReturnDeposit;
            }

        }

        if ($amountPay > 0) {
            $amountReturnUser = $amountReturnUser - $amountPay;
        }

        $details = MoneyDetail::query()->whereIn('money_info_id', $items->pluck('id')->toArray())->get();
        $discount = $amountDiscount;
        $pay = $amountPay;
        $f = new \NumberFormatter('vi_VN', \NumberFormatter::SPELLOUT);

        return view('admin.money.bill_end_contract', compact('items', 'amountSum', 'amountPay', 'details',
            'roomId', 'room', 'hostel', 'userId', 'contract', 'endDate', 'amountCollected', 'pay', 'f', 'isReturnDeposit', 'isReturnMoneyInfo',
            'messageReturnCollected', 'amountReturnDeposit', 'amountReturned', 'messageReturned', 'amountReturnUser', 'contract', 'discount'));

    }

    public function generatePaymentEndContractStat(Request $request)
    {
        $id = $request->input('contract_id');
        $isReturnDeposit = $request->input('is_return_deposit');
        $isReturnMoneyInfo = $request->input('is_return_money_info');
        $amountReturnDeposit = $request->input('amount_return_deposit');
        $amountReturnDeposit = Functions::filterInputNumber($amountReturnDeposit);

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

        if (empty($endContractDate)) {
            $endContractDate = Carbon::now();
        } else {
            $endContractDate = Carbon::createFromFormat('d/m/Y', $endContractDate);
        }

        $roomId = $contract->room_id;
        $room = $contract->room;
        $hostel = $contract->room->hostel;
        $userId = $contract->renter_id;
        $items = MoneyInfo::where('room_id', $roomId)
            // ->where('remain', '>', 0)
            ->where(function ($q) use ($contract) {

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

            })->where('remain', '>', 0);
        $itemsSum = clone $items;
        $itemsPay = clone $items;
        $amount = $itemsSum->sum('amount');
        $pay = $itemsPay->sum('pay');
        $discount = $itemsSum->sum('discount');
        $amount -= $discount;
        $messageReturned = '';

        $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::query()->whereIn('money_info_id', $itemsRoomPrice)
            ->orderBy('end_date', 'desc')->first();
        $latestEndDate = null;
        if ($moneyDetails) {
            $latestEndDate = $moneyDetails->end_date;
        }
        $endDate = null;
        if (!empty($latestEndDate)) {
            $endDate = Carbon::createFromFormat('Y-m-d', $latestEndDate)->addDay();
        }

        $items = $items->get();


        $amountRemain = MoneyInfo::where('room_id', $roomId)
            // ->where('remain', '>', 0)
            ->where(function ($q) use ($contract) {

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

            })->where('remain', '>', 0)->sum('remain');
        $amountReturnUser = 0;
        $amountReturned = 0;
        $messageReturnCollected = null;

        // $endDate = null;
        if ($moneyDetails) {

            $latestEndDate = $moneyDetails->end_date;
            $endDate = null;
            if (!empty($latestEndDate)) {
                $endDateCarbon = Carbon::createFromFormat('Y-m-d', $latestEndDate);
                $endDate = $endDateCarbon->copy()->addDay();
                $startDate = $endContractDate->copy()->addDay(1)->startOfDay();
                if ($startDate->lessThanOrEqualTo($endDateCarbon)) {
                    $amountReturned = Functions::calculateMoneyInRange4($startDate, $endDateCarbon, $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');
                }
            }

            $amountReturnUser = $amount;

            if ($isReturnMoneyInfo) {
                $amountReturnUser = $amountReturnUser - $amountReturned;
            }

            if ($isReturnDeposit) {
                if ($request->has('amount_return_deposit')) {
                    if ($amountReturnDeposit <= 0) {
                        return response([
                            'status' => 0,
                            'message' => 'Số tiền trả cọc phải lớn hơn 0'
                        ]);
                    }

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

                $amountReturnUser = $amountReturnUser - $amountReturnDeposit;
            }

            if ($pay > 0) {
                $amountReturnUser = $amountReturnUser - $pay;
            }

            return response([
                'status' => 1,
                'data' => view('admin2.room.payment_end_contract_stat', compact('amount', 'pay', 'isReturnMoneyInfo',
                    'items', 'roomId', 'room', 'hostel', 'userId', 'contract', 'amountReturnUser', 'amountReturned', 'messageReturned', 'amountReturnDeposit',
                    'endDate', 'endContractDate', 'isReturnDeposit'))->render()
            ]);
        }

        return response([
            'status' => 1,
            'data' => view('admin2.room.payment_end_contract_stat', compact('amount', 'pay', 'isReturnMoneyInfo',
                'items', 'roomId', 'room', 'hostel', 'userId', 'contract', 'amountReturnUser', 'amountReturned', 'messageReturned', 'amountReturnDeposit',
                'endDate', 'endContractDate', 'isReturnDeposit'))->render()
        ]);


    }

    public function uploadFile(Request $request)
    {
        $files = $request->file('files');
        $contractId = $request->input('contract_id');
        $contract = Contract::find($contractId);
        $user = Functions::getCurrentUser();
        if ($request->hasFile('files')) {
            foreach ($files as $file) {
                $fileName = str_slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));
                $fileExtension = $file->getClientOriginalExtension();
                $fileSize = $file->getSize();
                $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
                ]);


                $itemArr = [
                    'deleteType' => 'POST',
                    'deleteUrl' => url('admin/delete-file-system', ['id' => $fileId->id]),
                    'name' => $fileName,
                    'size' => $fileSize,
                    'thumbnailUrl' => $thumbnailUrl,
                    'type' => $mime,
                    'url' => '/files/' . $filePath,

                ];


                $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([
                'files' => [$itemArr]
            ]);
        }


    }

    public function getAttachments($id, Request $request)
    {
        $files = ContractAttachment::where('contract_id', $id)->orderBy('id', 'desc')->get();

        return view('admin2.contract.attachments', compact('files'))->render();
    }

    public function deleteFile($id)
    {
        $file = ContractAttachment::find($id);
        if ($file) {
            $contract = $file->contract;
            $fileName = $file->name;
            $file->delete();

            $user = Functions::getCurrentUser();
            if ($contract) {
                $desc = '{' . $user->name . '} đã xóa đí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 . '} đã xóa đí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' => 'delete-contract-attachment',
                    'user_id' => optional($user)->id,
                    'object_id' => $id,
                    'hostel_id' => $contract->hostel_id,
                    'room_id' => $contract->room_id,
                    'properties' => $file->toArray(),
                    'desc' => $desc
                ]));
            }

            return response([
                $fileName => true
            ]);
        }
    }

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

        if (auth('backend')->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' => 'Dữ liệu không hợp lệ'
            ]);
        }

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

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

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

        try {
            \DB::beginTransaction();

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

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

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

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

            $room = $item->room;

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

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

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

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

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

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

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


            $item->delete();

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

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

            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 sendMail(Request $request)
    {
        $id = $request->input('contract_id');
        $contract = Contract::find($id);
        if (!$contract) {
            return response([
                'status' => 0
            ]);
        }

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

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

    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,
            'contract' => $reContract
        ]);
    }

    public function importContract(Request $request)
    {
        $file = $request->file('file');
        if (!\File::exists(public_path('files'))) {
            \File::makeDirectory(public_path('files'), '0777', true);
        }

        $filename = time() . '_' . mt_rand(1111, 9999) . '_' . str_slug($request->file('file')->getClientOriginalName());
        $filename = $filename . '.' . $file->extension();
        $request->file('file')->move(public_path('files'), $filename);

        $filePath = public_path('files/' . $filename);
        $ownerId = auth('backend')->user()->id;
        if (auth('backend')->user()->type == User::STAFF) {
            $ownerId = auth('backend')->user()->staff_owner_id;
        }
        $userId = auth('backend')->user()->id;
        dispatch(new ImportContract($filePath, $ownerId, $userId));
        return response([
            'status' => 1,
            'message' => 'Hệ thống đang tiến hành xử lý'
        ]);
    }

    public function getCmndInfo(Request $request)
    {
        $image = $request->file('image');
        if (empty($image)) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $image = Functions::uploadImage($image);
        $base64 = base64_encode(\Image::make(public_path('files/' . $image))->encode()->encoded);
        $client = new Client();
        $response = $client->post('https://viettelgroup.ai/api/v2/ocr/idcard', [
            'headers' => [
                'api-key' => '7c8ba773-64cd-4ba5-a9bd-f035f06d0149',
                'Content-Type' => 'application/json'
            ],
            'json' => [
                'image' => $base64
            ]
        ]);

        $response = json_decode($response->getBody()->getContents(), true);

        $issueDate = null;
        if (isset($response['issue_date'])) {
            $issueDate = $response['issue_date'];
            if (!empty($issueDate)) {
                $issueDate = Carbon::createFromFormat('d-m-Y', $issueDate)->format('d/m/Y');
            }
        }
        $result = [
            'id' => isset($response['id']) ? $response['id'] : null,
            'issue_by' => isset($response['issue_by']) ? $response['issue_by'] : null,
            'issue_date' => $issueDate,
        ];

        return response($result);

    }

}
