<script>
    // dinamic card
    adjustCardWidths();
    $(function() {
        get_target_poin_harian_bulanan_karyawan();
        load_data("<?= date('Y-m') ?>", "all", "all", "all");

        $("#periode").inputmask({
            'alias': 'datetime',
            'inputFormat': 'mm-yyyy'
        });
        $("#periode").datepicker({
            format: "mm-yyyy",
            viewMode: "months",
            orientation: 'bottom',
            minViewMode: "months",
            autoclose: true,
            endDate: "today"
        }).change(function() {
            load_data(get_periode(), get_group(), get_pelanggan(), get_sales(), true);
        });

        $('#kanban_group').select2({
            placeholder: "Semua Group",
            allowClear: true,
            ajax: {
                url: '<?= route("sales_activity.kanban.list_group") ?>',
                dataType: 'json',
                delay: 250,
                processResults: function(data) {
                    return {
                        results: data
                    };
                },
                cache: false
            },
            minLength: 3
        }).on('change', function() {
            load_data(get_periode(), get_group(), get_pelanggan(), get_sales(), true);
        });

        $('#kanban_pelanggan').select2({
            placeholder: "Semua Pelanggan",
            allowClear: true,
            ajax: {
                url: '<?= route("sales_activity.kanban.list_pelanggan", ["kategori" => "all"]) ?>',
                dataType: 'json',
                delay: 250,
                processResults: function(data) {
                    return {
                        results: data
                    };
                },
                cache: false
            },
            minLength: 3
        }).on('change', function() {
            load_data(get_periode(), get_group(), get_pelanggan(), get_sales(), true);
        });

        $("#kanban_sales").select2({
            placeholder: "Semua Sales",
            allowClear: true,
            ajax: {
                url: '<?= route("sales_activity.kanban.list_sales") ?>',
                dataType: 'json',
                delay: 250,
                data: function(params) {
                    return {
                        search: params.term,
                        topic: "kanban",
                        range: 0,
                        start: get_periode()
                    };
                },
                processResults: function(data) {
                    return {
                        results: data
                    };
                },
                cache: false
            },
            minLength: 3
        }).on('change', function() {
            load_data(get_periode(), get_group(), get_pelanggan(), get_sales(), true);
        });
    })

    function get_periode() {
        let periode = $("#periode").val();
        if (!periode) {
            periode = "<?= date('Y-m') ?>";
        } else {
            const parts = periode.split("-");
            const result = parts[1] + "-" + parts[0];
            periode = result;
        }

        return periode;
    }

    function get_group() {
        return (!$("#kanban_group").val()) ? "all" : $("#kanban_group").val();
    }

    function get_pelanggan() {
        return (!$("#kanban_pelanggan").val()) ? "all" : $("#kanban_pelanggan").val();
    }

    function get_sales() {
        return (!$("#kanban_sales").val()) ? "all" : $("#kanban_sales").val();
    }

    function form_validation() {
        let result = true;
        let selector_scroll = "";

        const jenis_pelanggan = $("#form_kanban input[type='checkbox']:checked").val();
        if (!jenis_pelanggan) {
            $("#message").html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> <?= $this->lang->line('error_jenis_pelanggan_kosong') ?></font>");
            result = false;
        }

        <?php if ($this->level_user === '1' || $this->is_sales_admin === true || $this->is_sales_atasan === true) : ?>
            if (!$("#select_sales").val()) {
                let target = $("#select_sales").closest("div");
                error_form("select", target, "<?= $this->lang->line('error_pilih_sales_kosong') ?>", true);
                if (selector_scroll === "") {
                    selector_scroll = "#select_sales";
                }
                result = false;
            } else {
                let target = $("#select_sales").closest("div");
                error_form("select", target, '', false);
            }
        <?php endif; ?>

        if (jenis_pelanggan == "perusahaan") {
            if (!$("#select_pelanggan select").val()) {
                let target = $("#select_pelanggan");
                error_form("select", target, "<?= $this->lang->line('error_pilih_perusahaan_kosong') ?>", true);
                if (selector_scroll === "") {
                    selector_scroll = "#select_pelanggan select";
                }
                result = false;
            } else {
                let target = $("#select_pelanggan");
                error_form("select", target, "", false);
            }

            if (!$("#jenis_perusahaan select").val()) {
                let target = $("#jenis_perusahaan");
                error_form("select", target, "<?= $this->lang->line('error_pilih_jenis_perusahaan_kosong') ?>", true);
                if (selector_scroll === "") {
                    selector_scroll = "#jenis_perusahaan select";
                }
                result = false;
            } else {
                let target = $("#jenis_perusahaan");
                error_form("select", target, "", false);
            }

            if ($("#nama_pic input").val() == "") {
                let target = $("#nama_pic");
                error_form("input", target, "<?= $this->lang->line('error_nama_kosong') ?>", true);
                if (selector_scroll === "") {
                    selector_scroll = "#nama_pic input";
                }
                result = false;
            } else {
                let target = $("#nama_pic");
                error_form("input", target, "", false);
            }
        } else {
            if (!$("#select_pelanggan select").val()) {
                let target = $("#select_pelanggan");
                error_form("select", target, "<?= $this->lang->line('error_nama_kosong') ?>", true);
                if (selector_scroll === "") {
                    selector_scroll = "#select_pelanggan select";
                }
                result = false;
            } else {
                let target = $("#select_pelanggan");
                error_form("select", target, "", false);
            }
        }

        if (!$("#lead_source select").val()) {
            let target = $("#lead_source");
            error_form("select", target, "<?= $this->lang->line('error_pilih_lead_source_kosong') ?>", true);
            if (selector_scroll === "") {
                selector_scroll = "#lead_source select";
            }
            result = false;
        } else {
            let target = $("#lead_source");
            error_form("select", target, "", false);
        }

        if ($("#alamat_perusahaan input").val() == "") {
            let target = $("#alamat_perusahaan");
            error_form("input", target, "<?= $this->lang->line('error_alamat_kosong') ?>", true);
            if (selector_scroll === "") {
                selector_scroll = "#alamat_perusahaan input";
            }
            result = false;
        } else {
            let target = $("#alamat_perusahaan");
            error_form("input", target, "", false);
        }

        if (!$("#provinsi_perusahaan select").val()) {
            let target = $("#provinsi_perusahaan");
            error_form("select", target, "<?= $this->lang->line('error_provinsi') ?>", true);
            if (selector_scroll === "") {
                selector_scroll = "#provinsi_perusahaan select";
            }
            result = false;
        } else {
            let target = $("#provinsi_perusahaan");
            error_form("select", target, "", false);
        }

        if (!$("#kota_perusahaan select").val()) {
            let target = $("#kota_perusahaan");
            error_form("select", target, "<?= $this->lang->line('error_kota') ?>", true);
            if (selector_scroll === "") {
                selector_scroll = "#kota_perusahaan select";
            }
            result = false;
        } else {
            let target = $("#kota_perusahaan");
            error_form("select", target, "", false);
        }

        if ($("#telp_pic input").val() == "") {
            let target = $("#telp_pic");
            error_form("input", target, "<?= $this->lang->line('error_telp_kosong') ?>", true);
            if (selector_scroll === "") {
                selector_scroll = "#telp_pic input";
            }
            result = false;
        } else {
            let target = $("#telp_pic");
            error_form("input", target, "", false);
        }

        if ($("#title input").val() == "") {
            let target = $("#title");
            error_form("input", target, "<?= $this->lang->line('error_judul') ?>", true);
            if (selector_scroll === "") {
                selector_scroll = "#title input";
            }
            result = false;
        } else {
            let target = $("#title");
            error_form("input", target, "", false);
        }

        if (selector_scroll !== "") {
            scrollToElementWithOffset(selector_scroll, -30);
        }
        return result;
    }

    function error_form(form, element, message = '', error) {
        let target = element;
        if (form === "input") {
            if (error === true) {
                target.find(form).css("border", "1px solid red");
                target.find("p").html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> " + message + "</font>");
                target.find("p").show();
            } else {
                target.find(form).removeAttr("style");
                target.find("p").html("").hide();
            }
            return false;
        }
        if (form === "select") {
            if (error === true) {
                target.find(".select2-selection").css("border", "1px solid red");
                target.find("p").html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> " + message + "</font>");
                target.find("p").show();
            } else {
                target.find(".select2-selection").removeAttr("style");
                target.find("p").html("").hide();
            }
            return false;
        }
    }

    function scrollToElementWithOffset(selector, offset) {
        const element = document.querySelector(selector);
        if (element) {
            element.scrollIntoView();
            setTimeout(() => {
                const modalContent = document.querySelector('#modal_form');
                const newScrollPosition = modalContent.scrollTop + offset;
                modalContent.scrollTo({
                    top: newScrollPosition,
                    behavior: 'smooth'
                });
            }, 250);
        }
    }

    function adjustCardWidths() {
        const cards = document.querySelectorAll('#kanban_list_data .card');
        const containerWidth = document.querySelector('#kanban_list_data').parentElement.offsetWidth;
        const cardCount = cards.length;

        const percentWidth = <?= (100 / count($tahapan)) ?>;
        const percentWidthInPixels = (containerWidth * percentWidth) / 100;

        cards.forEach((card, index) => {
            if (percentWidthInPixels < 320) {
                card.style.width = '20rem';
            } else {
                card.style.width = `${percentWidth}%`;
                document.querySelector('#kanban_list_data').className = 'd-inline-flex w-100';
            }
        });
    }

    function load_data(periode, group = "all", pelanggan = "all", sales = "all", loading = false) {
        if (loading) {
            $("#periode").next("div").find("span").toggleClass("custom-loader");
            $("#periode").next("div").find("span > i").toggleClass("hidden");
        }
        $.get("<?= route('sales_activity.kanban.data', ['periode' => '" + periode + "', 'group' => '" + group + "', 'pelanggan' => '" + pelanggan + "', 'sales' => '" + sales + "']) ?>", function(data) {
            $("#kanban_list_data").html(data);
            screenUp(200);
            if (loading) {
                $("#periode").next("div").find("span").toggleClass("custom-loader");
                $("#periode").next("div").find("span > i").toggleClass("hidden");
            }
        });
    }
