@extends('layouts.contentLayoutMaster')

@section('title', $user->displayName())

@section('vendor-style')
    {{-- Page Css files --}}

    <link rel="stylesheet" href="{{ asset(mix('vendors/css/forms/select/select2.min.css')) }}">

    <link rel="stylesheet" href="{{ asset(mix('vendors/css/tables/datatable/dataTables.bootstrap5.min.css')) }}">
    <link rel="stylesheet" href="{{ asset(mix('vendors/css/tables/datatable/responsive.bootstrap5.min.css')) }}">
    <link rel="stylesheet" href="{{ asset(mix('vendors/css/tables/datatable/buttons.bootstrap5.min.css')) }}">
    <link rel="stylesheet" href="{{ asset(mix('vendors/css/extensions/sweetalert2.min.css')) }}">

    <link rel="stylesheet" href="{{ asset(mix('css/base/plugins/forms/form-validation.css')) }}">

@endsection

@section('content')
    <!-- users edit start -->
    <section class="users-edit">

        <ul class="nav nav-pills mb-2" role="tablist">

            <li class="nav-item">
                <a class="nav-link @if ((old('tab') == 'account' || old('tab') == null) && request()->input('tab') == null) active @endif"
                   id="account-tab" data-bs-toggle="tab" href="#account" aria-controls="account" role="tab"
                   aria-selected="true">
                    <i data-feather="user"></i> {{__('locale.labels.account')}}
                </a>
            </li>

            <li class="nav-item">
                <a class="nav-link {{ old('tab') == 'security' ? 'active':null }}" id="security-tab"
                   data-bs-toggle="tab" href="#security" aria-controls="security" role="tab" aria-selected="true">
                    <i data-feather="lock"></i> {{__('locale.labels.security')}}
                </a>
            </li>

            <li class="nav-item">
                <a class="nav-link {{ request()->input('tab') == 'notification' ? 'active':null }}"
                   id="notification-tab" data-bs-toggle="tab" href="#notification" aria-controls="notification"
                   role="tab" aria-selected="false">
                    <i data-feather="bell"></i> {{__('locale.labels.notifications')}}
                </a>
            </li>


            @if(config('app.two_factor'))
                <li class="nav-item">
                    <a class="nav-link {{ old('tab') == 'two_factor' ? 'active':null }}" id="two-factor-tab"
                       data-bs-toggle="tab" href="#two-factor" aria-controls="two-factor" role="tab"
                       aria-selected="false">
                        <i data-feather="log-in"></i> {{__('locale.labels.two_factor_authentication')}}
                    </a>
                </li>
            @endif

            @if($user->active_portal == 'customer')
                <li class="nav-item">
                    <a class="nav-link {{ old('tab') == 'information' ? 'active':null }}" id="information-tab"
                       data-bs-toggle="tab" href="#information" aria-controls="information" role="tab"
                       aria-selected="false">
                        <i data-feather="info"></i>{{__('locale.labels.information')}}
                    </a>
                </li>

                <li class="nav-item">
                    <a class="nav-link {{ old('tab') == 'webhook' ? 'active':null }}" id="webhook-tab"
                       data-bs-toggle="tab" href="#webhook" aria-controls="webhook" role="tab" aria-selected="false">
                        <i data-feather="link"></i> {{__('locale.developers.webhook_url')}}
                    </a>
                </li>
            @endif



            @if(config('app.trai_dlt') == 1
                && isset($user->customer)
                && $user->customer->activeSubscription()?->plan?->is_dlt)
                {{--Entity ID--}}
                <li class="nav-item">
                    <a class="nav-link {{ old('tab') == 'dlt_entity_id' ? 'active':null }}"
                       id="dlt_entity_id-tab" data-bs-toggle="tab" href="#dlt_entity_id"
                       aria-controls="dlt_entity_id" role="tab" aria-selected="false">
                        <i data-feather="key" class="font-medium-3 me-50"></i>
                        <span class="fw-bold">{{ __('locale.labels.dlt') }} {{ __('locale.labels.entity_id') }}</span>
                    </a>
                </li>

                <li class="nav-item">
                    <a class="nav-link {{ old('tab') == 'dlt_telemarketer_id' ? 'active':null }}"
                       id="dlt_telemarketer_id-tab" data-bs-toggle="tab" href="#dlt_telemarketer_id"
                       aria-controls="dlt_telemarketer_id" role="tab" aria-selected="false">
                        <i data-feather="headphones" class="font-medium-3 me-50"></i>
                        <span class="fw-bold">{{ __('locale.labels.dlt') }} {{ __('locale.labels.telemarketer_id') }}</span>
                    </a>
                </li>
            @endif

        </ul>


        <div class="tab-content">

            <div class="tab-pane @if ((old('tab') == 'account' || old('tab') == null) && request()->input('tab') == null) active @endif"
                 id="account" aria-labelledby="account-tab" role="tabpanel">
                <!-- users edit account form start -->
                @include('auth.profile._accounts')
                <!-- users edit account form ends -->
            </div>

            <div class="tab-pane {{ old('tab') == 'security' ? 'active':null }}" id="security"
                 aria-labelledby="security-tab" role="tabpanel">
                <!-- users edit Info form start -->
                @include('auth.profile._security')
                <!-- users edit Info form ends -->
            </div>

            <div class="tab-pane {{ request()->input('tab') == 'notification' ? 'active':null }}" id="notification"
                 aria-labelledby="notification-tab" role="tabpanel">
                <!-- users edit Info form start -->
                @include('auth.profile._notifications')
                <!-- users edit Info form ends -->
            </div>


            @if($user->active_portal == 'customer')
                <div class="tab-pane {{ old('tab') == 'information' ? 'active':null }}" id="information"
                     aria-labelledby="information-tab" role="tabpanel">
                    <!-- users edit Info form start -->
                    @include('auth.profile._information')
                    <!-- users edit Info form ends -->
                </div>

                <div class="tab-pane {{ old('tab') == 'webhook' ? 'active': null }}" id="webhook"
                     aria-labelledby="webhook-tab" role="tabpanel">
                    <!-- users edit Info form start -->
                    @include('auth.profile._webhook')
                    <!-- users edit Info form ends -->
                </div>

            @endif


            @if(config('app.two_factor'))
                <div class="tab-pane {{ old('tab') == 'two_factor' ? 'active':null }}" id="two-factor"
                     aria-labelledby="two-factor-tab" role="tabpanel">
                    @include('auth.profile._two_factor_authentication')
                </div>
            @endif



            @if(config('app.trai_dlt') == 1
                && isset($user->customer)
                && $user->customer->activeSubscription()?->plan?->is_dlt)
                <div class="tab-pane {{ old('tab') == 'dlt_entity_id' ? 'active':null }}"
                     id="dlt_entity_id" aria-labelledby="dlt_entity_id-tab" role="tabpanel">
                    @include('auth.profile._dlt_entity_id')
                </div>

                <div class="tab-pane {{ old('tab') == 'dlt_telemarketer_id' ? 'active':null }}"
                     id="dlt_telemarketer_id" aria-labelledby="dlt_telemarketer_id-tab" role="tabpanel">
                    @include('auth.profile._dlt_telemarketer_id')
                </div>
            @endif


        </div>
    </section>
    <!-- users edit ends -->
