<?php

namespace App\Http\Controllers\Frontend;

use App\Components\Functions;
use App\Http\Requests\UpdateAccountRequest;
use App\Http\Requests\UpdateAccountRequestSocial;
use App\Jobs\CreateDelayNotificationPhone;
use App\Jobs\RemindCreateRoom;
use App\Jobs\SendMailOwnerMessage;
use App\Jobs\SendMailResetPassword;
use App\Jobs\SendMailUser;
use App\Jobs\SendMailWhenNewOwner;
use App\Jobs\SendMessageBot;
use App\Models\Contact;
use App\Models\CouponTransaction;
use App\Models\Newsletter;
use App\Models\Notification;
use App\Models\OwnerMessage;
use App\Models\Package;
use App\Models\PasswordReset;
use App\Models\Renter;
use App\Models\Room;
use App\Models\TypeSpend;
use App\Models\UserPackage;
use App\Notifications\SendEmailActive;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Minishlink\WebPush\Subscription;
use Minishlink\WebPush\WebPush;
use Mpdf\Tag\U;
use Spatie\Permission\Models\Permission;


class AccountController extends Controller
{
    //
    public function changePasswordView(Request $request)
    {
        return view('frontend3.change_password');
    }

    public function loginWithOtp(Request $request)
    {
        $phone = $request->input('phoneNumber');
        $phone = str_replace('+84', '', $phone);
        $user = User::query()
            ->where('phone', 'LIKE', '%' . $phone)
            ->where('country_phone_code', '+84')
            ->where('type', User::OWNER)
            ->latest()
            ->first();

        if ($user) {
            auth('backend')->login($user);

            return response([
                'status' => 1,
                'url' => url('/admin2/dashboard')
            ]);
        }

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

    public function checkPhoneOwner(Request $request)
    {
        $phone = $request->input('phone');
        $check = User::query()
            ->where('type', User::OWNER)
            ->where('phone', $phone)
            ->count();

        if ($check == 0) {
            return response([
                'status' => 0,
                'message' => 'Không tồn tại tài khoản chủ trọ gắn với SĐT: ' . $phone
            ]);
        }

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

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

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

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

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

        if (!empty($data['date'])) {
            $data['date'] = Carbon::createFromFormat('d/m H:i', $data['date'])->toDateTimeString();
        }

        $hostel = $room->hostel;
        $ownerId = $hostel->owner_id;
        $data['hostel_id'] = $hostel->id;
        $data['owner_id'] = $ownerId;
        $item = OwnerMessage::create($data);

        $messageNoti = '';
        if (!empty($messageNoti->note)) {
            $messageNoti = ', nội dung: ' . $messageNoti->note;
        }

        Notification::create([
            'to_user' => $ownerId,
            'hostel_id' => $hostel->id,
            'room_id' => $data['room_id'],
            'title' => 'Thông báo từ itro.vn',
            'content' => 'Bạn có liên hệ mới từ khách hàng. Tên: ' . $item->name . ', SĐT: ' . $item->phone . $messageNoti
        ]);


        $message = view('admin2.user.message_to_owner', compact('item'))->render();

        dispatch(new SendMessageBot($message, $ownerId));
        dispatch(new SendMailOwnerMessage($item->id, $hostel->owner->email));

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

    public function countOwnerMessage(Request $request)
    {
        $ownerId = auth('backend')->user()->id;

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

        $cnt = OwnerMessage::where('owner_id', $ownerId)->where('status', OwnerMessage::NOT_PROCESS)->count();

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

    public function deleteOwnerMessage(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 = auth('backend')->user()->id;

        if (auth('backend')->user()->type == User::STAFF) {
            $ownerId = auth('backend')->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'
        ]);
    }

    public function updateStatusOwnerMessage(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'
        ]);
    }


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

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

        $messages = OwnerMessage::where('owner_id', $ownerId)->orderBy('id', 'desc');

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

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

        $messages = $messages->get();

