<?php

namespace App\Http\Controllers\Backend2;

use App\Components\Functions;
use App\Events\LogAction;
use App\Http\Controllers\Backend\AdminController;
use App\Jobs\CreateHostelConservation;
use App\Jobs\CreateHostelConservationV2;
use App\Jobs\DeleteHostelConversation;
use App\Jobs\GenerateDynamicLinkHostel;
use App\Jobs\GenerateNextContractInvoice;
use App\Models\Amenity;
use App\Models\CollectSpend;
use App\Models\Contract;
use App\Models\ElectricQuota;
use App\Models\Hostel;
use App\Models\HostelFee;
use App\Models\HostelType;
use App\Models\MoneyInfo;
use App\Models\Package;
use App\Models\Policy;
use App\Models\Room;
use App\Models\RoomBed;
use App\Models\RoomType;
use App\Models\Statistic;
use App\Models\StatisticLog;
use App\Models\Transaction;
use App\Models\UserPackage;
use App\Models\WaterQuota;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Yajra\Datatables\Datatables;

class HostelController extends AdminController
{
    //
    public function getRoomsByHostel(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        if (empty($hostelId)) {
            $ownerId = auth('backend')->user()->id;
            if (auth('backend')->user()->type == User::STAFF) {
                $ownerId = auth('backend')->user()->staff_owner_id;
            }
            $hostelArrs = Hostel::query()
                ->where('owner_id', $ownerId)->pluck('id')
                ->toArray();
            $items = Room::whereIn('hostel_id', $hostelArrs)->get();


        } else {
            $items = Room::query()->where('hostel_id', $hostelId)->get();
        }

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

    public function getInvoiceView(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        return response([
            'status' => 1,
            'data' => view('admin2.hostel.gen_invoice_all', compact('hostelId'))->render()
        ]);
    }

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


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

        }

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


    public function getHostelByAttributeView(Request $request)
    {
        if (auth('backend')->user()->type == User::RENTER) {
            abort(403);
        }

        if (auth('backend')->user()->type == User::EDITOR) {
            return redirect()->to(url('admin/blog'));
        }

        $package = null;
        $dateEndPackage = null;
        $remainHostel = 0;
        $userPackage = UserPackage::query()->where('user_id', auth('backend')->user()->id)->first();
        if ($userPackage) {
            $package = $userPackage->package;
            $dateEndPackage = $userPackage->end_date;
            $numberHostel = $userPackage->number_hostels;
            $useHostel = Hostel::query()->where('owner_id', auth('backend')->user()->id)->count();
            $remainHostel = $numberHostel - $useHostel;
            if ($remainHostel < 0) {
                $remainHostel = 0;
            }

            if ($dateEndPackage) {
                $dateEndPackage = $dateEndPackage->format('d/m/Y');
            }
        }

        return view('admin2.hostel.list', compact('remainHostel'));
    }

    public function remainHostel(Request $request)
    {
        $remainHostel = 0;
        $userPackage = UserPackage::where('user_id', auth('backend')->user()->id)->first();
        if ($userPackage) {
            $numberHostel = $userPackage->number_hostels;
            $useHostel = Hostel::query()
                ->where('owner_id', auth('backend')->user()->id)
                ->count();
            $remainHostel = $numberHostel - $useHostel;
            if ($remainHostel < 0) {
                $remainHostel = 0;
            }

        }

        if ($remainHostel == 0) {
            return response([
                'status' => 1,
                'message' => 'Số nhà trọ còn lại có thể tạo: 0. Nếu bạn muốn tạo Thêm nhà vui lòng nâng cấp gói cước hoặc gọi cho chúng tôi để được hỗ trợ'
            ]);
        }

        return response([
            'status' => 1,
            'message' => 'Số nhà trọ còn lại có thể tạo: ' . $remainHostel
        ]);
    }

