<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div class="panel-heading">
            <div class="panel-title"> <?php echo $title; ?></div>
            <?php
            if ((($permissions->hasPermission('add_pricing_class') && !$is_supp) || ($is_supp && $permissions->hasPermission('add_supplier_pricing_class'))) && smc_session()['default_setting']['sync_type'] != 2) {
                echo Forms::FloatingAddButton('4c0870', '#add_pricing_class', CommonLanguage::getMessage('add'));
            }
            ?>
        </div>
        <div class="panel-body">
            <div class="row">
                <div class="col-md-12 table-responsive">
                    <table class="table table-bordered table-hover inventory" id="tableWithSearch" >
                        <thead>
                            <tr>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('Name'); ?></th>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('ttc'); ?></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 bs-example-modal-md " id="add_pricing_class" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-md"  >
        <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="modal-title bold"><?php print CommonLanguage::getMessage('pricing_class') ?></h5>
            </div>
            <div class="modal-body">
                <div class="row"><?php echo Forms::AlertDiv('assignAlert'); ?></div>
                <form id="assignForm">
                    <div class="row form-group">
                        <div class=" col-md-6" >
                            <label><?php print CommonLanguage::getMessage('Name'); ?>
                                <span class="red-star">*</span>
                            </label>
                            <input type="text" class="form-control" id="Class_Name" name="Class_Name" required/>
                        </div>
                        <div class=" col-md-6" >
                            <label><?php print CommonLanguage::getMessage('currency'); ?></label>
                            <div id="CurrencyIDContainer" class=" " >
                                <div class="form-group form-material floating ">
                                    <div class="input-group-btn DropDownForForms Closable" id="CurrencyDropDown" data-symbol="<?php echo smc_session()['local_currency_symbol']; ?>">
                                        <button type="button" class="btn btn-primary btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                            <span class="currency-symbol"><strong ><?php echo smc_session()['local_currency_name'] . ' - ' . smc_session()['local_currency_symbol'] ?></strong></span>
                                            <input type="hidden"  value="<?php echo smc_session()['local_currency'] ?>" class="form-control ignore" onkeyup="return false" onkeydown="return false" id="Currency_ID" name="Currency_ID"/>
                                        </button>
                                        <ul class="dropdown-menu">
                                            <?php echo $CurList ?>
                                            <li class="divider"></li>
                                            <li><a class="LoadMore">More..</a></li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row form-group">
                        <?php if (smc_session()['default_setting']['activate_card_tax'] && !$is_supp) { ?>
                        <div class=" col-md-6" >
                            <label class="labelText"><?php print CommonLanguage::getMessage('tax'); ?></label>
                            <input type="text" class="form-control" id="tax_amount" name="tax_amount" />
                        </div>
                        <?php } ?>
                        <?php if ($is_supp) { ?>
                        <div class=" col-md-6" >
                            <label class="labelText"><?php print CommonLanguage::getMessage('supplier'); ?></label>
                            <input type="hidden" class="full-width" id="supplier_id" name="supplier_id" />
                        </div>
                        <?php } ?>
                        <div class=" col-md-2" style="display: grid;">
                            <label class="labelText"><?php print CommonLanguage::getMessage('ttc'); ?></label>
                            <input type="checkbox" id="is_ttc" name="is_ttc"/>
                        </div>
                        <div class=" col-md-2 <?php echo $is_supp ? 'hidden' : '' ?> " style="display: grid;">
                            <label class="labelText"><?php print CommonLanguage::getMessage('virtual') . '?'; ?></label>
                            <input type="checkbox" id="is_virtual" name="is_virtual"/>
                        </div>
                    </div>
                    <div class="pr-div hidden">
                        <div class="row  form-group" >
                            <div class="col-md-5">
                                <label><?php echo CommonLanguage::getMessage('pricing_class') ?></label>
                            </div>
                            <div class="col-md-5">
                                <label><?php echo CommonLanguage::getMessage('percent') ?></label>
                            </div>
                        </div>
                        <div class="row pr-row m-t-10" >
                            <div class="col-md-5">
                                <select  id="method"  class="full-width sub_class"  data-init-plugin="select2">
                                    <option value="" selected ><?php echo CommonLanguage::getMessage('select') ?></option>
                                    <?php foreach ($classes as $class): ?>
                                    <option value="price<?php echo $class['Class_ID']; ?>" data-type-id= "<?php echo $class['Class_ID']; ?>" type="0" data-currency= "<?php echo $class['Currency_Symbol']; ?>"><?php echo $class['Class_Name']; ?></option>
                                    <?php endforeach; ?>
                                    <?php foreach ($methods as $method): ?>
                                    <option  value="method<?php echo $method['Pricing_Method_ID']; ?>" data-type-id= "<?php echo $method['Pricing_Method_ID']; ?>" type="1" data-currency="<?php echo smc_session()['local_currency_symbol'] ?>"><?php echo $method['Pricing_Method_Name']; ?></option>
                                    <?php endforeach; ?>
                                    <option  value="last_cost" data-type-id= "0" type="2" data-currency="<?php echo smc_session()['local_currency_symbol'] ?>"><?php echo CommonLanguage::getMessage('last_cost') ?></option>
                                </select>
                            </div>
                            <div class="col-md-5">
                                <input type="number" class="full-width form-control class_percent"  />
                            </div>
                            <div class="col-md-2 buttons">
                                <span class="fa fa-plus-circle" style="color:#4c0870;margin-top:15px;margin-right:25px"></span>
                                <span class="fa fa-minus-circle" style="color:#ed9421;margin-top:15px;"></span>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><?php print CommonLanguage::getMessage('Close') ?></button>
                <button type="button" class="btn btn-primary white" id="assignBtn" style="width:auto"><?php print CommonLanguage::getMessage('Save') ?></button>
            </div>
            <?php echo Forms::ModalLoader('pricing_loader'); ?>
        </div>
    </div>