        return response([
            'status' => 1,
            'data' => view('admin2.user.owner_messages', compact('messages', 'ownerId'))->render()
        ]);

    }

    public function register(Request $request)
    {
        $data = $request->all();
        $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');
        $confirmPass = $request->input('confirm_password');


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

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

        if (empty($lastName)) {
            return response([
                'status' => 2,
                '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' => 2,
                'message' => 'Không được bỏ trống giới tính'
            ]);
        }

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

        if (empty($image)) {

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

            return redirect()->back()->with('error', 'Không được bỏ trống hình ảnh');

        }

        if ($password != $confirmPass) {
            if ($request->ajax()) {
                return response([
                    'status' => 0,
                    'message' => 'Mật khẩu và mật khẩu nhập lại phải giống nhau'
                ]);
            }

            return redirect()->back()->with('error', 'Mật khẩu và mật khẩu nhập lại phải giống nhau');
        }

//        $validatedData = $this->validate($request, [
//            'g-recaptcha-response' => 'required|recaptcha',
//        ], [
//            'g-recaptcha-response.required' => 'Không được bỏ trống recaptcha',
//            'g-recaptcha-response.recaptcha' => 'Recaptcha không hợp lệ',
//        ]);


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

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

                return redirect()->back()->with('error', 'Email đã tồn tại');
            }
        }

        $checkPhoneWithType = User::where('phone', $phone)->where('type', $type)->count();
        if ($checkPhoneWithType > 0) {
            if ($request->ajax()) {
                return response([
                    'status' => 2,
                    '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ợ'
                ]);
            }

            return redirect()->back()->with('error', 'SĐT đã tồn tại. Bạn vui lòng liên lạc với số 0868.987.355 để được hỗ trợ');
        }

        $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 web',
                'message' => 'Trùng số điện thoại ' . $phone . ' khi đăng ký trên web 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' => 2,
                        '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' => 2,
                    '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;
            }
        }

        try {
            \DB::beginTransaction();

            $tokenActive = uniqid() . Functions::quickRandom();
            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,
                                'token_active' => uniqid() . Functions::quickRandom()
                            ]);
                        } else {
                            return response([
                                'status' => 2,
                                '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,
                        'token_active' => $tokenActive,
                    ]);
                }
            } else {
                $userOwnerId = null;
                if ($type == User::STAFF) {
                    if (auth('backend')->check()) {
                        $userOwnerId = auth('backend')->user()->id;

                        $userPackage = UserPackage::where('user_id', $userOwnerId)->first();
                        if ($userPackage) {
                            $numberStaffs = $userPackage->number_staffs;
                            $useStaffs = User::where('staff_owner_id', auth('backend')->user()->id)->count();
                            $remainStaffs = $numberStaffs - $useStaffs;
                            if ($remainStaffs == 0) {
                                return response([
                                    'status' => 2,
                                    'message' => 'Bạn không thể thêm nhân viên. Vui lòng nâng cấp gói để tăng giới hạn'
                                ]);
                            }
                        }
                    }
                }

                $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,
                    'token_active' => $tokenActive,
                    'staff_owner_id' => $userOwnerId
                ]);

                //

                if ($user->type == User::RENTER) {
                    if (isset($data['room_id'])) {
                        Renter::create([
                            'image' => $image,
                            'name' => $user->name,
                            'room_id' => $data['room_id'],
                            'address' => isset($data['address']) ? $data['address'] : '',
                            'province_id' => isset($data['province_id']) ? $data['province_id'] : '',
                            'district_id' => isset($data['district_id']) ? $data['district_id'] : '',
                            'ward_id' => isset($data['ward_id']) ? $data['ward_id'] : '',
                            'phone' => $data['phone'],
                            'status' => Renter::JUST_REGISTER,
                            'user_id' => $user->id,
                            'is_self_register' => true,
                            'email' => isset($data['email']) ? $data['email'] : null,
//                    'residence_status' => $data['residence_status'],
//                    ''
                        ]);
                    }
                }

                \Notification::send($user, new SendEmailActive($tokenActive));

                //  $user->notify(new SendEmailActive($tokenActive));
            }

            Notification::create([
                'to_user' => $user->id,
                'title' => 'Thông báo từ itro.vn',
                'user_id' => $user->id,
                'content' => 'Chúc mừng bạn đã đăng ký thành công làm ' . $user->type_text . ' trên hệ thống itro.vn. Vui lòng truy cập https://itro.vn/blog để tìm hiểu cách sử dụng phần mềm'
            ]);

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

            //Thêm gói


            if ($user->type == User::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->addDays(10)->toDateString(),
                ]);

                $checkAgency = CouponTransaction::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);

            if ($user->type == User::OWNER) {
                $remindJob = (new RemindCreateRoom($user->id))->delay(Carbon::now()->addDay(3));

                dispatch($remindJob);
            }

            if ($user->type == User::OWNER) {
                $this->dispatch(new SendMailWhenNewOwner($user));
            }


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

            dd($ex->getTraceAsString());

            if ($request->ajax()) {

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

            return redirect()->back()->with('error', 'Có lỗi xảy ra vui lòng thử lại sau');

//			dd($ex->getMessage() . '|' . $ex->getLine());
//
//			return response([
//				'status' => 0,
//				'message' => 'Có lỗi xảy ra vui lòng thử lại sau'
//			]);
        }

        auth('backend')->login($user);

        if ($user->type == User::OWNER) {

            if ($request->ajax()) {
                return response([
                    'status' => 1,
                    'message' => 'Thành công',
                    'url' => url('admin2/dashboard')
                ]);
            }

            return redirect()->to(url('admin2/dashboard'));
        }

        if ($request->ajax()) {
            return response([
                'status' => 1,
                'message' => 'Thành công',
                'url' => ''
            ]);
        }

        return redirect()->to(url('/'))->with('success', 'Đăng ký thành công. Vui lòng kiểm tra email kích hoạt tài khoản.');

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

    public function registerQlnt(Request $request)
    {
        $data = $request->all();
        $email = $request->input('email');
        $phone = $request->input('phone');
        $password = $request->input('password');
        $name = $request->input('name');
        $confirmPass = $request->input('confirm_password');
        $isAcceptInputNews = $request->input('is_accept_news');
        $tokenActive = $request->input('token_active');
        $type = User::OWNER;

        $cacheName = 'process-register-' . $phone . '-' . $type;
        if (cache()->has($cacheName)) {
            return response([
                'status' => 0,
                'message' => 'Hệ thống đang tiến hành xử lý đăng ký tài khoản ' . $phone
            ]);
        }

        cache()->forever($cacheName, $phone);

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

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

        $isAcceptNews = false;

        if ($isAcceptInputNews == 'on') {
            $isAcceptNews = true;
        }

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

        if ($password != $confirmPass) {
            if ($request->ajax()) {
                cache()->forget($cacheName);
                return response([
                    'status' => 0,
                    'message' => 'Mật khẩu và mật khẩu nhập lại phải giống nhau'
                ]);
            }
        }


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

            if ($check->count() > 0) {
                cache()->forget($cacheName);
                if ($request->ajax()) {

                    return response([
                        'status' => 0,
                        'message' => 'Email đã tồn tại'
                    ]);
                }

                return redirect()->back()->with('error', 'Email đã tồn tại');
            }
        }

        if (!empty($tokenActive)) {
            $checkPhoneWithType = User::query()->where('phone', $phone)->where(function ($q) use ($tokenActive) {
                $q->orWhere('token_active', '<>', $tokenActive);
                $q->orWhereNull('token_active');

            })->where('type', $type)->count();
        } else {
            $checkPhoneWithType = User::query()->where('phone', $phone)->where('type', $type)->count();
        }
        if ($checkPhoneWithType > 0) {
            cache()->forget($cacheName);
            if ($request->ajax()) {
                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ợ'
                ]);
            }

            return redirect()->back()->with('error', 'SĐT đã tồn tại. Bạn vui lòng liên lạc với số 0868.987.355 để được hỗ trợ');
        }

        try {
            \DB::beginTransaction();

            if (!empty($tokenActive)) {
                $user = User::query()->where('token_active', $tokenActive)->first();
                $user->update([
                    'name' => $name,
                    'email' => $email,
                    'phone' => $phone,
                    'password' => \Hash::make($password),
                    'type' => $type,
                    'token_active' => null,
                    'is_accept_news' => $isAcceptNews
                ]);

            } else {
                $tokenActive = uniqid() . Functions::quickRandom();

                $user = User::create([
                    'name' => $name,
                    'email' => $email,
                    'phone' => $phone,
                    'password' => \Hash::make($password),
                    'type' => $type,
                    'token_active' => $tokenActive,
                    'is_accept_news' => $isAcceptNews
                ]);
            }
            //
            \Notification::send($user, new SendEmailActive($tokenActive));

            Notification::create([
                'to_user' => $user->id,
                'title' => 'Thông báo từ itro.vn',
                'user_id' => $user->id,
                'content' => 'Chúc mừng bạn đã đăng ký thành công làm ' . $user->type_text . ' trên hệ thống itro.vn. Vui lòng truy cập https://itro.vn/blog để tìm hiểu cách sử dụng phần mềm'
            ]);

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

            //Thêm gói


            if ($user->type == User::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->addDays(10)->toDateString(),
                ]);

                $checkAgency = CouponTransaction::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);

            if ($user->type == User::OWNER) {
                $remindJob = (new RemindCreateRoom($user->id))->delay(Carbon::now()->addDay(3));

                dispatch($remindJob);
            }

            if ($user->type == User::OWNER) {
                $this->dispatch(new SendMailWhenNewOwner($user));
            }


            \DB::commit();
        } catch (\Exception $ex) {
            \DB::rollBack();
            cache()->forget($cacheName);
            dd($ex->getTraceAsString());


            if ($request->ajax()) {

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

            return redirect()->back()->with('error', 'Có lỗi xảy ra vui lòng thử lại sau');

        }

        auth('backend')->login($user);

        if ($user->type == User::OWNER) {
            cache()->forget($cacheName);
            if ($request->ajax()) {
                return response([
                    'status' => 1,
                    'message' => 'Thành công',
                    'url' => url('admin2/dashboard')
                ]);
            }

            return redirect()->to(url('admin2/dashboard'));
        }

        if ($request->ajax()) {
            cache()->forget($cacheName);
            return response([
                'status' => 1,
                'message' => 'Thành công',
                'url' => url('admin2/dashboard')
            ]);
        }
        cache()->forget($cacheName);
        return redirect()->to(url('/'))->with('success', 'Đăng ký thành công. Vui lòng kiểm tra email kích hoạt tài khoản.');

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

    public function verifyPhone(Request $request)
    {
        auth('backend')->user()->status_phone = true;
        auth('backend')->user()->save();

        return response([
            'status' => 1,
            'message' => 'Đã xác nhận số di động'
        ]);
    }

    public function dropConnect(Request $request)
    {
        $type = $request->input('type');
        if ($type == 'google') {
            auth('backend')->user()->google_id = null;
        } else if ($type == 'facebook') {
            auth('backend')->user()->facebook_id = null;
        }

        auth('backend')->user()->save();

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

    public function logout(Request $request)
    {
        cache()->forget('images-dt-' . session()->getId());
        session()->forget('step');
        session()->forget('data');
        if (auth('backend')->check()) {
            auth('backend')->user()->webpush_token = null;
            auth('backend')->user()->save();
            auth('backend')->logout();
        }

        return redirect()->to(url('/'));
    }

    public function getNotificationView(Request $request)
    {
        if (!auth('backend')->check()) {
            return redirect()->to(url('/'))->with('error', 'Bạn phải đăng nhập');
        }

        $cnt = Notification::publish()->where('to_user', auth('backend')->user()->id)->count();

        return view('frontend3.notifications', compact('cnt'));

    }

    public function getNotification(Request $request)
    {
        if (!auth('backend')->check()) {
            if ($request->ajax()) {
                return response([
                    'status' => 0,
                    'message' => 'Bạn phải đăng nhập'
                ]);
            }

            return redirect()->back()->with('error', 'Bạn phải đăng nhập');
        }

        $page = $request->input('page', 1);
        $limit = 10;
        $offset = ($page - 1) * $limit;

        $items = Notification::publish()->where('to_user', auth('backend')->user()->id)
            ->limit($limit)
            ->offset($offset)->orderBy('id', 'desc')->get();


        return response([
            'html' => view('frontend3.notification_ajax', compact('items'))->render()
        ]);

    }

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


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

        if (empty($account)) {
            $account = User::query()->where('email', trim($phone))->where('type', $typeUser)->first();
        }

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

            return redirect()->back()->with('error', 'Tài khoản không tồn tại');
        }

//        if (!empty($account)) {
//            if ($account->status == User::IN_ACTIVE) {
//                return redirect()->back()->with('error', 'Tài khoản chưa được kích hoạt');
//            }
//        } else {
//            return redirect()->back()->with('error', 'Tài khoản không tồn tại');
//        }

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

        $userPassword = $account->password;

        if (!\Hash::check($password, $userPassword)) {
            if ($request->ajax()) {
                return response([
                    'status' => 0,
                    'message' => 'Tên đăng nhập hoặc mật khẩu không chính xác'
                ]);
            }

            return redirect()->back()->with('error', 'Tên đăng nhập hoặc mật khẩu không chính xác');
        }

        $isRemember = false;

        if ($remember == 1) {
            $isRemember = true;
        }

        auth('backend')->login($account, $isRemember);

//		if ($check->first()->type == User::OWNER) {
//			if ($check->first()->is_owner_first == true) {
//				return redirect()->to(url('admin/dashboard/step1'));
//			}
//
//			return redirect()->to(url('admin/dashboard'));
//		}

        if ($account->type == User::OWNER) {
            if ($request->ajax()) {
                return response([
                    'status' => 1,
                    'message' => 'Đăng nhập thành công',
                    'url' => url('admin2/dashboard')
                ]);
            }

            return redirect()->to(url('admin2/dashboard'))->with('success', 'Đăng nhập thành công');
        }


        if ($account->type == User::ADMIN) {
            if ($request->ajax()) {
                return response([
                    'status' => 1,
                    'message' => 'Đăng nhập thành công',
                    'url' => url('admin')
                ]);
            }

            return redirect()->to(url('admin'))->with('success', 'Đăng nhập thành công');
        }
        if ($request->ajax()) {
            return response([
                'status' => 1,
                'message' => 'Đăng nhập thành công',
                'url' => url('/')
            ]);
        }

        return redirect()->to(url('/'))->with('success', 'Đăng nhập thành công');
    }

    public function loginQlnt(Request $request)
    {
        $password = $request->input('password');
        $remember = $request->input('remember');
        $phone = $request->input('phone');
        $typeUser = [User::OWNER, User::STAFF];


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

        if (empty($account)) {
            $account = User::query()->where('email', trim($phone))->whereIn('type', $typeUser)->first();
        }

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

            return redirect()->back()->with('error', 'Tài khoản không tồn tại');
        }

