function success(message) {
    notifier.show('Well Done!', message, 'success', basePath + '../assets/admin/images/notification/ok-48.png', 4000);
}

function danger(message) {
    notifier.show('Sorry!', message, 'danger', basePath + '../assets/admin/images/notification/high_priority-48.png', 4000);
}

/*========== SCRIPT TO ADD NEW DESIGNATION =================*/

$('.add-btn').on('click', function (e) {
    e.preventDefault();
    CKEDITOR.instances.short_description.updateElement();
    var form_data = $('form#add-form').serializeArray();
    $.ajax({
        type: "POST",
        url: basePath + "admin/success-story",
        data: form_data,
        beforeSend: function () {
            $('.modal-spinner').show();
        },
        success: function (data) {
            $('form#add-form').find('.invalid-feedback').each(function () {
                $(this).empty().hide();
            });
            if (data.status) {
                masterTable.draw();
                $('#addModal').modal('hide');
                success(data.message);
            } else {
                danger(data.message);
            }
            $('.modal-spinner').hide();
        },
        error: function (error) {
            $('.modal-spinner').hide();
            if (error.status === 422 && error.readyState == 4) {
                $('form#add-form').find('.invalid-feedback').each(function () {
                    $(this).empty().hide();
                });
                var errors = $.parseJSON(error.responseText);
                let firstErrorKey = null;
                $.each(errors.errors, function (key, val) {
                    const errorElement = $('form#add-form').find('#' + key + '_err');
                    errorElement.empty().append(val).show();
                    if (!firstErrorKey) {
                        firstErrorKey = key;
                    }
                });
                // Focus on the first field with error
                if (firstErrorKey) {
                    if (firstErrorKey === 'short_description') {
                        // Focus CKEditor instance directly
                        CKEDITOR.instances.short_description.focus();
                    } else {
                        // Focus normal input/select/textarea fields
                        $('form#add-form').find('[name="' + firstErrorKey + '"]').focus();
                    }
                }
            }
        },
        complete: function () {
            $('.modal-spinner').hide();
        }
    });
});

$('#addModal').on('hidden.bs.modal', function () {
    $('form#add-form').find('.invalid-feedback').each(function () {
        $(this).empty().hide();
    });
    CKEDITOR.instances.short_description.setData('');
    $('form#add-form').find('img').attr('src', '');
    $('#addModal').find('form#add-form')[0].reset();
});

$('table#master-table').delegate('.view-btn', 'click', function () {
    var globalDataId = $(this).parents('tr').attr('data-id');
    $.get(basePath + "admin/success-story/" + globalDataId + "/edit", function (data) {
        var form = $('form#edit-form');
        form.find('input[name="editFormId"]').val(globalDataId);
        form.find('input[name="full_name"]').val(data.full_name);
        form.find('input[name="designation"]').val(data.designation);
        CKEDITOR.instances.short_description1.setData(data.short_description);
        form.find('input[name="user_profile_image"]').val(data.user_profile_image);
        if (data.user_profile_image) {
            form.find('#holder2 img').attr('src', imagePath + data.user_profile_image);
        }
        form.find('input[name="company_logo"]').val(data.company_logo);
        if (data.company_logo) {
            form.find('#holder3 img').attr('src', imagePath + data.company_logo);
        }
    });
});

$('#viewModal').on('hidden.bs.modal', function () {
    $('form#edit-form').find('.invalid-feedback').each(function () {
        $(this).empty().hide();
    });
    CKEDITOR.instances.short_description1.setData('');
    $('#viewModal').find('form#edit-form')[0].reset();
});

$('.update-btn').click(function (e) {
    e.preventDefault();
    CKEDITOR.instances.short_description1.updateElement();
    var globalDataId = $('form#edit-form').find('input[name="editFormId"]').val();
    var form_data = $('form#edit-form').serializeArray();
    $.ajax({
        type: "POST",
        url: basePath + "admin/success-story/" + globalDataId,
        data: form_data,
        beforeSend: function () {
            $('.modal-spinner').show();
        },
        success: function (data) {
            $('form#edit-form').find('.invalid-feedback').each(function () {
                $(this).empty().hide();
            });
            if (data.status) {
                masterTable.draw();
                $('#viewModal').modal('hide');
                success(data.message);
            } else {
                danger(data.message);
            }
            $('.modal-spinner').hide();
        },
        error: function (error) {
            $('.modal-spinner').hide();
            if (error.status === 422 && error.readyState == 4) {
                $('form#edit-form').find('.invalid-feedback').each(function () {
                    $(this).empty().hide();
                });
                var errors = $.parseJSON(error.responseText);
                let firstErrorKey = null;
                $.each(errors.errors, function (key, val) {
                    const errorElement = $('form#edit-form').find('#' + key + '_err');
                    errorElement.empty().append(val).show();
                    if (!firstErrorKey) {
                        firstErrorKey = key;
                    }
                });
                // Focus on the first field with error
                if (firstErrorKey) {
                    if (firstErrorKey === 'short_description') {
                        // Focus CKEditor instance directly
                        CKEDITOR.instances.short_description1.focus();
                    } else {
                        // Focus normal input/select/textarea fields
                        $('form#edit-form').find('[name="' + firstErrorKey + '"]').focus();
                    }
                }
            }
        },
        complete: function () {
            $('.modal-spinner').hide();
        }
    });
});
/*========== END SCRIPT TO EDIT AND VIEW DESIGNATION =================*/

