(function ($) {

    "use strict";



    var dTable = null;

    var _id = null;

    var _current_name_slug = null;

    $(document).ready(function () {



        //load datatable
        Manager.GetDataList(0, function() {

            //generate datatable serial no
            dTableManager.dTableSerialNumber(dTable);

        });


        //add  modal

        $("#btnAdd").on("click", function () {

            _id = null;

            Manager.ResetForm();

            $("#frmModal").modal('show');

        });



        //save or update

        // JsManager.JqBootstrapValidation('#inputForm', (form, event) => {

        //     event.preventDefault();

        //     if (_id == null) {

        //         Manager.Save(form);

        //     } else {

        //         Manager.Update(form, _id);

        //     }

        // });
    });

    $("#inputForm").on("submit", function(event) {
        event.preventDefault(); 

        const formData = $(this);
    
        try {
            if (_id == null) {
                Manager.Save(formData);
            } else {
                Manager.Update(formData, _id, _current_name_slug);
            }
        } catch (error) {
            console.error('Error during save/update:', error);
        }
    });

    // Initial shortened link value
    let currentLink = window.location.origin + '/';

    // Show edit info modal
    $(document).on('click', '.dTableEdit', function () {
        var rowData = dTable.row($(this).parent()).data();
        
        _id = rowData.id;
        _current_name_slug = rowData.name_slug;
        
        $('#id').val(rowData.id);
        $('#name').val(rowData.name);
        $('#short_name').val(rowData.short_name);
        $('#branch_code').val(rowData.branch_code);
        $('#original_branch_code').val(rowData.branch_code);
        $('#name_slug').val(rowData.name_slug);
        $('#phone').val(rowData.phone);
        $('#email').val(rowData.email);
        $('#address').val(rowData.address);

        // Set status radio buttons
        if (rowData['status'] == 1) {
            $('#statusYes').prop('checked', true);
        } else {
            $('#statusNo').prop('checked', true);
        }
        
        // Set the shorten link checkbox state
        $('#shortenLink').prop('checked', rowData['is_shorten_link'] == 1);

        // Update the current link after setting name_slug
        currentLink = window.location.origin + '/' + $('#name_slug').val();

        // Update the shortened link dynamically
        currentLink = window.location.origin + '/' + $('#name_slug').val();
        $('.shortened-link').text(currentLink); // Use class instead of id

        // Show the modal
        $("#frmModal").modal('show');

        // Check initial state of the shortenLink checkbox
        toggleSlugInput();

        // Listen to the change event of the shortenLink checkbox to toggle the read-only state dynamically
        $('#shortenLink').off('change').on('change', function () {
            toggleSlugInput();
        });

        // Listen to changes in the name_slug input to update the currentLink dynamically
        $('#name_slug').off('input').on('input', function () {
            updateCurrentLink();
        });
    });

    // Show view info modal
    $(document).on('click', '.dTableView', function () {
        var rowData = dTable.row($(this).parent()).data();
        
        _id = rowData.id;
    
        $('#viewName').text(rowData.name);
        $('#viewShortName').text(rowData.short_name);
        $('#viewBranchCode').text(rowData.branch_code);
        $('#viewNameSlug').text(rowData.name_slug);
        $('#viewPhone').text(rowData.phone);
        $('#viewEmail').text(rowData.email);
        $('#viewAddress').text(rowData.address);
    
        // Set status radio buttons
        if (rowData['status'] == 1) {
            $('#viewStatus').text('Active')
        } else {
            $('#viewStatusNo').text('Inactive');
        }
    
        // Update the current link after setting viewName_slug
        currentLink = window.location.origin + '/' + rowData.name_slug;
    
        // Update the shortened link dynamically
        $('.help-block-link').text(currentLink); // Use class instead of id
    
        // Show the modal
        $("#viewFrmModal").modal('show');
    });

    // Function to update the current link
    function updateCurrentLink() {
        currentLink = window.location.origin + '/' + $('#name_slug').val();
        $('.shortened-link').text(currentLink); // Update shortened link text
        $('.help-block-link').text(currentLink); // Update help-block link text
    }

    // Function to toggle the readonly state of name_slug input
    function toggleSlugInput() {
        if ($('#shortenLink').is(':checked')) {
            // Disable the slug input when checkbox is checked
            $('input[name="name_slug"]').prop('readonly', true);
            $('.help-block-link').text(currentLink).show(); // Show the help-block-link
            $('#copyButton').prop('disabled', false); // Enable the copy button
        } else {
            // Enable the slug input when checkbox is unchecked
            $('input[name="name_slug"]').prop('readonly', false);
            $('.shortened-link').hide(); // Hide the link
            $('.help-block-link').hide(); // Hide the help-block-link
            $('#copyButton').prop('disabled', true); // Disable the copy button
        }
    }

    if ($('#shortenLink').is(':checked')) {
        // Disable the slug input
        $('input[name="name_slug"]').prop('readonly', true); 
        $('.shortened-link').text(currentLink); // Show the link
        $('.help-block-link').text(currentLink).show();
        $('#copyButton').prop('disabled', false); // Enable the copy button
    } else {
        $('#shortenedLink').hide(); // Hide the link
        $('#copyButton').prop('disabled', true); // Disable the copy button

        // Enable the slug input
        $('input[name="name_slug"]').prop('readonly', false); 
    }
    

    // Toggle switch event listener
    $('#shortenLink').change(function() {
        if ($(this).is(':checked')) {
            // Show the updated shortened link when toggled on
            $('#copyButton').prop('disabled', false); // Enable the copy button
            $('.help-block-link').show();
        } else {
            $('#shortenedLink').hide(); // Hide the link
            $('.help-block-link').hide();
            $('#copyButton').prop('disabled', true); // Disable the copy button
        }
    });

    // Copy button click event
    $('#copyButton').click(function() {
        event.preventDefault(); // Prevent default action if necessary

        const linkToCopy = $(this).siblings('.shortened-link').text(); // Find the corresponding shortened link

        // Use the Clipboard API to copy text
        navigator.clipboard.writeText(linkToCopy).then(function() {
            alert('Shortened link copied to clipboard!');
        }).catch(function(err) {
            console.error('Error copying text: ', err);
        });
    });

    // Copy button click event
    $('#copyShortLink').click(function() {
        event.preventDefault(); // Prevent default action if necessary

        const linkToCopy = $(this).siblings('.help-block-link').text(); // Find the corresponding shortened link

        // Use the Clipboard API to copy text
        navigator.clipboard.writeText(linkToCopy).then(function() {
            alert('Shortened link copied to clipboard!');
        }).catch(function(err) {
            console.error('Error copying text: ', err);
        });
    });


    //delete

    $(document).on('click', '.dTableDelete', function () {

        var rowData = dTable.row($(this).parent()).data();

        Manager.Delete(rowData);

    });





    var Manager = {
        GetUserRole: function () {

            return new Promise((resolve, reject) => {
                JsManager.StartProcessBar();
        
                var serviceUrl = "get-user-role";
                JsManager.SendJsonAsyncON("GET", serviceUrl, '', function(jsonData) {
                    JsManager.EndProcessBar();
                    if (jsonData.status == "1" && jsonData.data.length > 0) {
                        var user_role = jsonData.data[0].name;
                        resolve(user_role); 
                    } else {
                        resolve(false);
                    }
                }, function(xhr, status, err) {
                    JsManager.EndProcessBar();
                    Message.Exception(xhr);
                    reject(false);  // Reject in case of failure
                });
            });

        },

        ResetForm: function () {

            $("#inputForm").trigger('reset');

        },

        Save: function (form) {

            if (Message.Prompt()) {

                JsManager.StartProcessBar();

                var jsonParam = form.serialize();

                var serviceUrl = "branch-save";

                JsManager.SendJson("POST", serviceUrl, jsonParam, onSuccess, onFailed);



                function onSuccess(jsonData) {

                    if (jsonData.status == "1") {

                        Message.Success("save");

                        Manager.ResetForm();

                        Manager.GetDataList(1); //reload datatable

                    } else {

                        Message.Error("save");

                    }

                    JsManager.EndProcessBar();



                }



                function onFailed(xhr, status, err) {

                    JsManager.EndProcessBar();

                    Message.Exception(xhr);

                }

            }

        },

        Update: function (form, id, current_name_slug) {

            if (Message.Prompt()) {

                JsManager.StartProcessBar();

                var jsonParam = form.serialize() + "&id=" + id + "&current_name_slug=" + encodeURIComponent(current_name_slug);

                var serviceUrl = "branch-update";

                JsManager.SendJson("POST", serviceUrl, jsonParam, onSuccess, onFailed);



                function onSuccess(jsonData) {

                    if (jsonData.status == "1") {

                        Message.Success("update");

                        _id = null;
                        
                        $("#frmModal").modal('hide');

                        Manager.ResetForm();

                        Manager.GetDataList(1); //reload datatable
                       

                    } else {

                        Message.Error("update");

                    }

                    JsManager.EndProcessBar();



                }



                function onFailed(xhr, status, err) {

                    JsManager.EndProcessBar();

                    Message.Exception(xhr);

                }

            }

        },

        Delete: function (data) {

            if (Message.Prompt()) {

                JsManager.StartProcessBar();

                var jsonParam = { id: data.id, name_slug: data.name_slug };

                var serviceUrl = "branch-delete";

                JsManager.SendJson("POST", serviceUrl, jsonParam, onSuccess, onFailed);



                function onSuccess(jsonData) {

                    if (jsonData.status == "1") {

                        Message.Success("delete");

                        Manager.GetDataList(1); //reload datatable

                    } else {

                        Message.Error("delete");

                    }

                    JsManager.EndProcessBar();



                }



                function onFailed(xhr, status, err) {

                    JsManager.EndProcessBar();

                    Message.Exception(xhr);

                }

            }

        },

        GetDataList: function (refresh, callback) {

            var jsonParam = '';

            var serviceUrl = "get-branch";

            JsManager.SendJsonAsyncON('GET', serviceUrl, jsonParam, onSuccess, onFailed);



            function onSuccess(jsonData) {

                Manager.GetUserRole()
                    .then(userRole => {
                        Manager.LoadDataTable(jsonData, refresh, userRole);
                        if (callback) callback();
                    })
                    .catch(error => {
                        console.log('Error fetching user role:', error);
                    });

            }



            function onFailed(xhr, status, err) {

                Message.Exception(xhr);

            }

        },





        LoadDataTable: function (data, refresh, userRole) {
            
            if (refresh == "0") {

                dTable = $('#tableElement').DataTable({

                    dom: "<'row'<'col-md-6'B><'col-md-3'l><'col-md-3'f>>" + "<'row'<'col-md-12'tr>>" + "<'row'<'col-md-5'i><'col-md-7 mt-7'p>>",

                    initComplete: function () {

                        dTableManager.Border(this, 350);

                    },

                    buttons: [

                        {

                            text: '<i class="fa fa-file-pdf"></i> PDF',

                            className: 'btn btn-sm',

                            extend: 'pdfHtml5',

                            exportOptions: {

                                columns: [2, 3]

                            },

                            title: 'Branch List'

                        },

                        {

                            text: '<i class="fa fa-print"></i> Print',

                            className: 'btn btn-sm',

                            extend: 'print',

                            exportOptions: {

                                columns: [2, 3]

                            },

                            title: 'Branch List'

                        },

                        {

                            text: '<i class="fa fa-file-excel"></i> Excel',

                            className: 'btn btn-sm',

                            extend: 'excelHtml5',

                            exportOptions: {

                                columns: [2, 3, 4, 5, 6, 7, 8]

                            },

                            title: 'Branch List'

                        }

                    ],



                    scrollY: "350px",

                    scrollX: true,

                    scrollCollapse: true,

                    lengthMenu: [[50, 100, 500, -1], [50, 100, 500, "All"]],

                    columnDefs: [

                        { visible: false, targets: [] },

                        { "className": "dt-center", "targets": [3] }

                    ],

                    columns: [

                        {

                            data: null,

                            name: '',

                            'orderable': false,

                            'searchable': false,

                            title: '#SL',

                            width: 8,

                            render: function () {

                                return '';

                            }

                        },

                        {

                            name: 'Option',

                            title: 'Option',

                            width: 60,

                            render: function (data, type, row) {
                                
                                return EventManager.DataTableCommonButton(userRole, 'branch');

                            }

                        },

                        {

                            data: 'name',

                            name: 'name',

                            title: 'Name'

                        },

                        {
                            data: 'name_slug',
                            name: 'name_slug',
                            title: 'Name Slug'
                        },

                        {
                            data: 'short_name',
                            name: 'short_name',
                            title: 'Short Name'
                        },

                        {
                            data: 'branch_code',
                            name: 'branch_code',
                            title: 'Branch Code'
                        },

                        {

                            data: 'phone',

                            name: 'phone',

                            title: 'Phone'

                        },

                        {

                            data: 'email',

                            name: 'email',

                            title: 'Email'

                        },

                        {

                            data: 'address',

                            name: 'address',

                            title: 'Address'

                        }

                        // {

                        //     data: 'order',

                        //     name: 'order',

                        //     title: 'Order'

                        // }

                    ],

                    fixedColumns: false,

                    data: data.data

                });

            } else {

                dTable.clear().rows.add(data.data).draw();

            }

        }

    };

})(jQuery);