@endsection

@section('vendor-script')
    {{-- Vendor js files --}}
    <script src="{{ asset(mix('vendors/js/forms/select/select2.full.min.js')) }}"></script>

    <script src="{{ asset(mix('vendors/js/tables/datatable/jquery.dataTables.min.js')) }}"></script>
    <script src="{{ asset(mix('vendors/js/tables/datatable/dataTables.bootstrap5.min.js')) }}"></script>
    <script src="{{ asset(mix('vendors/js/tables/datatable/dataTables.responsive.min.js')) }}"></script>
    <script src="{{ asset(mix('vendors/js/tables/datatable/responsive.bootstrap5.min.js')) }}"></script>
    <script src="{{ asset(mix('vendors/js/tables/datatable/datatables.checkboxes.min.js')) }}"></script>
    <script src="{{ asset(mix('vendors/js/tables/datatable/datatables.buttons.min.js')) }}"></script>
    <script src="{{ asset(mix('vendors/js/tables/datatable/buttons.html5.min.js')) }}"></script>
    <script src="{{ asset(mix('vendors/js/tables/datatable/dataTables.rowGroup.min.js')) }}"></script>

    <script src="{{ asset(mix('vendors/js/extensions/sweetalert2.all.min.js')) }}"></script>
    <script src="{{ asset(mix('vendors/js/extensions/polyfill.min.js')) }}"></script>

    <script src="{{ asset(mix('vendors/js/forms/validation/jquery.validate.min.js')) }}"></script>