</script>

<style>
    #kanban_list_data ::-webkit-scrollbar {
        width: 0px;
    }

    .bg-lighter {
        background-color: #F5F7F9;
    }

    .sortable {
        min-height: 80vh;
    }

    .button-new-card {
        min-height: 25px;
    }

    .shadow-card {
        box-shadow: 0px 0px 2px lightgray;
    }

    .shadow-card:hover {
        box-shadow: 0px 0px 5px lightgray;
    }

    .py-05 {
        padding-bottom: 0.5rem;
        padding-top: 0.5rem;
    }

    .p-10\.5px {
        padding: 10.5px !important;
    }

    .cursor-move {
        cursor: move;
    }

    .task-lock {
        cursor: not-allowed;
    }

    .bg-task-lock {
        background-color: #e5e5ea !important;
    }

    /* Loading */
    .custom-loader {
        width: 25px;
        height: 25px;
        border-radius: 50%;
        border: 4px solid;
        border-color: #E4E4ED;
        border-right-color: #1c77d4;
        animation: s2 1s infinite linear;
    }

    @keyframes s2 {
        to {
            transform: rotate(1turn)
        }
    }

    /* Required Drawer CSS */
    .js-menu__context {
        /* background: rgba(0, 0, 0, 0.5); */
        left: 0;
        opacity: 0;
        position: absolute;
        top: 0;
        transition: opacity 0.5s, visibility 0.5s;
        visibility: hidden;
        width: 100%;
        height: 100%;
        border-radius: 0 15px 15px 0;
        z-index: 99;
    }

    .js-menu {
        color: #000;
        height: 100%;
        width: 100%;
        padding: 20px;
        margin: 0;
        background: #fff;
        overflow-y: auto;
        border-radius: 0 15px 15px 0;

        -webkit-overflow-scrolling: touch;
        -ms-overflow-style: -ms-autohiding-scrollbar;
        transition: background 0.5s, transform 0.5s;
    }

    .js-menu--left {
        -webkit-transform: translateX(-100%);
        transform: translateX(-100%);
    }

    .js-menu--right {
        -webkit-transform: translateX(100%);
        transform: translateX(100%);
        position: absolute;
        right: 0;
    }

    .js-menu__open {
        cursor: pointer;
    }

    .js-menu__close {
        cursor: pointer;
    }

    .js-menu__expanded {
        -webkit-transform: translateX(0);
        transform: translateX(0);
        visibility: visible;
        opacity: 1;
    }

    .icon_target_poin {
        border-radius: 10px;
        box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
        padding: 7px;
        flex: 0 0 auto;
        height: 45px;
        width: 45px;
    }
