<script>
    // dinamic card
    adjustCardWidths();
    $(function() {
        $("#btn_tambah").on("click", function() {
            $("#tampil_form").load("<?= route("sales_activity.kanban.form") ?>", function() {
                $("#modal_form .modal-dialog").addClass("modal-lg");
                $("#modal_form").modal("show");
                $(".title").text("<?= $this->lang->line('title_form_tambah_data') ?>");
                $("#btn_submit").addClass("btn btn-primary");
                $("#btn_submit").html("<i class='fa fa-save'></i> <?= $this->lang->line('button_form_simpan') ?>");
                $("#btn_new_input").hide();

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

                    var valid = form_validation();
                    if (!valid) {
                        return false;
                    }

                    loading.start();

                    var param = {};
                    param.sales = $("#select_sales").val();
                    param.jenis_pelanggan = $("#form_kanban input[type='checkbox']:checked").val();
                    param.pelanggan = $("#select_pelanggan select").val();
                    param.jenis_perusahaan = $("#jenis_perusahaan select").val();
                    param.lead_source = $("#lead_source select").val();
                    param.alamat_perusahaan = $("#alamat_perusahaan textarea").val();
                    param.provinsi_perusahaan = $("#provinsi_perusahaan select").val();
                    param.kecamatan_perusahaan = $("#kecamatan_perusahaan select").val();
                    param.kelurahan_perusahaan = $("#kelurahan_perusahaan select").val();
                    param.kota_perusahaan = $("#kota_perusahaan select").val();
                    param.nama_pic = $("#nama_pic input").val();
                    param.email_pic = $("#email_pic input").val();
                    param.telp_pic = $("#telp_pic input").val();
                    param.title = $("#title input").val();
                    param.keterangan = $("#keterangan textarea").val();

                    param.produk = param.produk || [];
                    $("#prospek_layanan tbody tr").each(function() {
                        const id = $(this).find("td:eq(0) select").val();
                        const nominal = $(this).find("td:eq(1) input").val();
                        const jumlah = $(this).find("td:eq(2) input").val();
                        const diskon = $(this).find("td:eq(3) input").val();

                        param.produk.push([id, nominal, jumlah, diskon]);
                    });

                    $.ajax({
                        type: 'POST',
                        url: "<?= route('sales_activity.kanban.save_pipeline') ?>",
                        data: param,
                        dataType: 'JSON',
                        beforeSend: function() {
                            hide_product_form();
                            show_product_data();
                            disable_form("#form_kanban", ["input", "textarea", "select", "button"], true);
                        },
                        success: function(result) {
                            if (result.success == true) {
                                disable_form("#form_kanban", ["input", "textarea", "select", "button"], true);
                                $('#btn_submit').hide();
                                $('#btn_new_input').show();
                                load_data(get_periode(), get_group(), get_pelanggan(), get_sales());
                            } else {
                                disable_form("#form_kanban", ["input", "textarea", "select", "button"], false);
                            }
                            loading.stop();
                            $('#message').show();
                            $('#message').html(result.message);
                        },
                        error: function() {
                            loading.stop();
                            disable_form("#form_kanban", ["input", "textarea", "select", "button"], false);
                            $('#message').show();
                            $('#message').html('<font color="#eb3a28"><i class="fa fa-close (alias)">&nbsp;</i><strong>Gagal : Terjadi Kesalahan</strong></font>');
                        }
                    });
                });
            });
        });

        $("<?= implode(',', $id_tahapan) ?>").sortable({
            scroll: false,
            cancel: ".list-group-item .task-lock",
            connectWith: ".list-group-item",
            cursor: "move",
            receive: function(e, ui) {
                var jenis = $(e.target).data("jenis");
                var tahapan_sesudah = e.target.id;
                var id_pipeline = $(ui.item).find("div [data-id]").data("id");
                if (["wont", "lost"].includes(jenis)) {
                    $(ui.item).find(".badge:eq(0)").html("<?= $this->lang->line('pengajuan') ?>");
                    $(ui.item).find(".badge:eq(0)").addClass("badge-warning");
                    $(ui.item).find("a").toggleClass("custom-loader");
                    $(ui.item).find("a > i").toggleClass("hidden");
                    $("#tampil_form").load("<?= route("sales_activity.kanban.form", ['jenis' => '" + jenis + "', 'id_pipeline' => '" + id_pipeline + "']) ?>", function() {
                        $("#modal_form .modal-dialog").addClass("modal-lg");
                        $("#modal_form").modal("show");

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

                            var param = {};
                            param.tahapan_sesudah = tahapan_sesudah;
                            param.id_pipeline = id_pipeline;
                            param.action = "move";
                            param.periode = get_periode();
                            param.keterangan = $("#form_kanban #keterangan textarea").val();

                            $.ajax({
                                type: 'POST',
                                url: "<?= route('sales_activity.kanban.update_pipeline') ?>",
                                data: param,
                                dataType: 'JSON',
                                beforeSend: function() {
                                    loading.start();
                                    disable_form("#form_kanban", ["input", "textarea", "select", "button"], true);
                                },
                                success: function(result) {
                                    loading.stop();
                                    if (result.success == true) {
                                        showMsg(result.message);
                                        load_data(get_periode(), get_group(), get_pelanggan(), get_sales());
                                    } else {
                                        disable_form("#form_kanban", ["input", "textarea", "select", "button"], false);
                                        $('#message').show();
                                        $('#message').html(result.message);
                                    }
                                },
                                error: function() {
                                    loading.stop();
                                    disable_form("#form_kanban", ["input", "textarea", "select", "button"], false);
                                    $('#message').show();
                                    $('#message').html('<font color="#eb3a28"><i class="fa fa-close (alias)">&nbsp;</i><strong>Gagal : Terjadi Kesalahan</strong></font>');
                                }
                            });
                        });
                    });
                } else {
                    var param = {};
                    param.tahapan_sesudah = tahapan_sesudah;
                    param.id_pipeline = id_pipeline;
                    param.action = "move";
                    param.periode = get_periode();

                    $.ajax({
                        type: 'POST',
                        url: "<?= route('sales_activity.kanban.update_pipeline') ?>",
                        data: param,
                        dataType: 'JSON',
                        beforeSend: function() {
                            $(ui.item).find("a").toggleClass("custom-loader");
                            $(ui.item).find("a > i").toggleClass("hidden");
                        },
                        success: function(result) {
                            if (result.success == false) {
                                showMsg(result.message, true, 2000);
                                $(ui.item).find("a").toggleClass("custom-loader");
                                $(ui.item).find("a > i").toggleClass("hidden");
                            }
                            load_data(get_periode(), get_group(), get_pelanggan(), get_sales());
                        },
                        error: function() {
                            showMsg('error', false);
                            $(ui.item).find("a").toggleClass("custom-loader");
                            $(ui.item).find("a > i").toggleClass("hidden");
                            load_data(get_periode(), get_group(), get_pelanggan(), get_sales());
                        }
                    });
                }
            }
        }).disableSelection();

        $('.js-menu__open').on('touchend click', function() {
            var menu = $(this).attr('data-menu');

            $(menu).toggleClass('js-menu__expanded');
            $(menu).parent().toggleClass('js-menu__expanded');
        });

        $('.js-menu__context, .js-menu__close').on('touchend click', function(event) {
            if ($(event.target).hasClass('js-menu__context') || $(event.target).hasClass('js-menu__close')) {
                $('.js-menu__expanded').removeClass('js-menu__expanded');
            }
        });

        $("#kanban_list_data .dropdown-item").on("click", function() {
            const action = $(this).attr("data-action");
            const kategori = $(this).attr("data-kategori");
            const id = $(this).closest("div").data("id");
            option_task(id, action, kategori, get_periode(), this);
        })
    });

    function option_task(id, action, kategori, periode, e = '') {
        if (action === "detail") {
            $.get("<?= route('sales_activity.kanban.option_task', ['id' => '" + id + "', 'action' => '" + action + "']) ?>", function(data) {
                $("#drawer-content").html(data);
                screenUp(200);
            });
        } else if (action === "move_month") {
            $("#modal_form .modal-dialog").removeClass("modal-lg");
            $("#tampil_form").load("<?= route('sales_activity.kanban.option_task', ['id' => '" + id + "', 'action' => '" + action + "', 'periode' => '" + periode + "']) ?>", function() {
                $("#modal_form").modal("show");
                $("#nama_tahapan").html($(e).data("tahapan"));
            });
        } else {
            let route = "";
            if (action === "hapus") {
                route = "<?= route('sales_activity.kanban.delete_pipeline') ?>";
            } else if (action === "batal") {
                route = "<?= route('sales_activity.kanban.update_pipeline') ?>";
            }
            $("#modal_form .modal-dialog").removeClass("modal-lg");
            $("#tampil_form").load("<?= route('sales_activity.kanban.option_task', ['id' => '" + id + "', 'action' => '" + action + "']) ?>", function() {
                $("#modal_form").modal("show");
                $("#modal_form #btn_submit").on("click", function(e) {
                    e.preventDefault();
                    var loading = Ladda.create(this);

                    loading.start();

                    var param = {};
                    param.id_pipeline = id;
                    param.action = action;
                    param.periode = periode;
                    param.kategori = kategori;

                    $.ajax({
                        type: 'POST',
                        url: route,
                        data: param,
                        dataType: 'JSON',
                        success: function(result) {
                            loading.stop();
                            if (result.success == true) {
                                showMsg(result.message);
                                load_data(get_periode(), get_group(), get_pelanggan(), get_sales());
                            } else {
                                showMsg(result.message, true, 2000);
                            }
                        },
                        error: function() {
                            loading.stop();
                            showMsg('error', false);
                        }
                    });
                });
            });
        }
    }

    function disable_form(id, list, status) {
        list.forEach(function(e) {
            $(id + " " + e).prop("disabled", status);
        });
    }
