<style>
    .div_auto_scroll {
        overflow-x: auto; 
        overflow-y: hidden;
        background-color: #f2f2f7;
        border-radius: 10px;
        margin-top: 60px;
        border: 2px solid black;
    }
</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>

<?php if(!empty($data_group)){ ?>
    <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="div_auto_scroll d-inline-flex p-2">
        <!-- BULAN -->
        <div style="width:100px">
            <div class="row">
                <label class="font-weight-bold align-self-middle">BULAN</label>
            </div>

            <?php for($i=1; $i <= 12; $i++) {?>
                <div class="row mt-2" style="height: 35px;">
                    <label><?= $this->fungsi->konversi_bulan($i); ?></label>
                </div>
            <?php } ?>

            <div class="row mt-2" style="margin-top: 15px;">
                <label class="font-weight-bold">GRAND TOTAL</label>
            </div>
        </div>
        
        <!-- TOTAL -->
        <div class="pr-3 mr-3" style="width:150px">
            <div class="row justify-content-center">
                <label class="font-weight-bold">TOTAL</label>
            </div>

            <?php 
                $total_seluruh_target   = $data_target['total_seluruh_target'][$tahun];

                for($i=1; $i <= 12; $i++) {
                    $id_bulan               = sprintf("%02d", $i);
                    $total_target_per_bulan = $data_target['total_target_per_bulan'][$tahun][$id_bulan];
            ?>
                    <div class="row mt-2 justify-content-end" style="height: 35px;">
                        <label class="total_target_per_bulan font-weight-bold" data-idbulan="<?= $id_bulan; ?>"><?= (!empty($total_target_per_bulan) ? number_format($total_target_per_bulan, 0, ", ", ".") : '0') ?></label>
                    </div>
            <?php 
                } 
            ?>

            <div class="row mt-2 justify-content-end" style="margin-top: 15px;">
                <label id="total_seluruh_target" class="font-weight-bold"><?= (!empty($total_seluruh_target) ? number_format($total_seluruh_target, 0, ", ", ".") : '0') ?></label>
            </div>
        </div>

        <!-- INPUT -->
        <?php
            foreach($data_group AS $rows){
                $nama_group    = $rows->kode_group. " - ". $rows->nama_group;
                $total_nominal = $data_target['total_nominal'][$rows->id_group_m][$tahun];
        ?>
            <div id="<?= $rows->id_group_m ?>" class="form_input pr-4" style="width:250px">
                <div class="row justify-content-center">
                    <label class="font-weight-bold"><?= $nama_group ?></label>
                </div>

                <?php 
                    for($i=1; $i <= 12; $i++){
                        $id_bulan   = sprintf("%02d", $i);
                        $nominal    = $data_target['data'][$rows->id_group_m][$tahun][$id_bulan]['nominal'];
                        $nominal    = number_format($nominal, 0, ", ", ".")
                ?>
                        <div class="row mt-2">
                            <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; ?>">
                        </div>
                <?php 
                    } 
                ?>

                <div class="row justify-content-end"  style="margin-top: 25px;">
                    <label id="total_target_tahunan" class="font-weight-bold"><?= (!empty($total_nominal) ? number_format($total_nominal, 0, ", ", ".") : '0') ?></label>
                </div>
            </div>
        <?php 
            } 
        ?>
    </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', 150);

        var jumlahGroup         = "<?= COUNT($data_group) ?>";
        var widthDynamicContent = $(".div_auto_scroll").outerWidth();
        var widthDynamicDrawer  = $("#drawer-content").outerWidth();

        if(widthDynamicContent > widthDynamicDrawer){
            $(".footer_button").css('width', (widthDynamicDrawer*102/100));
            $(".header_form_target").css('width', (widthDynamicDrawer*102/100));
        }else{
            $(".footer_button").css('width', (widthDynamicContent*104/100));
            $(".header_form_target").css('width', (widthDynamicDrawer*102/100));
        }
    });

    // 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 ?>";
            var nominal    = $("#"+id_group_m+" input[name='nominal']");
            array_id_group.push(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){
        var actionDiv  = $(e).closest('.form_input');
        var id_group_m = actionDiv.attr('id');

        var nominal = actionDiv.find('input[name="nominal"]');
        var array_nominal = [];

        // Total Target Tahunan per Group
        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);

        actionDiv.find('#total_target_tahunan').html(idr(total));

        // 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));
    }

    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>