</style>

<div class="row align-items-center mt-1">
    <div class="content-header-left col-md-6 col-12 mb-md-0 mb-1">
        <label class="content-header-title" style="font-size: 16px"><?= $judul ?></label>
    </div>
    <div class="content-header-right col-md-6 col-12">
        <?php
            if($this->level_user != "1"):
        ?>
                <div class="target_poin_per_karyawan content-header-right">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="row">
                                <div class="col-md-2 mr-1">
                                    <div class="icon_target_poin" style="background-color:#007aff;">
                                        <img src="<?= $this->config->item('dir_assets') ?>images/icon/target_icon.png" style="width:30px;height:30px;">
                                    </div>
                                </div>
                                <div class="col-md-9">
                                    <label>Poin Anda Hari Ini</label><BR>
                                    <label id="target_poin_harian" class="font-weight-bold">0 / 0</label>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="row">
                                <div class="col-md-2 pl-0">
                                    <div class="icon_target_poin" style="background-color:#ff9500;">
                                        <img src="<?= $this->config->item('dir_assets') ?>images/icon/target_icon.png" style="width:30px;height:30px;">
                                    </div>
                                </div>
                                <div class="col-md-9">
                                    <label>Realisasi Poin Anda Bulan Ini</label><BR>
                                    <label id="target_poin_bulanan" class="font-weight-bold">0 / 0</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
        <?php
            endif;
        ?>
    </div>
