<?php  
$cust_sub_fields_hide = smc_session()['default_setting']['customer_subscription_fields_to_hide'] != '' ? explode(",", smc_session()['default_setting']['customer_subscription_fields_to_hide']) : [];
$default_bill_depend_cust_sub = smc_session()['default_setting']['default_bill_depend_cust_sub'];
?>
<style>
    .current_row{
        background: #e5e5e5;
        padding: 10px;
        border-radius: 6px;
        margin-bottom: 10px;
    }
</style>
<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 class="row">
                <div class="col-md-2">
                    <label><?php echo CommonLanguage::getMessage('status'); ?></label>
                    <select id="status_id" name="status_id" class="full-width" data-init-plugin="select2" >
                        <option value=""><?php echo CommonLanguage::getMessage('All'); ?></option>
                        <option value="1"><?php echo CommonLanguage::getMessage('enabled'); ?></option>
                        <option value="0"><?php echo CommonLanguage::getMessage('disabled'); ?></option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label><?php print CommonLanguage::getMessage('address'); ?></label>
                    <input type="hidden" id="customer_address" name="customer_address" class="full-width" >
                </div>
                <div class="col-md-2">
                    <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 class="col-md-2">
                    <label><?php  echo CommonLanguage::getMessage('block');?></label>
                    <input type="hidden" name="current_block_id" id="current_block_id" class="full-width"/>
                </div>
                <?php
                if ($permissions->hasPermission('add_customer_subscription')) {
                    echo Forms::FloatingAddButton('4c0870', '#customer_subscription_modal', CommonLanguage::getMessage('add'));
                }
                ?>
            </div>

        </div>
        <div class="panel-body">
            <div class="row">
                <div class="col-md-12 table-responsive">
                    <table class="table table-bordered inventory" id="tableWithSearch" >
                        <thead>
                            <tr>
                                <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('block'); ?></th>
                                <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('start_date'); ?></th>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('next_date'); ?></th>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('note'); ?></th>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('status'); ?></th>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('Action'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade " id="customer_subscription_modal" data-backdrop="static" >
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header clearfix text-left">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i>
                </button>
                <h5 class="add-label h-labels hidden bold"><?php echo CommonLanguage::getMessage('add_customer_subscription'); ?></h5>
                <h5 class="edit-label h-labels hidden bold"><?php echo CommonLanguage::getMessage('edit_customer_subscription'); ?></h5>
            </div>
            <div class="modal-body">
                <div class="row">
                    <?php echo Forms::AlertDiv('customer_subscription_alert'); ?>
                </div>
                <form id="customer_subscription_form" method="POST" onsubmit="return false">
                    <input type="hidden" name="customer_subscription_id" id="customer_subscription_id" />
                    <input type="hidden" name="next_due_date" id="next_due_date" />
                    <div class="row form-group">
                        <div class="col-md-3">
                            <label><?php print CommonLanguage::getMessage('customer_name'); ?></label>
                            <span class="red-star">*</span>
                            <span class="fa fa-plus-circle m-l-5 openFrame" data-src="Inventory/CustomerList?is_pop=1&new=1" style="color:#8a7dbe;cursor:pointer"></span>
                            <input type="hidden" id="customer_id" name="customer_id" class="full-width common-to-be-disabled" required>
                        </div>
                    </div>
                    <div class=" row form-group current_row">
                        <div class="col-md-12">
                            <div class="col-md-3">
                                <label><?php print CommonLanguage::getMessage('customer_subscription_title'); ?></label>
                                <span class="red-star">*</span>
                                <input type="text" name="customer_subscription_title" class="form-control customer_subscription_title req" >
                            </div> 
                            <div class="col-md-3">
                                <label><?php print CommonLanguage::getMessage('subscription_name'); ?></label>
                                <span class="red-star">*</span>
                                <input type="hidden" name="subscription_id" class="full-width common-to-be-disabled subscription_id req empty" >
                            </div>
                            <div class="col-md-2">
                                <label><?php print CommonLanguage::getMessage('bill_depend_on'); ?></label>
                                <span class="red-star">*</span>
                                <select name="bill_depend" data-init-plugin="select2" class="full-width common-to-be-disabled bill_depend req" >
                                    <option value=""><?php  echo CommonLanguage::getMessage('select');?></option>
                                    <option value="1" <?php echo (!empty($default_bill_depend_cust_sub) && $default_bill_depend_cust_sub == 1) ? 'selected' : '';?> ><?php  echo CommonLanguage::getMessage('customer_start_date');?></option>
                                    <option value="2" <?php echo (!empty($default_bill_depend_cust_sub) && $default_bill_depend_cust_sub == 2) ? 'selected' : '';?>><?php  echo CommonLanguage::getMessage('subscription_period_bill');?></option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label><?php print CommonLanguage::getMessage('start_date'); ?></label>
                                <span class="red-star">*</span>
                                <input type="text"  name="start_date" class="form-control common-to-be-disabled start_date req empty">
                            </div>
                            <div class="col-md-1">
                                <div><label><?php print CommonLanguage::getMessage('is_active'); ?></label></div>
                                <div><input type="checkbox" class="is_active"/></div>
                            </div>
                            <div class="col-md-1 AddButtons">
                                <span class="fa fa-plus" style="color:#4c0870;margin-top:15px;margin-right:25px"></span>
                                <span class="fa fa-minus" style="color:#ed9421;margin-top:15px;"></span>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <div class="col-md-3 <?php echo in_array(0, $cust_sub_fields_hide) ? 'hidden' : '' ?>">
                                <label><?php  echo CommonLanguage::getMessage('job');?></label>
                                <span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/job_list?is_pop=1&new=1" style="color:#8a7dbe;cursor:pointer"></span>
                                <input type="hidden" name="job_id" class="full-width job_id empty" />
                            </div>
                            <div class="col-md-3 <?php echo in_array(1, $cust_sub_fields_hide) ? 'hidden' : '' ?>">
                                <label><?php  echo CommonLanguage::getMessage('project');?></label>
                                <span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/project_list?is_pop=1&new=1" style="color:#8a7dbe;cursor:pointer"></span>
                                <input type="hidden" name="project_id"  class="full-width project_id empty" />
                            </div>
                            <div class="col-md-3 <?php echo in_array(3, $cust_sub_fields_hide) ? 'hidden' : '' ?>">
                                <label><?php  echo CommonLanguage::getMessage('block');?></label>
                                <input type="hidden" name="block_id"  class="full-width block_id" />
                            </div>
                            <div class="col-md-3 <?php echo in_array(2, $cust_sub_fields_hide) ? 'hidden' : '' ?>">
                                <label><?php print CommonLanguage::getMessage('note'); ?></label>
                                <input type="text" name="note" class="form-control note empty" >
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" id="CloseProduct" data-dismiss="modal"  >  <?php print CommonLanguage::getMessage('Close'); ?></button>
                <button class="btn btn-primary" id="submit_customer_subscription"  >   <?php print CommonLanguage::getMessage('Save'); ?> </button>
            </div>
            <?php echo Forms::ModalLoader('customer_subscription_loader'); ?>
        </div>
    </div>
</div>
<script>
    $(function () {

        build_select2($("#customer_address"), "xhr/customerAddressSearch");
        build_select2($(".job_id"), "ACCAjax/JobSearch")
        build_select2($(".project_id"), "ACCAjax/projectSearch");
        build_select2($('#current_block_id'), 'xhr/searchSubscriptionBlocks?main_block_id='+$('#main_block_id').val());
        $('#main_block_id').on('change',function(){
            $('#current_block_id').val('');
            build_select2($('#current_block_id'), 'xhr/searchSubscriptionBlocks?main_block_id='+$('#main_block_id').val());
        });
        changeTable()
        $('#tableWithSearch').on('click', '.delete', function () {
            var entry_value = $(this).parents('div.Action').attr('data-id');
            IncludeDeleteModal(common_delete_modal, {customer_subscription_id: entry_value}, function () {
                changeTable()
            }, "InventoryAjax/deleteCustomerSubscription");
        });
        build_select2($(".block_id"), "xhr/searchSubscriptionBlocks");
        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");
        $('input.start_date').datepicker({autoclose:true});

        new Switchery($(".is_active").get(0), {color: $.Pages.getColor("primary")});
        $('#customer_id').on('change',function(){
            if($(this).val()){
                $('.customer_subscription_title').val($(this).select2('data').cust_name);
            }
        });
        $(".floatingContainer").on("click", function () {
            $('#customer_subscription_id').val(0);
            $('#next_due_date').val('');
            if(!$('.is_active').is(":checked")){
                $('.is_active').trigger('click');
            }
            $('#customer_subscription_modal .add-label,#customer_subscription_modal .AddButtons').removeClass('hidden');
        });
        $("#customer_subscription_modal").on("hidden.bs.modal", function () {
            $('.current_row:gt(0)').remove();
            $('.common-to-be-disabled').attr("disabled",false);
            $("input.job_id,input.project_id,input.subscription_id").val('').trigger('change');
            //            $("select.bill_depend").val('').select2();
        });
        $("#customer_subscription_form").on("click", " .fa-plus", function (e) {
            var Parent = $(this).parents(".current_row"), NewItem = Parent.clone().insertAfter(Parent);
            NewItem.find("input.empty").val('');
            NewItem.find(".select2-container,span.switchery").remove()
            NewItem.find("input.job_id,input.project_id,input.subscription_id,input.block_id").attr("data-select-name", "");
            build_select2($(".job_id",NewItem), "ACCAjax/JobSearch");
            build_select2($(".project_id",NewItem), "ACCAjax/projectSearch");
            build_select2($(".block_id",NewItem), "xhr/searchSubscriptionBlocks");
            build_select2($(".subscription_id",NewItem), "xhr/commonSearch?col_id=subscription_id&col_name=subscription_name&table=tbl_subscription"); 
            $('input.start_date',NewItem).datepicker({autoclose:true});
            new Switchery($(".is_active",NewItem).get(0), {color: $.Pages.getColor("primary")});
            $("select.bill_depend",NewItem).select2();
            $(".select2-container", NewItem).show()
        });
        $("#customer_subscription_form").on("click", ".fa-minus", function (e) {
            if ($(".current_row").length > 1)
                $(this).closest(".current_row").empty().remove();
        });

        $("#submit_customer_subscription").on("click", function () {
            if (!$("#customer_subscription_form").valid()) {
                return;
            }
            var cust_sub = [],is_cust_sub_empty = false;
            $(".current_row").each(function () {
                var parent = $(this),not_empty_count = 0;//required fields
                $('.req', parent).each(function () {
                    if ($(this).val())
                        not_empty_count++;
                });
                if (not_empty_count != 0 && not_empty_count < 4)
                    is_cust_sub_empty = true;
                //                console.log('hello')
                //                console.log($("input[name=subscription_id]",parent).val())
                //                console.log($("select[name=bill_depend]",parent).val())
                //                console.log($("input[name=start_date]",parent).val())
                //                console.log($("input[name=customer_subscription_title]",parent).val())
                if ($(this).find("input[name=subscription_id]").val() &&
                    $(this).find("select[name=bill_depend]").val() &&
                    $(this).find("input[name=start_date]").val() &&
                    $(this).find("input[name=customer_subscription_title]").val()) {
                    cust_sub.push({
                        subscription_id: $(this).find("input[name=subscription_id]").val(),
                        is_active:  $(this).find('.is_active').is(":checked") ? 1 : 0,
                        bill_depend: $(this).find("select[name=bill_depend]").val(),
                        customer_subscription_title: $(this).find("input[name=customer_subscription_title]").val(),
                        note: $(this).find("input[name=note]").val(),
                        start_date: $(this).find("input[name=start_date]").val(),
                        project_id: $(this).find("input[name=project_id]").val(),
                        job_id: $(this).find("input[name=job_id]").val(),
                        block_id: $(this).find("input[name=block_id]").val(),
                    })
                }
            });
            var Data = {is_active: $('.is_active').is(":checked") ? 1 : 0,
                        subscription_id :$('input[name=subscription_id]').val(),
                        customer_id :$('#customer_id').val(),
                        customer_subscription_id :$('#customer_subscription_id').val(),
                        bill_depend :$('select[name=bill_depend]').val(),
                        customer_subscription_title :$('.customer_subscription_title').val(),
                        note :$('.note').val(),
                        start_date :$('.start_date').val(),
                        next_due_date :$('#next_due_date').val(),
                        project_id :$('input.project_id').val(),
                        job_id :$('input.job_id').val(),
                        block_id :$('input.block_id').val(),
                        is_disabled:$('.start_date').is(':disabled') ? 1 : 0,
                        cust_sub: cust_sub
                       };
            if(cust_sub.length == 0){
                AddAlert("#customer_subscription_alert",'<?php  echo CommonLanguage::getMessage( 'input_option');?>', 'danger');
                return;
            }
            if(is_cust_sub_empty){
                AddAlert("#customer_subscription_alert",'<?php  echo CommonLanguage::getMessage( 'input_field_empty');?>', 'danger');
                return; 
            }
            $("#customer_subscription_loader").removeClass('hidden');
            $.ajax({
                url: "InventoryAjax/submitCustomerSubscription",
                method: "POST",
                data: Data,
                dataType: "json",
                complete: function (jqXHR, v2) {
                    if (v2 == 'success') {
                        if (jqXHR.responseJSON[1] == "success") {
                            hideModalAlert('customer_subscription_modal', 'customer_subscription_alert');
                            changeTable()
                        }
                        AddAlert("#customer_subscription_alert", jqXHR.responseJSON[0], jqXHR.responseJSON[1]);
                    }
                    $("#customer_subscription_loader").addClass('hidden');
                }
            });
        });
        $('#status_id,#customer_address,#current_block_id,#main_block_id').on('change',function(){
            changeTable()
        });

        $('#tableWithSearch').on('click', '.edit', function () {
            $("#customer_subscription_modal .edit-label").removeClass('hidden');
            $("#customer_subscription_modal .AddButtons").addClass('hidden');
            var customer_subscription_id = $(this).parents('div.Action').attr('data-id');
            $('#customer_subscription_id').val(customer_subscription_id);
            CommonViewById('InventoryAjax/getCustomerSubscriptionData', {customer_subscription_id: customer_subscription_id},
                           '#customer_subscription_loader', function (response) {
                var response =  response;
                $('#customer_id').val(response.customer_id).attr('data-select-name',response.Customer_Name).trigger('change');
                $('input.subscription_id').val(response.subscription_id).attr('data-select-name',response.subscription_name).trigger('change');
                $('input.block_id').val(response.block_id).attr('data-select-name',response.block_name).trigger('change');
                $('input.start_date').val(response.start_date);
                $('input.note').val(response.note);
                $('#next_due_date').val(response.next_due_date);
                $('input.customer_subscription_title').val(response.customer_subscription_title);
                $('select.bill_depend').val(response.bill_depend).select2();
                if((response.is_active == 1 && !$('.is_active').is(":checked")) || (response.is_active == 0 && $('.is_active').is(":checked"))){
                    $('.is_active').trigger('click');                    
                }
                if(response.job_id){
                    $('input.job_id').val(response.job_id).attr('data-select-name',response.job_code+' - '+response.job_name).trigger('change');
                } 
                if(response.project_id){
                    $('input.project_id').val(response.project_id).attr('data-select-name',response.project_code+' - '+response.project_name).trigger('change');
                }
                $('.common-to-be-disabled').attr("disabled",response.check_cust_sub_used == 1 ? true : false)
            });
        });
    });
    function changeTable(){
        var Data ={status_id:$('#status_id').val(),
                   customer_address:$('#customer_address').val(),
                   main_block_id:$('#main_block_id').val(),
                   block_id:$('#current_block_id').val()
                  };
        RebuildDataTable($('.panel-heading .panel-title').html(), [0], "InventoryAjax/customer_subscription_list_ajax",Data);

    }
</script>