/*========== START SCRIPT TO DELETE DESIGNATION =================*/
$('table#master-table').delegate('.delete-btn', 'click', function (e) {
    e.preventDefault();
    var globalDataId = $(this).parents('tr').attr('data-id');
    var thisReference = $(this);
    Swal.fire({
        title: "Are you sure want to delete this?",
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: "#136ba7",
        confirmButtonText: "Yes",
        denyButtonText: "Cancel",
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: basePath + 'admin/success-story/' + globalDataId,
                type: 'post',
                data: {
                    id: globalDataId, _method: 'DELETE', _token: csrfToken
                },
                success: function (data) {
                    if (data.status) {
                        Swal.fire({
                            title: data.msg,
                            icon: 'success',
                            confirmButtonColor: "#136ba7",
                            confirmButtonText: "Ok",
                        }).then((result) => {
                            if (result.isConfirmed) {
                                thisReference.parents('tr').remove();
                            }
                        });
                    } else {
                        Swal.fire("Not Deleted", data.msg, "error");
                    }
                },
                error: function () {
                },
            });
        } else {
            Swal.fire("Not Deleted", "Data is not Deleted. it is save.", "error");
        }
    });
});
/*========== END SCRIPT TO DELETE DESIGNATION =================*/

/*========== SCRIPT FOR JQUERY DATATABLE =================*/
var masterTable = $('#master-table').DataTable({
    order: [0, 'desc'],
    dom: 'lfrtip',
    serverSide: true,
    responsive: true,
    processing: true,
    "ajax": {
        url: basePath + 'admin/fetch-success-story',
        type: "POST",
        dataType: 'json',
        'data': function (data) {
            data._token = csrfToken;
        },
        error: function (error) {
            console.log(error);
        }
    },
    'createdRow': function (row, data, dataIndex) {
        $(row).attr('data-id', data.globalDataId);
    },
    columns: [
        {
            data: 'id',
            render: function (data, type, dataObject, meta) {
                if (data) {
                    return `<i class="fa fa-arrows-alt" aria-hidden="true"></i> `;
                }
            }, sortable: false, orderable: false
        },
        {data: 'id'},
        {data: 'full_name'},
        {data: 'designation'},
        {data: 'short_description'},
        {data: 'user_profile_image',searchable: false, orderable: false, sortable: false,
            render: function (data, type, dataObject, meta){
                return '<img src="' +imagePath+ data +'" width="80" height="80;"> ';
            }
        },
        // {data: 'created_by_admin_users_info_id'},
        {
            data: 'active_status',
            render: function (data, type, dataObject, meta) {
                var action = `
                        <div class="form-check form-switch custom-switch-v1 mb-2">
                        <input type="checkbox" class="form-check-input input-success changeStatus" id="customswitchv2-3" value="${dataObject.globalDataId}" ${dataObject.active_status == 1 ? 'checked' : ''}>
                      </div>
`;
                return action;
            }
        },
        {data: 'created_at'},

        {
            data: 'actions', searchable: false, orderable: false, sortable: false,
            render: function (data, type, dataObject, meta) {
                var action = '';
                if (dataObject.edit_permission) {
                    action += `
                        <li class="list-inline-item align-bottom" data-bs-toggle="tooltip" title="Edit">
                          <a href="javascript:void(0);" data-bs-toggle="modal" data-bs-target="#viewModal" class="avtar avtar-xs btn-link-success btn-pc-default view-btn" data-backdrop="static" data-keyboard="false">
                            <i class="ti ti-edit-circle f-18"></i>
                          </a>
                        </li>
                      `;
                }
                if (dataObject.delete_permission) {
                    action += `
                        <li class="list-inline-item align-bottom" data-bs-toggle="tooltip" title="Delete">
                          <a href="javascript:void(0);" class="avtar avtar-xs btn-link-danger btn-pc-default delete-btn">
                            <i class="ti ti-trash f-18"></i>
                          </a>
                        </li>
                      `;
                }
                return `<ul class="list-inline me-auto mb-0">${action}</ul>`;
            }
        }
    ],
});

$("body").delegate(".changeStatus", "change", function () {

    let statusId = $(this).val();
    $.get(basePath + "admin/success-story-status/" + statusId, function (data) {
        if (data.status) {
            masterTable.draw();
            success(data.message);
        } else {
            danger(data.message);
        }
    });
});

//sortable
$( "#tablecontents" ).sortable({
    items: "tr",
    cursor: 'move',
    opacity: 0.6,
    update: function() {
        sendOrderToServer();
    }
});
function sendOrderToServer() {
    var order = [];
    var token = $('meta[name="csrf-token"]').attr('content');
    $('#tablecontents tr').each(function(index,element) {
        order.push({
            id: $(this).attr('data-id'),
            position: index+1
        });
    });

    $.ajax({
        type: "POST",
        dataType: "json",
        url: basePath + 'admin/success-story-sortable',
        data: {
            order: order,
            _token: token
        },
        success: function(data) {
            console.log(data)
            if (data.status) {
                success(data.message);
            } else {
                danger(data.message);
            }
        }
    });
}
