$(function () {
    document.querySelectorAll('.post-date, .post-date1').forEach(el => {
        new Datepicker(el, {
            buttonClass: 'btn'
        });
    });
});

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();
    CKEDITOR.instances.project_overview.updateElement();
    var form_data = $('form#add-form').serializeArray();
    $.ajax({
        type: "POST",
        url: basePath + "admin/our-project",
        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) {
                    key = key.split(".").join("_");
                    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' || firstErrorKey === 'project_overview') {
                        // Focus CKEditor instance directly
                        CKEDITOR.instances[firstErrorKey].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.project_overview.setData('');
    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/our-project/" + globalDataId + "/edit", function (data) {
        var form = $('form#edit-form');
        form.find('input[name="editFormId"]').val(globalDataId);
        form.find('input[name="title"]').val(data.title);
        form.find('input[name="location"]').val(data.location);
        form.find('input[name="meta_title"]').val(data.meta_title);
        form.find('textarea[name="meta_description"]').val(data.meta_description);
        CKEDITOR.instances.short_description1.setData(data.short_description);
        CKEDITOR.instances.project_overview1.setData(data.project_overview);
        form.find('input[name="banner_image"]').val(data.banner_image);
        if (data.banner_image) {
            form.find('#holder3 img').attr('src', imagePath + data.banner_image);
        }

        form.find('input[name="image"]').val(data.image);
        if (data.image) {
            form.find('#holder4 img').attr('src', imagePath + data.image);
        }

        form.find('input[name="side_image"]').val(data.side_image);
        if (data.side_image) {
            form.find('#holder5 img').attr('src', imagePath + data.side_image);
        }
        const wrapper = $('#highlight-wrapper-edit');
        wrapper.empty();


        let highlights = data.highlights;
        if (typeof highlights === 'string') {
            highlights = JSON.parse(highlights);
        }
        highlightIndex['highlight-wrapper-edit'] = 0;

        if (!Array.isArray(highlights) || highlights.length === 0) {
            highlights = [{ title: '', value: '' }];
        }

        $.each(highlights, function (i, item) {
            const row = `
    <div class="highlight-row row mb-2" data-index="${i}">
        <div class="col-sm-5">
            <div class="form-group">
                <label class="form-label">Title </label>
                <input type="text" name="highlights[${i}][title]" value="${item.title ?? ''}" class="form-control form-control-sm required" placeholder="Title">
               <div class="invalid-feedback" id="highlights_${i}_title_err"></div>
            </div>
        </div>
        <div class="col-sm-5">
            <div class="form-group">
                <label class="form-label">Value </label>
                <input type="text" name="highlights[${i}][value]" value="${item.value ?? ''}" class="form-control form-control-sm required" placeholder="Value">
                <div class="invalid-feedback" id="highlights_${i}_value_err"></div>
            </div>
        </div>
        <div class="col-sm-2 d-flex align-items-end">
            <button type="button" class="btn btn-sm btn-danger remove-highlight-btn" style="margin-bottom: 16px;">
                <i class="fa fa-trash"></i>
            </button>
        </div>
    </div>`;
            wrapper.append(row);
            highlightIndex['highlight-wrapper-edit'] = i + 1;
        });
    });
});


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

$('.update-btn').click(function (e) {
    e.preventDefault();
    CKEDITOR.instances.short_description1.updateElement();
    CKEDITOR.instances.project_overview1.updateElement();
    var globalDataId = $('form#edit-form').find('input[name="editFormId"]').val();
    var form_data = $('form#edit-form').serializeArray();
    $.ajax({
        type: "POST",
        url: basePath + "admin/our-project/" + 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) {
                    key = key.split(".").join("_");
                    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 === 'description') {
                        // Focus CKEditor instance directly
                        CKEDITOR.instances.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/our-project/' + 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-our-project',
        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'},
        {
            data: 'banner_image', searchable: false, orderable: false, sortable: false,
            render: function (data, type, dataObject, meta) {
                return '<img src="' + imagePath + data + '" width="80" height="80;"> ';
            }
        },
        {data: 'title'},
        {data: 'location'},
        {data: 'short_description'},
        {
            data: 'image', searchable: false, orderable: false, sortable: false,
            render: function (data, type, dataObject, meta) {
                return '<img src="' + imagePath + data + '" width="80" height="80;"> ';
            }
        },
        {
            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>
                      `;
                }
                if (dataObject.edit_permission) {
                    action += `
                         <li class="list-inline-item align-bottom" data-bs-toggle="tooltip" title="Add images">
                              <a href="${dataObject.galleryImageUrl}" class="avtar avtar-xs btn-link-warning btn-pc-default">
                                <i class="ti ti-photo f-18"></i> (${dataObject.totalImage})
                              </a>
                        </li>`;
                }
                return `<ul class="list-inline me-auto mb-0 d-flex">${action}</ul>`;
            }
        }
    ],
});

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

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

