<style>
    .table_form th, .table_form td {
        vertical-align: middle;
        border-collapse: separate;
    }

    .table_form tbody tr td:first-child {
        position: sticky;
        left: 0;
        background-color: white;
        z-index: 2;
        border-right: 2px solid #ddd;
        min-width: 150px;
        max-width: 150px;
    }
    .table_form thead tr th:first-child {
        position: sticky;
        left: 0;
        background-color: #1c77d4;
        z-index: 3;
        border-right: 2px solid #ddd;
        min-width: 150px;
        max-width: 150px;
    }

    <?php if($this->fungsi->cek_adm_satu_grup() == false) : ?>
        .table_form tbody tr td:nth-child(2) {
            position: sticky;
            left: 150px;
            background-color: white;
            z-index: 2;
            border-right: 2px solid #ddd;
        }

        .table_form thead tr th:nth-child(2) {
            position: sticky;
            left: 150px;
            background-color: #1c77d4;
            color: white;
            z-index: 3;
            border-right: 2px solid #ddd;
        }
    <?php endif; ?>
</style>

<div class="header_form_target row align-items-center position-absolute">
    <div class="content-header-left col-md-6 col-12 mb-md-0 mb-1">
        <h5 id="header_form" class="dark-blue-color">Edit Target Tahunan</h5>
    </div>
    <div class="content-header-right col-md-6 col-12">
        <button type="button" class="btn btn-secondary pull-right ml-1 js-menu__close">
            <i class="fa fa-arrow-left"></i> <?= $this->lang->line('button_form_kembali') ?>
        </button>
    </div>
</div>

<div class="header_form_target row align-items-center position-absolute">
    <div class="content-header-left col-md-6 col-12 mb-md-0 mb-1">
        <h5 id="header_form" class="dark-blue-color"></h5>
    </div>
    <div class="content-header-right col-md-6 col-12">
        <button type="button" class="btn btn-secondary pull-right ml-1 js-menu__close">
            <i class="fa fa-arrow-left"></i> <?= $this->lang->line('button_form_kembali') ?>
        </button>
    </div>
</div>

<?php 
    if(!empty($data_group)){ 
        $total_seluruh_target   = $data_target['total_seluruh_target'][$tahun];
?>
        <div class="footer_button row position-absolute" style="bottom: 0;">
            <div class="col-md-11 align-self-center pr-3">
                <div id="message_t_tahunan" class="pull-right"></div>
            </div>
            <div class="col-md-1">
                <button type="button" class="btn btn-success ladda-button pull-right ml-1" data-style="zoom-in" onclick="simpan(this)">
                    <i class="fa fa-save"></i> <?= $this->lang->line('button_form_simpan') ?>
                </button>
            </div>
        </div>

        <div class="table-responsive d-inline-flex" style="margin-top: 60px;">
            <table class="table_form table table-striped table-bordered">
                <!-- TABLE HEADER -->
                <thead style="background-color: #1c77d4; color: white;">
                    <tr>
                        <th class="text-center">BULAN</th>
                        
                        <?php if($this->fungsi->cek_adm_satu_grup() == false) : ?>
                            <th class="text-center">TOTAL</th>
                        <?php endif; ?>

                        <?php
                            foreach($data_group AS $rows){
                                $nama_group    = $rows->kode_group. " - ". $rows->nama_group;
                        ?>
                                <th class="th_nama_group text-center text-uppercase"><?= $nama_group ?></th>
                        <?php } ?>
                    </tr>
                </thead>
                
                <tbody>
                    <!-- TABLE BODY -->
                    <?php 
                        for($i=1; $i <= 12; $i++) {
                            $id_bulan               = sprintf("%02d", $i);
                            $total_target_per_bulan = $data_target['total_target_per_bulan'][$tahun][$id_bulan];
                    ?>
                            <tr>
                                <td><?= $this->fungsi->konversi_bulan($i); ?></td>

                                <?php if($this->fungsi->cek_adm_satu_grup() == false) : ?>
                                    <td class="total_target_per_bulan text-right font-weight-bold" data-idbulan="<?= $id_bulan; ?>">
                                        <?= (!empty($total_target_per_bulan) ? number_format($total_target_per_bulan, 0, ", ", ".") : '0') ?>
                                    </td>
                                <?php endif; ?>

                                <?php
                                    foreach($data_group AS $rows){
                                        $nominal    = $data_target['data'][$rows->id_group_m][$tahun][$id_bulan]['nominal'];
                                        $nominal    = number_format($nominal, 0, ", ", ".")
                                ?>
                                        <td class="text-center">
                                            <input type="text" 
                                                id="nominal" 
                                                name="nominal" 
                                                class="form-control text-right"
                                                onkeyup="hitung_total(this)" 
                                                oninput="format_amount($(this))" 
                                                value="<?= $nominal ?>" 
                                                data-idbulan="<?= $id_bulan; ?>"
                                                data-id_group_m="<?= $rows->id_group_m; ?>"
                                            >
                                        </td>
                                <?php } ?>
                            </tr>
                    <?php 
                        } 
                    ?>

                    <!-- TABLE FOOTER -->
                    <tr>
                        <td class="text-uppercase" style="background-color: #1c77d4; color: white; text-wrap:nowrap">Grand Total</td>
                        
                        <?php if($this->fungsi->cek_adm_satu_grup() == false) : ?>
                            <td id="total_seluruh_target" class="text-uppercase font-weight-bold text-right" style="background-color: #ccedff;">
                                <?= (!empty($total_seluruh_target) ? number_format($total_seluruh_target, 0, ", ", ".") : '0') ?>
                            </td>
                        <?php endif; ?>

                        <?php
                            foreach($data_group AS $rows){
                                $total_nominal = $data_target['total_nominal'][$rows->id_group_m][$tahun];
                        ?>
                                <td class="total_tahunan font-weight-bold text-right" style="background-color: #ccedff;" data-id_group_m="<?= $rows->id_group_m; ?>">
                                    <?= (!empty($total_nominal) ? number_format($total_nominal, 0, ", ", ".") : '0') ?>
                                </td>
                        <?php } ?>
                    </tr>
                </tbody>

                <!-- <tfooter></tfooter> -->
            </table>
        </div>
<?php 
    }else{ 
?>
        <h3 class="mt-2">Silahkan buat group terlebih dahulu.</h3>
<?php 
    } 