@endsection

@section('page-script')
    {{-- Page js files --}}

    <script>

        $(document).ready(function () {
            "use strict"

            let firstInvalid = $('form').find('.is-invalid').eq(0);

            if (firstInvalid.length) {
                $('body, html').stop(true, true).animate({
                    'scrollTop': firstInvalid.offset().top - 200 + 'px'
                }, 200);
            }

            // Basic Select2 select
            $(".select2").each(function () {
                let $this = $(this);
                $this.wrap('<div class="position-relative"></div>');
                $this.select2({
                    // the following code is used to disable x-scrollbar when click in select input and
                    // take 100% width in responsive also
                    dropdownAutoWidth: true,
                    width: '100%',
                    dropdownParent: $this.parent()
                });
            });

            //show response message
            function showResponseMessage(data) {

                if (data.status === 'success') {
                    toastr['success'](data.message, '{{__('locale.labels.success')}}!!', {
                        closeButton: true,
                        positionClass: 'toast-top-right',
                        progressBar: true,
                        newestOnTop: true,
                        rtl: isRtl
                    });
                    dataListView.draw(false);
                } else if (data.status === 'error') {
                    toastr['error'](data.message, '{{ __('locale.labels.opps') }}!', {
                        closeButton: true,
                        positionClass: 'toast-top-right',
                        progressBar: true,
                        newestOnTop: true,
                        rtl: isRtl
                    });
                    dataListView.draw(false);
                } else {
                    toastr['warning']("{{__('locale.exceptions.something_went_wrong')}}", '{{ __('locale.labels.warning') }}!', {
                        closeButton: true,
                        positionClass: 'toast-top-right',
                        progressBar: true,
                        newestOnTop: true,
                        rtl: isRtl
                    });
                }

              // Fix: Replace icons after redraw
              setTimeout(() => {
                feather.replace();
              }, 100); // slight delay to ensure DOM update completes
            }

            // init table dom
            let Table = $("table");

            // init list view datatable
            let dataListView = $('.datatables-basic').DataTable({

                "processing": true,
                "serverSide": true,
                "ajax": {
                    "url": "{{ route('user.account.notifications') }}",
                    "dataType": "json",
                    "type": "POST",
                    "data": {_token: "{{csrf_token()}}"}
                },
                "columns": [
                    {"data": 'responsive_id', orderable: false, searchable: false},
                    {"data": "uid"},
                    {"data": "uid"},
                    {"data": "notification_type"},
                    {"data": "message"},
                    {"data": "mark_read", orderable: false, searchable: false},
                    {"data": "action", orderable: false, searchable: false}
                ],

                searchDelay: 1500,
                columnDefs: [
                    {
                        // For Checkboxes
                        targets: 1,
                        orderable: false,
                        responsivePriority: 3,
                        render: function (data) {
                            return (
                                '<div class="form-check"> <input class="form-check-input dt-checkboxes" type="checkbox" value="" id="' +
                                data +
                                '" /><label class="form-check-label" for="' +
                                data +
                                '"></label></div>'
                            );
                        },
                        checkboxes: {
                            selectAllRender:
                                '<div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="checkboxSelectAll" /><label class="form-check-label" for="checkboxSelectAll"></label></div>',
                            selectRow: true
                        }
                    },
                    {
                        targets: 2,
                        visible: false
                    },
                    {
                        targets: 0,
                        visible: false
                    },
                    {
                        // Actions
                        targets: -1,
                        title: '{{ __('locale.labels.actions') }}',
                        orderable: false,
                        render: function (data, type, full) {
                            return (
                                '<span class="action-delete text-danger pe-1 cursor-pointer" data-id=' + full['uid'] + '>' +
                                feather.icons['trash'].toSvg({class: 'font-medium-4'}) +
                                '</span>'
                            );
                        }
                    }
                ],
                dom: '<"d-flex justify-content-between align-items-center mx-0 row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>t<"d-flex justify-content-between mx-0 row"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>',

                language: {
                    paginate: {
                        // remove previous & next text from pagination
                        previous: '&nbsp;',
                        next: '&nbsp;'
                    },
                    sLengthMenu: "_MENU_",
                    sZeroRecords: "{{ __('locale.datatables.no_results') }}",
                    sSearch: "{{ __('locale.datatables.search') }}",
                    sProcessing: "{{ __('locale.datatables.processing') }}",
                    sInfo: "{{ __('locale.datatables.showing_entries', ['start' => '_START_', 'end' => '_END_', 'total' => '_TOTAL_']) }}"
                },
                responsive: false,
                aLengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
                select: {
                    style: "multi"
                },
                order: [[2, "desc"]],
                displayLength: 10,
            });

            // On Delete
            Table.delegate(".action-delete", "click", function (e) {
                e.stopPropagation();
                let id = $(this).data('id');
                Swal.fire({
                    title: "{{ __('locale.labels.are_you_sure') }}",
                    text: "{{ __('locale.labels.able_to_revert') }}",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: "{{ __('locale.labels.delete_it') }}",
                    customClass: {
                        confirmButton: 'btn btn-primary',
                        cancelButton: 'btn btn-outline-danger ms-1'
                    },
                    buttonsStyling: false,
                }).then(function (result) {
                    if (result.value) {
                        $.ajax({
                            url: "{{ url('account/notifications/')}}" + '/' + id + '/delete',
                            type: "POST",
                            data: {
                                _token: "{{csrf_token()}}"
                            },
                            success: function (data) {
                                showResponseMessage(data);
                            },
                            error: function (reject) {
                                if (reject.status === 422) {
                                    let errors = reject.responseJSON.errors;
                                    $.each(errors, function (key, value) {
                                        toastr['warning'](value[0], "{{__('locale.labels.attention')}}", {
                                            closeButton: true,
                                            positionClass: 'toast-top-right',
                                            progressBar: true,
                                            newestOnTop: true,
                                            rtl: isRtl
                                        });
                                    });
                                } else {
                                    toastr['warning'](reject.responseJSON.message, "{{__('locale.labels.attention')}}", {
                                        positionClass: 'toast-top-right',
                                        containerId: 'toast-top-right',
                                        progressBar: true,
                                        closeButton: true,
                                        newestOnTop: true
                                    });
                                }
                            }
                        })
                    }
                })
            });

            //Bulk Read
            $(".bulk-read").on('click', function (e) {

                e.preventDefault();

                Swal.fire({
                    title: "{{__('locale.labels.are_you_sure')}}",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: "Yes! Mark read",
                    customClass: {
                        confirmButton: 'btn btn-primary',
                        cancelButton: 'btn btn-outline-danger ms-1'
                    },
                    buttonsStyling: false,
                }).then(function (result) {
                    if (result.value) {
                        let notification_ids = [];
                        let rows_selected = dataListView.column(1).checkboxes.selected();

                        $.each(rows_selected, function (index, rowId) {
                            notification_ids.push(rowId)
                        });

                        if (notification_ids.length > 0) {

                            $.ajax({
                                url: "{{ route('user.account.notifications.batch_action') }}",
                                type: "POST",
                                data: {
                                    _token: "{{csrf_token()}}",
                                    action: 'read',
                                    ids: notification_ids
                                },
                                success: function (data) {
                                    showResponseMessage(data);
                                },
                                error: function (reject) {
                                    if (reject.status === 422) {
                                        let errors = reject.responseJSON.errors;
                                        $.each(errors, function (key, value) {
                                            toastr['warning'](value[0], "{{__('locale.labels.attention')}}", {
                                                closeButton: true,
                                                positionClass: 'toast-top-right',
                                                progressBar: true,
                                                newestOnTop: true,
                                                rtl: isRtl
                                            });
                                        });
                                    } else {
                                        toastr['warning'](reject.responseJSON.message, "{{__('locale.labels.attention')}}", {
                                            closeButton: true,
                                            positionClass: 'toast-top-right',
                                            progressBar: true,
                                            newestOnTop: true,
                                            rtl: isRtl
                                        });
                                    }
                                }
                            })
                        } else {
                            toastr['warning']("{{ __('locale.labels.at_least_one_data') }}", "{{ __('locale.labels.attention') }}", {
                                closeButton: true,
                                positionClass: 'toast-top-right',
                                progressBar: true,
                                newestOnTop: true,
                                rtl: isRtl
                            });
                        }
                    }
                })
            });

            //Bulk Delete
            $(".bulk-delete").on('click', function (e) {

                e.preventDefault();

                Swal.fire({
                    title: "{{__('locale.labels.are_you_sure')}}",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: "{{__('locale.labels.delete_selected')}}",
                    customClass: {
                        confirmButton: 'btn btn-primary',
                        cancelButton: 'btn btn-outline-danger ms-1'
                    },
                    buttonsStyling: false,
                }).then(function (result) {
                    if (result.value) {
                        let notification_ids = [];
                        let rows_selected = dataListView.column(1).checkboxes.selected();

                        $.each(rows_selected, function (index, rowId) {
                            notification_ids.push(rowId)
                        });

                        if (notification_ids.length > 0) {

                            $.ajax({
                                url: "{{ route('user.account.notifications.batch_action') }}",
                                type: "POST",
                                data: {
                                    _token: "{{csrf_token()}}",
                                    action: 'destroy',
                                    ids: notification_ids
                                },
                                success: function (data) {
                                    showResponseMessage(data);
                                },
                                error: function (reject) {
                                    if (reject.status === 422) {
                                        let errors = reject.responseJSON.errors;
                                        $.each(errors, function (key, value) {
                                            toastr['warning'](value[0], "{{__('locale.labels.attention')}}", {
                                                closeButton: true,
                                                positionClass: 'toast-top-right',
                                                progressBar: true,
                                                newestOnTop: true,
                                                rtl: isRtl
                                            });
                                        });
                                    } else {
                                        toastr['warning'](reject.responseJSON.message, "{{__('locale.labels.attention')}}", {
                                            closeButton: true,
                                            positionClass: 'toast-top-right',
                                            progressBar: true,
                                            newestOnTop: true,
                                            rtl: isRtl
                                        });
                                    }
                                }
                            })
                        } else {
                            toastr['warning']("{{ __('locale.labels.at_least_one_data') }}", "{{ __('locale.labels.attention') }}", {
                                closeButton: true,
                                positionClass: 'toast-top-right',
                                progressBar: true,
                                newestOnTop: true,
                                rtl: isRtl
                            });
                        }

                    }
                })
            });


            Table.delegate(".get_status", "click", function () {
                let notification_id = $(this).data('id');
                $.ajax({
                    url: "{{ url('account/notifications/')}}" + '/' + notification_id + '/active',
                    type: "POST",
                    data: {
                        _token: "{{csrf_token()}}"
                    },
                    success: function (data) {
                        showResponseMessage(data);
                    }
                });
            });


            // On Remove Avatar
            $('#remove-avatar').on("click", function (e) {

                e.stopPropagation();
                Swal.fire({
                    title: "{{ __('locale.labels.are_you_sure') }}",
                    text: "{{ __('locale.labels.able_to_revert') }}",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: "{{ __('locale.labels.delete_it') }}",
                    customClass: {
                        confirmButton: 'btn btn-primary',
                        cancelButton: 'btn btn-outline-danger ms-1'
                    },
                    buttonsStyling: false,

                }).then(function (result) {
                    if (result.value) {
                        $.ajax({
                            url: "{{ route('user.remove_avatar') }}",
                            type: "POST",
                            data: {
                                _method: 'POST',
                                _token: "{{csrf_token()}}"
                            },
                            success: function (data) {
                                showResponseMessage(data);
                                setTimeout(function () {
                                    location.reload();
                                }, 5000);
                            },
                            error: function (reject) {
                                if (reject.status === 422) {
                                    let errors = reject.responseJSON.errors;
                                    $.each(errors, function (key, value) {
                                        toastr['warning'](value[0], "{{__('locale.labels.attention')}}", {
                                            closeButton: true,
                                            positionClass: 'toast-top-right',
                                            progressBar: true,
                                            newestOnTop: true,
                                            rtl: isRtl
                                        });
                                    });
                                } else {
                                    toastr['warning'](reject.responseJSON.message, "{{__('locale.labels.attention')}}", {
                                        positionClass: 'toast-top-right',
                                        containerId: 'toast-top-right',
                                        progressBar: true,
                                        closeButton: true,
                                        newestOnTop: true
                                    });
                                }
                            }
                        })
                    }
                })
            });


            let canDelete = {{ json_encode(config('account.can_delete')) }};

            if (canDelete) {

                let deactivateAcc = document.querySelector('#formAccountDeactivation'),
                    deactivateButton = deactivateAcc.querySelector('.deactivate-account'),
                    form = $('.validate-form');


                // disabled submit button on checkbox unselect
                if (deactivateAcc) {
                    $(document).on('click', '#accountActivation', function () {
                        if (accountActivation.checked === true) {
                            deactivateButton.removeAttribute('disabled');
                        } else {
                            deactivateButton.setAttribute('disabled', 'disabled');
                        }
                    });
                }

                // Deactivate account alert
                const accountActivation = document.querySelector('#accountActivation');

                // Alert With Functional Confirm Button
                if (deactivateButton) {
                    deactivateButton.onclick = function () {
                        if (accountActivation.checked === true) {
                            Swal.fire({
                                text: "{{ __('locale.auth.want_to_delete_your_account') }}?",
                                icon: 'warning',
                                showCancelButton: true,
                                confirmButtonText: "{{ __('locale.labels.yes') }}",
                                customClass: {
                                    confirmButton: 'btn btn-primary',
                                    cancelButton: 'btn btn-outline-danger ms-2'
                                },
                                buttonsStyling: false
                            }).then(function (result) {
                                if (result.value) {
                                    $.ajax({
                                        url: "{{ route('user.account.delete')}}",
                                        type: "POST",
                                        data: {
                                            _token: "{{csrf_token()}}"
                                        },
                                        success: function (data) {
                                            showResponseMessage(data);
                                            setTimeout(function () {
                                                window.location.href = "{{ route('login') }}";
                                            }, 3000);
                                        },
                                        error: function (reject) {
                                            if (reject.status === 422) {
                                                let errors = reject.responseJSON.errors;
                                                $.each(errors, function (key, value) {
                                                    toastr['warning'](value[0], "{{__('locale.labels.attention')}}", {
                                                        closeButton: true,
                                                        positionClass: 'toast-top-right',
                                                        progressBar: true,
                                                        newestOnTop: true,
                                                        rtl: isRtl
                                                    });
                                                });
                                            } else {
                                                toastr['warning'](reject.responseJSON.message, "{{__('locale.labels.attention')}}", {
                                                    positionClass: 'toast-top-right',
                                                    containerId: 'toast-top-right',
                                                    progressBar: true,
                                                    closeButton: true,
                                                    newestOnTop: true
                                                });
                                            }
                                        }
                                    })
                                } else if (result.dismiss === Swal.DismissReason.cancel) {
                                    Swal.fire({
                                        title: 'Cancelled',
                                        text: 'Deactivation Cancelled!!',
                                        icon: 'error',
                                        customClass: {
                                            confirmButton: 'btn btn-success'
                                        }
                                    });
                                }
                            });
                        }
                    };
                }

                // jQuery Validation for all forms
                // --------------------------------------------------------------------
                if (form.length) {
                    form.each(function () {
                        const $this = $(this);

                        $this.validate({
                            rules: {
                                accountActivation: {
                                    required: true
                                }
                            }
                        });
                    });
                }

            }


        });
    </script>

@endsection
