@extends('layouts.app')

@section('content')

    <!-- Content -->
    <div class="position-relative">
        <div class="authentication-wrapper authentication-basic container-p-y p-4 p-sm-0">
            <div class="authentication-inner py-6">

                <!-- Login -->
                <div class="card p-md-7 p-1">
                    <!-- Logo -->
                    <div class="app-brand justify-content-center mt-5">
                        <a href="#" class="app-brand-link gap-2">
                            <span class="app-brand-logo demo">
                                <span class="app-brand-logo demo">
                                    <span class="app-brand-text demo text-heading fw-semibold">
                                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img style="margin-left: 5%" src="{{ asset('assets/img/logo/cafeg-logo-1.png') }}"  width="50%" height="50%" alt="{{ asset('img/logo/cafeg-logo.png') }}"> </img>
                                    </span>
                                </span>

                        </a>
                    </div>
                    <!-- /Logo -->
                    @php
                        if (empty($data)) {
                            $data = Auth::guard('member')->user();
                            unset($data['password']);
                        }
                    @endphp
                    <div class="card-body mt-1">
                        <h4 class="mb-1">卡菲姬個人資料</h4>
                        <p class="mb-5">Hi, <span class="text-ifno"> {{ $data->name }} 用戶 </span> 歡迎你 ! ,請花幾分鐘完善資料</p>
                        <div class="card" id="editUser">
                            <div class="content">
                                <div class="body p-0">
                                    <div class="text-center mb-6">
                                        <h4 class="mb-2">編輯您的資訊</h4>
                                        <p class="mb-6">更新用戶詳細資訊</p>
                                    </div>
                                    <form id="editUserForm" class="row g-5">
                                        <!-- 暱稱 -->
                                        <div class="col-12">
                                            <div class="form-floating form-floating-outline">
                                                <input readonly type="text" id="modalEditUserFirstName"
                                                    name="modalEditUserFirstName" class="form-control"
                                                    value="{{ $data->name }}" placeholder="暱稱" aria-label="暱稱" />
                                                <label for="modalEditUserFirstName">暱稱 </label>
                                            </div>
                                        </div>

                                        <!-- Email -->
                                        <div class="col-12">
                                            <div class="form-floating form-floating-outline">
                                                <input type="email" id="formValidationEmail" class="form-control"
                                                    placeholder="john.doe@example.com" aria-label="Email" required
                                                    value="{{ $data->email ?? '' }}" @if(isset($data->email)) readonly @endif />
                                                <label for="formValidationEmail">Email</label>
                                                <div class="invalid-feedback">請輸入有效的 Email</div>
                                            </div>
                                        </div>

                                        <!-- 密碼 -->
                                        <div class="col-12">
                                            <div class="form-password-toggle">
                                                <div class="input-group input-group-merge">
                                                    <div class="form-floating form-floating-outline">
                                                        <input type="password" id="basic-default-password"
                                                            class="form-control" placeholder="密碼" aria-label="密碼"
                                                            value="" />
                                                        <label for="basic-default-password">密碼</label>
                                                        <div class="invalid-feedback">請輸入有效密碼</div>

                                                    </div>
                                                    <span class="input-group-text cursor-pointer"
                                                        id="basic-default-password3">
                                                        <i class="ri-eye-off-line"></i>
                                                    </span>
                                                </div>
                                            </div>

                                        </div>

                                        <!-- 確認密碼 -->
                                        <div class="col-12">
                                            <div class="form-password-toggle">
                                                <div class="input-group input-group-merge">
                                                    <div class="form-floating form-floating-outline">
                                                        <input type="password" id="formValidationConfirmPass"
                                                            name="formValidationConfirmPass" class="form-control"
                                                            placeholder="確認密碼" aria-label="確認密碼" value="" />
                                                        <label for="formValidationConfirmPass">確認密碼</label>
                                                        <div class="invalid-feedback">密碼與確認密碼不相符</div>

                                                    </div>
                                                    <span class="input-group-text cursor-pointer"
                                                        id="multicol-confirm-password2">
                                                        <i class="ri-eye-off-line"></i>
                                                    </span>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- 電話 -->
                                        <div class="col-12">
                                            <div class="input-group input-group-merge">

                                                <div class="form-floating form-floating-outline">
                                                    <input type="text" id="modalEditUserPhone" name="modalEditUserPhone"
                                                        class="form-control phone-number-mask" value="{{ $data->phone }}"
                                                        placeholder="0920111222" aria-label="電話" />
                                                    <label for="modalEditUserPhone">電話</label>
                                                    <div class="invalid-feedback">請輸入有效電話</div>

                                                </div>
                                            </div>

                                        </div>

                                        <!-- 按鈕 -->
                                        <div
                                            class="col-12 text-center d-flex flex-wrap justify-content-center gap-4 row-gap-4">
                                            <button type="submit" class="btn btn-primary">送出</button>
                                            <button id='cancel' type="button" class="btn btn-outline-secondary"
                                                data-bs-dismiss="modal" aria-label="Close">
                                                取消
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>



                    </div>
                </div>
            </div>
        </div>
    </div>
    </div>
    <!--/ Content -->

    <!--/ Layout Content -->


    {{-- <div class="buy-now">
    <a href="#" target="" class="btn btn-danger btn-buy-now">Buy Now</a>
  </div> --}}


    <!-- Include Scripts -->
    <!-- $isFront is used to append the front layout scripts only on the front layout otherwise the variable will be blank -->
    <!-- BEGIN: Vendor JS-->
