@extends('quanlynhatro.layout')

@section('title')
    <title>quanlynhatro.com - Đăng nhập</title>
@endsection

@section('meta')
    <meta property="og:url" content="{{ url()->current() }}"/>
    <meta property="og:type" content="website"/>
    <meta property="og:title" content="Quản lý nhà trọ - Đăng nhập"/>
    <meta property="og:description"
          content="iTro.vn - Tìm là thấy, ở là thích"/>
    <meta property="og:image" content="https://quanlynhatro.com/frontend3/assets/img/logo.png"/>
@endsection
@section('content')
    <script src="https://www.gstatic.com/firebasejs/7.12.0/firebase-app.js"></script>

    <!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
    <script src="https://www.gstatic.com/firebasejs/7.12.0/firebase-analytics.js"></script>

    <!-- Add Firebase products that you want to use -->
    <script src="https://www.gstatic.com/firebasejs/7.12.0/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.12.0/firebase-firestore.js"></script>
    <script>
        // Your web app's Firebase configuration
        var firebaseConfig = {
            apiKey: "AIzaSyDzyVgQ6Z6rqTZ6WnKjaR2uuv_hizsySjk",
            authDomain: "itro-b9c1a.firebaseapp.com",
            databaseURL: "https://itro-b9c1a.firebaseio.com",
            projectId: "itro-b9c1a",
            storageBucket: "itro-b9c1a.appspot.com",
            messagingSenderId: "761922008105",
            appId: "1:761922008105:web:dffaa82661365b98d89838"
        };
        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);
    </script>
    <div class="page-si">
        <div class="page-si__wrap">
            <div class="block-si-form shadow-sm">
                <div class="block-si-form__wrap">
                    <div class="block-si-form__header">
                        <div class="si-top-logo">
                            <a href="/"><img src="/quanlynhatro/assets/img/itro-logo-colored.png" alt="" height="32px"></a>
                        </div>
                        <div class="si-top-action">
                            <a href="https://app.resident.vn/register" class="#">Đăng ký</a>
                        </div>
                    </div>
                    <div class="block-si-form__body">
                        <div class="si-main">
                            <div class="si-main__wrap">
                                <div class="si-main__top">
                                    <h2 class="si-main__title">Đăng nhập hệ thống quản lý ITRO</h2>
                                    <div class="si-main__subtitle">Chào mừng bạn đã quay trở lại</div>
                                </div>
                                <div class="si-main__body">
                                    <div class="si-main__form">
                                        <form action="#" id="login-form">
                                            <div class="form-group">
                                                <label class="form-label">Số điện thoại</label>
                                                <input type="text" class="form-control" placeholder="Nhập số điện thoại"
                                                       name="phone"
                                                       id="phone">
                                            </div>
                                            <div class="form-group">
                                                <label class="form-label">Mật khẩu</label>
                                                <input type="password" class="form-control" placeholder="********"
                                                       name="password"
                                                       id="password">
                                            </div>
                                            <button class="btn btn-primary btn-block" type="button" id="btn-login">Đăng
                                                nhập
                                            </button>
                                            <div class="mt-2 text-right">
                                                <a href="/forgot-password" class="link-forgot-pass">Quên mật khẩu?</a>
                                            </div>
                                        </form>
                                    </div>
                                    <!--<div class="si-main__divider text-center"><span>hoặc</span></div>-->
                                    <!--<div class="si-main__social">-->
                                    <!--    <button class="btn btn-social btn-block"-->
                                    <!--       href="#" id="btn-login-otp">-->
                                    <!--        <span class="btn-social__icon"><i class="mdi mdi-phone"></i></span>-->
                                    <!--        Đăng nhập với OTP-->
                                    <!--    </button>-->
                                    <!--    <a class="btn btn-social btn-social--facebook btn-block"-->
                                    <!--       href="{{ url('/connect/facebook') }}">-->
                                    <!--        <span class="btn-social__icon"><i class="mdi mdi-facebook"></i></span>-->
                                    <!--        Đăng nhập với Facebook-->
                                    <!--    </a>-->
                                    <!--    <a class="btn btn-social btn-social--zalo btn-block"-->
                                    <!--       href="{{ url('/connect/zalo') }}">-->
                                    <!--    <span class="btn-social__icon"><img-->
                                    <!--                src="/quanlynhatro/assets/img/icon-zalo.svg" alt=""></span>-->
                                    <!--        Đăng nhập với with Zalo-->
                                    <!--    </a>-->
                                    <!--</div>-->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="block-si-intro">
                <div class="block-si-intro__wrap">
                    <div class="si-intro-header text-center">
                        <h1 class="si-intro-title c-section-title">ITRO tự hào là hệ thống quản lý nhà cho thuê tốt nhất
                            <br> với đầy đủ
                            nền
                            tảng từ Web đến App</h1>
                        <p class="si-intro-subtitle c-section-subtitle">Với ITRO, bạn có thể quản lý và vận hành nhà cho
                            thuê một cách đầy
                            đủ
                            nhất, từ việc theo dõi tình hình thanh toán tiền thuê của khách đến việc quản lý tình hình
                            kinh
                            doanh và theo dõi tất cả thông tin, hình ảnh của khách thuê thật dễ dàng.</p>
                        <div class="si-intro-action">
                            <a href="/blog" class="btn btn-primary btn-md">Xem hướng dẫn sử dụng</a>
                        </div>
                    </div>
                    <div class="si-intro-divider"></div>
                    <div class="si-intro-main">
                        <div class="si-intro-app">
                            <div class="si-intro-app__screen">
                                <img src="/quanlynhatro/mockups/iphone-login-screen.svg" alt="">
                            </div>
                            <div class="si-intro-app__content text-center">
                                <h3 class="si-intro-app__title text-uppercase">Đâu chỉ mình website, <br> chúng tôi có
                                    cả app dành cho
                                    bạn
                                </h3>
                                <p class="si-intro-app__subtitle"></p>
                                <div class="si-intro-app__download">
                                    <a target="_blank"
                                       href="https://itunes.apple.com/us/app/itro-qu%E1%BA%A3n-l%C3%BD-tr%E1%BB%8D-th%C3%B4ng-minh/id1352848785?ls=1&mt=8"><img
                                                src="/quanlynhatro/assets/img/download-app-store.png" alt=""
                                                height="48"></a>
                                    <br>
                                    <a target="_blank"
                                       href="https://play.google.com/store/apps/details?id=com.blue.hoantran.itro_host"><img
                                                src="/quanlynhatro/assets/img/download-google-play.png" alt=""
                                                height="48"></a>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="si-intro-footer text-center">
                        <div class="si-intro-footer__copyright">© 2020 ITRO</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
        function validate() {
            var formStatus = $("#login-form").validate(
                {
                    ignore: ".ignore",
                    errorElement: "span",
                    errorClass: "help-block help-block-error",

                    highlight: function (e) {
                        $(e).closest(".form-group").addClass("has-error")
                    },
                    unhighlight: function (e) {
                        $(e).closest(".form-group").removeClass("has-error")
                    },
                    success: function (e) {
                        e.closest(".form-group").removeClass("has-error")
                    },
                    rules: {
                        password: "required",
                        phone: "required",
                    },
                    messages: {
                        phone: {
                            required: "Vui lòng không bỏ trống số điện thoại",
                        },
                        password: {
                            required: "Vui lòng không bỏ trống mật khẩu"
                        }
                    }
                }
            ).form();
            return formStatus;
        }

        $(document).ready(function () {
            $('#btn-login').click(function () {
                login();
            });
        });

        $('#phone, #password').keypress(function (e) {
            if (e.keyCode == 13) {
                login();
            }
        });

        function login() {
            var formStatus = validate();
            if (formStatus) {
                var phone = $('#phone').val();
                var password = $('#password').val();

                $.ajax({
                    url: '{{ url('process-login-qlnt') }}',
                    type: 'post',
                    data: {
                        phone: phone,
                        password: password,
                    },
                    dataType: 'json',
                    success: function (response) {
                        if (response.status == 0) {
                            swal('Thông báo', response.message, 'info');
                            return;
                        }

                        window.location.href = response.url;
                    }
                });
            }
        }

        window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('btn-login-otp', {
            'size': 'invisible',
            'callback': function (response) {
                // reCAPTCHA solved, allow signInWithPhoneNumber.
             //   submitPhoneNumberAuth();
            }
        });

        $('#btn-login-otp').click(function () {

            swal({
                title: "Thông báo",
                text: "Vui lòng nhập SĐT của bạn",
                type: "input",
                showCancelButton: true,
                cancelButtonText: 'Hủy',
                closeOnConfirm: false,
                inputPlaceholder: "SĐT đăng nhập Itro"
            }, function (inputValue) {
                if (inputValue === false) return false;
                if (inputValue === "") {
                    swal.showInputError("Bạn chưa nhập mã xác nhận");
                    return false
                }
                var phone = inputValue;

                $.ajax({
                    url: '{{ url('check-phone-owner') }}',
                    type: 'post',
                    data: {
                        phone: phone
                    },
                    dataType: 'json',
                    success: function (response) {
                        if (response.status == 1) {
                            if (phone.indexOf('@') !== -1) {
                                submitEmailAuth(inputValue);
                            } else {
                                submitPhoneNumberAuth(inputValue);
                            }
                        } else {
                            swal('Thông báo', response.message, 'warning');
                            return;
                        }
                    }
                });


            });


        });

        function submitEmailAuth(email) {
            $.ajax({
                url: '{{ url('auth/send-otp-email') }}',
                type: 'post',
                data: {
                    email: email
                },
                dataType: 'json',
                success: function (response) {
                    if (response.status == 1) {
                        swal('Thông báo', 'Hệ thống đã gửi email đặt lại mật khẩu vào email của bạn. Bạn vui lòng kiểm tra email (bao gồm cả hòm thư spam) và làm theo hướng dẫn', 'success');
                    } else {
                        swal('Thông báo', response.message, 'warning');
                    }
                }
            });

        }


        function submitPhoneNumberAuth(phoneNumber) {
            if(typeof phoneNumber == 'undefined')
            {
                return;
            }
            phoneNumber = '+84' + phoneNumber;
            if (phoneNumber.indexOf('@') !== -1) {
                //swal('Thông báo', 'Dữ liệu không hợp lệ', 'info');
                return;
            }
            var appVerifier = window.recaptchaVerifier;
            firebase
                .auth()
                .signInWithPhoneNumber(phoneNumber, appVerifier)
                .then(function (confirmationResult) {
                    console.log('here');
                    window.confirmationResult = confirmationResult;
                    // SMS sent. Prompt user to type the code from the message, then sign the
                    // user in with confirmationResult.confirm(code).
                    swal({
                        title: "Thông báo",
                        text: "Vui lòng nhập mã được gửi đến SĐT của bạn",
                        type: "input",
                        showCancelButton: true,
                        closeOnConfirm: false,
                        inputPlaceholder: "Mã xác nhận"
                    }, function (inputValue) {
                        if (inputValue === false) return false;
                        if (inputValue === "") {
                            swal.showInputError("Bạn chưa nhập mã xác nhận");
                            return false
                        }
                        submitPhoneNumberAuthCode(inputValue);
                    });
                }).catch(function (error) {
                    console.log(error);
                swal('Thông báo', 'Tin nhắn không thể gửi. Bạn vui lòng thử lại sau', 'info')
                // Error; SMS not sent
                // ...
            });
        }

        function submitPhoneNumberAuthCode(code) {
            confirmationResult
                .confirm(code)
                .then(function (result) {
                    var user = result.user;
                    var phoneNumber = user.phoneNumber;
                    $.ajax({
                        url: '{{ url('login-with-otp') }}',
                        type: 'post',
                        data: {
                            phoneNumber: phoneNumber
                        },
                        dataType: 'json',
                        success: function (response) {
                            if (response.status == 1) {
                                window.location.href = response.url;
                            } else {
                                swal('Thông báo', response.message, 'warning');
                            }
                        }
                    });
                })
                .catch(function (error) {
                    console.log(error);
                    swal('Thông báo', 'Lỗi xác nhận, bạn vui lòng thử lại sau', 'info')
                });
        }
    </script>
@endpush