    public function getDetailHostelRoom($id)
    {
        $hostel = Hostel::find($id);
        if ($hostel) {
            setcookie('room-hostel-id', $hostel->id, time() + (86400 * 30), '/');

            $numberRooms = Room::query()->where('hostel_id', $hostel->id)->count();
            $emptyRooms = \App\Components\Functions::getEmptyRoomHostel($hostel);

            if ($hostel->type_rent == Hostel::TYPE_RENT_ALL) {
                $chartRoom = [
                    [
                        'name' => 'Đã cho thuê',
                        'value' => $numberRooms - $emptyRooms,
                        'color' => '#4b77be'
                    ],
                    [
                        'name' => 'Phòng trống',
                        'value' => $emptyRooms,
                        'color' => '#ef4836'
                    ]
                ];
            } else if ($hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                $numberBeds = RoomBed::where('hostel_id', $hostel->id)->count();
                $fillBeds = RoomBed::where('hostel_id', $hostel->id)->where('status', RoomBed::UNAVAILABLE)->count();
                $chartRoom = [
                    [
                        'name' => 'Đã cho thuê',
                        'value' => $fillBeds,
                        'color' => '#4b77be'
                    ],
                    [
                        'name' => 'Giường trống',
                        'value' => $numberBeds - $fillBeds,
                        'color' => '#ef4836'
                    ]
                ];
            }


            $notRemain = MoneyInfo::where('hostel_id', $hostel->id)
                ->where('remain', 0)->count();
            $remain = MoneyInfo::where('hostel_id', $hostel->id)
                ->where('remain', '<>', 0)->count();

            $chartPayment = [
                [
                    'name' => 'Đã thanh toán',
                    'value' => $notRemain,
                    'color' => '#4b77be'
                ],
                [
                    'name' => 'Chưa thanh toán',
                    'value' => $remain,
                    'color' => '#ef4836'
                ]
            ];

            return response([
                'status' => 1,
                'data' => view('admin2.hostel.hostel_info_room', compact('hostel'))->render(),
                'buttons' => view('admin2.room.hostel_buttons', compact('hostel'))->render(),
                'chart_room' => $chartRoom,
                'chart_payment' => $chartPayment
            ]);
        }


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

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

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

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

        $fees = HostelFee::where('hostel_id', $hostelId)->get();

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

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


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

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

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

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

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


        return response([
            'status' => 1,
            'data' => view('admin2.money.quota', compact('item', 'hostel', 'type', 'feeId'))->render()
        ]);
    }

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

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

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

        $amenities = Amenity::where('type', Amenity::AMENITY)->whereIn('user_id', [
            0,
            auth('backend')->user()->id
        ])->get();
        $policies = Amenity::where('type', Amenity::POLICY)->whereIn('user_id', [
            0,
            auth('backend')->user()->id
        ])->get();
        $provinces = Functions::getProvinces();

