$(document).ready(function () {

    var curr_obj='';
    var base_url = 'https://redlineassociate.com/admin/';
    // var base_url = 'http://localhost:8000/admin/';

    $(".project_start_date,.project_end_date").datepicker({dateFormat: "yy-mm-dd"});

    //user events start

    $(document).on('click', '#login_btn', function (event) {

        event.preventDefault();

        var username = $('.login_username').val();
        if (username == "") {
            alert_msg('Please enter username.');
            return false;
        }

        var password = $('.login_password').val();
        if (password == "") {
            alert_msg('Please enter password.');
            return false;
        }

        $.ajax({
            url: base_url + "login/",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: "post",
            data: $("#login_frm").serialize(),
            dataType: "json",
            success: function (result) {
                if (result.status == true) {
                    window.location.href = base_url + 'projects';
                    return true;
                }
                alert_msg(result.message || 'Login failed. Please try again.');
                return false;
            },
            error: function(xhr, status, error) {
                console.error('Login error:', xhr.responseText);
                if (xhr.status === 419) {
                    alert_msg('CSRF token mismatch. Please refresh the page and try again.');
                } else if (xhr.status === 500) {
                    alert_msg('Server error. Please try again later.');
                } else if (xhr.status === 0) {
                    alert_msg('Network error. Please check your connection.');
                } else {
                    alert_msg('Login failed: ' + (xhr.responseJSON?.message || error));
                }
            }
        });

    });

    //user events start


    //project events start

    $(document).on('click', '.save_project', function (event) {

        event.preventDefault();

        var id = $('.project_id').val();
        var slug = $('.project_slug').val();
        var price = $('.project_price').val();
        var title = $('.project_title').val();
        var client = $('.project_client').val();
        var start_date = $('.project_start_date').val();
        var end_date = $('.project_end_date').val();
        var description = CKEDITOR.instances.editor1.getData();

        if (title === "") return alert_msg('Please enter project title.');
        if (slug === "") return alert_msg('Please enter project slug.');
        // if (client === "") return alert_msg('Please enter project client.');
        // if (start_date === "") return alert_msg('Please select project start time.');
        // if (description === "") return alert_msg('Please enter project description.');

        var formData = new FormData();
        formData.append('id', id);
        formData.append('title', title);
        formData.append('slug', slug);
        formData.append('price', price);
        formData.append('client', client);
        formData.append('start_date', start_date);
        formData.append('end_date', end_date);
        formData.append('description', description);
        formData.append('image', $('input[type=file]')[0].files[0]);

        $.ajax({
            url: base_url + "saveProject/",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: "post",
            data: formData,
            dataType: "json",
            contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
            processData: false, // NEEDED, DON'T OMIT THIS
            success: function (result) {
                if (result.status === true) {
                    window.location.href = base_url + 'projects?save=true';
                    return true;
                }
                alert_msg(result.message);
                return false;
            }
        });

    });

    $(document).on('click', '.delete_project', function (event) {

        event.preventDefault();
        curr_obj = $(this);

        var result = confirm("Want to delete?");
        if (result) {

            id = $(this).attr('data-id');
            $.ajax({
                type: "POST",
                url: base_url + "project/deleteProject",
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                dataType: "json",
                data: {
                    id: id
                },
                success: function (result) {
                    if (result.status == true) {
                        alert_msg("Project is successfully deleted.", 'success');
                        curr_obj.parents('.project-section').remove();
                        return;

                    }
                    alert_msg(result.message);
                }
            });

        }

    });

    //project events end


    //career events start

    $(document).on('click', '.save_career', function (event) {

        event.preventDefault();

        var id = $('.career_id').val();
        var title = $('.career_title').val();
        var description = CKEDITOR.instances.editor1.getData();

        if (title === "") return alert_msg('Please enter career title.');
        if (description === "") return alert_msg('Please enter career description.');

        $.ajax({
            url: base_url + "saveCareer/",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: "post",
            data: {
                id: id,
                title: title,
                description: description,
            },
            dataType: "json",
            success: function (result) {
                if (result.status === true) {
                    window.location.href = base_url + 'careers?save=true';
                    return true;
                }
                alert_msg(result.message);
                return false;
            }
        });

    });

    $(document).on('click', '.change_career_status', function (event) {

        event.preventDefault();
        curr_obj = $(this);

        $.ajax({
            url: base_url + "changeCareerStatus/",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: "post",
            data: {
                id: $(this).attr('data-id'),
            },
            dataType: "json",
            success: function (result) {
                if (result.status === true) {
                    alert_msg("Career status is successfully changed.", 'success');
                    curr_obj.parents('.career-section').find('.career-status').text(result.text);
                    return;
                }
                alert_msg(result.message);
                return false;
            }
        });

    });

    $(document).on('click', '.delete_career', function (event) {

        event.preventDefault();
        curr_obj = $(this);

        var result = confirm("Want to delete?");
        if (result) {

            id = $(this).attr('data-id');
            $.ajax({
                type: "POST",
                url: base_url + "career/deleteCareer",
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                dataType: "json",
                data: {
                    id: id
                },
                success: function (result) {
                    if (result.status == true) {
                        alert_msg("Career is successfully deleted.", 'success');
                        curr_obj.parents('.career-section').remove();
                        return;

                    }
                    alert_msg(result.message);
                }
            });

        }

    });

    //career events end

    //posts events start

    $(document).on('click', '.save_post', function (event) {

        event.preventDefault();

        var id = $('.post_id').val();
        var title = $('.post_title').val();
        var slug = $('.post_slug').val();
        var description = CKEDITOR.instances.editor1.getData();

        if (title === "") return alert_msg('Please enter post title.');
        if (slug === "") return alert_msg('Please enter post slug.');
        if (description === "") return alert_msg('Please enter post description.');

        var formData = new FormData();
        formData.append('id', id);
        formData.append('title', title);
        formData.append('slug', slug);
        formData.append('description', description);
        formData.append('image', $('input[type=file]')[0].files[0]);

        $.ajax({
            url: base_url + "savePost/",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: "post",
            data: formData,
            dataType: "json",
            contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
            processData: false, // NEEDED, DON'T OMIT THIS
            success: function (result) {
                if (result.status === true) {
                    window.location.href = base_url + 'posts?save=true';
                    return true;
                }
                alert_msg(result.message);
                return false;
            }
        });

    });

    $(document).on('click', '.delete_post', function (event) {

        event.preventDefault();
        curr_obj = $(this);

        var result = confirm("Want to delete?");
        if (result) {

            id = $(this).attr('data-id');
            $.ajax({
                type: "POST",
                url: base_url + "post/deletePost",
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                dataType: "json",
                data: {
                    id: id
                },
                success: function (result) {
                    if (result.status == true) {
                        alert_msg("Post is successfully deleted.", 'success');
                        curr_obj.parents('.post-section').remove();
                        return;

                    }
                    alert_msg(result.message);
                }
            });

        }

    });

    //posts events end


    //contact events start

    $(document).on('click', '.delete_contact', function (event) {

        event.preventDefault();
        curr_obj = $(this);

        var result = confirm("Want to delete?");
        if (result) {

            id = $(this).attr('data-id');
            $.ajax({
                type: "POST",
                url: base_url + "contact/deleteContact",
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                dataType: "json",
                data: {
                    id: id
                },
                success: function (result) {
                    if (result.status == true) {
                        alert_msg("Contact is successfully deleted.", 'success');
                        curr_obj.parents('.contact-section').remove();
                        return;

                    }
                    alert_msg(result.message);
                }
            });

        }

    });

    //contact events end


    function alert_msg(message, type_of_message) {
        if (typeof(type_of_message) === 'undefined') type_of_message = 'error';
        var n = noty({
            timeout: 5000,
            text: message,
            type: type_of_message,//alert, success, error, warning, information, confirm
            layout: 'topRight',
            maxVisible: 5, // you can set max visible notification for dismissQueue true option,

        });
    }

});
