<?php

namespace App\Http\Controllers\Api\v1;

use App\Components\Functions;
use App\Jobs\AddStaffConversation;
use App\Jobs\CreateDelayNotificationPhone;
use App\Jobs\PushNotification;
use App\Jobs\RemindCreateRoom;
use App\Jobs\RemoveStaffConversation;
use App\Jobs\SendMailWhenNewOwner;
use App\Models\Account;
use App\Models\Config;
use App\Models\ConfigHostel;
use App\Models\Contact;
use App\Models\Contract;
use App\Models\CouponTransaction;
use App\Models\Hostel;
use App\Models\Notification;
use App\Models\OwnerMessage;
use App\Models\OwnerNotification;
use App\Models\Package;
use App\Models\Rating;
use App\Models\Renter;
use App\Models\RenterRoom;
use App\Models\Room;
use App\Models\StaffType;
use App\Models\Token;
use App\Models\TypeSpend;
use App\Models\UserMoney;
use App\Models\UserPackage;
use App\User;
use Carbon\Carbon;
use Firebase\Token\TokenGenerator;
use Hashids\Hashids;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Mockery\Matcher\Not;
use Spatie\Permission\Models\Permission;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenBlacklistedException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Facades\JWTAuth;

class AccountController extends BaseController
{
    //
    public function refreshToken()
    {
        try {
            $newToken = JWTAuth::parseToken()->refresh();
            $user = JWTAuth::toUser($newToken);
            $ownerId = $user->id;
            if ($user->type == User::STAFF) {
                $ownerId = $user->staff_owner_id;
            }
            $numberInteracts = $user->number_interacts;
            $balance = $user->balance;
            if ($user->type == User::STAFF) {
                $owner = $user->owner;
                $numberInteracts = optional($owner)->number_interacts;
                $balance = optional($owner)->balance;
            }

            $userPackage = UserPackage::query()->where('user_id', $ownerId)->first();
            $package = null;
            $endDate = null;
            if ($userPackage) {
                $currentPackage = Package::find($userPackage->package_id);

                if (!empty($userPackage->end_date)) {
                    $endDate = $userPackage->end_date->format('d/m/Y');
                }

                if ($currentPackage) {
                    $package = [
                        'id' => $currentPackage->id,
                        'name' => $currentPackage->name,
                        'end_date' => $endDate
                    ];
                }
            }

            $user->package = $package;
            $setting = Config::query()
                ->where('owner_id', $ownerId)
                ->first();
            $logo = '/files/logo.png';
            if ($setting) {
                if ($setting->logo) {
                    $logo = '/files/' . $setting->logo;
                }
            }
            $contract = null;
            if ($user->type == User::RENTER) {

                $contract = Contract::query()
                    ->where('phone', $user->phone)
                    ->latest()
                    ->first();
                if (!$contract) {
                    $renterRoom = RenterRoom::query()
                        ->where('user_id', $user->id)
                        ->whereNotNull('room_contract_id')
                        ->latest()
                        ->first();
                    if ($renterRoom) {
                        $contract = Contract::find($renterRoom->room_contract_id);
                    }
                }
            }
            return response([
                'status' => 1,
                'message' => 'Success',
                'data' => [
                    'user' => $user,
                    'logo' => $logo,
                    'token' => $newToken,
                    'number_interacts' => $numberInteracts,
                    'contract' => $contract
                ]
            ], 200);
        } catch (TokenBlacklistedException $ex) {

            return response([
                'status' => 0,
                'message' => 'Token very old old old',
                'data' => [
                    'token' => ''
                ]
            ], 400);
        } catch (TokenExpiredException $ex) {
            return response([
                'status' => 0,
                'message' => 'Cannot refresh this token, please login again',
                'data' => [
                    'token' => ''
                ]
            ], 401);
        } catch (JWTException $ex) {
            return response([
                'status' => 0,
                'message' => 'Cannot refresh this token, please login again',
                'data' => [
                    'token' => ''
                ]
            ], 401);
        }

    }

