<?php  $sub_fees_group = smc_session()['default_setting']['subscription_fees_group_by'];?>
<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div class="panel-heading">
            <div class="panel-title"> <?php print $title; ?></div>
        </div>
        <div class="panel-body">
            <div class="row">
                <?php echo Forms::AlertDiv('subscription_fees_alert'); ?>
            </div>
            <div class="row form-group">
                <div class="col-md-3">
                    <label><?php print CommonLanguage::getMessage('subscription_name'); ?></label>
                    <input type="hidden" id="subscription_id" name="subscription_id" class="full-width" >
                </div>
                <div class="col-md-3">
                    <label><?php print CommonLanguage::getMessage('customer_name'); ?></label>
                    <input type="hidden" id="customer_id" name="customer_id" class="full-width" >
                </div>
                <div class="col-md-3">
                    <label><?php print CommonLanguage::getMessage('address'); ?></label>
                    <input type="hidden" id="customer_address" name="customer_address" class="full-width" >
                </div>
                <div class="col-md-3">
                    <label><?php  echo CommonLanguage::getMessage('main_block');?></label>
                    <select id="main_block_id" name="main_block_id" data-init-plugin="select2" class="full-width">
                        <option value=""><?php echo CommonLanguage::getMessage('select');?></option>
                        <?php $main_blocks = explode(",",smc_session()['block_ids']);  foreach($main_block as $block){ 
    if(empty(smc_session()['block_ids']) || in_array($block['block_id'],$main_blocks)){?>
                        <option value="<?php echo $block['block_id'];?>"><?php echo $block['block_name'];?></option>
                        <?php }}?>
                    </select>
                </div>
            </div>
            <div class="row form-group">
                <div class="col-md-2">
                    <label><?php print CommonLanguage::getMessage('period_unit'); ?></label>
                    <span class="red-star">*</span>
                    <select name="period_unit" id="period_unit" class="full-width" data-init-plugin="select2" required > 
                        <option value=""><?php echo CommonLanguage::getMessage('select'); ?></option>
                        <option value="1"><?php echo CommonLanguage::getMessage('week'); ?></option>
                        <option value="2"><?php echo CommonLanguage::getMessage('month'); ?></option>
                        <option value="3"><?php echo CommonLanguage::getMessage('year'); ?></option>
                    </select>
                </div>

                <div class="date-div month-div hidden">
                    <div class="col-md-2">
                        <label><?php echo CommonLanguage::getMessage('month') ?></label>
                        <span class="red-star">*</span>
                        <input class="month_year form-control" type="text" data-date-format="yyyy-mm" value=""  />
                    </div>
                    <div class=" col-md-2">
                        <label><?php echo CommonLanguage::getMessage('start_date') ?></label>
                        <span class="red-star">*</span>
                        <input class="month_from_date form-control" type="text"  />
                    </div>
                    <div class=" col-md-2">
                        <label><?php echo CommonLanguage::getMessage('end_date') ?></label>
                        <span class="red-star">*</span>
                        <input class="month_to_date form-control" type="text" />
                    </div>
                </div>
                <div class=" week-div date-div  hidden">
                    <div class=" col-md-2">
                        <label><?php echo CommonLanguage::getMessage('start_date') ?></label>
                        <span class="red-star">*</span>
                        <input class="week_from_date form-control" type="text"  />
                    </div>
                    <div class=" col-md-2">
                        <label><?php echo CommonLanguage::getMessage('end_date') ?></label>
                        <span class="red-star">*</span>
                        <input class="week_to_date form-control" type="text"  readonly/>
                    </div>
                </div>
                <div class="date-div year-div hidden">
                    <div class="col-md-2">
                        <label><?php echo CommonLanguage::getMessage('year') ?></label>
                        <span class="red-star">*</span>
                        <input class="year form-control" type="text" data-date-format="yyyy" value=""  />
                    </div>
                    <div class=" col-md-2">
                        <label><?php echo CommonLanguage::getMessage('start_date') ?></label>
                        <span class="red-star">*</span>
                        <input class="year_from_date form-control" type="text"  />
                    </div>
                    <div class=" col-md-2">
                        <label><?php echo CommonLanguage::getMessage('end_date') ?></label>
                        <span class="red-star">*</span>
                        <input class="year_to_date form-control" type="text" />
                    </div>
                </div>
                <div class="col-md-1 pull-right m-t-20">
                    <button class="btn btn-primary" id="search_subscription_fees"><?php print CommonLanguage::getMessage('search'); ?> </button>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12 table-responsive">
                    <table class="table table-bordered inventory" id="tableWithSearch" >
                        <thead>
                            <tr>
                                <?php  if($sub_fees_group == 0){?>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('subscription_name'); ?></th>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('customer_name'); ?></th>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('address'); ?></th>
                                <?php }else{?>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('customer_name'); ?></th>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('address'); ?></th>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('subscription_name'); ?></th>
                                <?php }?>

                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('Date'); ?></th>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('customer_subscription_title'); ?></th>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('product'); ?></th>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('previous'); ?></th>
                                <?php  if($permissions->hasPermission('submit_subscription_fees')){?>
                                <th class="text-center" style="width:15%"  ><?php print CommonLanguage::getMessage('current'); ?></th>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('quantity'); ?></th>
                                <?php }?>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                        <?php
                        if ($permissions->hasPermission('submit_subscription_fees')) {?>
                        <tfoot>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th>
                                <button class="btn btn-primary full-width" id="submit_subscription_fees"><?php echo CommonLanguage::getMessage('Save'); ?></button>
                            </th>
                        </tfoot>
                        <?php }?>
                    </table>
                </div>
            </div>
            <?php echo Forms::ModalLoader('subscription_fees_loader'); ?>
        </div>
    </div>
