<script type="text/javascript">
    $(function() {
        $("#modal_form .modal-dialog").removeClass("modal-lg");

        set_masking();
        list_produk();
        hide_product_form();

        // add new product
        $("#detail-prospek-layanan #add_product").on("click", function() {
            const row = $("#detail-prospek-layanan tfoot");
            const product_id = row.find("select option:selected").val();
            const product_name = row.find("select option:selected").text();
            let nominal = parseInt(row.find("input:eq(0)").val().replaceAll('.', ''));
            let jumlah = parseInt(row.find("input:eq(1)").val().replaceAll('.', ''));
            let diskon = parseFloat(row.find("input:eq(2)").val().replace(',', '.'));

            // validation
            row.find(".select2-selection").removeAttr('style');
            if (!product_id) {
                row.find(".select2-selection").css('border', '1px solid red');
                row.find('td:eq(0) p').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> <?= $this->lang->line('error_pilih_layanan_kosong') ?></font>");
                row.find('td:eq(0) p').show();
                return false;
            }
            if (!nominal) {
                nominal = 0;
            }
            if (!jumlah) {
                jumlah = 0;
            }
            if (!diskon) {
                diskon = 0;
            }

            var param = {};
            param.harga = nominal;
            param.jumlah = jumlah;
            param.diskon = diskon;
            param.id_product = product_id;
            param.id_main = "<?= $id ?>";

            $.ajax({
                type: 'POST',
                url: "<?= route('sales_activity.kanban.detail.save_layanan') ?>",
                data: param,
                dataType: 'JSON',
                beforeSend: function() {
                    disable_form("#detail-prospek-layanan", ["input", "select", "button"], true);
                },
                success: function(result) {
                    if (result.success == true) {
                        showMsg(result.message);
                        $("#detail-layanan").load("<?= route('sales_activity.kanban.detail.layanan', ['id' => $id]) ?>");
                        load_data(get_periode(), get_pelanggan(), get_sales());
                    } else {
                        showMsg(result.message, true, 2000);
                        disable_form("#detail-prospek-layanan", ["input", "select", "button"], false);
                    }
                },
                error: function() {
                    disable_form("#detail-prospek-layanan", ["input", "select", "button"], false);
                    showMsg('error', false);
                }
            });
        });
    });

    // prospek layanan
    function set_masking() {
        // nominal
        $(".produk-nominal input").inputmask('numeric', {
            rightAlign: true,
            min: 0,
            digits: 0,
            groupSeparator: '.',
            autoGroup: true,
            allowMinus: false
        });

        // diskon
        $(".produk-diskon input").inputmask('decimal', {
            rightAlign: true,
            min: 0,
            max: 100,
            digits: 2,
            radixPoint: ',',
            allowMinus: false
        });
    }

    function list_produk() {
        $('#detail-prospek-layanan select').select2({
            placeholder: 'Pilih Produk/Layanan',
            allowClear: true,
            ajax: {
                url: '<?= route("sales_activity.kanban.list_produk") ?>',
                dataType: 'json',
                delay: 250,
                processResults: function(data) {
                    return {
                        results: data
                    };
                },
                cache: false
            },
            minLength: 3
        }).change(function() {
            let row = $(this).closest("tr");
            if (!this.value) {
                row.find("select").empty();
            }
            if ($(this).find("option").length > 1) {
                row.find('option:not([value="' + $(this).val() + '"])').remove();
            }

            let parts = this.value.split('#');
            let value = parseInt(parts[1]);

            row.find("input:eq(0)").val(value);
            row.find("input:eq(1)").val((!value) ? "" : 1);
            row.find("input:eq(2)").val((!value) ? "" : 0);

            total_price(this);
        });
    }

    function save_product(e) {
        let target = $(e).closest("tr");
        const produk = target.find("select").val();
        const nominal = parseInt(target.find("input:eq(0)").val().replaceAll('.', ''));
        const jumlah = parseInt(target.find("input:eq(1)").val().replaceAll('.', ''));
        const diskon = parseFloat(target.find("input:eq(2)").val().replace(",", "."));

        // validation
        target.find(".select2-selection").removeAttr('style');
        if (!produk) {
            target.find(".select2-selection").css('border', '1px solid red');
            target.find('td:eq(0) p').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> <?= $this->lang->line('error_pilih_layanan_kosong') ?></font>");
            target.find('td:eq(0) p').show();
            return false;
        }

        // assign last value
        target.find("td:eq(0) span:eq(0)").attr("data-id", produk);
        target.find("td:eq(0) span:eq(0)").text(target.find("td:eq(0) :selected").text());

        target.find("td:eq(1) span:eq(0)").html(nominal.toLocaleString("id-ID"));
        target.find("input:eq(0)").attr("value", nominal);

        target.find("td:eq(2) span:eq(0)").html(jumlah.toLocaleString("id-ID"));
        target.find("input:eq(1)").attr("value", jumlah);

        target.find("td:eq(3) span:eq(0)").html(diskon.toLocaleString("id-ID") + "%");
        target.find("input:eq(2)").attr("value", diskon.toLocaleString("id-ID"));

        let total = total_price(e);
        target.find("td:eq(4) span:eq(0)").attr("data-total", total.toLocaleString('id-ID'));

        var param = {};
        param.harga = nominal;
        param.jumlah = jumlah;
        param.diskon = diskon;
        param.id_product = produk;
        param.id_layanan = target.find('td:eq(-1)').data("layanan");
        param.id_main = "<?= $id ?>";

        $.ajax({
            type: 'POST',
            url: "<?= route('sales_activity.kanban.detail.update_layanan') ?>",
            data: param,
            dataType: 'JSON',
            beforeSend: function() {
                disable_form("#detail-prospek-layanan", ["input", "select", "button"], true);
            },
            success: function(result) {
                if (result.success == true) {
                    showMsg(result.message);
                    load_data(get_periode(), get_pelanggan(), get_sales());
                } else {
                    showMsg(result.message, true, 2000);
                    disable_form("#detail-prospek-layanan", ["input", "select", "button"], false);
                }
                $("#detail-layanan").load("<?= route('sales_activity.kanban.detail.layanan', ['id' => $id]) ?>");
            },
            error: function() {
                disable_form("#detail-prospek-layanan", ["input", "select", "button"], false);
                showMsg('error', false);
                $("#detail-layanan").load("<?= route('sales_activity.kanban.detail.layanan', ['id' => $id]) ?>");
            }
        });
    }

    function cancel_product(e) {
        let target = $(e).closest("tr");
        let produk = target.find("td:eq(0) span:eq(0)").data("id");
        let nama_produk = target.find("td:eq(0) span:eq(0)").text();

        target.find(".select2-selection").removeAttr('style');
        target.find("td:eq(0) select").html('<option value="' + produk + '">' + nama_produk + '</option>');
        target.find("td:eq(0) select").val(produk).trigger('change');
        target.find('td:eq(0) p').hide();
        target.find('td:eq(0) p').html("");

        hide_product_form(e);
        show_product_data(e);
    }

    function edit_product(e) {
        let target = $(e).closest("tr");
        target.find("td:not(:nth-last-child(-n+2)) > span").hide();
        target.find("td .select2").show();
        target.find("td input").show();
        target.find("td:last-child div:first-child").show();
        target.find("td:last-child div:last-child").hide();

        // assign last value
        let nominal = parseInt(target.find("td:eq(1) span:eq(0)").text().replaceAll(".", ""));
        let jumlah = parseInt(target.find("td:eq(2) span:eq(0)").text().replaceAll(".", ""));
        let diskon = target.find("td:eq(3) span:eq(0)").text().replace("%", "");

        target.find("input:eq(0)").val(nominal);
        target.find("input:eq(1)").val((!jumlah) ? "" : jumlah);
        target.find("input:eq(2)").val((!diskon) ? "" : diskon);

        total_price(e);
    }

    function remove_product(e) {
        let layanan = $(e).closest("td").data("layanan");
        $("#tampil_form").load("<?= route('sales_activity.kanban.detail.layanan.hapus', ['id' => $id, 'id_layanan' => '"+ layanan +"']) ?>", function() {
            $("#modal_form").modal("show");
            $("#modal_form .title").text("<?= $this->lang->line('title_form_hapus_data') ?>");
            $("#modal_form #btn_submit").addClass("btn btn-danger");
            $("#modal_form #btn_submit").html("<i class='fa fa-trash'></i> <?= $this->lang->line('button_form_hapus') ?>");

            $("#btn_submit").on("click", function(e) {
                e.preventDefault();
                var loading = Ladda.create(this);

                loading.start();

                var param = {};
                param.id_layanan = layanan;
                param.id_main = "<?= $id ?>";

                $.ajax({
                    type: 'POST',
                    url: "<?= route('sales_activity.kanban.detail.delete_layanan') ?>",
                    data: param,
                    dataType: 'JSON',
                    beforeSend: function() {
                        disable_form("#detail-prospek-layanan", ["input", "select", "button"], true);
                    },
                    success: function(result) {
                        loading.stop();
                        if (result.success == true) {
                            showMsg(result.message);
                            $("#detail-layanan").load("<?= route('sales_activity.kanban.detail.layanan', ['id' => $id]) ?>");
                            load_data(get_periode(), get_pelanggan(), get_sales());
                        } else {
                            showMsg(result.message, true, 2000);
                            disable_form("#detail-prospek-layanan", ["input", "select", "button"], false);
                        }
                    },
                    error: function() {
                        loading.stop();
                        disable_form("#detail-prospek-layanan", ["input", "select", "button"], false);
                        showMsg('error', false);
                    }
                });
            });
        });
    }

    function hide_product_form(e = null) {
        if (e != null) {
            let target = $(e).closest("tr");
            target.find(".select2").hide();
            target.find("input").hide();
            target.find("td:last-child div:first-child").hide();
            target.find("td:last-child div:last-child").show();
            target.find("td:nth-last-child(2) span").html(target.find("td:nth-last-child(2) span").attr("data-total"));
        } else {
            $("tbody .select2").hide();
            $("tbody input").hide();
            $("tbody td:last-child div:first-child").hide();
            $("tbody td:last-child div:last-child").show();

            // assign total
            $("tbody td:nth-last-child(2) span").each(function() {
                $(this).html($(this).attr("data-total"));
            });
        }
    }

    function show_product_data(e = null) {
        if (e != null) {
            let target = $(e).closest("tr");
            target.find("td").each(function() {
                $(this).find("span:eq(0)").show();
            });
        } else {
            $("tbody td").each(function() {
                $(this).find("span:eq(0)").show();
            });
        }
    }

    function total_price(e) {
        const row = $(e).closest('tr');
        let nominal = parseInt(row.find("input:eq(0)").val().replaceAll('.', ''));
        let jumlah = parseInt(row.find("input:eq(1)").val().replaceAll('.', ''));
        let diskon = parseFloat(row.find("input:eq(2)").val().replace(',', '.'));
        let total = 0;

        if (!nominal) {
            nominal = 0;
        }
        if (!jumlah) {
            jumlah = 0;
        }
        if (!diskon) {
            diskon = 0;
        }

        total = (nominal * jumlah) - ((nominal * jumlah) * diskon / 100);

        row.find("td:eq(4) span:eq(0)").html(total.toLocaleString('id-ID'));

        return total;
    }