        return response([
            'lat' => $hostel->lat,
            'lng' => $hostel->lng,
            'status' => 1,
            'data' => view('admin2.hostel.edit', compact('hostel', 'amenities', 'policies', 'provinces'))->render()
        ]);
    }

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

        $amenities = Amenity::where('type', Amenity::AMENITY)->whereIn('user_id', [
            0,
            auth('backend')->user()->id
        ])->get();
        $policies = Amenity::where('type', Amenity::POLICY)->whereIn('user_id', [
            0,
            auth('backend')->user()->id
        ])->get();
        $provinces = Functions::getProvinces();

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

    public function getRoomTypes(Request $request)
    {
        $userId = auth('backend')->user()->id;
        $hostelId = $request->input('hostel_id');
        $roomTypes = RoomType::where('hostel_id', $hostelId)->get();

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

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

        $feeId = $request->input('fee_id');
        $fee = HostelFee::find($feeId);
        $hostelId = null;
        if ($fee) {
            $hostelId = $fee->hostel_id;
            $fee->delete();
        }

        $fees = HostelFee::where('hostel_id', $hostelId)->get();

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

    public function storeHostelFee(Request $request)
    {
        if (auth('backend')->user()->cannot('add-hostel-fee')) {
            return response([
                'status' => 0,
                'message' => 'Bạn không có quyền thực hiện'
            ]);
        }
        $feeNames = $request->input('fee_name');
        //  dd($request->all());
        $feeTypes = $request->input('fee_type');
        $fees = $request->input('fee');
        $feeUnits = $request->input('fee_unit');
        $hostelId = $request->input('hostel_id');
        $ids = $request->input('fee_ids');

        if (!is_array($feeNames) && empty($ids)) {
            return response([
                'status' => 0,
                'message' => 'Bạn chưa tạo dữ liệu mới'
            ]);
        }

        $feeTypesEdits = $request->input('fee_type_edit');
        $feesEdits = $request->input('fee_edit');
        $feeNamesEdits = $request->input('fee_name_edit');
        $user = Functions::getCurrentUser();
        try {

            \DB::beginTransaction();

            if (is_array($ids)) {
                foreach ($ids as $key => $id) {
                    $type = !isset($feeTypesEdits[$key]) ? 0 : $feeTypesEdits[$key];
                    $fee = !isset($feesEdits[$key]) ? 0 : Functions::filterInputNumber($feesEdits[$key]);
                    $feeName = !isset($feeNamesEdits[$key]) ? '' : $feeNamesEdits[$key];

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

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

                    if ($type != HostelFee::DYNAMIC && $type != HostelFee::ELECTRIC && $type != HostelFee::WATER
                        && $type != HostelFee::ELECTRIC_DYNAMIC && $type != HostelFee::WATER_DYNAMIC
                    ) {
                        if (empty($fee)) {
                            return response([
                                'status' => 0,
                                'message' => 'Không được bỏ trống đơn giá'
                            ]);
                        }
                    }
//                if ($type == HostelFee::WATER || $type == HostelFee::ELECTRIC) {
//                    $check = HostelFee::where('type', $type)->where('hostel_id', $hostelId)->count();
//                    if ($check) {
//                        return response([
//                            'status' => 0,
//                            'message' => 'Bạn không thể thiết lập 2 giá điện nước'
//                        ]);
//                    }
//                }

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

                    $item = HostelFee::find($id);
                    if ($item) {
                        $item->name = $feeName;
                        $item->unit = $unit;
                        $item->fee = $fee;
                        $item->type = $type;
                        $item->save();
                    }
                }
            }

            if (is_array($feeNames)) {

                foreach ($feeNames as $key => $feeName) {


                    $type = !isset($feeTypes[$key]) ? 0 : $feeTypes[$key];
                    $fee = !isset($fees[$key]) ? 0 : Functions::filterInputNumber($fees[$key]);

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

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

                    if ($type != HostelFee::DYNAMIC && $type != HostelFee::ELECTRIC && $type != HostelFee::WATER
                        && $type != HostelFee::ELECTRIC_DYNAMIC && $type != HostelFee::WATER_DYNAMIC
                    ) {

                        if (empty($fee)) {

                            return response([
                                'status' => 0,
                                'message' => 'Không được bỏ trống đơn giá'
                            ]);
                        }
                    }

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

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


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

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

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

        $fees = HostelFee::where('hostel_id', $hostelId)->get();

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

    public function getHostelByAttribute(Request $request)
    {
        $items = Hostel::query();

        if (auth('backend')->check()) {

            if (auth('backend')->user()->type == User::RENTER) {
                abort(403);
            }

            if (auth('backend')->user()->type == User::OWNER) {
                $items = $items->where('owner_id', auth('backend')->user()->id);
            }

            if (auth('backend')->user()->type == User::STAFF) {
                $hostelArrs = Functions::getHostelArrStaff();
                $items = $items->whereIn('id', $hostelArrs);
            }
        }


        return Datatables::of($items)
            ->addIndexColumn()
            ->editColumn('number_rooms', function ($item) {
                $numberRooms = Room::where('hostel_id', $item->id)->count();
                if ($numberRooms > 0) {
                    return '<a target="_blank" class="btn red" href="' . url('admin2/room/list?hostel=' . $item->id) . '">' . $numberRooms . ' phòng </a>';
                } else {
                    return '<a target="_blank"  class="btn btn-success"  href="' . url('admin2/room/list?hostel=' . $item->id) . '">' . 'Quản lý phòng' . '</a>';
                }
            })
            ->editColumn('number_empty_rooms', function ($item) {
                $number = Functions::getNumberRoomsHostel($item);

                return $number['number_empty_rooms'];
                //return $item->number_empty_rooms;
            })
            ->editColumn('status', function ($item) {
                return $item->status_text;
            })
            ->editColumn('name', function ($item) {
                return '<a target="_blank" href="' . url('admin2/room/list?hostel=' . $item->id) . '">' . $item->name . '</a>';
            })
            ->editColumn('created_at', function ($item) {
                return $item->created_at->format('d/m/Y');
            })
            ->addColumn('action', function ($item) {

                $retVal = '';

                if (auth('backend')->user()->can('edit-hostel')) {
                    $retVal .= '<a data-hostel="' . $item->id . '" href="#edit-hostel" data-href="' . url('admin2/hostel/edit', ['id' => $item->id]) . '" data-toggle="modal" class="btn btn-sm btn-outline btn-editable btn-edit-hostel purple"><i class="fa fa-edit"></i> Sửa</a>';
                }

                if (auth('backend')->user()->can('delete-hostel')) {
                    $retVal .= '<a data-id="' . $item->id . '" data-href="' . url('admin2/hostel/delete', ['id' => $item->id]) . '" class="btn btn-sm btn-outline btn-editable btn-delete dark black"><i class="fa fa-trash"></i> Xóa</a>';
                }

                return $retVal;

            })
            ->make(true);
    }

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

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

        $amenityArr = [];
        $policyArr = [];
        $dateEw = $request->input('date_ew');
        $dateMoney = $request->input('date_money');
        $types = $request->input('types');
        $electricPrice = $request->input('electric_price');
        $waterPrice = $request->input('water_price');

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

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


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

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

            $numberHostel = $userPackage->number_hostels;
        }

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

        try {

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

            \DB::beginTransaction();

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

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

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

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

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

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

            if (isset($data['is_display'])) {

                if ($data['is_display'] == 'off') {
                    $data['is_display'] = false;
                } else {
                    $data['is_display'] = true;
                }
            } else {
                $data['is_display'] = false;
            }
            //dd($data);
            $hostel = Hostel::create($data);

            // dd($hostel);

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

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

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

                $currentNumberHostel = auth('backend')->user()->number_hostels;
                auth('backend')->user()->number_hostels = $currentNumberHostel + 1;
                auth('backend')->user()->save();
            }


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

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


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

            \DB::commit();

            if (auth('backend')->user()->type == User::STAFF) {
                auth('backend')->user()->staffHostel()->attach($hostel->id);
            }

            dispatch(new CreateHostelConservation($hostel->id, auth('backend')->user()->id));
            dispatch(new CreateHostelConservationV2($hostel->id, auth('backend')->user()->id));
            dispatch(new GenerateDynamicLinkHostel($hostel->id));
        } catch (\Exception $exception) {
            \DB::rollBack();
            dd($exception->getMessage() . '|' . $exception->getLine());

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

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

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

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

        if ($item) {
            $hostelId = $item->hostel_id;
            \DB::table('hostel_images')->where('id', $id)->delete();
            $images = \DB::table('hostel_images')->where('hostel_id', $hostelId)->get();

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

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

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

                $room->delete();
            }

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

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

        }


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

    public function update($id, Request $request)
    {
        if (auth('backend')->user()->type != User::ADMIN) {
            if (auth('backend')->user()->cannot('edit-hostel')) {
                return response([
                    'status' => 2,
                    'message' => 'Bạn chưa được phân quyền thực hiện'
                ]);
            }
        }
        $data = $request->except('images');

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


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

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

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

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

        try {

            \DB::beginTransaction();

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

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

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

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

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

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

            $data['is_display'] = false;
            $data['status_confirm'] = 0;

            if (isset($data['is_display'])) {

                if ($data['is_display'] != 'off') {
                    $data['is_display'] = true;
                }
            }


            if (isset($data['status_confirm'])) {

                if ($data['status_confirm'] != 'off') {
                    $data['status_confirm'] = 1;
                }
            }

            $hostel->update($data);

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

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

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

                $currentNumberHostel = auth('backend')->user()->number_hostels;
                auth('backend')->user()->number_hostels = $currentNumberHostel + 1;
                auth('backend')->user()->save();
            }

            Room::where('hostel_id', $hostel->id)->update([
                'lat' => $data['lat'],
                'lng' => $data['lng']
            ]);

            \DB::commit();

            $user = Functions::getCurrentUser();
            event(new LogAction([
                'type' => 'update-hostel',
                'user_id' => optional($user)->id,
                'object_id' => $hostel->id,
                'hostel_id' => $hostel->id,
                'properties' => $hostel->toArray(),
                'desc' => '{'.$user->name.'} đã sửa nhà {'.$hostel->name.'}'
            ]));
        } catch (\Exception $exception) {
            \DB::rollBack();

            dd($exception->getMessage());

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

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

    public function delete(Request $request)
    {
        $id = $request->input('id');
        $hostel = Hostel::find($id);
        if ($hostel) {
            $hostel->delete();
        }

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

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

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

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

    }

    public function getFilterPaymentHistory(Request $request)
    {
        $type = $request->input('type');
        $month = $request->input('month');
        $year = $request->input('year');
        $hostelId = $request->input('hostel_id');
        $contractCode = $request->input('contract_code');
        $contractId = null;
        if (!empty($contractCode)) {
            $contract = Contract::where('code', $contractCode)->first();
            if ($contract) {
                $contractId = $contract->id;
            }
        }


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

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

            $items = $items->whereIn('hostel_id', $hostels);
        }


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

        $items = $items->get();

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

        return response([
            'status' => 1,
            'data' => view('admin2.hostel.pay_history_hostel', compact('items', 'hostelId', 'type', 'contractId', 'owner', 'month'))->render(),
        ]);
    }

    public function downloadSampleImportService($id, Request $request)
    {
        $hostel = Hostel::find($id);
        $month = $request->input('month', Carbon::now()->format('m/Y'));
        $fees = HostelFee::query()
            ->where('hostel_id', $hostel->id)
            ->get();


        //return view('admin.sample.sample_service', compact( 'fees' ) );

        return \Excel::create('Nhap-dich-vu', function ($excel) use ($fees, $hostel, $month) {

            $excel->sheet('dich-vu', function ($sheet) use ($fees, $hostel, $month) {
                $monthCarbon = Carbon::createFromFormat('d/m/Y', '01/' . $month);
                $sheet->setAllBorders('medium');
                $sheet->setAutoSize(true);

                $sheet->setStyle(array(
                    'font' => array(
                        'name' => 'Times New Roman',
                        'size' => 12,
                    ),
                    'borders' => [
                        'allborders' => [
                            'style' => 'medium']
                    ]
                ));

                $contracts = Contract::query()
                    ->with('room')
                    ->where('hostel_id', $hostel->id)
                    ->where('status', '<>', Contract::LIQUIDATED)
                    ->get()
                    ->sortBy('room.name');

                $sheet->loadView('admin.sample.sample_service', compact('fees', 'contracts', 'monthCarbon'));


            });
        })->download('xlsx');
    }

    public function getType()
    {
        $items = HostelType::all();
        return $items->map(function ($item) {
            return [
                'value' => $item->id,
                'text' => $item->name
            ];
        })->toArray();
    }

    public function downloadSampleImportContract($id, Request $request)
    {
        $hostel = Hostel::find($id);
        $fees = HostelFee::query()
            ->where('hostel_id', $hostel->id)
            ->get();

        //return view('admin.sample.sample_service', compact( 'fees' ) );

        return \Excel::create('Nhap-hop-dong', function ($excel) use ($fees, $hostel) {
            $excel->sheet('hop-dong', function ($sheet) use ($fees, $hostel) {
                $sheet->setAllBorders('medium');
                $sheet->setAutoSize(true);
//                $sheet->getRowDimension(1)->setRowHeight(200);

                $sheet->setStyle(array(
                    'font' => array(
                        'name' => 'Times New Roman',
                        'size' => 12,
                    ),
                    'borders' => [
                        'allborders' => [
                            'style' => 'medium'
                        ]
                    ]
                ));


                $sheet->loadView('admin.sample.sample_contract', compact('fees', 'hostel'));


            });
        })->download('xlsx');
    }

    public function importView(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $hostel = Hostel::find($hostelId);
        if (!$hostel) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        return response([
            'status' => 1,
            'data' => view('admin2.hostel.import', compact('hostel'))->render()
        ]);
    }
}