</div>
<script>
    $(function(){
        ChangeTable();
        build_select2($("#subscription_id"), "xhr/commonSearch?col_id=subscription_id&col_name=subscription_name&table=tbl_subscription");
        build_select2($("#customer_id"), "xhr/customerSearch?is_customer_group=1");
        build_select2($("#customer_address"), "xhr/customerAddressSearch");
        $(".week_from_date").datepicker({autoclose: true});
        $(".month_from_date,.month_to_date").datepicker({autoclose: true});
        $(".year_from_date,.year_to_date").datepicker({autoclose: true});

        $(".week_from_date").on("changeDate", function () {
            var date2 = $(this).datepicker('getDate', '+6d');
            date2.setDate(date2.getDate() + 6);
            $('.week_to_date').val(moment(date2).format('YYYY-MM-DD'));
        });
        $('#period_unit').on('change',function(){
            $('.date-div').addClass('hidden');
            if($(this).val() == 1){
                $('.week-div').removeClass('hidden');
            }else if($(this).val() == 2){
                $('.month-div').removeClass('hidden');
            }else if($(this).val() == 3){
                $('.year-div').removeClass('hidden');
            }

        });

        $(".month_year").datepicker({autoclose: true,viewMode: "months",minViewMode: "months"}); 
        $(".year").datepicker({autoclose: true,viewMode: "years",minViewMode: "years"});

        $('.month_year').on("changeDate",function(){
            var date = new Date($(this).val()), y = date.getFullYear(), m = date.getMonth();
            var firstDay = new Date(y, m, 1);
            var lastDay = new Date(y, m + 1, 0);
            if($(this).val()){
                $('.month_from_date').datepicker("setDate",moment(firstDay).format('YYYY-MM-DD'));
                $('.month_to_date').datepicker("setDate",moment(lastDay).format('YYYY-MM-DD')); 
            }else{
                $('.month_from_date,.month_to_date').datepicker("setDate",""); 
            }
        });
        $('.year').on("changeDate",function(){
            var date = new Date($(this).val()), y = date.getFullYear(), m = date.getMonth();
            var firstDay = new Date(y, m, 1);
            var lastDay = new Date(y, m + 12, 0);
            if($(this).val()){
                $('.year_from_date').datepicker("setDate",moment(firstDay).format('YYYY-MM-DD'));
                $('.year_to_date').datepicker("setDate",moment(lastDay).format('YYYY-MM-DD')); 
            }else{
                $('.year_from_date,.year_to_date').datepicker("setDate",""); 
            }
        });
        $(".month_year").on("changeDate", function () {
            var date = new Date($(this).val() + '-01T12:00:00');
            var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
            window.startDate = $(this).val() + '-01';
            window.endDate = $(this).val() + '-' + lastDay;
        });
        $('#search_subscription_fees').on('click',function(){
            if(($('#period_unit').val() == 1 && (!$(".week_from_date").val() || !$(".week_to_date").val())) || 
               ($('#period_unit').val() == 2 && (!$(".month_from_date").val() || !$(".month_to_date").val())) || 
               ($('#period_unit').val() == 3 && (!$(".year_from_date").val()  || !$(".year_to_date").val())) || 
               !$('#period_unit').val()){
                AddAlert("#subscription_fees_alert", "<?php echo CommonLanguage::getMessage('Required_Fields'); ?>", "danger");
                return;
            }
            $('#submit_subscription_fees').prop('disabled',false);
            ChangeTable();
        });
        $('#tableWithSearch').on('blur keyup','input[name=current_balance]',function(){
            var parent = $(this).parents("tr"),
                previous_balance= parseFloat($('span.previous_balance',parent).html());
            $('input[name=quantity]',parent).val(parseFloat($(this).val()) - previous_balance)
        }); 
        $('#tableWithSearch').on('blur keyup','input[name=quantity]',function(){
            if($(this).attr('data-depend-previous') == 1){
                var parent = $(this).parents("tr"),
                    previous_balance= parseFloat($('span.previous_balance',parent).html());
                $('input[name=current_balance]',parent).val(parseFloat($(this).val()) + previous_balance);
            }
        }); 
        $('#submit_subscription_fees').on('click',function(){
            var subscription_fees = {},is_empty_input = false,is_curr_great_prev = false,is_negative_value = false,
                row = $("#tableWithSearch").dataTable().fnGetNodes();
            if(row.length == 0){
                return;
            }
            for (var i = 0; i < row.length; i++) {
                var parent = $(row[i]),
                    customer_subscription_id = $('span.main_date',parent).attr('data-customer-subscription-id'),
                    main_date_field = $('span.main_date',parent),
                    input_qty = $('input[name=quantity]',parent),
                    current_balance = $('input[name=current_balance]',parent),
                    previous_balance = $('span.previous_balance',parent);
                if((!$('input[name=quantity]',parent).val() && $('input[name=quantity]',parent).length >0) ||
                   (!$('input[name=current_balance]',parent).val() && $('input[name=current_balance]',parent).length > 0)){
                    is_empty_input = true;
                }
                if(!(customer_subscription_id in  subscription_fees)){
                    var subscription_details = [];
                    subscription_details.push({current_quantity:$('input[name=current_balance]',parent).val() || 0,
                                               quantity:$('input[name=quantity]',parent).val() || 0,
                                               subscription_detail_id:$('span.product_name_uom',parent).attr('data-subscription-detail-id'),
                                               is_service:$('span.product_name_uom',parent).attr('data-product-is-service')});
                    subscription_fees[customer_subscription_id] = {customer_subscription_id:customer_subscription_id,
                                                                   main_date:main_date_field.html(),
                                                                   customer_id:main_date_field.attr('data-customer-id'),
                                                                   is_ttc:main_date_field.attr('data-is-tcc'),
                                                                   customer_name:main_date_field.attr('data-customer-name'),
                                                                   currency_id:main_date_field.attr('data-currency-id'),
                                                                   currency_symbol:main_date_field.attr('data-currency-symbol'),
                                                                   subscription_id:main_date_field.attr('data-subscription-id'),
                                                                   job_id:main_date_field.attr('data-job-id'),
                                                                   project_id:main_date_field.attr('data-project-id'),
                                                                   subscription_details:subscription_details
                                                                  }
                    if(parseFloat($('input[name=current_balance]',parent).val()) < 0 || parseFloat($('input[name=quantity]',parent).val()) < 0)
                        is_negative_value = true;
                }else{
                    subscription_fees[customer_subscription_id]['subscription_details'].push({current_quantity:$('input[name=current_balance]',parent).val() || 0,
                                                                                              quantity:$('input[name=quantity]',parent).val() || 0,
                                                                                              subscription_detail_id:$('span.product_name_uom',parent).attr('data-subscription-detail-id'),
                                                                                              is_service:$('span.product_name_uom',parent).attr('data-product-is-service')}); 
                    if(parseFloat($('input[name=current_balance]',parent).val()) < 0 || parseFloat($('input[name=quantity]',parent).val()) < 0)
                        is_negative_value = true;
                }

                if(current_balance && (input_qty.attr('data-type-id') != 1 && input_qty.attr('data-depend-previous') == 1 && parseFloat(current_balance.val() || 0) < parseFloat(previous_balance.html() || 0))){
                    is_curr_great_prev = true;
                }

            }
            if(is_empty_input){
                toastr.error('<?php echo CommonLanguage::getMessage('Required_Fields');?>');
                return;
            }  
            if(is_curr_great_prev){
                toastr.error('<?php echo CommonLanguage::getMessage('current_greater_previous');?>');
                return;
            } 
            if(is_negative_value){
                toastr.error('<?php echo CommonLanguage::getMessage('negative_value');?>');
                return;
            }
            $('#submit_subscription_fees').prop('disabled',true);
            $('#subscription_fees_loader').removeClass('hidden');
            $.ajax({
                url: "InventoryAjax/submitCustomerSubscriptionFees",
                data: {subscription_fees:subscription_fees},
                method:"post",
                dataType:"json",
                complete: function (jqXHR, v2) {
                    if (v2 == 'success') {
                        if (jqXHR.responseJSON[1] == "success") {
                            ChangeTable();
                            toastr.success(jqXHR.responseJSON[0]);
                            //                            $('#submit_subscription_fees').prop('disabled',false);
                        }else{
                            toastr.error(jqXHR.responseJSON[0]);
                            $('#submit_subscription_fees').prop('disabled',false);
                        }
                    }
                    $('#subscription_fees_loader').addClass('hidden')
                }
            }); 
        });
    });
    function ChangeTable() {
        var data = {week_from_date: $('.week_from_date').val(),
                    week_to_date: $('.week_to_date').val(),
                    month_from_date: $('.month_from_date').val(),
                    month_to_date: $('.month_to_date').val(),
                    year_from_date: $('.year_from_date').val(),
                    year_to_date: $('.year_to_date').val(),
                    period_unit:$('#period_unit').val(),
                    customer_id:$('#customer_id').val(),
                    customer_address:$('#customer_address').val(),
                    main_block_id:$('#main_block_id').val(),
                    subscription_id:$('#subscription_id').val()}
        $.ajax({
            url: "InventoryAjax/customer_subscription_fees",
            data: data,
            complete: function (v1, v2) {
                if (v2 == 'success') {
                    $("#tableWithSearch").DataTable().destroy();
                    $("#tableWithSearch tbody").empty().html(v1.responseText);
                    var optns = {
                        cb_ft: function (dt_optns) {
                            // stop sorting for column since on click on header checkbox the sorting is triggered
                            dt_optns.columnDefs.push({targets: [0,1,2,3,4,5,6,7], "orderable": false});
                        },
                    };
                    RebuildDataTable($('#panel-heading .panel-title').html(), [], "", {}, '', [0,1,2,3,4],optns);
                }
            }
        });
    }
</script>