'use strict';

$(document).ready(function () {

    // ==================================================
    // ADD BOOK FORM SUBMIT
    // ==================================================

    $('#bookForm').on('submit', function (event) {

        event.preventDefault();

        const saveBtn =
            $('#saveBtn');

        saveBtn.prop('disabled', true);

        saveBtn.html(
            '<i class="fas fa-spinner fa-spin"></i> Saving...'
        );

        $.ajax({

            url: 'book_process.php',

            type: 'POST',

            dataType: 'json',

            data: {

                action: 'add',

                book_title:
                    $('#book_title').val(),

                book_no:
                    $('#book_no').val(),

                isbn_no:
                    $('#isbn_no').val(),

                publish:
                    $('#publish').val(),

                author:
                    $('#author').val(),

                subject:
                    $('#subject').val(),

                rack_no:
                    $('#rack_no').val(),

                qty:
                    $('#qty').val(),

                perunitcost:
                    $('#perunitcost').val(),

                postdate:
                    $('#postdate').val(),

                description:
                    $('#description').val()
            },

            success: function (response) {

                $('#responseMessage')

                    .removeClass()

                    .addClass(
                        'alert alert-success'
                    )

                    .html(response.message)

                    .fadeIn();

                // RESET FORM

                $('#bookForm')[0].reset();

                // DEFAULT VALUES

                $('#qty').val(1);

                $('#perunitcost').val(0);

                // BUTTON RESTORE

                saveBtn.prop('disabled', false);

                saveBtn.html(
                    '<i class="fas fa-save"></i> Save Book'
                );
            },

            error: function (xhr) {

                let response =
                    xhr.responseJSON;

                $('#responseMessage')

                    .removeClass()

                    .addClass(
                        'alert alert-danger'
                    )

                    .html(
                        response?.message ||
                        'Something went wrong.'
                    )

                    .fadeIn();

                saveBtn.prop('disabled', false);

                saveBtn.html(
                    '<i class="fas fa-save"></i> Save Book'
                );
            }
        });
    });
});