</div>
<hr>

<div class="form-group pt-1">
    <div class="d-flex justify-content-between">
        <div class="d-flex flex-column">
            <h6>Periode</h6>
            <div class="input-group d-flex flex-row">
                <input type="text" id="periode" class="form-control" style="width: 100px" value="<?= date('m-Y') ?>" autocomplete="off" spellcheck="false" placeholder="Pilih Bulan-Tahun">
                <div class="input-group-append">
                    <label for="periode" class="input-group-text py-0 px-1" style="width: 55px">
                        <span class="m-auto"><i class="fa fa-calendar"></i></span>
                    </label>
                </div>
            </div>
        </div>
        <div class="<?= ($this->level_user === '1' || $this->is_sales_admin === true) ? 'w-75' : (($this->level_user !== '1' || $this->is_sales_admin === false || $this->is_sales_atasan === false) ? 'w-50' : 'w-50') ?>">
            <div class="d-flex flex-row">
                <?php if ($this->level_user === '1' || $this->is_sales_admin === true) : ?>
                    <div class="form-group w-100 mr-1">
                        <h6>Group</h6>
                        <select id="kanban_group" class="select2 form-control" style="width: 100%;"></select>
                    </div>
                <?php endif; ?>
                <div class="form-group w-100 mr-1">
                    <h6>Pelanggan</h6>
                    <select id="kanban_pelanggan" class="select2 form-control" style="width: 100%;"></select>
                </div>
                <?php if ($this->level_user === '1' || $this->is_sales_admin === true || $this->is_sales_atasan === true) : ?>
                    <div class="form-group w-100">
                        <h6>Sales</h6>
                        <select id="kanban_sales" class="select2 form-control" style="width: 100%;"></select>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<div class="w-100" style="overflow-x: auto;">
    <div id="kanban_list_data" class="d-inline-flex">
        <?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') {
                $classes     = '';
                $styles      = 'style="height: 80vh; overflow-x: hidden; overflow-y: auto; position: initial;"';
                $add_product = '
                <li class="loading-skeleton list-group-item button-new-card border-0 bg-lighter pt-1">
                    <label class="btn btn-link w-100 shadow-card rounded">Tambah Data</label>
                </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 class="loading-skeleton">
                        <label class="m-0" style="padding: 6px 8px">10</label>
                        <label class="m-0" style="padding: 4px 8px">100 M</label>
                    </div>
                </div>
                <ul class="list-group list-group-flush">
                    <?= $add_product ?>
                    <li class="loading-skeleton sortable list-group-item border-0 bg-lighter py-05 <?= $classes ?>" <?= $styles ?>>
                        <div class="cursor-move bg-white rounded shadow-card p-2 mb-1">
                            <div class="pull-right">
                                <span class="text-light position-relative" style="top: -10px;"><i class="fa fa-ellipsis-h"></i></span>
                            </div>
                            <label class="font-weight-bold my-1">Nama Perusahaan</label>
                            <div class="d-flex flex-column text-secondary">
                                <label><i style="width: 20px" class="fa fa-id-card mr-1"></i>Nama PIC</label>
                                <label><i style="width: 20px" class="fa fa-phone mr-1"></i>Telepon PIC</label>
                                <label><i style="width: 20px" class="fa fa-money mr-1"></i>100.000.000</label>
                                <label><i style="width: 20px" class="fa fa-th-large mr-1"></i>1 Layanan</label>
                                <label><i style="width: 20px" class="fa fa-calendar-o mr-1"></i>00-00-0000</label>
                            </div>
                        </div>
                    </li>
                </ul>
            </div>
        <?php
        }
        ?>
    </div>
</div>

<div class="js-menu__context">
    <div id="drawer" class="js-menu js-menu--right" style="overflow: hidden">
        <div class="d-flex flex-row justify-content-between mb-1">
            <label class="content-header-title align-self-center m-0" style="font-size: 16px">Detail Task</label>
            <button class="btn btn-secondary js-menu__close">
                <i class="fa fa-chevron-left"></i> <?= $this->lang->line('button_form_kembali') ?>
            </button>
        </div>
        <hr>
        <div id="drawer-content"></div>
    </div>
</div>