</script>

<h6 class="font-weight-bold mb-1" style="color: #1c77d4;">Prospek Layanan</h6>
<div id="detail-prospek-layanan">
    <div class="table-responsive">
        <table class="table table-bordered">
            <thead class="bg-secondary text-white">
                <tr>
                    <th class="text-center align-middle">Produk/Layanan</th>
                    <th class="text-center align-middle" style="width: 140px;">Nominal</th>
                    <th class="text-center align-middle p-10.5px" style="width: 80px;">Jumlah<br>Produk</th>
                    <th class="text-center align-middle p-10.5px" style="width: 80px;">Diskon<br>(%)</th>
                    <th class="text-center align-middle" style="width: 150px;">Total</th>
                    <th class="text-center align-middle p-10.5px" style="width: 60px;">Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($layanan as $data) {
                ?>
                    <tr style="font-size: 12px">
                        <td class="p-10.5px">
                            <span data-id="<?= $data->id_product_m ?>"><?= $data->nama_product ?></span>
                            <select class="select2 form-control" style="width: 100%;font-size: 11px">
                                <option value="<?= $data->id_product_m ?>" selected><?= $data->nama_product ?></option>
                            </select>
                            <p class="alert-layanan mt-1 mb-0 text-left" style="display: none;font-size: 11px;"></p>
                        </td>
                        <td class="produk-nominal p-10.5px" style="width:140px;">
                            <span class="float-right">
                                <?= number_format($data->harga, 0, ',', '.'); ?>
                            </span>
                            <input type="text" class="form-control" value="<?= $data->harga ?>" placeholder="0" style="font-size: 11px" oninput="total_price(this)">
                        </td>
                        <td class="produk-nominal text-center p-10.5px" style="width:80px;">
                            <span><?= number_format($data->jumlah, 0, ',', '.'); ?></span>
                            <input type="text" class="form-control" value="<?= $data->jumlah ?>" placeholder="0" style="font-size: 11px" oninput="total_price(this)">
                        </td>
                        <td class="produk-diskon text-center p-10.5px" style="width:80px;">
                            <span><?= number_format($data->diskon, 2, ',', '.'); ?>%</span>
                            <input type="text" class="form-control" value="<?= number_format($data->diskon, 2, ',', '.'); ?>" placeholder="0" style="font-size: 11px" oninput="total_price(this)">
                        </td>
                        <td class="align-top p-10.5px">
                            <span class="float-right" data-total="<?= number_format($data->harga_total, 2, ',', '.'); ?>"><?= number_format($data->harga_total, 2, ',', '.'); ?></span>
                        </td>
                        <td class="p-10.5px align-top text-center" data-layanan="<?= $data->id_pipeline_layanan ?>" style="width: 70px;white-space:nowrap;">
                            <div>
                                <button class="btn btn-sm btn-link text-primary" onclick="save_product(this)" style="padding: 1px;font-size: medium;" title="<?= $this->lang->line('button_form_simpan') ?>"><i class="fa fa-check"></i></button>
                                <button class="btn btn-sm btn-link text-danger" onclick="cancel_product(this)" style="padding: 1px;font-size: medium;" title="<?= $this->lang->line('button_form_batal') ?>"><i class="fa fa-times"></i></button>
                            </div>
                            <div>
                                <button class="btn btn-sm btn-link text-warning" onclick="edit_product(this)" style="padding: 1px;font-size: medium;" title="EDIT"><i class="fa fa-edit"></i></button>
                                <button class="btn btn-sm btn-link text-danger" onclick="remove_product(this)" style="padding: 1px;font-size: medium;" title="<?= $this->lang->line('hapus') ?>"><i class="fa fa-trash"></i></button>
                            </div>
                        </td>
                    </tr>
                <?php
                } ?>
            </tbody>
            <tfoot>
                <tr>
                    <td class="p-10.5px">
                        <select class="select2 form-control" style="width: 100%;font-size: 11px"></select>
                        <p class="alert-layanan mt-1 mb-0 text-left" style="display: none;font-size: 11px;"></p>
                    </td>
                    <td class="produk-nominal p-10.5px" style="width:140px;">
                        <input type="text" class="form-control" placeholder="0" style="font-size: 11px" oninput="total_price(this)">
                    </td>
                    <td class="produk-nominal p-10.5px" style="width: 80px;">
                        <input type="text" class="form-control" placeholder="0" style="font-size: 11px" oninput="total_price(this)">
                    </td>
                    <td class="produk-diskon p-10.5px" style="width: 80px;">
                        <input type="text" class="form-control" placeholder="0" style="font-size: 11px" oninput="total_price(this)">
                    </td>
                    <td class="align-top" style="padding: 1.5rem 10.5px;">
                        <span class="float-right" style="font-size: 12px">0</span>
                    </td>
                    <td class="p-0 pt-1 text-center">
                        <button type="button" id="add_product" class="btn btn-link btn-sm" style="font-size: medium;" title="<?= strtoupper($this->lang->line('button_form_simpan')) ?>"><i class="fa fa-save"></i></button>
                    </td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>
