$(document).ready(function (e) {
    $("#btn-notify").on("click", function (e) {
        notify();
        notify("success", "Yes its done");
        notify("info", "Yes its done");
        notify("warning", "Yes its done");
        notify("error", "Yes its done");
    });
    $("#supplierTable").DataTable({
        ajax: {
            url: base_url + "suppliers/show",
            type: "GET", // or 'POST' if needed
        },
        language: {
            lengthMenu: "_MENU_",
        },
        pageLength: 100,
        order: [],
        responsive: true,
    });

    $("#spl_category").on("change", function (e) {
        var category_id = $(this).val();
        $.ajax({
            url: base_url + "stock/get_items_by_category",
            type: "POST",
            data: { category_id: category_id },
            success: function (response) {
                $("#spl_items").html(response);
            },
            error: function (jqXHR, exception) {
                alert(jqXHR.status);
            },
        }); //End of Ajax Request
    });

    $("#spl_items").on("change", function (e) {
        var opt = $(this);
        if ($("#spl_sitems").val() == "") {
            $("#spl_sitems").val(opt.val());
        } else {
            $("#spl_sitems").val($("#spl_sitems").val() + "," + opt.val());
        }
    });

    $("#btn-add-supplier").on("click", function (e) {
        $("#spl-msg").fadeOut("slow");
        $("#spl-msg").removeClass();
        var spl_name = $("#spl_name").val();
        var spl_address = $("#spl_address").val();
        var spl_contact = $("#spl_contact").val();
        var spl_email = $("#spl_email").val();
        var spl_notes = $("#spl_notes").val();
        if (spl_name == "") {
            $("#spl-msg")
                .html("Please provide Name")
                .addClass("text-warning")
                .fadeIn("slow");
            return false;
        }
        if (spl_contact == "") {
            $("#spl-msg")
                .html("Please provide Contact")
                .addClass("text-warning")
                .fadeIn("slow");
            return false;
        }
        $.ajax({
            url: base_url + "suppliers/add",
            type: "POST",
            data: {
                spl_name: spl_name,
                spl_contact: spl_contact,
                spl_email: spl_email,
                spl_address: spl_address,
                spl_notes: spl_notes,
            },
            success: function (response) {
                if (response == 1) {
                    notify("success", "Added Successfully");
                    $("#spl_name").val("");
                    $("#spl_address").val("");
                    $("#spl_contact").val("");
                    $("#spl_email").val("");
                    $("#spl_notes").val("");
                } else {
                    notify("error", "Error try again");
                }
                $("#supplierTable").DataTable().ajax.reload();
            },
            error: function (msg) {
                let res_errors = "";
                $.each(msg.responseJSON.errors, function (key, value) {
                    res_errors += value + "<br>";
                });
                notify("warning", res_errors);
            },
        });
    });

    $("#supplier-edit-modal").on("show.bs.modal", function (e) {
        var spl_id = e.relatedTarget.id;
        $("#e_spl-msg").html("");
        $("#e_spl_id").val(spl_id);
        $.ajax({
            url: base_url + "suppliers/edit",
            type: "POST",
            data: { spl_id: spl_id },
            success: function (msg) {
                var res = $.parseJSON(msg);
                $("#e_spl_name").val(res["spl_name"]);
                $("#e_spl_contact").val(res["spl_contact"]);
                $("#e_spl_email").val(res["spl_email"]);
                $("#e_spl_address").val(res["spl_address"]);
                $("#e_spl_notes").val(res["spl_notes"]);
            },
        });
    });

    $("#e_spl_category").on("change", function (e) {
        var category_id = $(this).val();
        $.ajax({
            url: base_url + "stock/get_items_by_category",
            type: "POST",
            data: { category_id: category_id },
            success: function (response) {
                $("#e_spl_items").html(response);
            },
            error: function (jqXHR, exception) {
                alert(jqXHR.status);
            },
        }); //End of Ajax Request
    });

    $("#e_spl_items").on("change", function (e) {
        var opt = $(this);
        if ($("#e_spl_sitems").val() == "") {
            $("#e_spl_sitems").val(opt.val());
        } else {
            $("#e_spl_sitems").val($("#e_spl_sitems").val() + "," + opt.val());
        }
    });

    $("#btn-update-supplier").on("click", function (e) {
        $("#e_item-msg").fadeOut("slow");
        $("#e_item-msg").removeClass();
        var spl_id = $("#e_spl_id").val();
        var spl_name = $("#e_spl_name").val();
        var spl_contact = $("#e_spl_contact").val();
        var spl_email = $("#e_spl_email").val();
        var spl_address = $("#e_spl_address").val();
        var spl_notes = $("#e_spl_notes").val();
        if (spl_name == "") {
            $("#e_spl-msg")
                .html("Please provide Name")
                .addClass("text-warning")
                .fadeIn("slow");
            return false;
        }
        if (spl_contact == "") {
            $("#e_spl-msg")
                .html("Please provide Contact")
                .addClass("text-warning")
                .fadeIn("slow");
            return false;
        }

        $.ajax({
            url: base_url + "suppliers/update",
            type: "POST",
            data: {
                spl_id: spl_id,
                spl_name: spl_name,
                spl_contact: spl_contact,
                spl_email: spl_email,
                spl_address: spl_address,
                spl_notes: spl_notes,
            },
            success: function (response) {
                if (response == 1) {
                    notify("success", "Updated Successfully");
                } else {
                    notify("error", "Error try again");
                }
                $("#supplierTable").DataTable().ajax.reload();
            },
            error: function (msg) {
                let res_errors = "";
                $.each(msg.responseJSON.errors, function (key, value) {
                    res_errors += value + "<br>";
                });
                notify("warning", res_errors);
            },
        });
    });

    $("#supplierTable").on("click", ".ifdel", function (e) {
        e.preventDefault();
        spl_id = $(this).attr("data-uid");
        swal(
            {
                title: "Are you sure?",
                text: "You will not be able to recover this data!",
                type: "warning",
                showCancelButton: true,
                confirmButtonClass:
                    "btn-danger btn-md waves-effect waves-light",
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "Yes, delete it!",
                cancelButtonText: "No, cancel it!",
                closeOnConfirm: true,
                closeOnCancel: true,
            },
            function (isConfirm) {
                if(isConfirm){
                    $.ajax({
                        url: base_url + "suppliers/delete",
                        type: "POST",
                        data: { spl_id: spl_id },
                        success: function (response) {
                            if (response == 1) {
                                notify("success", "Deleted");
                            } else {
                                notify("error", "Error deleting please try again");
                            }
                        },
                        error: function (msg) {
                            let res_errors = "";
                            $.each(msg.responseJSON.errors, function (key, value) {
                                res_errors += value + "<br>";
                            });
                            notify("warning", res_errors);
                        },
                    }); //End of Ajax Request
                    $("#supplierTable").DataTable().ajax.reload();
                }

            }
        );s
    });

    $("#supplier-invoices-modal").on("show.bs.modal", function (e) {
        var spl_id = e.relatedTarget.id;
        $.ajax({
            url: base_url + 'suppliers/get-invoices',
            type: "POST",
            data: { spl_id: spl_id },
            success: function (msg) {
                var res = $.parseJSON(msg);
                $("#pinv-mbody").html("");
                $("#pinv-mbody").html(res[0]);
            },
        });
    });

    $("#make-payment-modal").on("show.bs.modal", function (e) {
        var invoice = e.relatedTarget.id;
        var amount = e.relatedTarget.getAttribute("href");
        var advance = parseFloat(e.relatedTarget.getAttribute("title"));
        $("#invoice_number").html("");
        $("#invoice_number").html(invoice);
        $("#payment-tbody").html("");
        $("#payment-tbody").html(
            '<tr><td></td><td></td><td class="pamount">' +
                amount +
                "</td><td></td><td></td><td></td><td></td><td></td></tr>"
        );
        if (advance > 0) {
            $("#payment-tbody").append(
                '<tr><td></td><td class="adv">' +
                    advance +
                    '</td><td class="pamount">' +
                    (amount - advance) +
                    "</td><td></td><td></td><td></td><td></td><td></td></tr>"
            );
        }
        recalcId();
        $.ajax({
            url: base_url + "suppliers/get-payments",
            type: "POST",
            data: { invoice: invoice, amount: amount, sadv: "yes" },
            success: function (msg) {
                var res = $.parseJSON(msg);
                $("#payment-tbody").append(res[0]);
                recalcId();
            },
        });
    });

    $("#ptext").on("keyup", function (e) {
        var amount = parseFloat($(".pamount:last").text());
        var pamount = parseFloat($(this).val());
        if (pamount > amount) {
            $("#ifnotify-warning").text(
                " Amount must be less or equal last payment"
            );
            $("#ifnotify-warning").trigger("click");
            return false;
        }
    });

    $("#btn-make-payment").on("click", function (e) {
        var famount = parseFloat($(".pamount:first").text());
        var amount = parseFloat($(".pamount:last").text());
        var pamount = parseFloat($("#ptext").val());
        var advance = parseFloat($(".adv").text());
        var payment_method = $("#pbank").val();
        var cheque = $("#pcheque").val();
        var chequed = $("#pchequed").val();
        if (isNaN(pamount)) {
            pamount = 0;
        }
        if (pamount == 0) {
            notify("warning", "Please enter amount to pay");
            return false;
        }
        if (pamount > amount) {
            notify("warning", "Amount must be less or equal last payment");
            return false;
        }
        if (payment_method=='cheque' && cheque == "") {
            notify("warning", "Please Enter Cheque Number");
            return false;
        }
        if (cheque != "" && payment_method != "cheque") {
            notify("warning", "Please Choose \"Payment Method\" Cheque If Using Cheque Number");
            return false;
        }
        var invoice = $("#invoice_number").text();
        $.ajax({
            url: base_url + "suppliers/make-payments",
            type: "POST",
            data: {
                invoice: invoice,
                pamount: pamount,
                bank: payment_method,
                cheque: cheque,
                chequed: chequed,
            },
            success: function (msg) {
                $("#ptext").val("");
                $("#pbank").val("");
                $("#pcheque").val("");
                $("#pchequed").val("");
                var res = $.parseJSON(msg);
                if (res[0] != 0) {
                    $.ajax({
                        url: base_url + "suppliers/get-payments",
                        type: "POST",
                        data: {
                            invoice: invoice,
                            amount: famount,
                            sadv: "yes",
                        },
                        success: function (msg) {
                            var res = $.parseJSON(msg);
                            $("#payment-tbody").html("");
                            $("#payment-tbody").html(
                                '<tr><td></td><td></td><td class="pamount">' +
                                    famount +
                                    "</td><td></td><td></td><td></td><td></td><td></td></tr>"
                            );
                            if (!isNaN(advance)) {
                                $("#payment-tbody").append(
                                    '<tr><td></td><td class="adv">' +
                                        advance +
                                        '</td><td class="pamount">' +
                                        eval(famount - advance) +
                                        "</td><td></td><td></td><td></td><td></td><td></td></tr>"
                                );
                            }
                            $("#payment-tbody").append(res[0]);
                            recalcId();
                        },
                    });
                }
            },
        });
    });

    $(document).on("click", ".rmv-supplier-payments", function (e) {
        var pay_id = $(this).attr("id");
        $.ajax({
            url: base_url + "suppliers/remove-payments",
            type: "POST",
            data: { pay_id: pay_id },
            success: function (msg) {
                if (msg == 1) {
                    notify("success", "Removed Successfully");
                    $("#make-payment-modal").modal("hide");
                } else {
                    notify("error", "Error removing payment, please try again");
                }
            },
        });
    });
});
