'use strict';

$(document).ready(function () {

    // ==================================================
    // SET DEFAULT DUE DATE
    // ==================================================

    let today = new Date();

    today.setDate(
        today.getDate() + 7
    );

    let dueDate =
        today.toISOString()
             .split('T')[0];

    $('#due_date').val(dueDate);

    // ==================================================
    // ISSUE BOOK
    // ==================================================

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

        event.preventDefault();

        const issueBtn =
            $('#issueBtn');

        issueBtn.prop('disabled', true);

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

        $.ajax({

            url: 'issue_process.php',

            type: 'POST',

            dataType: 'json',

            data: {

                action: 'issue',

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

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

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

            success: function (response) {

                $('#responseMessage')

                    .removeClass()

                    .addClass(
                        'alert alert-success'
                    )

                    .html(response.message)

                    .fadeIn();

                // RESET FORM

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

                // RESET DUE DATE

                $('#due_date').val(dueDate);

                // RESTORE BUTTON

                issueBtn.prop('disabled', false);

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

            error: function (xhr) {

                let response =
                    xhr.responseJSON;

                $('#responseMessage')

                    .removeClass()

                    .addClass(
                        'alert alert-danger'
                    )

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

                    .fadeIn();

                issueBtn.prop('disabled', false);

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