</script>

<?php
foreach ($tahapan as $tahap) {
    $add_product = '';
    $classes     = 'pt-1';
    $styles      = 'style="height: 90vh; overflow-x: hidden; overflow-y: auto; position: initial;"';
    if ($tahap->jenis === 'incoming' && $periode === date('Y-m')) {
        $classes     = '';
        $styles      = 'style="height: 80vh; overflow-x: hidden; overflow-y: auto; position: initial;"';
        $add_product = '
            <li class="list-group-item button-new-card border-0 bg-lighter pt-1">
                <button id="btn_tambah" class="btn btn-link bg-white text-secondary w-100 shadow-card rounded" type="button"><span class="badge badge-pill badge-primary mr-1"><i class="fa fa-plus" style="padding: 2px 1px"></i></span> ' . $this->lang->line('button_tambah_data') . '</button>
            </li>
        ';
    }
?>
    <div class="card mr-1">
        <div class="card-header rounded-top p-1 text-white font-weight-bold d-flex justify-content-between align-items-center" <?= 'style="background-color: ' . $tahap->warna . '"' ?>>
            <span style="font-size: 16px;<?= 'color:' . $tahap->warna_text ?>"><?= $tahap->nama ?></span>
            <div>
                <span class="badge badge-pill bg-white text-secondary font-weight-bold" style="padding: 8px 12px"></span>
                <span class="badge badge-pill bg-white text-secondary font-weight-bold" style="padding: 8px 12px"></span>
            </div>
        </div>
        <ul class="list-group list-group-flush">
            <?= $add_product ?>
            <li id="<?= $tahap->id_tahapan_m ?>" data-jenis="<?= $tahap->jenis ?>" class="sortable list-group-item border-0 bg-lighter py-05 <?= $classes ?>" <?= $styles ?>>
                <?php
                $total_task  = 0;
                $total_harga = 0;
                foreach ($list_kanban[$tahap->id_tahapan_m] as $data) {
                    if (($data['tahun'] . '-' . $data['bulan']) === date('Y-m')) {
                        $task_lock = 'bg-white cursor-move';
                    } else {
                        $task_lock = 'bg-white task-lock';
                    }
                    $task_action          = '';
                    if ($data['id_karyawan'] == $this->id_karyawan) {
                        if ($data['status'] == 'pengajuan') {
                            if (empty($data['tahapan_sebelum_id'])) {
                                $task_lock   = 'task-lock bg-task-lock';
                                $task_action = '<a class="dropdown-item" href="javascript:void(0)" data-action="hapus">Hapus data</a>';
                            } else {
                                if ($data['kategori'] === 'move') {
                                    $task_lock = 'bg-white task-lock';
                                }
                                $task_action = '<a class="dropdown-item" href="javascript:void(0)" data-action="batal" data-kategori="' . $data['kategori'] . '">Batalkan pengajuan</a>';
                            }
                        } elseif ($data['status'] == 'approve' && in_array($tahap->jenis, ['wont', 'lost'])) {
                            $task_lock = 'bg-white task-lock';
                        }
                    } else {
                        $task_lock = 'bg-white task-lock';
                    }

                    if (!in_array($tahap->jenis, ['wont', 'lost']) && $data['status'] == 'approve' && $periode !== date('Y-m')) {
                        $task_action .= '<a class="dropdown-item" href="javascript:void(0)" data-tahapan="' . $data['tahapan_sesudah_nm'] . '" data-action="move_month">Pindah bulan</a>';
                    }
                ?>
                    <div class="rounded shadow-card p-2 mb-1 <?= $task_lock ?>">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <?php if ($data['status'] == 'pengajuan') : ?>
                                    <span class="badge badge-warning badge-pill"><?= $this->lang->line('pengajuan') ?></span>
                                <?php elseif ($data['status'] == 'approve') : ?>
                                    <span class="badge badge-success badge-pill"><?= $this->lang->line('disetujui') ?></span>
                                <?php endif; ?>
                                <?php if ($data['kategori'] == 'move') : ?>
                                    <?php
                                    $get_periode   = substr(substr($data['id_pindah_bulan'], strlen($this->id_company)), 0, 6);
                                    $year          = substr($get_periode, 0, 4);
                                    $month         = substr($get_periode, -2);
                                    $compiled_date = $year . '-' . $month . '-01';
                                    ?>
                                    <span class="badge badge-light badge-pill">Data <?= ($this->code_lang == 'id') ? indo_date(strtotime($compiled_date), 'F  Y') : date('F  Y ', strtotime($compiled_date)) ?></span>
                                <?php endif; ?>
                            </div>
                            <div>
                                <div class="pull-right">
                                    <div class="btn-group">
                                        <a href="javascript:void(0)" class="text-light position-relative" style="top: -10px;" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i class="fa fa-ellipsis-h"></i></a>
                                        <div class="dropdown-menu" data-id="<?= $data['id_pipeline_main'] ?>">
                                            <a class="dropdown-item js-menu__open" data-menu="#drawer" href="javascript:void(0)" data-action="detail">Detail</a>
                                            <?= $task_action ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <h6 class="font-weight-bold my-1 js-menu__open btn-link" onclick="$(this).prev().find('.js-menu__open').click()"><?= $data['nama_perusahaan'] ?></h6>
                        <table class="w-100">
                            <?php if ($data['id_karyawan'] == $this->id_karyawan) : ?>
                                <tr class="align-top" title="PIC">
                                    <td class="p-0" style="width: 20px"><i class="fa fa-id-card mr-1"></i></td>
                                    <td class="p-0"><?= $data['pic_nama'] ?></td>
                                </tr>
                                <tr class="align-top">
                                    <td class="p-0" style="width: 20px"><i class="fa fa-phone mr-1"></i></td>
                                    <td class="p-0"><?= $data['pic_telp'] ?></td>
                                </tr>
                            <?php else: ?>
                                <tr class="align-top" title="Sales">
                                    <td class="p-0" style="width: 20px"><i class="fa fa-user mr-1"></i></td>
                                    <td class="p-0"><?= $data['sales_nama'] ?></td>
                                </tr>
                            <?php endif; ?>
                            <tr class="align-top">
                                <td class="p-0" style="width: 20px"><i class="fa fa-money mr-1"></i></td>
                                <td class="p-0"><?= number_format($data['harga'], 0, ',', '.') ?></td>
                            </tr>
                            <tr class="align-top">
                                <td class="p-0" style="width: 20px"><i class="fa fa-th-large mr-1"></i></td>
                                <td class="p-0"><?= $data['layanan'] ?> Layanan</td>
                            </tr>
                            <tr class="align-top">
                                <td class="p-0" style="width: 20px"><i class="fa fa-database mr-1"></i></td>
                                <td class="p-0"><?= $data['nama_lead_source'] ?: '-' ?></td>
                            </tr>
                            <tr class="align-top">
                                <td class="p-0" style="width: 20px"><i class="fa fa-calendar-o mr-1"></i></td>
                                <td class="p-0"><?= timespan(strtotime($data['tgl_update']), time(), 1) . ' ' . $this->lang->line('yang_lalu') ?></td>
                            </tr>
                        </table>
                    </div>
                <?php
                    $total_task++;
                    $total_harga += $data['harga'];
                }
                ?>
                <script>
                    $("#<?= $tahap->id_tahapan_m ?>").closest(".card").find(".badge:eq(0)").text("<?= $total_task ?>");
                    // total_harga = new Intl.NumberFormat("<?= $this->code_lang . '-' . strtoupper($this->code_lang) ?>", {
                    //     notation: "compact",
                    //     compactDisplay: "short",
                    // }).format(<?= $total_harga ?>);
                    $("#<?= $tahap->id_tahapan_m ?>").closest(".card").find(".badge:eq(1)").text("<?= number_format($total_harga, 0, ',', '.') ?>");
                </script>
            </li>
        </ul>
    </div>
<?php
}
?>
