<script type="text/javascript">
    // ACTION EDIT
    $(document).on('click', '.div_right_tahapan #btn_edit', function() {
        $(".btn_tambah_tahapan").prop("disabled", true);

        var data_stage = $(this).attr('data-stage');
        var actionDiv  = $(this).closest('.div_list_tahapan');
        
        if(data_stage == 'active'){
            var tahapan = $(".ul-list-tahapan .sortable-item-tahapan");
            if(tahapan.length > 1){
                actionDiv.find('.div_right_tahapan #btn_delete').hide();
            }
        }
        
        actionDiv.find('.div_right_tahapan #btn_edit').hide();
        actionDiv.find('.div_right_tahapan #btn_simpan').show();
        actionDiv.find('.div_right_tahapan #btn_batal').show();
        actionDiv.find('.div_right_tahapan #btn_warna').show();
        actionDiv.find('.div_left_tahapan #input_isi_tahapan').show();
        actionDiv.find('.div_left_tahapan #span_isi_tahapan').hide();
    });

    // ACTION BATAL
    $(document).on('click', '.div_right_tahapan #btn_batal', function() {
        $(".btn_tambah_tahapan").prop("disabled", false);
        $(".btn_delete_tahapan").prop("disabled", false);
        $(".btn_edit_tahapan").prop("disabled", false);

        var action_crud = $(this).attr('data-action-crud');
        var data_stage = $(this).attr('data-stage');
        var actionDiv  = $(this).closest('.div_list_tahapan');

        // mengembalikan warna background
        var prev_color = actionDiv.find('.div_right_tahapan #head_colorpicker').attr('data-prev-color');
        actionDiv.find('.div_left_tahapan div').css('background-color', prev_color);

        // mengembalikan warna text
        var checkLightDark = lightOrDark(prev_color);
        if(checkLightDark == "light"){
            actionDiv.find('.div_left_tahapan div').css('color', '#0e1217');
        }else{
            actionDiv.find('.div_left_tahapan div').css('color', '#FFFFFF');
        }

        if(action_crud == 'EDIT'){
            actionDiv.find('.div_right_tahapan #btn_edit').show();
            actionDiv.find('.div_right_tahapan #btn_simpan').hide();
            actionDiv.find('.div_right_tahapan #btn_batal').hide();
            actionDiv.find('.div_right_tahapan #btn_warna').hide();            
            actionDiv.find('.div_left_tahapan #span_isi_tahapan').show();
            actionDiv.find('.div_left_tahapan #input_isi_tahapan').hide();
            
            var isi_tahapan = actionDiv.find('.div_left_tahapan #span_isi_tahapan').text();
            actionDiv.find('.div_left_tahapan #input_isi_tahapan').val(isi_tahapan);

            if(data_stage == 'active'){
                var tahapan = $(".ul-list-tahapan .sortable-item-tahapan");
                if(tahapan.length > 1){
                    actionDiv.find('.div_right_tahapan #btn_delete').show();
                }
            }

        }else if(action_crud == 'SIMPAN'){
            $(this).closest('.sortable-item-tahapan').remove();
            active_stage_less_5();
        }else{
            alert('ERROR');
        }

        $(".ul-list-tahapan").sortable("enable");
    });

    // ACTION TAMBAH
    $(document).on('click', '.div_tambah_tahapan  #btn_tambah', function() {
        $(".ul-list-tahapan").sortable("disable");
        $(".btn_delete_tahapan").prop("disabled", true);
        $(".btn_edit_tahapan").prop("disabled", true);
        $(".btn_tambah_tahapan").prop("disabled", true);


        // cek apakah tahapan berjumlah 5
        var tahapan = $(".ul-list-tahapan .sortable-item-tahapan");
        if(tahapan.length >= 4){
            $('.row_tambah_tahapan').remove();
        }

        // start random color
        var name_colorpicker = $("input[name='name_colorpicker']");
        var array_color = [];
        for (let i = 0; i < name_colorpicker.length; i++) {
            array_color.push(name_colorpicker[i].value);
        }
        var new_color_bg = getRandomColor(array_color);

        var checkLightDark = lightOrDark(new_color_bg);
        if(checkLightDark == "light"){
            var new_color_text = "#0e1217";
        }else{
            var new_color_text = "#FFFFFF";
        }
        // end random color

        var newStage = `
                        <li class="sortable-item-tahapan" data-id="">
                            <div class="div_list_tahapan">
                                <div class="d-inline-flex justify-content-between w-100">
                                    <div class="div_left_tahapan pt-0 pb-1 w-100">
                                        <div class="d-flex justify-content-between align-items-center rounded pb-1 cursor-move" 
                                            style="background-color: ${new_color_bg}; color: ${new_color_text}">
                                                <div class="font-weight-bold mt-1 ml-1" style="width: 100%;">
                                                    <i class="fa fa-sort mr-2"></i>
                                                    <span id="span_isi_tahapan"  style="display:none;">Stage Title</span>
                                                    <input type="text" id="input_isi_tahapan" class="input_isi_tahapan" 
                                                        value="Stage Title" 
                                                        style="color: ${new_color_text}; border-color: ${new_color_text}">
                                                </div>
                                        </div>
                                    </div>
                                    <div class="div_right_tahapan p-0 pb-1 px-1 d-flex align-items-center justify-content-end" style="font-size: 12px; !important">
                                        <a id="btn_delete" class="btn_delete_tahapan text-nowrap text-danger font-weight-bold mr-3" data-stage="active"
                                            data-id_tahapan_m="" style="display:none">
                                                    <i  class="fa fa-trash (alias)"></i> <?= ucwords(strtolower($this->lang->line('button_form_hapus'))) ?>
                                        </a>
                                        <a id="btn_edit" class="btn_edit_tahapan text-nowrap text-secondary font-weight-bold" data-stage="active" style="display:none">
                                            <i  class="fa fa-edit (alias)"></i> <?= ucwords(strtolower($this->lang->line('button_form_perbarui'))) ?>
                                        </a>
                                        <a id="btn_warna" class="text-secondary text-nowrap font-weight-bold mr-3">
                                            <input id="head_colorpicker" type="color" class="colorpicker align-middle" name="name_colorpicker" list="colors" style="width:13px; height:13px;" onchange="set_color(this)" value="${new_color_bg}" data-prev-color="${new_color_bg}">
                                            <?= $this->lang->line('warna') ?>
                                        </a>
                                        <a id="btn_batal" class="text-danger text-nowrap font-weight-bold mr-3" data-stage="active" data-action-crud="SIMPAN">
                                            <i  class="fa fa-close (alias)"></i> <?= ucwords(strtolower($this->lang->line('button_form_batal'))) ?>
                                        </a>
                                        <a id="btn_simpan" class="text-primary text-nowrap font-weight-bold" data-stage="active" data-action-crud="SIMPAN"
                                            data-id_tahapan_m="">
                                                    <i  class="fa fa-save (alias)"></i> <?= ucwords(strtolower($this->lang->line('button_form_simpan'))) ?>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </li>
                    `;

        $('.ul-list-tahapan').append(newStage);
    });

    // ACTION SIMPAN
    $(document).on('click', '.div_right_tahapan #btn_simpan', function() {
        var action_crud  = $(this).attr('data-action-crud');
        var data_stage  = $(this).attr('data-stage');
        var id_tahapan_m = $(this).attr('data-id_tahapan_m');

        var actionDiv   = $(this).closest('.div_list_tahapan');
        var isi_tahapan = actionDiv.find('.div_left_tahapan #input_isi_tahapan').val();
        var warna       = actionDiv.find('.div_left_tahapan div').css('background-color');
        var warna_text  = actionDiv.find('.div_left_tahapan div input').css('color');

        var param              = {};
            param.action_crud  = action_crud;
            param.id_tahapan_m = id_tahapan_m;
            param.isi_tahapan  = isi_tahapan;
            param.warna        = rgbToHex(warna);
            param.warna_text   = rgbToHex(warna_text);

        $.ajax({
            type: 'POST',
            url: "<?= route('sales_activity.master.tahapan.save') ?>",
            data: param,
            dataType: 'JSON',
            success: function(result) {
                if (result.success == true) {
                    if(data_stage == "active"){
                        var tahapan = $(".ul-list-tahapan .sortable-item-tahapan");
                        if(tahapan.length > 1){
                            actionDiv.find('.div_right_tahapan #btn_delete').show();
                        }else{
                        }
                    }

                    if(result.type == 'save'){
                        actionDiv.closest('li').attr('data-id', result.id); //id untuk li
                        actionDiv.find('.div_right_tahapan #btn_simpan').attr('data-id_tahapan_m', result.id_md5); //id attr untuk button simpan
                        actionDiv.find('.div_right_tahapan #btn_delete').attr('data-id_tahapan_m', result.id_md5); //id attr untuk button hapus
                        actionDiv.find('.div_right_tahapan #btn_batal').attr('data-action-crud', "EDIT");
                        actionDiv.find('.div_right_tahapan #btn_simpan').attr('data-action-crud', "EDIT");
                        $(".btn_edit_tahapan").prop("disabled", false);
                        active_stage_not_only_1();
                    }
                    
                    // action show hide
                    actionDiv.find('.div_left_tahapan #input_isi_tahapan').hide();
                    actionDiv.find('.div_left_tahapan #span_isi_tahapan').text(isi_tahapan).show();
                    actionDiv.find('.div_right_tahapan #btn_edit').show();
                    actionDiv.find('.div_right_tahapan #btn_simpan').hide();
                    actionDiv.find('.div_right_tahapan #btn_batal').hide();
                    actionDiv.find('.div_right_tahapan #btn_warna').hide();
                    
                    var prev_color = actionDiv.find('.div_right_tahapan #head_colorpicker').attr('data-prev-color', warna);    // replace attr prev color
                    $(".ul-list-tahapan").sortable("enable");   // enable sortable
                    $(".btn_tambah_tahapan").prop("disabled", false);
                    $(".btn_delete_tahapan").prop("disabled", false);
                    
                    // alert modal
                    showMsg(result.message);
                }
            },
            error: function() {
                // alert modal
                showMsg("<?= $this->lang->line('error') ?>");
            }
        });        
    });

    // ACTION CLICK BUTTON WARNA
    $(document).on('click', '.div_right_tahapan #btn_warna', function() {
        $(this).find('#head_colorpicker').click();
    });
    
    // MODAL ALERT HAPUS
    $(document).on('click', '.btn_delete_tahapan', function() {
        var id_tahapan_m = $(this).attr('data-id_tahapan_m');
        var status_hapus = $(this).attr('data-status_hapus');
        $("#modal_hapus #id_tahapan_m").val(id_tahapan_m);
        $(".title").text("Apakah Anda ingin menghapus data ini?");
        
        if(status_hapus == "TIDAK"){
            $("#modal_hapus .card-body").show();
            $("#modal_hapus .card-body #div_status_hapus_tidak").show();
            $("#modal_hapus .card-footer").hide();
        }else{
            $("#modal_hapus .card-body").hide();
            $("#modal_hapus .card-footer").show();
            $(".btn_hapus").removeClass("btn_hapus").addClass("btn_hapus_tahapan btn btn-danger");
        }
            
        $('#modal_hapus').modal('show');
    });
    
    // ACTION HAPUS
    $(document).on('click', '.btn_hapus_tahapan', function() {
        var id_tahapan_m = $("#modal_hapus #id_tahapan_m").val();

        var loading = Ladda.create(this);
        loading.start();
    
        var param = {};
        param.id_tahapan_m = id_tahapan_m;
    
        $.ajax({
            type: 'POST',
            url: "<?= route('sales_activity.master.tahapan.delete') ?>",
            data: param,
            dataType: 'JSON',
            success: function(result) {
                var elemen = $('.btn_delete_tahapan[data-id_tahapan_m="'+id_tahapan_m+'"]');
                elemen.closest('.sortable-item-tahapan').remove();
                active_stage_only_1();
                active_stage_less_5();

                $("#modal_hapus .card-body").hide();
                $("#modal_hapus .card-footer").hide();
                $("#modal_hapus .title").html(result.message.replace("009900", "FFFFFF"));
                setTimeout(function() {
                    $('#modal_hapus').modal('hide');
                }, 1000);
                loading.stop();
            },
            error: function() {
                loading.stop();
                $("#modal_hapus .card-body").hide();
                $("#modal_hapus .card-footer").hide();
                $("#modal_hapus .title").html('<font color="#eb3a28"><i class="fa fa-close(alias)">&nbsp;</i><strong><?= $this->lang->line('error') ?></strong></font>');
                setTimeout(function() {
                    $('#modal_hapus').modal('hide');
                }, 3000);
            }
        });
    });

    // ACTION CHANGE COLOR PICKER
    function set_color(e){
        $(e).closest('div').prev().find('div').css('background-color', e.value);

        var checkLightDark = lightOrDark(e.value);
        if(checkLightDark == "light"){
            $(e).closest('div').prev().find('div').css('color', '#0e1217');
            $(e).closest('div').prev().find('div').find('input').css({
                'color': '#0e1217',
                'border-color': '#0e1217'
            });
        }else{
            $(e).closest('div').prev().find('div').css('color', '#FFFFFF');
            $(e).closest('div').prev().find('div').find('input').css({
                'color': '#FFFFFF',
                'border-color': '#FFFFFF'
            });
        }
    }

    function active_stage_only_1(){
        var tahapan = $(".ul-list-tahapan .sortable-item-tahapan");
        if(tahapan.length <= 1){
            var id_tahapan_1 = tahapan[0].getAttribute('data-id');
            var li_tahapan_1 = $('.sortable-item-tahapan[data-id="'+id_tahapan_1+'"]');
            li_tahapan_1.find('.div_right_tahapan #btn_delete').hide();
        }
    }

    function active_stage_not_only_1(){
        var tahapan = $(".ul-list-tahapan .sortable-item-tahapan");
        if(tahapan.length == 2){
            var id_tahapan_1 = tahapan[0].getAttribute('data-id');
            var li_tahapan_1 = $('.sortable-item-tahapan[data-id="'+id_tahapan_1+'"]');
            li_tahapan_1.find('.div_right_tahapan #btn_delete').show();
        }
    }

    function active_stage_less_5(){
        var tahapan = $(".ul-list-tahapan .sortable-item-tahapan");
        if(tahapan.length <= 4){
            if ($(".row_tambah_tahapan").length == 0) {
                var row_tambah_tahapan = `
                                            <div id="btn_tambah" class="row row_tambah_tahapan btn_tambah_tahapan" style="cursor:pointer;">
                                                <div class="col-md-12">
                                                    <div class="d-flex justify-content-center align-items-center rounded pb-1 border border-dashed text-center">
                                                        <a class="text-secondary font-weight-bold mt-1">
                                                            <i  class="fa fa-plus (alias)"></i> Stage Title
                                                        </a>
                                                    </div>
                                                </div>
                                            </div>
                                    `;
    
                $('.div_tambah_tahapan').append(row_tambah_tahapan);
            }
        }
    }

    function lightOrDark(color) {
        // Variables for red, green, blue values
        var r, g, b, hsp;

        // Check the format of the color, HEX or RGB?
        if (color.match(/^rgb/)) {
            // If RGB --> store the red, green, blue values in separate variables
            color = color.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/);
            
            r = color[1];
            g = color[2];
            b = color[3];
        } else {
            // If hex --> Convert it to RGB: http://gist.github.com/983661
            color = +("0x" + color.slice(1).replace( 
            color.length < 5 && /./g, '$&$&'));

            r = color >> 16;
            g = color >> 8 & 255;
            b = color & 255;
        }

        // HSP (Highly Sensitive Poo) equation from http://alienryderflex.com/hsp.html
        hsp = Math.sqrt(
        0.299 * (r * r) +
        0.587 * (g * g) +
        0.114 * (b * b)
        );

        // Using the HSP value, determine whether the color is light or dark
        if (hsp>200.5) {
            return 'light';
        } else {
            return 'dark';
        }
    }

    function rgbToHex(rgb) {
        // Ambil nilai RGB dari string 'rgb(142, 142, 147)'
        var rgbValues = rgb.match(/\d+/g);

        // Konversi setiap komponen RGB menjadi nilai hex
        var r = parseInt(rgbValues[0]).toString(16).padStart(2, '0');
        var g = parseInt(rgbValues[1]).toString(16).padStart(2, '0');
        var b = parseInt(rgbValues[2]).toString(16).padStart(2, '0');

        return `#${r}${g}${b}`.toUpperCase(); // Hasilkan warna dalam format hex
    }

    function getRandomColor(array_color) {
        var letters = '0123456789ABCDEF';
        var color;
        
        // Loop hingga mendapatkan warna yang tidak ada dalam array_color
        do {
            color = '#';
            for (var i = 0; i < 6; i++) {
                color += letters[Math.floor(Math.random() * 16)];
            }
        } while (array_color.includes(color)); // Cek apakah warna sudah ada di array

        return color;
    }
</script>