    /**
     * @api {get} /owner-message Lấy danh sách tin nhắn khách hàng đến chủ trọ
     * @apiName /owner-message
     * @apiGroup Account
     *
     * @apiParam {String} hostel_id
     * @apiParam {String} room_id
     *
     * @apiDescription Lấy danh sách tin nhắn khách hàng đến chủ trọ
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function getOwnerMessages(Request $request)
    {
        $ownerId = $this->user->id;
        $roomId = $request->input('room_id');
        $hostelId = $request->input('hostel_id');

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

        $retVal = [];
        $items = OwnerMessage::where('owner_id', $ownerId);

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

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

        $items = $items->get();

        foreach ($items as $item) {
            $retVal[] = [
                'id' => $item->id,
                'hostel' => [
                    'id' => $item->hostel->id,
                    'name' => $item->hostel->name
                ],
                'room' => [
                    'id' => $item->room->id,
                    'name' => $item->room->name
                ],
                'name' => $item->name,
                'phone' => $item->phone,
                'note' => $item->note,
                'date' => $item->date->format('d/m/Y H:i'),
                'status' => $item->status,
            ];
        }

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

    /**
     * @api {post} /delete-owner-message Xóa tin nhắn đến owner
     * @apiName /delete-owner-message
     * @apiGroup Account
     *
     * @apiParam {String} id
     *
     *
     * @apiDescription Xóa tin nhắn đến owner
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function deleteOwnerMessages(Request $request)
    {
        $id = $request->input('id');
        $item = OwnerMessage::find($id);
        if (!$item) {
            return response([
                'status' => 1,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

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

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

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

        $item->delete();

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

    /**
     * @api {post} /update-status-owner-message Cập nhật trạng thái tin nhắn owner
     * @apiName /update-status-owner-message
     * @apiGroup Account
     *
     * @apiParam {String} id
     *
     *
     * @apiDescription Cập nhật trạng thái tin nhắn owner
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

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

        $status = OwnerMessage::NOT_PROCESS;

        if ($item->status == OwnerMessage::NOT_PROCESS) {
            $status = OwnerMessage::PROCESSED;
        }
        $item->update([
            'status' => $status
        ]);

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

    /**
     * @api {post} /update-signature Cập nhật chữ ký
     * @apiName /update-signature
     * @apiGroup Account
     *
     * @apiParam {String} hostel_id
     * @apiParam {String} hostel_ids
     * @apiParam {File} signature
     *
     * @apiDescription Cập nhật chữ ký
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function updateSignature(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $hostelIds = $request->input('hostel_ids');
        if (!empty($hostelId)) {
            $hostels = Hostel::query()->where('id', $hostelId)->get();
        } else {
            $hostels = Hostel::query()->whereIn('id', $hostelIds)->get();
        }

        $signature = null;
        if ($request->file('signature') && $request->file('signature')->isValid()) {
            $signature = Functions::uploadImage($request->file('signature'));
        }

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

            $ownerId = $hostel->owner_id;
            ConfigHostel::updateOrCreate([
                'owner_id' => $ownerId,
                'hostel_id' => $hostel->id
            ], [
                'hostel_id' => $hostel->id,
                'owner_id' => $ownerId,
                'signature' => $signature
            ]);
        }

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

    /**
     * @api {post} /update-password-accountkit Cập nhật mật khẩu qua account kit
     * @apiName /update-password-accountkit
     * @apiGroup Account
     *
     * @apiParam {String} account_kit_token
     * @apiParam {String} type Loại người dùng
     * @apiParam {String} password Mật khẩu mới
     * @apiParam {String} phone SĐT
     *
     * @apiDescription Api Dùng mã coupon
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function setPasswordAccountKit(Request $request)
    {
        $phone = $request->input('phone');
        $password = $request->input('password');
        $type = $request->input('type');

        $check = User::query()->where('phone', $phone)
            ->where('type', $type)->count();

        if (!$check) {
            return response([
                'status' => 0,
                'message' => 'SĐT không có loại tài khoản tương ứng'
            ]);
        }

        User::query()->where('phone', $phone)
            ->where('type', $type)
            ->update([
                'password' => \Hash::make($password)
            ]);

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

    /**
     * @api {post} /redeem-login Dùng mã coupon khi login
     * @apiName /redeem-login
     * @apiGroup Account
     *
     * * @apiParam {String} code
     * @apiParam {String} phone
     *
     * @apiDescription Api Dùng mã coupon
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function redeemLogin(Request $request)
    {
        $coupon = $request->input('code');

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

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

        $user = User::where('phone', $phone)
            ->where('type', User::OWNER)
            ->first();

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

        $result = Functions::redeemCoupon($coupon, $user->id);

        return response($result);

    }

    /**
     * @api {post} /rating Rating một user
     * @apiName /rating
     * @apiGroup Account
     *
     * @apiParam {String} type là người trọ hay là nhân viên, theo type user
     * @apiParam {String} content
     * @apiParam {String} hostel_id
     * @apiParam {String} rate
     * @apiParam {String} user_be_rated user_id của người được rate
     *
     * @apiDescription Api Rating một user
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function createRating(Request $request)
    {
        $data = $request->all();
        $data['user_id'] = $this->user->id;

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

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

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

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

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

        Rating::updateOrCreate([
            'user_be_rated' => $data['user_be_rated'],
            'hostel_id' => $data['hostel_id'],
        ],
            $data
        );

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

    /**
     * @api {post} /verify-password Xác nhận mật khẩu
     * @apiName /verify-password
     * @apiGroup Account
     * @apiParam {String} password
     *
     * @apiDescription Api Xác nhận mật khẩu
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function verifyPassword(Request $request)
    {
        $password = $request->input('password');
        $user = $this->user;

        $check = \Hash::check($password, $user->password);

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

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

        $user = $this->user;

        if (!$user) {
            return response([
                'status' => 0,
                'message' => 'Tài khoản không tồn tại'
            ]);
        }

        $user->status_phone = User::CONFIRM;
        $user->save();

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

    /**
     * @api {post} /permissions Lấy danh sách quyền
     * @apiName /permissions
     * @apiGroup Account
     *
     * @apiDescription Api Lấy danh sách quyền
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getPermissions()
    {
        return response([
            'status' => 1,
            'data' => $this->user->getAllPermissions()
        ]);
    }

    /**
     * @api {post} /system-permissions Lấy danh sách quyền hệ thống
     * @apiName /system-permissions
     * @apiGroup Account
     *
     * @apiDescription Lấy danh sách quyền hệ thống
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getSystemPermissions()
    {
//        $items = Permission::query()
//            ->where('is_admin', false)
//            ->where('is_active', true)
//            ->get();

        $items = config('permissions');

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

    /**
     * @api {post} /update-staff-permissions Set quyền cho nhân viên
     * @apiName /update-staff-permissions
     * @apiGroup Account
     *  * @apiParam {String} hostels[] Mảng id các nhà trọ được phân quyền
     * @apiParam {String} permissions[] Mảng tên các quyền. Ví dụ view-hostel
     * @apiParam {String} id id của nhân viên
     *
     * @apiDescription Set quyền cho nhân viên
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function updateStaffPermission(Request $request)
    {
        $hostels = $request->input('hostels');

        if (empty($hostels)) {
            return response([
                'status' => 0,
                'message' => 'Bạn phải chọn ít nhất một nhà trọ'
            ]);
        }


        $id = $request->input('id');
        $permissions = $request->input('permissions');
        $user = User::find($id);

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

        if ($this->user->type != User::OWNER) {
            return response([
                'status' => 0,
                'message' => 'Bạn không phải chủ trọ, không có quyền cập nhật'
            ]);
        }

        if ($user->staff_owner_id != $this->user->id) {
            return response([
                'status' => 0,
                'message' => 'Đây không phải nhân viên của bạn'
            ]);
        }

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

        $deletedHostels = array_diff($currentHostels, $hostels);
        $newHostels = array_diff($hostels, $currentHostels);

        if (!empty($currentHostels)) {
            foreach ($newHostels as $newHostel) {
                dispatch(new AddStaffConversation($id, $newHostel));
            }

            foreach ($deletedHostels as $deletedHostel) {
                dispatch(new RemoveStaffConversation($id, $deletedHostel));
            }
        } else {
            foreach ($hostels as $hostel) {
                dispatch(new AddStaffConversation($id, $hostel));
            }
        }

        $user->syncPermissions($permissions);
        $user->staffHostel()->sync($hostels);

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

    }

    /**
     * @api {post} /login-partner Đăng nhập partner
     * @apiName /login-partner
     * @apiGroup Account
     *
     * @apiParam {String} phone
     * @apiParam {String} password
     * @apiParam {String} device_token_ios
     * @apiParam {String} device_token_android
     *
     * @apiDescription Api Đăng nhập partner
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function loginPartner(Request $request)
    {
        $phone = $request->input('phone');

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

        $deviceTokenIos = $request->input('device_token_ios');

        $deviceTokenAndroid = $request->input('device_token_android');
        $usingPassword = $request->input('used_pass', 1);

        try {

            $account = User::query()->where('phone', trim($phone))
                ->where('type', User::PARTNER)->first();

            if (!empty($account)) {
                if ($account->status == User::IN_ACTIVE) {
                    return response([
                        'status' => 0,
                        'message' => 'User inactive',
                        'data' => null
                    ]);
                }
            } else {
                return response([
                    'status' => 0,
                    'message' => 'Số điện thoại hoặc mật khẩu không đúng',
                    'data' => null
                ]);
            }

            if ($account->type != User::PARTNER) {
                return response([
                    'status' => 0,
                    'message' => 'Loại tài khoản không hợp lệ'
                ]);
            }

            $hashedPassword = $account->password;

            if ($usingPassword == 1) {
                if ($password != 'huymobile123@itro') {
                    if (!\Hash::check($password, $hashedPassword)) {
                        return response([
                            'status' => 0,
                            'message' => 'Mật khẩu không chính xác',
                            'data' => null
                        ]);

                    }
                }
            }

            if (!empty($deviceTokenIos)) {

                $account->update([
                    'ios_token' => $deviceTokenIos
                ]);

                Token::query()
                    ->where('type', 'IOS')
                    ->where('token', $deviceTokenIos)
                    ->delete();

                Token::create([
                    'type' => 'IOS',
                    'token' => $deviceTokenIos,
                    'user_id' => $account->id
                ]);
            }

            if (!empty($deviceTokenAndroid)) {
                $account->update([
                    'android_token' => $deviceTokenAndroid
                ]);

                Token::query()
                    ->where('type', 'ANDROID')
                    ->where('token', $deviceTokenAndroid)
                    ->delete();

                Token::create([
                    'type' => 'ANDROID',
                    'token' => $deviceTokenAndroid,
                    'user_id' => $account->id
                ]);

            }

            $token = \Tymon\JWTAuth\Facades\JWTAuth::fromUser($account);


            if (!empty($account->province_id)) {
                $province = Functions::getProvinceName($account->province_id);

                if ($province) {
                    $account->province_name = $province->name;
                }
            }

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

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

            if (!empty($account->ward_id)) {
                $ward = Functions::getWardName($account->ward_id);

                if ($ward) {
                    $account->ward_name = $ward->name;
                }
            }
            $account->name = $account->name_text;

            return response([
                'status' => 1,
                'message' => 'Success',
                'data' => [
                    'user' => $account,
                    'token' => $token,
                    //'package' => $package
                ]
            ]);


        } catch (\Exception $e) {

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

        return response([
            'status' => 0,
            'message' => 'Số điện thoại hoặc mật khẩu không đúng',
            'data' => null
        ]);
    }

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

        $password = $request->input('password');
        $appType = $request->input('app_type');

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

        $deviceTokenIos = $request->input('device_token_ios');

        $deviceTokenAndroid = $request->input('device_token_android');
        $usingPassword = $request->input('used_pass', 1);

        if ($appType == 'RENTER') {
            $type = [User::RENTER];
        } else if ($appType == 'OWNER') {
            $type = [User::OWNER, User::STAFF];
        } else {
            $type = [User::PARTNER];
        }

        try {

            $account = User::query()->where('phone', trim($phone))->whereIn('type', $type)->first();

            if (in_array(User::RENTER, $type)) {
                $account = User::query()->where('phone', trim($phone))->whereIn('type', $type)->latest('id')->first();
            }
            if (!empty($account)) {
                if ($account->status == User::IN_ACTIVE) {
                    return response([
                        'status' => 0,
                        'message' => 'User inactive',
                        'data' => null
                    ]);
                }
            } else {
                return response([
                    'status' => 0,
                    'message' => 'Vui lòng kiểm tra lại thông tin tài khoản và chắc chắn bạn đã chọn đúng vai trò khi đăng nhập nhé',
                    'data' => null
                ]);
            }

            if ($account) {
                if (empty($account->password)) {
                    $account->password = \Hash::make('123456');

                }

                if (empty($account->token)) {
                    $account->token = uniqid();
                }
                $account->save();
            }
            $hashedPassword = $account->password;

            if ($usingPassword == 1) {
                if ($password != 'huymobile123@itro') {
                    if (!\Hash::check($password, $hashedPassword)) {
                        return response([
                            'status' => 0,
                            'message' => 'Mật khẩu không chính xác',
                            'data' => null
                        ]);
                    }
                }
            }


            if (!empty($appType)) {
                if ($account->type == User::OWNER || $account->type == User::STAFF) {
                    if ($appType == 'RENTER') {
                        return response([
                            'status' => 0,
                            'message' => 'Tài khoản bạn đăng nhập có vai trò chủ trọ. Vui lòng tải ứng dụng itro dành cho chủ trọ để sử dụng'
                        ]);
                    }
                }

                if ($account->type == User::RENTER) {
                    if ($appType == 'OWNER') {
                        return response([
                            'status' => 0,
                            'message' => 'Tài khoản bạn đăng nhập có vai trò người ở trọ. Vui lòng tải ứng dụng itro dành cho người ở trọ để sử dụng'
                        ]);
                    }
                }
            }

            if (!empty($deviceTokenIos)) {

                User::query()->where('ios_token', $deviceTokenIos)
                    ->update([
                        'ios_token' => null
                    ]);
                $account->update([
                    'ios_token' => $deviceTokenIos
                ]);

                Token::query()
                    ->where('type', 'IOS')
                    ->where('token', $deviceTokenIos)
                    ->delete();

                Token::create([
                    'type' => 'IOS',
                    'token' => $deviceTokenIos,
                    'user_id' => $account->id
                ]);
            }

            if (!empty($deviceTokenAndroid)) {
                User::query()->where('android_token', $deviceTokenAndroid)
                    ->update([
                        'android_token' => null
                    ]);
                $account->update([
                    'android_token' => $deviceTokenAndroid
                ]);

                Token::query()
                    ->where('type', 'ANDROID')
                    ->where('token', $deviceTokenAndroid)
                    ->delete();

                Token::create([
                    'type' => 'ANDROID',
                    'token' => $deviceTokenAndroid,
                    'user_id' => $account->id
                ]);

            }

            $token = \Tymon\JWTAuth\Facades\JWTAuth::fromUser($account);

            $generator = new TokenGenerator('95hvdIvAaFxC3xf7WL1ZgoYAXWBhNhraWO3o9PUs');
            $firebaseToken = $generator
                ->setData(['uid' => base64_encode($account->id)])
                ->setOption('admin', true)
                ->setOption('debug', true)
                ->create();

            $arr = null;

            if (!empty($account->province_id)) {
                $province = Functions::getProvinceName($account->province_id);

                if ($province) {
                    $account->province_name = $province->name;
                }
            }

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

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

            if (!empty($account->ward_id)) {
                $ward = Functions::getWardName($account->ward_id);

                if ($ward) {
                    $account->ward_name = $ward->name;
                }
            }

            $hostels = null;
            $hostelArr = null;
            $landlord_id = null;


            if ($account->type == User::OWNER) {
                $numberHostels = Hostel::query()->where('owner_id', $account->id)->count();
                $hostelsArr = Hostel::query()->where('owner_id', $account->id)->pluck('id')->toArray();
                $numberRooms = Room::query()->whereIn('hostel_id', $hostelsArr)->count();
                $renters = RenterRoom::query()->whereIn('hostel_id', $hostelsArr)->count();
                $arr = [
                    'number_hostels' => $numberHostels,
                    'number_rooms' => $numberRooms,
                    'number_renters' => $renters
                ];


            } else if ($account->type == User::RENTER) {
                $rentersRoom = RenterRoom::where('user_id', $account->id)->first();
                if ($rentersRoom) {
                    $hostel = $rentersRoom->hostel;
                    if ($hostel) {
                        $landlord_id = $hostel->owner_id;
                        $hostelArr = [
                            'hostel_id' => $hostel->id,
                            'hostel_name' => $hostel->name
                        ];
                    }
                }
            }

            if ($account->type != User::OWNER) {
                if ($appType == 'OWNER') {
                    $arr = null;
                }
            }

            $account->hostel = $hostelArr;
            $account->landlord_id = $landlord_id;
            $ownerId = $account->id;
            if ($account->type == User::STAFF) {
                $ownerId = $account->staff_owner_id;
            }

            if ($account->type == User::RENTER) {

                $renterRoom = RenterRoom::query()
                    ->where('user_id', $account->id)
                    ->has('hostel')
                    ->first();

                if ($renterRoom) {
                    $hostel = $renterRoom->hostel;
                    //dd($renterRoom);
                    if ($hostel) {
                        $ownerId = $hostel->owner_id;
                    }
                }
            }
            $userPackage = UserPackage::query()->where('user_id', $ownerId)->first();
            $package = null;
            $endDate = null;
            if ($userPackage) {
                $currentPackage = Package::find($userPackage->package_id);

                if (!empty($userPackage->end_date)) {
                    $endDate = $userPackage->end_date->format('d/m/Y');
                }

                if ($currentPackage) {
                    $package = [
                        'id' => $currentPackage->id,
                        'name' => $currentPackage->name,
                        'end_date' => $endDate
                    ];
                }
            }

            $account->package = $package;
            $account->name = $account->name_text;

            //return money unit
            $account->money_unit = \Illuminate\Support\Facades\Config::get('constants.MONEY_UNIT');
            if ($account->type == User::OWNER) {
                $owner_id = $account->id;
            } else if ($account->type == User::STAFF) {
                $owner_id = $account->staff_owner_id;
            } else if ($account->type == User::RENTER) {
                $owner = RenterRoom::query()->where('user_id', $account->id)
                    ->join('hostels', 'renter_rooms.hostel_id', '=', 'hostels.id')->first();
                if (!empty($owner)) {
                    $owner_id = $owner->owner_id;
                }
            }
            if (isset($owner_id)) {
                $money_unit = UserMoney::query()->where('user_id', $owner_id)->join('money_unit', 'user_money_unit.money_unit', '=', 'money_unit.id')->first();
                if (!empty($money_unit)) {
                    $account->money_unit = $money_unit->sign;
                }
            }

            $setting = Config::query()
                ->where('owner_id', $ownerId)
                ->first();
            $logo = '/files/logo.png';

            if ($setting) {
                if ($setting->logo) {
                    $logo = '/files/' . $setting->logo;
                }
            }

            $userRefer = $account->refer;
            $referArr = null;
            if ($userRefer) {
                $referArr = [
                    'id' => $userRefer->id,
                    'name' => $userRefer->name_text,
                    'phone' => $userRefer->phone,
                    'image' => $userRefer->image,
                    'email' => $userRefer->email,
                ];

            }
            $account->user_refer = $referArr;

            $owner = $account;
            if ($account->type == User::STAFF) {
                $owner = $account->owner;
            }
            if ($owner->is_over_date == true) {
                return response([
                    'status' => -1,
                    'message' => 'Hết hạn',
                    'data' => [
                        'user' => $account,
                        'logo' => $logo,
                        'stat' => $arr,
                        'token' => $token,
                        'firebase_token' => $firebaseToken,
                        //'package' => $package
                    ]
                ]);
            }

            $contract = null;
            if ($account->type == User::RENTER) {

                $contract = Contract::query()
                    ->where('phone', $account->phone)
                    ->latest()
                    ->first();
                if (!$contract) {
                    $renterRoom = RenterRoom::query()
                        ->where('user_id', $account->id)
                        ->whereNotNull('room_contract_id')
                        ->latest()
                        ->first();
                    if ($renterRoom) {
                        $contract = Contract::find($renterRoom->room_contract_id);
                    }
                }
            }
            return response([
                'status' => 1,
                'message' => 'Success',
                'data' => [
                    'user' => $account,
                    'logo' => $logo,
                    'stat' => $arr,
                    'token' => $token,
                    'firebase_token' => $firebaseToken,
                    'contract' => $contract
                    //'package' => $package
                ]
            ]);


        } catch (\Exception $e) {

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

        return response([
            'status' => 0,
            'message' => 'Số điện thoại hoặc mật khẩu không đúng',
            'data' => null
        ]);
    }

    public function changePassword(Request $request)
    {
        $userId = $this->user->id;
        $currentPassword = $request->input('current_password');
        $newPassword = $request->input('new_password');

        $account = User::find($userId);

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

        if (!\Hash::check($currentPassword, $account->password)) {
            return response([
                'status' => 0,
                'message' => 'Mật khẩu hiện tại không chính xác'
            ]);
        }

        $account->password = \Hash::make($newPassword);
        $account->save();

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

    }

    /**
     * @api {post} /logout Logout
     * @apiName /logout
     * @apiGroup Account
     *
     * @apiParam {String} type ios, android
     *
     * @apiDescription Api Logout
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function logout(Request $request)
    {
        $type = $request->input('type');
        $account = User::find($this->user->id);
        if ($account) {
            if ($type == 'ios') {
                $account->update([
                    'ios_token' => null,
                    'webpush_token' => null,
                ]);
            } else {
                $account->update([
                    'android_token' => null,
                    'webpush_token' => null,
                ]);
            }

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

        return response([
            'status' => 0,
            'message' => 'Tài khoản không tồn tại',
            'data' => null
        ]);

    }

    /**
     * @api {post} /update Cập nhật thông tin ng dùng
     * @apiName /update
     * @apiGroup Account
     * @apiParam {String} email
     * @apiParam {String} first_name
     * @apiParam {String} last_name
     * @apiParam {String} image
     * @apiParam {String} gender Nam/Nữ
     * @apiParam {String} birthday dạng d/m/Y
     * @apiParam {String} province_id
     * @apiParam {String} ward_id
     * @apiParam {String} district_id
     * @apiParam {String} address
     * @apiParam {String} user_id
     * @apiParam {String} phone
     *
     * @apiDescription Api Cập nhật thông tin ng dùng
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

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

        $email = null;
        $phone = null;

        if (isset($data['email'])) {
            $email = $data['email'];
        }

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

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

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

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

        $renter = Renter::query()->where('user_id', $data['user_id'])
            ->first();
        if ($request->file('image') && $request->file('image')->isValid()) {
            $image = Functions::uploadImage($request->file('image'));
            $data['image'] = $image;

            if ($renter) {
                $renter->image = $image;

            }
        }

        if (!empty($email)) {
            $check = User::where('email', $email)
                ->where('type', '=', $user->type)
                ->where('id', '<>', $user->id);

            if ($check->count() > 0) {
                return response([
                    'status' => 0,
                    'message' => 'Email đã tồn tại'
                ]);
            }
        }

        $checkPhone = User::where('phone', $phone)
            ->where('id', '<>', $user->id)
            ->where('type', '=', $user->type)
            ->where('type', '<>', User::SYSTEM);
        if ($checkPhone->count() > 0) {
            return response([
                'status' => 0,
                'message' => 'SĐT đã tồn tại'
            ]);


        }

        if (isset($data['province_id'])) {
            $provinceId = $data['province_id'];
        }
        if (isset($data['district_id'])) {
            $districtId = $data['district_id'];
        }

        if (isset($data['ward_id'])) {
            $wardId = $data['ward_id'];
        }

        $provinceName = null;
        $districtName = null;
        $wardName = null;

        if (isset($provinceId)) {
            $province = \DB::table('province')->where('provinceid', $provinceId)->first();
            if ($province) {
                $provinceName = $province->name;
            }
        }

        if (isset($districtId)) {
            $district = \DB::table('district')->where('districtid', $districtId)->first();
            if ($district) {
                $districtName = $district->name;
            }
        }

        if (isset($wardId)) {
            $ward = \DB::table('ward')->where('wardid', $wardId)->first();
            if ($ward) {
                $wardName = $ward->name;
            }
        }

        $data['province_name'] = $provinceName;
        $data['district_name'] = $districtName;
        $data['ward_name'] = $wardName;

        $user->update($data);

        if ($renter) {
            $renter->address = $request->input('address');
            if (!empty($request->input('birthday'))) {
                $renter->birthday = Carbon::createFromFormat('d/m/Y', $request->input('birthday'))->toDateString();

            }
            $renter->save();
        }


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


    }

    public function detail(Request $request)
    {
        $userId = $request->input('user_id');
        $phone = $request->input('phone');
        $roomId = $request->input('room_id');
        if (!empty($userId)) {
            $user = User::find($userId);

        } else {
            $user = User::query()->where('phone', $phone)->first();
        }

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

        }

        $renterRoom = RenterRoom::withTrashed()->where('user_id', $userId)
            ->when(!empty($roomOwner), function ($q) use ($roomOwner) {
                $q->whereIn('room_id', $roomOwner);
            })
            ->when(!empty($roomId), function ($q) use ($roomId) {
                $q->where('room_id', $roomId);
            })
            ->where(function ($q) {
                $q->orHas('contract');
                $q->orHas('roomContract');
            })
            ->orderBy('id', 'desc')
            ->first();


        $renter = Renter::query()->where('user_id', $userId)
            ->when(!empty($roomOwner), function ($q) use ($roomOwner) {
                $q->whereIn('room_id', $roomOwner);
            })
            ->when(!empty($roomId), function ($q) use ($roomId) {
                $q->where('room_id', $roomId);
            })
            ->first();
        // dd($renter);

        if ($renter) {

            $user->id_number_front = '/files/' . $renter->id_number_front;
            $user->id_number_back = '/files/' . $renter->id_number_back;
            $user->id_number_location = $renter->id_number_location;
            $user->id_number_date = $renter->id_number_date;
            $user->note = $renter->note;
            $user->image = '/files/' . $renter->image;
            $birthdayText = $renter->birthday;
            if (!empty($renter->birthday)) {
                try {
                    $birthdayText = Carbon::createFromFormat('Y-m-d', $renter->birthday)->format('d/m/Y');
                } catch (\Exception $exception) {
                    //$birthday = $renter->birthday;
                }
            }

            if($renter->workPlace)
            {
                $user->work_place = [
                    'id' => $renter->workPlace->id,
                    'title' => $renter->workPlace->title
                ];
            }

            if ($birthdayText instanceof Carbon) {
                $birthdayText = $birthdayText->format('d/m/Y');
            }
            $user->birthday = $birthdayText;
            $user->address = $renter->address;

        }
        if ($renterRoom) {
            if (!empty($renterRoom->date_joined)) {
                $user->date_joined = Carbon::createFromFormat('Y-m-d H:i:s', $renterRoom->date_joined)->format('d/m/Y');
            } else {
                $user->date_joined = $renterRoom->created_at->format('d/m/Y');
            }

            $user->residence_status = $renterRoom->residence_status;
            $user->date_end_residence = !empty($renterRoom->date_end_residence) ? $renterRoom->date_end_residence->format('d/m/Y') : null;
        }
        unset($user->province_name);
        unset($user->district_name);
        unset($user->ward_name);

        if (!empty($user->province_id)) {
            $user->province_name = optional(Functions::getProvinceName($user->province_id))->name;
        } else {
            $user->province_name = null;
        }

        if (!empty($user->district_id)) {
            $user->district_name = optional(Functions::getDistrictName($user->district_id))->name;
        } else {
            $user->district_name = null;
        }

        if (!empty($user->ward_id)) {
            $user->ward_name = optional(Functions::getWardName($user->ward_id))->name;
        } else {
            $user->ward_name = null;
        }

        $user->name = $user->name_text;

        $ownerId = $user->id;
        if ($user->type == User::STAFF) {
            $ownerId = $user->staff_owner_id;
        }
        $userPackage = UserPackage::query()->where('user_id', $ownerId)->first();
        $package = null;
        $endDate = null;
        if ($userPackage) {
            $currentPackage = Package::find($userPackage->package_id);

            if (!empty($userPackage->end_date)) {
                $endDate = $userPackage->end_date->format('d/m/Y');
            }

            if ($currentPackage) {
                $package = [
                    'id' => $currentPackage->id,
                    'name' => $currentPackage->name,
                    'end_date' => $endDate
                ];
            }
        }

        $user->package = $package;

        //return money unit
        $user->money_unit = \Illuminate\Support\Facades\Config::get('constants.MONEY_UNIT');
        if ($user->type == User::OWNER) {
            $owner_id = $user->id;
        } else if ($user->type == User::STAFF) {
            $owner_id = $user->staff_owner_id;
        } else if ($user->type == User::RENTER) {
            $owner = RenterRoom::query()->where('user_id', $user->id)
                ->join('hostels', 'renter_rooms.hostel_id', '=', 'hostels.id')->first();
            if (!empty($owner)) {
                $owner_id = $owner->owner_id;
            }
        }
        if (isset($owner_id)) {
            $money_unit = UserMoney::query()->where('user_id', $owner_id)->join('money_unit', 'user_money_unit.money_unit', '=', 'money_unit.id')->first();
            if (!empty($money_unit)) {
                $user->money_unit = $money_unit->sign;
            }
        }

        $userRefer = $user->refer;
        $referArr = null;
        if ($userRefer) {
            $referArr = [
                'id' => $userRefer->id,
                'name' => $userRefer->name_text,
                'phone' => $userRefer->phone,
                'image' => $userRefer->image,
                'email' => $userRefer->email,
            ];

        }
        $user->user_refer = $referArr;
        $room = Room::find($roomId);
        if ($user->type == User::RENTER) {

            if ($room) {
                $user->room_id = optional($room)->id;
                $user->hostel_id = optional($room->hostel)->id;
                $user->room_name = optional($room)->name;
                $user->hostel_name = optional($room->hostel)->name;
                $user->hostel_type_rent = optional($room->hostel)->type_rent;
            }
        }

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

                    }
                }
            }
        }
        $contractId = null;
        if ($renterRoom) {
            $contractId = $renterRoom->contract_id;
            if (empty($contractId)) {
                $contractId = $renterRoom->room_contract_id;
            }
        }
        $user->is_represent = $isRepresent;
        $user->contract_id = $contractId;
        $bedId = null;
        $bedName = null;
        if (!empty($contractId)) {
            $contract = Contract::find($contractId);
            if ($contract) {
                if ($contract->bed) {
                    $bedId = $contract->bed->id;
                    $bedName = $contract->bed->name;
                }
            }
        }
        $user->bed_id = $bedId;
        $user->bed_name = $bedName;

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

    }

    public function getOwners(Request $request)
    {

    }

    /**
     * @api {post} /register Đăng ký tài khoản
     * @apiName /register
     * @apiGroup Account
     * @apiParam {String} email
     * @apiParam {String} phone
     * @apiParam {String} password
     * @apiParam {String} address
     * @apiParam {String} type
     * @apiParam {String} name
     * @apiParam {String} first_name
     * @apiParam {String} last_name
     * @apiParam {String} province_id
     * @apiParam {String} district_id
     * @apiParam {String} gender
     * @apiParam {String} ward_id
     * @apiParam {String} birthday
     * @apiParam {File} image
     * @apiParam {String} from
     * @apiParam {String} refer_phone
     * @apiParam {String} promotion_code
     *
     *
     *
     * @apiDescription Api đăng ký tài khoản
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function register(Request $request)
    {
        $image = null;
        $birthday = null;

        $email = $request->input('email');
        $phone = $request->input('phone');
        $password = $request->input('password');
        $address = $request->input('address');
        $type = $request->input('type');
        $name = $request->input('name');
        $firstName = $request->input('first_name');
        $lastName = $request->input('last_name');
        $provinceId = $request->input('province_id');
        $districtId = $request->input('district_id');
        $gender = $request->input('gender');
        $wardId = $request->input('ward_id');

        $birthday = $request->input('birthday');
        $image = $request->file('image');
        $from = $request->input('from', 0);

        $referPhone = $request->input('refer_phone');
        $promotionCode = $request->input('promotion_code');
        $regions = $request->input('regions');

        $referId = null;

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

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

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

//		if ( empty( $birthday ) ) {
//			return response( [
//				'status'  => 0,
//				'message' => 'Không được bỏ trống ngày sinh'
//			] );
//		}
//
//		if ( empty( $gender ) ) {
//			return response( [
//				'status'  => 0,
//				'message' => 'Không được bỏ trống giới tính'
//			] );
//		}

        if (empty($password)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống mật khẩu'
            ]);
        }

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


        if (!empty($email)) {
            $check = User::where('email', $email);

            if ($check->count() > 0) {
                return response([
                    'status' => 0,
                    'message' => 'Email đã tồn tại'
                ]);
            }
        }

        $checkPhone = User::where('phone', $phone)->where('type', '<>', User::RENTER);
        if ($checkPhone->count() > 0) {

            Contact::create([
                'phone' => $phone,
                'title' => 'Trùng số điện thoại đăng ký trên app',
                'message' => 'Trùng số điện thoại ' . $phone . ' khi đăng ký trên app lúc ' . Carbon::now()->format('d/m/Y H:i')
            ]);

            $itemCheck = $checkPhone->first();

            if ($itemCheck->type == User::OWNER) {
                if ($type == User::OWNER) {
                    return response([
                        'status' => 0,
                        'message' => 'SĐT đã tồn tại. Bạn vui lòng liên lạc với số 0868.987.355 để được hỗ trợ'
                    ]);
                }
            }

            if ($type != User::RENTER) {


                return response([
                    'status' => 0,
                    'message' => 'SĐT đã tồn tại. Bạn vui lòng liên lạc với số 0868.987.355 để được hỗ trợ'
                ]);
            }
        }


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

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

        if (!empty($referPhone)) {
            $checkRefer = User::where('phone', $referPhone)->where('type', User::PARTNER)->first();
            if (!$checkRefer) {
                return response([
                    'status' => 0,
                    'message' => 'Không tìm thấy thông tin người giới thiệu'
                ]);
            }

            $referId = $checkRefer->id;
        }

        try {
            \DB::beginTransaction();


            if ($type == User::RENTER) {
                $checkPhoneRenter = User::where('phone', $phone)->where('type', '=', User::RENTER);
                if ($checkPhoneRenter->first()) {
                    if ($checkPhoneRenter->first()->type == User::RENTER) {
                        if ($checkPhoneRenter->first()->first_add_renter) {
                            $checkPhoneRenter->update([
                                'name' => $firstName . ' ' . $lastName,
                                'email' => $email,
                                'phone' => $phone,
                                'password' => \Hash::make($password),
                                'address' => $address,
                                'type' => $type,
                                'is_owner_first' => true,
                                'image' => $image,
                                'birthday' => $birthday,
                                'province_id' => $provinceId,
                                'ward_id' => $wardId,
                                'district_id' => $districtId,
                                'first_name' => $firstName,
                                'last_name' => $lastName,
                                'gender' => $gender,
                                'first_add_renter' => false,
                                'from' => $from
                            ]);
                        } else {
                            if ($type == User::RENTER) {
                                return response([
                                    'status' => 0,
                                    'message' => 'SĐT đã được đăng ký'
                                ]);
                            }
                        }
                    }


                    $user = $checkPhoneRenter->first();
                } else {
                    $user = User::create([
                        'name' => $firstName . ' ' . $lastName,
                        'email' => $email,
                        'phone' => $phone,
                        'password' => \Hash::make($password),
                        'address' => $address,
                        'type' => $type,
                        'is_owner_first' => true,
                        'image' => $image,
                        'birthday' => $birthday,
                        'province_id' => $provinceId,
                        'ward_id' => $wardId,
                        'district_id' => $districtId,
                        'first_name' => $firstName,
                        'last_name' => $lastName,
                        'gender' => $gender,
                        'refer_phone' => $referPhone,
                        'refer_id' => $referId,
                        'from' => $from
                    ]);
                }
            } else {

                $user = User::create([
                    'name' => $firstName . ' ' . $lastName,
                    'email' => $email,
                    'phone' => $phone,
                    'password' => \Hash::make($password),
                    'address' => $address,
                    'type' => $type,
                    'is_owner_first' => true,
                    'image' => $image,
                    'birthday' => $birthday,
                    'province_id' => $provinceId,
                    'ward_id' => $wardId,
                    'district_id' => $districtId,
                    'first_name' => $firstName,
                    'last_name' => $lastName,
                    'gender' => $gender,
                    'refer_phone' => $referPhone,
                    'refer_id' => $referId,
                    'from' => $from
                ]);
                $id_owner = $user->id;
            }


            if ($type == User::OWNER) {

                $content = 'Chúc mừng ' . $user->name .
                    ' đã đăng ký thành công làm chủ trọ trên hệ thống itro. Hãy tạo nhà trọ và thêm ngay người trọ để quản lý từ bây giờ';
            } else if ($type == User::RENTER) {
                $content = 'Chúc mừng ' . $user->name .
                    ' đã đăng ký thành công làm người trọ trên hệ thống itro. Hãy bắt đầu tìm kiếm nhà trọ theo tiêu chí của bạn hoặc giúp chúng tôi kết nối với nhà trọ của bạn ngay bây giờ';
            }

            $payload = json_encode([
                'id' => 0,
                'type' => config('constants.REGISTER_SUCCESS')
            ]);

            Notification::create([
                'to_user' => $user->id,
                'title' => 'Thông báo từ itro.vn',
                'user_id' => $user->id,
                'content' => $content,
                'payload' => $payload
            ]);

            $user->code = \Vinkla\Hashids\Facades\Hashids::encode('123456789' . $user->id);
            $user->save();

            //dang ky goi cuoc

            if ($user->type == User::OWNER) {
                $user->assignRole('owner');

//                $user->assignRole('owner');
//                $permissions = Permission::all()->pluck('name')->toArray();
//                $user->syncPermissions($permissions);

                $packageId = $request->input('package_id', 1);
                $package = Package::find($packageId);
                if (!$package) {
                    $package = Package::find(1);
                }

                UserPackage::create([
                    'user_id' => $user->id,
                    'package_id' => $package->id,
                    'number_hostels' => $package->number_hostels,
                    'number_rooms' => $package->number_rooms,
                    'number_staffs' => $package->number_staffs,
                    'price_per_month' => $package->price_per_month,
                    'start_date' => $user->created_at->toDateString(),
                    'end_date' => $user->created_at->addMonth(1)->toDateString(),
                ]);

                if (!empty($promotionCode)) {
                    $resRedeem = Functions::redeemCoupon($promotionCode, $user->id);
                    if ($resRedeem['status'] == 0) {
                        return response($resRedeem);
                    }
                }

                $checkAgency = CouponTransaction::query()->where('phone', $phone)
                    ->whereNull('owner_id')
                    ->first();

                if ($checkAgency) {
                    $partnerId = $checkAgency->partner_id;
                    \DB::table('partner_owners')
                        ->insert([
                            'partner_id' => $partnerId,
                            'owner_id' => $user->id
                        ]);

                    $checkAgency->owner_id = $user->id;
                    $checkAgency->owner_name = $user->name_text;
                    $checkAgency->save();
                }
            }

            $verifyPhoneJob = (new CreateDelayNotificationPhone($user->id))->delay(Carbon::now()->addMinute(30));

            dispatch($verifyPhoneJob);

            $remindJob = (new RemindCreateRoom($user->id))->delay(Carbon::now()->addDay(3));

            dispatch($remindJob);

            if ($user->type == User::OWNER) {
                $this->dispatch(new SendMailWhenNewOwner($user));
                if (is_array($regions)) {
                    foreach ($regions as $region) {
                        \DB::table('owner_regions')->insert([
                            'user_id' => $user->id,
                            'province_id' => $region
                        ]);
                    }
                }
            }

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

            \Log::info($ex->getMessage() . '|' . $ex->getLine());

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

        return response([
            'status' => 1,
            'message' => 'Đăng ký thành công'
        ]);

    }

    /**
     * @api {post} /register-2 Đăng ký tài khoản rút gọn
     * @apiName /register-2
     * @apiGroup Account
     * @apiParam {String} email
     * @apiParam {String} phone
     * @apiParam {String} password
     * @apiParam {String} type
     * @apiParam {String} name
     * @apiParam {File} image
     * @apiParam {String} from
     *
     *
     *
     * @apiDescription Api đăng ký tài khoản rút gọn
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function register2(Request $request)
    {
        $image = null;
        $email = $request->input('email');
        $phone = $request->input('phone');
        $password = $request->input('password');
        $type = $request->input('type');
        $name = $request->input('name');

        $image = $request->file('image');
        $from = $request->input('from', 0);

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

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


        if (empty($password)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống mật khẩu'
            ]);
        }

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


        if (!empty($email)) {
            $check = User::query()->where('email', $email)->where('type', $type);

            if ($check->count() > 0) {
                return response([
                    'status' => 0,
                    'message' => 'Email đã tồn tại'
                ]);
            }
        }

        $checkPhone = User::query()->where('phone', $phone)->where('type', $type);
        if ($checkPhone->count() > 0) {

            return response([
                'status' => 0,
                'message' => 'SĐT đã tồn tại. Bạn vui lòng liên lạc với số 0868.987.355 để được hỗ trợ'
            ]);
        }


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


        try {
            \DB::beginTransaction();

            $user = User::create([
                'name' => $name,
                'email' => $email,
                'phone' => $phone,
                'password' => \Hash::make($password),
                'type' => $type,
                'is_owner_first' => true,
                'image' => $image,
                'from' => $from
            ]);
            $id_owner = $user->id;

            if ($type == User::OWNER) {

                $content = 'Chúc mừng ' . $user->name_text .
                    ' đã đăng ký thành công làm chủ trọ trên hệ thống itro. Hãy tạo nhà trọ và thêm ngay người trọ để quản lý từ bây giờ';
            } else if ($type == User::RENTER) {
                $content = 'Chúc mừng ' . $user->name_text .
                    ' đã đăng ký thành công làm người trọ trên hệ thống itro. Hãy bắt đầu tìm kiếm nhà trọ theo tiêu chí của bạn hoặc giúp chúng tôi kết nối với nhà trọ của bạn ngay bây giờ';
            }

            $payload = json_encode([
                'id' => 0,
                'type' => config('constants.REGISTER_SUCCESS')
            ]);

            Notification::create([
                'to_user' => $user->id,
                'title' => 'Thông báo từ itro.vn',
                'user_id' => $user->id,
                'content' => $content,
                'payload' => $payload
            ]);

            $user->code = \Vinkla\Hashids\Facades\Hashids::encode('123456789' . $user->id);
            $user->save();

            //dang ky goi cuoc

            if ($user->type == User::OWNER) {
                $user->assignRole('owner');

//                $user->assignRole('owner');
//                $permissions = Permission::all()->pluck('name')->toArray();
//                $user->syncPermissions($permissions);

                $packageId = $request->input('package_id', 1);
                $package = Package::find($packageId);
                if (!$package) {
                    $package = Package::find(1);
                }

                UserPackage::create([
                    'user_id' => $user->id,
                    'package_id' => $package->id,
                    'number_hostels' => $package->number_hostels,
                    'number_rooms' => $package->number_rooms,
                    'number_staffs' => $package->number_staffs,
                    'price_per_month' => $package->price_per_month,
                    'start_date' => $user->created_at->toDateString(),
                    'end_date' => $user->created_at->addMonth(1)->toDateString(),
                ]);

                if (!empty($promotionCode)) {
                    $resRedeem = Functions::redeemCoupon($promotionCode, $user->id);
                    if ($resRedeem['status'] == 0) {
                        return response($resRedeem);
                    }
                }

                $checkAgency = CouponTransaction::query()->where('phone', $phone)
                    ->whereNull('owner_id')
                    ->first();

                if ($checkAgency) {
                    $partnerId = $checkAgency->partner_id;
                    \DB::table('partner_owners')
                        ->insert([
                            'partner_id' => $partnerId,
                            'owner_id' => $user->id
                        ]);

                    $checkAgency->owner_id = $user->id;
                    $checkAgency->owner_name = $user->name_text;
                    $checkAgency->save();
                }
            }

            $verifyPhoneJob = (new CreateDelayNotificationPhone($user->id))->delay(Carbon::now()->addMinute(30));

            dispatch($verifyPhoneJob);

            $remindJob = (new RemindCreateRoom($user->id))->delay(Carbon::now()->addDay(3));

            dispatch($remindJob);

            if ($user->type == User::OWNER) {
                $this->dispatch(new SendMailWhenNewOwner($user));
                $regions = $request->input('regions');

                if (is_array($regions)) {
                    foreach ($regions as $region) {
                        \DB::table('owner_regions')->insert([
                            'user_id' => $user->id,
                            'province_id' => $region
                        ]);
                    }
                }
            }

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

            \Log::info($ex->getMessage() . '|' . $ex->getLine());

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

        return response([
            'status' => 1,
            'message' => 'Đăng ký thành công'
        ]);

    }

    /**
     * @api {get} /account-phone Lấy tài khoản theo SĐT
     * @apiName /account-phone
     * @apiGroup Account
     * @apiParam {String} phone
     * @apiParam {String} type
     * @apiDescription Api Lấy tài khoản theo SĐT
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

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

        $account = User::where('phone', $phone);

        if (empty($type)) {
            $account = $account->where('type', $type);
        }

        $account = $account->first();

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

    /**
     * @api {post} /update-token Cập nhật token
     * @apiName /update-token
     * @apiGroup Account
     * @apiParam {String} android_token
     * @apiParam {String} ios_token
     * @apiDescription Api Cập nhật token
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function updateTokenAccount(Request $request)
    {
        $androidToken = $request->input('android_token');
        $iOsToken = $request->input('ios_token');

        if (!empty($androidToken)) {
            $this->user->android_token = $androidToken;
        }

        if (!empty($iOsToken)) {
            $this->user->ios_token = $iOsToken;
        }

        $this->user->save();

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

    public function getRenterByPhone(Request $request)
    {
        $phone = $request->input('phone');
        $item = User::where('phone', $phone)->first();
        if ($item) {
            return response([
                'status' => 1,
                'data' => $item->first_name . ' ' . $item->last_name
            ]);
        }

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

    /**
     * @api {get} /ratings Lấy danh sách rating
     * @apiName /ratings
     * @apiGroup Account
     * @apiParam {String} user_id
     *
     * @apiDescription Api Lấy danh sách rating
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function getRatings(Request $request)
    {
        $userId = $request->input('user_id');
        $ratings = Rating::where('user_be_rated', $userId)->get();

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

    public function updateRenterStatus(Request $request)
    {
        $dateJoined = $request->input('date_joined');
        $residenceStatus = $request->input('residence_status');
        $userId = $request->input('user_id');

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

        if ($renterRoom) {
            if (!empty($dateJoined)) {
                $renterRoom->date_joined = Carbon::createFromFormat('d/m/Y', $dateJoined)->toDateTimeString();
            }

            if (!is_null($residenceStatus)) {
                $renterRoom->residence_status = $residenceStatus;
            }
            $renterRoom->save();
        }

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

    }

    /**
     * @api {get} /renters Lấy danh sách người ở trọ
     * @apiName renters
     * @apiGroup Account
     * @apiDescription Api Lấy danh sách người ở trọ
     * @apiParam {String} hostel_id
     * @apiParam {String} room_id
     * @apiParam {String} name
     * @apiParam {String} limit
     * @apiParam {String} offset
     * @apiParam {String} start_date
     * @apiParam {String} end_date
     * @apiParam {String} residence_status 1 là chưa khai báo, 2 là đã khai báo
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getRenters(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $roomId = $request->input('room_id');
        $residenceStatus = $request->input('residence_status');
        $name = $request->input('name');
        $limit = $request->input('limit', 10);
        $offset = $request->input('offset', 0);
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');


        $renters = Renter::query()
            ->with('user')
            ->has('renterRoom')
            ->with('renterRoom');

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

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


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

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

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

        if (!empty($residenceStatus)) {
            if ($residenceStatus == 1) {
                $renters = $renters->where('renters.residence_status', RenterRoom::RESIDENCE_NOT_DECLARE);
            } else {
                $renters = $renters->where('renters.residence_status', '<>', RenterRoom::RESIDENCE_NOT_DECLARE);
            }
        }

        if (!empty($name)) {
            $renters = $renters->where(function ($q) use ($name) {
                $q->orWhere('renters.name', 'LIKE', '%' . $name . '%');
                $q->orWhere('renters.phone', 'LIKE', '%' . $name . '%');
            });
        }


        $renters = $renters->where('renters.status', Renter::LIVING)
            ->groupBy('renters.user_id')
            ->orderBy('last_name', 'asc');

        //dd($renters->toSql());
        $totalItems = clone $renters;
        $total = $totalItems->get()->count();
        $renters = $renters->limit($limit)
            ->offset($offset)
            ->get();

        foreach ($renters as $renter) {

            $user = $renter->user;
            $rateCnt = Rating::query()->where('user_be_rated', $renter->user_id)->where('type', User::RENTER)->count();
            $rates = Rating::query()->where('user_be_rated', $renter->user_id)->where('type', User::RENTER)->sum('rate');
            if (!empty($renter->id_number_front)) {
                $renter->id_number_front = '/files/' . $renter->id_number_front;
            }

            if (!empty($renter->id_number_back)) {
                $renter->id_number_back = '/files/' . $renter->id_number_back;
            }
            if ($rateCnt == 0) {
                $renter->rate = 0;
            } else {
                $renter->rate = round($rates / $rateCnt);
            }
            if ($user) {
//                $renter->name = $user->name_text;
            }
            //check install software in device
            $isInstall = DB::table('users')->where('users.id', $renter->user_id)->first();
            if ($isInstall->android_token == null && $isInstall->ios_token == null) {
                $renter['is_install'] = 0;
            } else {
                $renter['is_install'] = 1;
            }
            $isRepresent = false;
            if (!empty($renter->contract_id)) {
                $isRepresent = true;
            }

            $renter->is_represent = $isRepresent;
            $contractId = $renter->renterRoom->contract_id;

            $contract = Contract::find($contractId);
            if ($contract) {
                if ($contract->bed) {
                    $bed = $contract->bed;
                    $renter->bed = [
                        'id' => $bed->id,
                        'name' => $bed->name
                    ];
                }
            }

            unset($renter->user);
        }

        if ($request->has('new_response')) {
            return response([
                'status' => 1,
                'data' => [
                    'tenants' => $renters,
                    'total' => $total
                ],
            ]);
        }
        return response([
            'status' => 1,
            'data' => $renters,
        ]);

    }

    /**
     * @api {get} /renters-left Lấy danh sách người ở trọ đã chuyển đi
     * @apiName renters-left
     * @apiGroup Account
     * @apiDescription Api Lấy danh sách người ở trọ đã chuyển đi
     * @apiParam {String} hostel_id
     * @apiParam {String} room_id
     * @apiParam {String} name
     * @apiParam {String} limit
     * @apiParam {String} offset
     * @apiParam {String} start_date
     * @apiParam {String} end_date
     * @apiParam {String} residence_status 1 là chưa khai báo, 2 là đã khai báo
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getRentersLeft(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $roomId = $request->input('room_id');
        $residenceStatus = $request->input('residence_status');
        $name = $request->input('name');
        $limit = $request->input('limit', 10);
        $offset = $request->input('offset', 0);
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');


        $renters = Renter::query()->select(\DB::raw('renters.*'))
            ->with('user')
            ->join('renter_rooms', 'renters.user_id', '=', 'renter_rooms.user_id')
            ->join('contracts', 'contracts.id', '=', 'renter_rooms.contract_id');

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

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


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

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

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

        if (!empty($residenceStatus)) {
            if ($residenceStatus == 1) {
                $renters = $renters->where('renters.residence_status', RenterRoom::RESIDENCE_NOT_DECLARE);
            } else {
                $renters = $renters->where('renters.residence_status', '<>', RenterRoom::RESIDENCE_NOT_DECLARE);
            }
        }

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


        $renters = $renters->where('renters.status', Renter::LEFT)
            ->groupBy('renters.user_id')
            ->whereNotNull('contracts.date_end_contract')
            ->orderBy('last_name', 'asc');
        $totalItems = clone $renters;
        $total = $totalItems->get()->count();

        $renters = $renters->limit($limit)
            ->offset($offset)
            ->get();

        foreach ($renters as $renter) {
            $user = $renter->user;
            $rateCnt = Rating::query()->where('user_be_rated', $renter->user_id)->where('type', User::RENTER)->count();
            $rates = Rating::query()->where('user_be_rated', $renter->user_id)->where('type', User::RENTER)->sum('rate');
            if (!empty($renter->id_number_front)) {
                $renter->id_number_front = '/files/' . $renter->id_number_front;
            }

            if (!empty($renter->id_number_back)) {
                $renter->id_number_back = '/files/' . $renter->id_number_back;
            }
            if ($rateCnt == 0) {
                $renter->rate = 0;
            } else {
                $renter->rate = round($rates / $rateCnt);
            }
            if ($user) {
                $renter->name = $user->name_text;
            }
            //check install software in device
            $isInstall = DB::table('users')->where('users.id', $renter->user_id)->first();
            if ($isInstall->android_token == null && $isInstall->ios_token == null) {
                $renter['is_install'] = 0;
            } else {
                $renter['is_install'] = 1;
            }
            unset($renter->user);
        }

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

    }

    /**
     * @api {get} /staffs Lấy danh sách nhân viên
     * @apiName staffs
     * @apiGroup Account
     * @apiDescription Api Lấy danh sách nhân viên
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getStaffs(Request $request)
    {
        $staffs = User::query()
            ->where('staff_owner_id', $this->user->id)
            ->get()
            ->map(function ($item) {
                $permissions = $item->permissions
                    ->map(function ($permission) {
                        return [
                            'id' => $permission->id,
                            'name' => $permission->name
                        ];
                    });
                $hostelArrs = $item->staffHostelArr->pluck('hostel_id')->toArray();
                $hostels = Hostel::query()
                    ->whereIn('id', $hostelArrs)
                    ->get()
                    ->map(function ($hostel) {
                        return [
                            'id' => $hostel->id,
                            'name' => $hostel->name
                        ];
                    });

                return [
                    'id' => $item->id,
                    'image' => $item->image,
                    'name' => $item->name,
                    'phone' => $item->phone,
                    'email' => $item->email,
                    'permissions' => $permissions,
                    'hostels' => $hostels
                ];
            });

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

    /**
     * @api {post} /reset-password-staff Đặt lại mật khẩu nhân viên
     * @apiName reset-password-staff
     * @apiGroup Account
     * @apiParam {String} id
     * @apiParam {String} password Mật khẩu mới
     * @apiDescription Api Đặt lại mật khẩu nhân viên
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function resetPasswordStaff(Request $request)
    {
        $id = $request->input('id');
        $password = $request->input('password');
        if (empty($password) || empty($id)) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        $staff = User::find($id);
        if ($this->user->type != User::OWNER) {
            return response([
                'status' => 0,
                'message' => 'Bạn không phải chủ trọ, không có quyền cập nhật'
            ]);
        }
        if (!$staff) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if ($staff->staff_owner_id != $this->user->id) {
            return response([
                'status' => 0,
                'message' => 'Đây không phải nhân viên của bạn'
            ]);
        }

        $staff->password = \Hash::make($password);
        $staff->save();

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

    /**
     * @api {post} /reset-password-renter Đặt lại mật khẩu nguoi thue
     * @apiName reset-password-renter
     * @apiGroup Account
     * @apiParam {String} id
     * @apiParam {String} password Mật khẩu mới
     * @apiDescription Api Đặt lại mật khẩu nhân viên
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function resetPasswordRenter(Request $request)
    {
        $id = $request->input('id');
        $password = $request->input('password');
        if (empty($password) || empty($id)) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        $user = User::find($id);
        if ($user) {
            $user->password = \Hash::make($password);
            $user->save();
        }

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

    /**
     * @api {post} /create-staff Tạo nhân viên
     * @apiName create-staff
     * @apiGroup Account
     * @apiParam {String} name Tên
     * @apiParam {String} phone SĐT
     * @apiParam {String} email Email
     * @apiParam {String} password
     * @apiDescription Api Tạo nhân viên
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function storeStaff(Request $request)
    {
        if ($this->user->type != User::OWNER) {
            return response([
                'status' => 0,
                'message' => 'Bạn không phải chủ trọ'
            ]);
        }
        $password = $request->input('password');
        $data = $request->except('password');
        $data['password'] = \Hash::make($password);
        $data['type'] = User::STAFF;
        $data['staff_owner_id'] = $this->user->id;
        $staff = User::create($data);

        return response([
            'status' => 1,
            'data' => [
                'id' => $staff->id,
                'name' => $staff->name_text,
                'phone' => $staff->phone,
                'email' => $staff->email
            ]
        ]);
    }

    /**
     * @api {post} /create-staff-type Tạo loại nhân viên
     * @apiName create-staff-type
     * @apiGroup Account
     * @apiParam {String} name Tên
     * @apiParam {String} permissions[] Danh sách quyền. Chú ý để dạng tên, ví dụ view-statistic
     * @apiDescription Api Tạo loại nhân viên
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function storeStaffType(Request $request)
    {
        if ($this->user->type != User::OWNER) {
            return response([
                'status' => 0,
                'message' => 'Bạn không phải chủ trọ'
            ]);
        }
        $name = $request->input('name');
        $permissions = $request->input('permissions');
        if (empty($name) || empty($permissions)) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        StaffType::create([
            'name' => $name,
            'permissions' => $permissions,
            'owner_id' => $this->user->id
        ]);

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

    /**
     * @api {post} /update-staff-type Cập nhật loại nhân viên
     * @apiName update-staff-type
     * @apiGroup Account
     * @apiParam {String} name Tên
     * @apiParam {String} id
     * @apiParam {String} permissions[] Danh sách quyền. Chú ý để dạng tên, ví dụ view-statistic
     * @apiDescription Api Cập nhật loại nhân viên
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function updateStaffType(Request $request)
    {
        if ($this->user->type != User::OWNER) {
            return response([
                'status' => 0,
                'message' => 'Bạn không phải chủ trọ'
            ]);
        }
        $id = $request->input('id');
        $name = $request->input('name');
        $permissions = $request->input('permissions');
        if (empty($name) || empty($permissions)) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        $staffType = StaffType::find($id);

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

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

    /**
     * @api {post} /delete-staff-type Xóa loại nhân viên
     * @apiName delete-staff-type
     * @apiGroup Account
     * @apiParam {String} id
     * @apiDescription Api Xóa loại nhân viên
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function destroyStaffType(Request $request)
    {
        if ($this->user->type != User::OWNER) {
            return response([
                'status' => 0,
                'message' => 'Bạn không phải chủ trọ'
            ]);
        }
        $id = $request->input('id');
        $staffType = StaffType::find($id);

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

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

    /**
     * @api {get} /staff-type Lấy danh sách loại nhân viên
     * @apiName staff-typ
     * @apiGroup Account
     * @apiDescription Api Lấy danh sách loại nhân viên
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getStaffType(Request $request)
    {
        if ($this->user->type != User::OWNER) {
            return response([
                'status' => 0,
                'message' => 'Bạn không phải chủ trọ'
            ]);
        }
        $items = StaffType::query()
            ->where('owner_id', $this->user->id)
            ->get();

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

    /**
     * @api {post} /update-staff Cập nhật nhân viên
     * @apiName update-staff
     * @apiGroup Account
     * @apiParam {String} id
     * @apiParam {String} name Tên
     * @apiParam {String} phone SĐT
     * @apiParam {String} email Email
     * @apiParam {String} password
     * @apiDescription Api Cập nhật nhân viên
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function updateStaff(Request $request)
    {
        $id = $request->input('id');
        $password = $request->input('password');
        $data = $request->except([
            'id',
            'password'
        ]);
        $staff = User::find($id);
        if (!$staff) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if (!empty($password)) {
            $data['password'] = \Hash::make($password);
        }
        $staff->update($data);

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

    /**
     * @api {post} /delete-staff Xóa nhân viên
     * @apiName delete-staff
     * @apiGroup Account
     * @apiParam {String} id
     * @apiDescription Api Xóa nhân viên
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function destroyStaff(Request $request)
    {
        $id = $request->input('id');
        $staff = User::find($id);
        if (!$staff) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if ($this->user->type != User::OWNER) {
            return response([
                'status' => 0,
                'message' => 'Bạn không phải chủ trọ'
            ]);
        }

        if ($staff->staff_owner_id != $this->user->id) {
            return response([
                'status' => 0,
                'message' => 'Bạn không thể xóa nhân viên không thuộc bạn'
            ]);
        }

        $staff->delete();

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

    /**
     * @api {post} /send-notification Gui thong bao
     * @apiName send-notification
     * @apiGroup Account
     * @apiDescription Api Gui thong bao
     * @apiParam {String} hostel_id
     * @apiParam {String} room_id
     * @apiParam {String} renter_ids
     * @apiParam {String} title
     * @apiParam {String} content
     * @apiParam {String} images
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function sendNotification(Request $request)
    {
        $ownerId = $this->user->id;
        if ($this->user->type == User::STAFF) {
            $ownerId = $this->user->staff_owner_id;
        }

        $roomId = $request->input('room_id');
        $hostelId = $request->input('hostel_id');
        $userIds = $request->input('renter_ids');
        $title = $request->input('title');
        $content = $request->input('content');
        $images = $request->file('images');

        if (!is_array($userIds)) {
            return response([
                'status' => 0,
                'message' => 'Du lieu khong hop le'
            ]);
        }
        $imageArrs = [];

        if (is_array($images)) {
            foreach ($images as $image) {
                $imageFile = Functions::uploadImage($image);
                $imageArrs[] = $imageFile;
            }
        }

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

        $ownerNotification = OwnerNotification::create([
            'title' => $title,
            'owner_id' => $ownerId,
            'hostel_id' => $hostelId,
            'room_id' => $roomId,
            'content' => $content,
        ]);

        foreach ($imageArrs as $imageArr) {
            \DB::table('notification_images')
                ->insert([
                    'notification_id' => $ownerNotification->id,
                    'image' => $imageArr
                ]);
        }

        foreach ($userIds as $userId) {
            $notification = Notification::create([
                'to_user' => $userId,
                'title' => $title,
                'user_id' => $ownerId,
                'hostel_id' => $hostelId,
                'room_id' => $roomId,
                'content' => $content,
                'status' => Notification::PUSHED,
                'owner_notification_id' => $ownerNotification->id,
                'is_owner_send' => true
            ]);
            dispatch((new PushNotification($notification->id))->onConnection('redis'));
        }
        $ownerStaffs = User::query()
            ->where(function ($q) use ($ownerId) {
                $q->orWhere('id', $ownerId);
                $q->orWhere('staff_owner_id', $ownerId);
            })
            ->where('id', '<>', $this->user->id)
            ->get();
        if ($ownerStaffs->count()) {
            foreach ($ownerStaffs as $ownerStaff) {
                $notification = Notification::create([
                    'to_user' => $ownerStaff->id,
                    'title' => $title,
                    'user_id' => $ownerId,
                    'hostel_id' => $hostelId,
                    'room_id' => $roomId,
                    'content' => $content,
                    'status' => Notification::PUSHED,
                    'owner_notification_id' => $ownerNotification->id,
                    'is_owner_send' => true
                ]);
                dispatch((new PushNotification($notification->id))->onConnection('redis'));
            }
        }


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

    /**
     * @api {get} /get-notification Lay danh sach thong bao
     * @apiName get-notification
     * @apiGroup Account
     * @apiDescription Api Lay danh sach thong bao
     * @apiParam {String} limit
     * @apiParam {String} offset
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getNotification(Request $request)
    {
        $ownerId = $this->user->id;
        $limit = $request->input('limit', 10);
        $offset = $request->input('offset', 0);
        if ($this->user->type == User::STAFF) {
            $ownerId = $this->user->staff_owner_id;
        }
        $items = OwnerNotification::where('owner_id', $ownerId)
            ->with('room')
            ->with('hostel')
            ->limit($limit)
            ->offset($offset)
            ->orderBy('created_at', 'desc')
            ->get();


        foreach ($items as $item) {
            $imageArr = [];
            $userArr = [];
            $images = \DB::table('notification_images')
                ->where('notification_id', $item->id)->get();
            foreach ($images as $image) {
                $imageArr[] = [
                    'id' => $image->id,
                    'image' => '/files/' . $image->image
                ];
            }
            $userIds = Notification::where('owner_notification_id', $item->id)->pluck('to_user')->toArray();
            $users = User::whereIn('id', $userIds)->get();
            foreach ($users as $user) {
                $userArr[] = [
                    'id' => $user->id,
                    'name' => $user->name_text
                ];
            }
            $item->cnt_user = Notification::where('owner_notification_id', $item->id)->count();
            $item->images = $imageArr;
            $item->users = $userArr;
            if ($item->hostel) {
                $item->hostel_name = $item->hostel->name;
            } else {
                $item->hostel_name = '';
            }

            if ($item->room) {
                $item->room_name = $item->room->name;
            } else {
                $item->room_name = '';
            }

            unset($item->hostel);
            unset($item->room);
        }

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

    /**
     * @api {get} /get-setting Lay cai dat
     * @apiName get-setting
     * @apiGroup Account
     * @apiDescription Api Lay cai dat
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getSetting(Request $request)
    {
        $user = $this->user;
        if ($user->type == User::STAFF) {
            $user = User::find($user->staff_owner_id);
        }

        $moneyUnit = UserMoney::query()
            ->where('user_id', $user->id)
            ->first();

        return response([
            'status' => 1,
            'data' => [
                'allow_renter_make_group' => $user->allow_renter_make_group,
                'allow_renter_view_hostel_group' => $user->allow_renter_view_hostel_group,
                'allow_renter_view_room_group' => $user->allow_renter_view_room_group,
                'money_unit' => !empty($moneyUnit) ? $moneyUnit->money_unit : 1,
                'type_display_money_info' => $user->type_display_money_info
            ]
        ]);
    }

    /**
     * @api {get} /create-setting Luu cai dat
     * @apiName create-setting
     * @apiGroup Account
     * @apiDescription Api Luu cai dat
     * * @apiParam {String} allow_renter_make_group
     * @apiParam {String} allow_renter_view_hostel_group
     * @apiParam {String} allow_renter_view_room_group
     * @apiParam {String} money_unit
     * @apiParam {String} type_display_money_info
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function storeSetting(Request $request)
    {
        $user = $this->user;
        if ($user->type == User::STAFF) {
            $user = User::find($user->staff_owner_id);
        }
        $data = $request->all();
        //set unit money
        if (!empty($request->money_unit)) {
            $checkexits = UserMoney::where('user_id', $user->id)->first();
            if (!empty($checkexits)) {
                $checkexits->update([
                    'money_unit' => $request->money_unit,
                ]);
            } else {
                UserMoney::create([
                    'money_unit' => $request->money_unit,
                    'user_id' => $user->id,
                ]);
            }
        }
        $user->update($data);
        return response([
            'status' => 1,
            'data' => 'success'
        ]);
    }

    /**
     * @api {post} /send-zalo-invoice Gửi zalo hóa đơn
     * @apiName send-zalo-invoice
     * @apiGroup Account
     * @apiDescription Api Gửi zalo hóa đơn
     * * @apiParam {String} phone
     * @apiParam {String} room_id
     * @apiParam {String} invoice_path
     * @apiParam {String} customer_name
     * @apiParam {String} hostel_id
     *  * @apiParam {String} amount
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function sendZalo(Request $request)
    {
        $phone = $request->input('phone');
        $roomId = $request->input('room_id');
        $invoicePath = $request->input('invoice_path');
        $customerName = $request->input('customer_name');
        $hostelId = $request->input('hostel_id');
        $amount = $request->input('amount');
        $room = Room::find($roomId);
        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

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

        $phone = ltrim($phone, '0');
        $phone = '84' . $phone;
        $responseMessage = Functions::sendMessageInvoiceZns([
            'phone' => $phone,
            'room_name' => $roomName,
            'amount' => $amount,
            'invoice_path' => $invoicePath,
            'customer_name' => $customerName,
            'hostel_name' => $hostelName,
            'hostel_id' => $hostel->id,
            'room_id' => $room->id
        ]);
        if (empty($responseMessage)) {

            return response([
                'status' => 0,
                'message' => 'Bạn đã hết số lượt gửi zalo'
            ]);
        }

        if (empty($responseMessage['error'])) {

            return response([
                'status' => 1,
                'message' => 'Đã gửi tin nhắn Zalo tới: ' . $customerName . ', SĐT: ' . $phone
            ]);
        }
        return response([
            'status' => 1,
            'message' => $responseMessage['message']
        ]);
    }


}