</div>
<script>
    var title = <?php echo json_encode(CommonLanguage::getMessage('pricing_class')); ?>,
        Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
                Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
                    is_supp = <?php echo json_encode($is_supp); ?>;
                    var IsEdit = false, IDToEdit = 0;
    $(function () {
        new Switchery($("#is_ttc").get(0), {color: $.Pages.getColor("primary")});
        new Switchery($("#is_virtual").get(0), {color: $.Pages.getColor("primary")});
        //        build_select2($("input.sub_class"), "xhr/PricingClassSearch?is_virtual=0")
        build_select2($("#supplier_id"), "xhr/supplierSearch")
        $(".floatingContainer").on("click", function () {
            IsEdit = false;
            IDToEdit = 0;
            if ($("#is_ttc").is(":checked"))
                $("#is_ttc").trigger("click")
            if ($("#is_virtual").is(":checked"))
                $("#is_virtual").trigger("click")
        })
        $("#is_virtual").on("change", function () {
            if ($("#is_virtual").is(":checked"))
                $(".pr-div").removeClass("hidden")
            else {
                $(".pr-div").addClass("hidden")
                $(".pr-row:gt(0)").remove()
                $(".pr-row:eq(0) .class_percent").val('');
                //                $(".pr-row:eq(0) .sub_class").val('').attr("data-select-name", "");
                $(".pr-row:eq(0) select.sub_class").val('').select2();
                //                build_select2($(".pr-row:eq(0) .sub_class"), "xhr/PricingClassSearch?is_virtual=0")
            }
        })
        RebuildDataTable(title, [0], "InventoryAjax/pricing_class_ajax", {is_supp: is_supp})
        $(".pr-div").on("click", " .fa-plus-circle", function (e) {
            $(".pr-row  .fa-minus-circle").css("display", "inline-block")
            var Parent = $(this).parents(".pr-row"), NewItem = Parent.clone().insertAfter(Parent);
            NewItem.find(".select2-container").remove()
            NewItem.find(".class_percent").val('');
            NewItem.find("select.sub_class").val('').select2();
            $(".select2-container", NewItem).show()
        });
        $(".pr-div").on("click", ".fa-minus-circle", function (e) {
            if ($(".pr-row").length == 1) {
                $(".class_percent").val("")
            } else {
                $(this).closest(".pr-row").empty().remove();
            }
        });
        $("#assignBtn").on("click", function () {
            if ($("#Class_Name").val() == '' || $("#Currency_ID").val() == '') {
                AddAlert("#assignAlert", Required_Fields, 'danger');
                return false;
            }
            var DataArr = new FormData(document.getElementById("assignForm"));
            DataArr.append("Class_ID", IDToEdit)
            DataArr.append("is_edit", (IsEdit ? 1 : 0))
            DataArr.append("is_supp", (is_supp ? 1 : 0))
            var sub_classes = [];
            //&& $(this).hasClass(':not(.hidden)')
            $(".pr-row").each(function () {
                if ($(this).find("select.sub_class").val() != '' ) {
                    sub_classes.push({
                        sub_class_id: $(this).find("select.sub_class option:selected").attr("data-type-id"),
                        class_percent: $(this).find(".class_percent").val(),
                        type: $(this).find("select.sub_class option:selected").attr("type"),
                        //                        type_id: $("#method option:selected").attr("data-type-id"),
                    })
                }
            });
            if($("#is_virtual").is(":checked") && sub_classes.length == 0){
                AddAlert("#assignAlert", '<?php  echo CommonLanguage::getMessage('input_option');?>', 'danger');
                return;
            }
            DataArr.append("sub_classes", JSON.stringify(sub_classes));
            $('#pricing_loader').removeClass('hidden');
            $.ajax({
                url: "InventoryAjax/add_edit_pricing_class",
                method: "POST",
                dataType: 'json',
                data: DataArr,
                processData: false,
                contentType: false,
                complete: function (v1, v2) {
                    if (v2 == "success" && v1.responseJSON == 'OK') {
                        AddAlert("#assignAlert", Submitted_Successfully, 'success');
                        RebuildDataTable(title, [0], "InventoryAjax/pricing_class_ajax", {is_supp: is_supp});
                        hideModalAlert('add_pricing_class', 'assignAlert');
                    } else {
                        AddAlert("#assignAlert", v1.responseJSON, 'danger');
                    }
                    $('#pricing_loader').addClass('hidden');
                }
            })
        })
        $("#tableWithSearch tbody").on('click', '.edit_class', function () {
            $(".update_emp_div").removeClass("hidden")
            IsEdit = true;
            IDToEdit = $(this).attr('data-id');
            $.ajax({
                url: "InventoryAjax/get_pricing_class_by_id",
                method: "GET",
                dataType: 'json',
                data: {id: IDToEdit},
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        var data = v1.responseJSON;
                        //                        console.log(data['main'])
                        //                        if (data['main'].length > 0) {
                        $("#Class_Name").val(data['main']['Class_Name'])
                        $("#tax_amount").val(data['main']['tax_amount'])
                        $("#Currency_ID").val(data['main']['Currency_ID'])
                        $("#supplier_id").val(data['main']['supplier_id']).attr("data-select-name", data['main']['Supplier_Name'])
                        build_select2($("#supplier_id"), "xhr/supplierSearch")
                        $(".currency-symbol").html(data['main']['Currency_Name'] + ' - ' + data['main']['Currency_Code'])
                        if ((data['main']['is_ttc'] == 1 && !$("#is_ttc").is(":checked")) || (data['main']['is_ttc'] == 0 && $("#is_ttc").is(":checked"))) {
                            $("#is_ttc").trigger("click")
                        }
                        if ((data['main']['is_virtual'] == 1 && !$("#is_virtual").is(":checked")) || (data['main']['is_virtual'] == 0 && $("#is_virtual").is(":checked"))) {
                            $("#is_virtual").trigger("click")
                        }
                        //                        }
                        $(".pr-row:gt(0)").remove()
                        if (data['details'].length > 0) {
                            for (var i = 0; i < data['details'].length; i++) {
                                var class_val = (data['details'][i]['type'] == 0 ? ('price' + data['details'][i]['sub_class_id']) : (data['details'][i]['type'] == 1 ? ('method' + data['details'][i]['sub_class_id']) : 'last_cost'))
                                if (i == 0) {
                                    $('.pr-row:eq(0) .class_percent').val(data['details'][i]['percent'])
                                    $('.pr-row:eq(0) select.sub_class').val(class_val).select2()
                                    //                                    build_select2($('.pr-row:eq(0) input.sub_class'), "xhr/PricingClassSearch?is_virtual=0")
                                } else {
                                    var Parent = $(".pr-row:eq(0)"), NewItem = Parent.clone().appendTo($(".pr-div"));
                                    NewItem.find(".select2-container").remove()
                                    NewItem.find(".class_percent").val(data['details'][i]['percent']);
                                    NewItem.find("select.sub_class").val(class_val).select2();
                                    //                                    build_select2(NewItem.find(".sub_class"), "xhr/PricingClassSearch?is_virtual=0")
                                    $(".select2-container", NewItem).show()
                                }
                            }
                            $(".pr-div").removeClass("hidden")
                        }
                    }
                }
            })
            $("#add_pricing_class").modal("show")
        })
    })
</script>