?>

<script>
    // Document ready Function
    $(function() {
        $(".div_pembungkus_js_menu_context").css('height', 170);

        var widthDynamicContent = $(".table-responsive").outerWidth();
        var widthDynamicDrawer  = $("#drawer-content").outerWidth();
        if(widthDynamicContent > widthDynamicDrawer){
            $(".footer_button").css('width', (widthDynamicDrawer*103/100));
            $(".header_form_target").css('width', (widthDynamicDrawer*103/100));
        }else{
            $(".footer_button").css('width', (widthDynamicContent*103/100));
            $(".header_form_target").css('width', (widthDynamicContent*103/100));
        }

        var jumlahGroup         = "<?= COUNT($data_group) ?>";
        if(jumlahGroup > 2){
            $(".th_nama_group").css('width', "200px");
            $('input[name="nominal"]').css('width', "200px");
        }else{
            $(".th_nama_group").css('width', '');
            $('input[name="nominal"]').css('width', '');
        }
    });

     // Action Simpan
     function simpan(e){
        $('#message_t_tahunan').html("");
        var loading = Ladda.create(e);
        loading.start();

        var ttl_array_nominal = [];
        var array_id_group    = [];
        
        // Olah Array
        <?php 
            foreach($data_group AS $rows){    
        ?>
            var id_group_m = "<?= $rows->id_group_m ?>";
            array_id_group.push(id_group_m);

            var nominal       = $('input[name="nominal"][data-id_group_m="'+id_group_m+'"]');
            var array_nominal = [];

            for (let i = 0; i < nominal.length; i++) {
                array_nominal.push({
                    tahun : "<?= $tahun ?>",
                    bulan : nominal[i].getAttribute('data-idbulan'),
                    nominal: nominal[i].value,
                    id_group_m: id_group_m,
                });
            }

            ttl_array_nominal.push(...array_nominal);
        <?php 
            }
        ?>

        var param                   = {};
            param.ttl_array_nominal = ttl_array_nominal;
            param.array_id_group    = array_id_group;
            param.tahun             = "<?= $tahun ?>";

        $.ajax({
            type: 'POST',
            url: "<?= route('sales_activity.master.target.tahunan.save') ?>",
            data: param,
            dataType: 'JSON',
            success: function(result) {
                if (result.success == true) {
                    if(result.type == 'save'){
                        check_tambah_or_edit();
                    }
                }
                loading.stop();
                $('#message_t_tahunan').show();
                $('#message_t_tahunan').html(result.message);
            },
            error: function() {
                loading.stop();
                $('#message_t_tahunan').show();
                $('#message_t_tahunan').html('<font color="#eb3a28"><i class="fa fa-close(alias)">&nbsp;</i><strong><?= $this->lang->line('error') ?></strong></font>');
            }
        });
    }

    function hitung_total(e){
        // Total Target Tahunan per Group
        var id_group_m = $(e).attr('data-id_group_m');
        var nominal    = $('input[name="nominal"][data-id_group_m="'+id_group_m+'"]');
        var array_nominal = [];
        for (let i = 0; i < nominal.length; i++) {
            var v_nominal = replaceIdr(nominal[i].value);
            array_nominal.push(v_nominal);
        }

        var filteredArray = array_nominal.filter(function(value) {
            return value !== '';
        }).map(function(value) {
            return Number(value);
        });

        var total = filteredArray.reduce(function(sum, value) {
            return sum + value;
        }, 0);

        $('.total_tahunan[data-id_group_m="'+id_group_m+'"]').html(idr(total));

        <?php if($this->fungsi->cek_adm_satu_grup() == false) : ?>
            // Total Target Tahunan per Bulan
            var id_bulan            = $(e).attr('data-idbulan');
            var nominal_bulan       = $('input[name="nominal"][data-idbulan="'+id_bulan+'"]');
            var total_nominal_bulan = 0;

            for (let i = 0; i < nominal_bulan.length; i++) {
                var v_nominal_bulan      = replaceIdr(nominal_bulan[i].value);
                    total_nominal_bulan += v_nominal_bulan;
            }

            $('.total_target_per_bulan[data-idbulan="'+id_bulan+'"]').html(idr(total_nominal_bulan));

            // Total Seluruh Target
            var total_target_per_bulan = $('.total_target_per_bulan');
            var total_seluruh_target   = 0;

            for (let i = 0; i < total_target_per_bulan.length; i++) {
                var v_total_target_per_bulan  = replaceIdr(total_target_per_bulan[i].innerText);
                    total_seluruh_target     += v_total_target_per_bulan;
            }

            $('#total_seluruh_target').html(idr(total_seluruh_target));
        <?php endif; ?>
    }

    function idr(nStr){
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + '.' + '$2');
        }
        return x1 + x2;
    }

    function replaceIdr(str){
        if(str == ""){
            str = 0;
        }else{
            str = str.replace(/\./g,'')
        }

        return parseInt(str);
    }
</script>