@section('scripts')
    <!-- Core JS -->


    <!-- endbuild -->

    <!-- Vendors JS -->
    <script src="{{ asset('assets') }}/vendor/libs/select2/select2.js"></script>
    <script src="{{ asset('assets') }}/vendor/libs/bootstrap-select/bootstrap-select.js"></script>
    <script src="{{ asset('assets') }}/vendor/libs/moment/moment.js"></script>
    <script src="{{ asset('assets') }}/vendor/libs/flatpickr/flatpickr.js"></script>
    <script src="{{ asset('assets') }}/vendor/libs/tagify/tagify.js"></script>
    <script src="{{ asset('assets') }}/vendor/libs/@form-validation/popular.js"></script>
    <script src="{{ asset('assets') }}/vendor/libs/@form-validation/bootstrap5.js"></script>
    <script src="{{ asset('assets') }}/vendor/libs/@form-validation/auto-focus.js"></script>

    <!-- Main JS -->




    <!-- Page JS -->
    <script src="../../assets/js/form-validation.js"></script>



    </body>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {

            $("#formValidationEmail").on('blur', function() {
                var email = $(this).val(); // 獲取電子郵件輸入框的值

                // 簡單的電子郵件格式驗證（可選）
                if (!email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
                    Swal.fire({
                        icon: 'error',
                        title: '格式錯誤',
                        text: '請輸入有效的電子郵件地址！'
                    });
                    return;
                }

                // 發送 AJAX 請求到伺服器進行進一步驗證
                $.ajax({
                    url: "{{ route('member.validemail') }}", // 替換成你的 API 路徑
                    type: 'get', // 或 'GET'，根據你的需求
                    data: {
                        email: email
                    },
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr(
                            'content') // 如果使用 Laravel CSRF 保護
                    },
                    success: function(response) {
                        // 如果電子郵件已被註冊
                        if (!response.valid) {
                            Swal.fire({
                                icon: 'warning',
                                title: '電子郵件已被註冊',
                                text: '該電子郵件已存在，請選擇下一步操作。',
                                showCancelButton: true,
                                confirmButtonText: '驗證電子郵件',
                                cancelButtonText: '我知道了，換一個',
                                reverseButtons: true // 按鈕排列反向
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    // 使用者選擇驗證電子郵件
                                    Swal.fire({
                                        icon: 'info',
                                        title: '驗證發送中',
                                        text: '已向該電子郵件發送驗證信，請檢查郵箱。'
                                    });
                                    // 可在此處調用發送驗證郵件的函式
                                    sendVerificationEmail(email);
                                } else if (result.dismiss === Swal.DismissReason
                                    .cancel) {
                                    // 使用者選擇換一個電子郵件
                                    $('#formValidationEmail').val(''); // 清空輸入框
                                }
                            });
                        } else {
                            Swal.fire({
                                icon: 'success',
                                title: '電子郵件可用',
                                text: '您可以繼續使用此電子郵件。'
                            });
                        }
                    },
                    error: function(xhr) {
                        // 錯誤處理
                        Swal.fire({
                            icon: 'error',
                            title: '伺服器錯誤',
                            text: '驗證失敗，請稍後再試！'
                        });
                    }
                });
            });
            // 發送驗證郵件的函式
            function sendVerificationEmail(email) {
                console.log('email:', email);
                $.ajax({
                    url: "{{ route('member.sendemail') }}", // 替換為發送驗證郵件的 API
                    type: 'POST',
                    data: {
                        email: email
                    },
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    success: function(Response) {
                        console.log('Response:', Response);

                        if (Response.status == 'success') {
                            Swal.fire({
                                icon: 'success',
                                title: '驗證信已發送',
                                text: '請檢查您的電子郵件以完成驗證。'
                            });
                        }

                    },
                    error: function() {
                        Swal.fire({
                            icon: 'error',
                            title: '驗證信發送失敗',
                            text: '請稍後再試！'
                        });
                    }
                });
            }


            $('#editUserForm').on('submit', function(e) {
                e.preventDefault(); // 防止表單提交

                let valid = true;

                // Email 驗證
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                const emailInput = $('#formValidationEmail');
                if (!emailRegex.test(emailInput.val())) {
                    valid = false;
                    emailInput.addClass('is-invalid');
                } else {
                    emailInput.removeClass('is-invalid');
                }

                // 密碼長度驗證
                const passwordInput = $('#basic-default-password');
                //if (passwordInput.val().length < 6) {
                //  valid = false;
                //passwordInput.addClass('is-invalid');
                //} else {
                //  passwordInput.removeClass('is-invalid');
                //}

                // 確認密碼驗證
                const confirmPasswordInput = $('#formValidationConfirmPass');
                if (passwordInput.val() !== confirmPasswordInput.val()) {
                    valid = false;
                    confirmPasswordInput.addClass('is-invalid');
                } else {
                    confirmPasswordInput.removeClass('is-invalid');
                }

                // 手機號碼驗證
                const phoneRegex = /^09\d{8}$/;
                const phoneInput = $('#modalEditUserPhone');
                if (!phoneRegex.test(phoneInput.val())) {
                    valid = false;
                    phoneInput.addClass('is-invalid');
                } else {
                    phoneInput.removeClass('is-invalid');
                }

                // 若通過所有驗證，發送 AJAX 請求
                if (valid) {
                    const formData = {
                        email: emailInput.val(),
                        password: passwordInput.val(),
                        phone: phoneInput.val(),
                    };

                    $.ajax({
                        url: "{{ route('member.profile.update') }}",
                        type: 'put',
                        data: formData,
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        success: function(response) {
                            Swal.fire({
                                title: '成功',
                                text: "{{ session('success') }}",
                                icon: 'success',
                                confirmButtonText: '确定'
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    // 跳轉到 member.index 路由
                                    window.location.href =
                                        "{{ route('member.index') }}";
                                }
                            });


                        },
                        error: function(error) {
                            Swal.fire({
                                title: '失敗',
                                text: "更新失敗",
                                icon: 'error',
                                confirmButtonText: '确定'
                            });
                        },
                    });
                }
            });
        });

        $("#cancel").on('click', function() {
            let valid = true;

            // Email 驗證
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            const emailInput = $('#formValidationEmail');
            if (!emailRegex.test(emailInput.val())) {
                valid = false;
                emailInput.addClass('is-invalid');
            } else {
                emailInput.removeClass('is-invalid');
            }
            if (valid == true) {
                window.location.href = "{{ route('member.index') }}";
            }

        });
    </script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <link rel="module" href="{{ asset('assets') }}/vendor/libs/@form-validation/popular.js" />

    <script>
        $("#cancel").on('click', function() {

            window.location.href = "{{ route('member.index') }}";
        });
        $(document).ready(function() {
    // 監聽表單提交事件
    $('#editUserForm').on('submit', function(e) {
        e.preventDefault(); // 阻止默認的表單提交行為

        // 獲取表單數據
        let email = $('#formValidationEmail').val();
        let password = $('#basic-default-password').val();
        let confirmPassword = $('#formValidationConfirmPass').val();
        let phone = $('#modalEditUserPhone').val();

        // 表單驗證
        let valid = true;

        // 驗證 Email
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            valid = false;
            $('#formValidationEmail').addClass('is-invalid');
        } else {
            $('#formValidationEmail').removeClass('is-invalid');
        }

        // 驗證密碼與確認密碼是否相符
        if (password !== confirmPassword) {
            valid = false;
            $('#formValidationConfirmPass').addClass('is-invalid');
        } else {
            $('#formValidationConfirmPass').removeClass('is-invalid');
        }

        // 驗證手機號碼格式
        const phoneRegex = /^09\d{8}$/;
        if (!phoneRegex.test(phone)) {
            valid = false;
            $('#modalEditUserPhone').addClass('is-invalid');
        } else {
            $('#modalEditUserPhone').removeClass('is-invalid');
        }

        // 若驗證通過，發送 AJAX 請求
        if (valid) {
            // 打包數據
            let formData = {
                email: email,
                password: password,
                phone: phone
            };

            $.ajax({
                url: "{{ route('member.profile.update') }}", // 替換為後端處理路由
                type: 'PUT', // 使用 HTTP PUT 方法
                data: formData,
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') // CSRF 驗證
                },
                success: function(response) {
                    // 成功處理邏輯
                    Swal.fire({
                        title: '更新成功',
                        text: response.message || '您的個人資訊已成功更新！',
                        icon: 'success',
                        confirmButtonText: '確定'
                    }).then(() => {
                        // 跳轉至其他頁面
                        window.location.href = "{{ route('member.index') }}";
                    });
                },
                error: function(xhr, status, error) {
                    // 錯誤處理邏輯
                    Swal.fire({
                        title: '更新失敗',
                        text: xhr.responseJSON.message || '請稍後重試！',
                        icon: 'error',
                        confirmButtonText: '確定'
                    });
                }
            });
        }
    });
});

    </script>
@endsection
@endsection