//        if (!empty($account)) {
//            if ($account->status == User::IN_ACTIVE) {
//                return redirect()->back()->with('error', 'Tài khoản chưa được kích hoạt');
//            }
//        } else {
//            return redirect()->back()->with('error', 'Tài khoản không tồn tại');
//        }

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

        $userPassword = $account->password;

        if (!\Hash::check($password, $userPassword)) {
            if ($request->ajax()) {
                return response([
                    'status' => 0,
                    'message' => 'Tên đăng nhập hoặc mật khẩu không chính xác'
                ]);
            }

            return redirect()->back()->with('error', 'Tên đăng nhập hoặc mật khẩu không chính xác');
        }

        $isRemember = false;

        if ($remember == 1) {
            $isRemember = true;
        }

        auth('backend')->login($account, $isRemember);

//		if ($check->first()->type == User::OWNER) {
//			if ($check->first()->is_owner_first == true) {
//				return redirect()->to(url('admin/dashboard/step1'));
//			}
//
//			return redirect()->to(url('admin/dashboard'));
//		}

        if ($account->type == User::OWNER || $account->type == User::STAFF) {
            if ($request->ajax()) {
                return response([
                    'status' => 1,
                    'message' => 'Đăng nhập thành công',
                    'url' => url('admin2/dashboard')
                ]);
            }

            return redirect()->to(url('admin2/dashboard'))->with('success', 'Đăng nhập thành công');
        }


        if ($account->type == User::ADMIN) {
            if ($request->ajax()) {
                return response([
                    'status' => 1,
                    'message' => 'Đăng nhập thành công',
                    'url' => url('admin')
                ]);
            }

            return redirect()->to(url('admin'))->with('success', 'Đăng nhập thành công');
        }
        if ($request->ajax()) {
            return response([
                'status' => 1,
                'message' => 'Đăng nhập thành công',
                'url' => url('/')
            ]);
        }

        return redirect()->to(url('/'))->with('success', 'Đăng nhập thành công');
    }

    public function profile()
    {
        if (!auth('backend')->check()) {
            return redirect()->to(url('/'))->with('error', 'Bạn chưa đăng nhập');
        }

        $account = auth('backend')->user();

        return view('frontend3.profile', compact('account'));
    }

    public function subscribeEmail(Request $request)
    {
        $email = $request->input('email');
        if (empty($email)) {
            return response([
                'status' => 0,
                'message' => 'Không được để trống email'
            ]);
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return response([
                'status' => 0,
                'message' => 'Định dạng email chưa đúng'
            ]);
        }

        \Newsletter::subscribe($email);

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

    public function update(Request $request)
    {
        $type = $request->input('type');
        if ($type == 'fb') {

            if ($request->getHost() == 'quanlynhatro.com') {
                return redirect()->to('/admin');
            }

            if (!session()->has('fb_id')) {
                return redirect()->to(url('/'))->with('error', 'Dữ liệu không hợp lệ');
            }

            $facebookId = session()->get('fb_id');

            $user = User::query()->where('facebook_id', $facebookId)->first();

            if ($user) {
                return view('frontend3.update', compact('user'));
            }

        } else if ($type == 'gg') {
            if (!session()->has('gg_id')) {
                return redirect()->to(url('/'))->with('error', 'Dữ liệu không hợp lệ');
            }

            $googleId = session()->get('gg_id');

            $user = User::query()->where('google_id', $googleId)->first();

            if ($user) {
                return view('frontend3.update', compact('user'));
            }
        } else {
            if (!auth('backend')->check()) {
                return redirect()->to(url('/'))->with('error', 'Dữ liệu không hợp lệ');
            }

            $user = auth('backend')->user();

            return view('frontend3.update', compact('user'));
        }
    }

    public function updatePassword(Request $request)
    {
        $oldPassword = $request->input('old_password');
        $newPassword = $request->input('new_password');
        $confirmPassword = $request->input('confirm_password');

        $user = auth('backend')->user();

        if (!\Hash::check($oldPassword, $user->password)) {
            return redirect()->back()->with('error', 'Mật khẩu hiện tại không đúng');
        }

        if ($confirmPassword != $newPassword) {
            return redirect()->back()->with('error', 'Mật khẩu xác nhận không khớp');
        }

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

        return redirect()->back()->with('success', 'Thành công');
    }

    public function edit(UpdateAccountRequest $request)
    {
        $data = $request->all();
        $phone = $request->input('phone');
        $user = null;

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

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

            $data['birthday'] = $birthday;
        }
        \DB::beginTransaction();

        try {


            if (auth('backend')->check()) {
                $check = User::query()->where('phone', $phone)
                    ->where('type', auth('backend')->user()->type)
                    ->where('id', '<>', auth('backend')->user()->id)
                    ->count();
                if ($check) {
                    return redirect()->back()->with('error', 'SĐT đã được sử dụng');
                }

                auth('backend')->user()->update($data);
                $user = User::query()->find(auth('backend')->user()->id);
            } else {

                if (session()->has('fb_id')) {
                    $facebookId = session()->get('fb_id');
                    $user = User::query()->where('facebook_id', $facebookId)->first();
                    if ($user) {

                        $check = User::where('phone', $phone)
                            ->where('type', $user->type)
                            ->where('id', '<>', $user->id)
                            ->count();
                        if ($check) {
                            return redirect()->back()->with('error', 'SĐT đã được sử dụng');
                        }

                        if (empty($user->type)) {
                            if (empty($data['type'])) {
                                return redirect()->back()->with('error', 'Không được bỏ trống loại người dùng');
                            }
                        }

                        $user->update($data);
                    }
                }

                if (session()->has('gg_id')) {
                    $googleId = session()->get('gg_id');
                    $user = User::query()->where('google_id', $googleId)->first();
                    if ($user) {
                        $check = User::where('phone', $phone)
                            ->where('type', $user->type)
                            ->where('id', '<>', $user->id)
                            ->count();
                        if ($check) {
                            return redirect()->back()->with('error', 'SĐT đã được sử dụng');
                        }

                        if (empty($user->type)) {
                            if (empty($data['type'])) {
                                return redirect()->back()->with('error', 'Không được bỏ trống loại người dùng');
                            }
                        }
                        $user->update($data);
                    }
                }

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

            }

            \DB::commit();
            if (!empty($user)) {

                Functions::syncCrm($user);
            }
        } catch (\Exception $ex) {
            \DB::rollBack();
            \Log::info($ex->getMessage());
            \Log::info($ex->getTraceAsString());

            return redirect()->back()->with('error', 'Có lỗi xảy ra vui lòng thử lại sau');
        }

        return redirect()->back()->with('success', 'Cập nhật thành công');

    }

    public function editSocial(UpdateAccountRequest $request)
    {
        $data = $request->all();

        if (Functions::checkDisplayType()) {
            if (empty($data['type'])) {
                return redirect()->back()->with('error', 'Không được bỏ trống loại người dùng');
            }
        }

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

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

            $data['birthday'] = $birthday;
        }
        \DB::beginTransaction();

        try {
            if (auth('backend')->check()) {
                auth('backend')->user()->update($data);
            } else {

                if (session()->has('fb_id')) {
                    $facebookId = session()->get('fb_id');
                    $user = User::where('facebook_id', $facebookId)->first();
                    if ($user) {
                        $user->update($data);
                    }
                }

                if (session()->has('gg_id')) {
                    $googleId = session()->get('gg_id');
                    $user = User::where('google_id', $googleId)->first();
                    if ($user) {
                        $user->update($data);
                    }
                }

            }

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

            return redirect()->back()->with('error', 'Có lỗi xảy ra vui lòng thử lại sau');
        }

        return redirect()->back()->with('success', 'Cập nhật thành công');

    }

    public function seenAllNotification(Request $request)
    {
        if (!auth('backend')->check()) {
            return response([
                'status' => 0
            ]);
        }

        $userId = auth('backend')->user()->id;
        Notification::where('to_user', $userId)->where('is_read', false)->update([
            'is_read' => true
        ]);

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

    public function subscribeWebPush(Request $request)
    {
        $key = $request->input('key');
        $token = $request->input('token');
        $endpoint = $request->input('endpoint');

        $webpushToken = [
            'key' => $key,
            'token' => $token,
            'endpoint' => $endpoint
        ];

        if (auth('backend')->check()) {
            if (empty(auth('backend')->user()->webpush_token)) {
                auth('backend')->user()->webpush_token = json_encode($webpushToken);
                auth('backend')->user()->save();


//                $firstNotification = ['title' => 'Thông báo từ itro.vn',
//                    'body' => 'Cám ơn bạn đã nhận thông báo từ itro.vn',
//                    'icon' => 'https://itro.vn/frontend3/assets/img/logo.png'];
//                $notification =
//                    [
//                        'subscription' => Subscription::create([
//                            'endpoint' => $endpoint,
//                            'publicKey' => $key, // base 64 encoded, should be 88 chars
//                            'authToken' => $token, // base 64 encoded, should be 24 chars
//                            'contentEncoding' => 'aesgcm'
//                        ]),
//                        'payload' => json_encode($firstNotification),
//                    ];
//
//                $auth = array(
//                    'VAPID' => array(
//                        'subject' => 'https://itro.vn',
//                        'publicKey' => config('constants.VAPID_PUBLIC_KEY'),
//                        'privateKey' => config('constants.VAPID_SECRET_KEY'), // in the real world, this would be in a secret file
//                    ),
//                );
//
//                $webPush = new WebPush($auth);
//
//
//                $webPush->sendNotification(
//                    $notification['subscription'],
//                    $notification['payload'], // optional (defaults null)
//                    true
//                );

            }
        }


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

    }

    public function getInfoFb(Request $request)
    {
        $uiid = $request->input('uiid');

        $item = \DB::connection('data2')->table('vnphone')->where('uid', $uiid)->first();
        if ($item) {
            return response([
                'status' => 1,
                'data' => $item->phone
            ]);
        }

        return response([
            'status' => 1,
            'data' => 'Không thấy'
        ]);

    }

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

        $phone = str_replace('+84', '', $phone);
        $phone = '0' . $phone;
        $user = User::query()
            ->where('phone', $phone)
            ->where('country_phone_code', '+84')
            ->whereIn('type', [User::OWNER, User::STAFF])
            ->first();

        if (!$user) {
            return response([
                'status' => 0,
                'message' => 'Không tìm thấy SĐT trên hệ thống'
            ]);
        }

        $token = app('auth.password.broker')->createToken($user);
        PasswordReset::create([
            'user_id' => $user->id,
            'token' => $token,
            'expired_at' => Carbon::now()->addMinute(60)
        ]);

        return response([
            'status' => 1,
            'url' => url('/user/reset-password', [
                'token' => $token
            ])
        ]);
    }

    public function resetPasswordPhoneFirebase($token, Request $request)
    {
        $token = PasswordReset::query()
            ->where('token', $token)
            ->where('expired_at', '>=', Carbon::now())
            ->first();

        if (!$token) {
            return redirect()->to(url('/'))->with([
                'error' => 'Đường link hết hạn truy cập'
            ]);
        }

        return view('quanlynhatro.reset_password', compact('token'));
    }

    public function resetPasswordToken(Request $request)
    {
        $tokenConfirm = $request->input('confirm_token');
        $password = $request->input('confirm_password');

        $token = PasswordReset::query()
            ->where('token', $tokenConfirm)
            ->where('expired_at', '>=', Carbon::now())
            ->first();
        //	dd($token);

        if (!$token) {
            return response([
                'status' => 0,
                'message' => 'Token đã hết hạn'
            ]);
        }

        $user = User::find($token->user_id);

        if (!$user) {
            return response([
                'status' => 0,
                'message' => 'User không tồn tại'
            ]);
        }
        if ($user) {
            $user->password = \Hash::make($password);
            $user->save();

            PasswordReset::query()->where('token', $tokenConfirm)->delete();
        }

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

    }

    public function resetPasswordEmail(Request $request)
    {
        $email = $request->input('email');
        $user = User::query()
            ->where('email', $email)
            ->whereIn('type', [User::OWNER, User::STAFF])
            ->latest()
            ->first();

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

        $token = app('auth.password.broker')->createToken($user);
        PasswordReset::create([
            'user_id' => $user->id,
            'token' => $token,
            'expired_at' => Carbon::now()->addMinute(60)
        ]);

        $url = url('/user/reset-password', [
            'token' => $token
        ]);

        $this->dispatch(new SendMailResetPassword($url, $email, $user));

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

    }
}
