<?php
if ($permissions->hasPermission('addProduct')) {
    include("Views/Inventory/addproduct.php");
}
include 'Views/Inventory/disable_enable_modal.php';
?>
<div id="Barcode" style="display:none"></div>
<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div class="panel-heading">
            <div class="panel-title"> <?php print CommonLanguage::getMessage('product_list'); ?></div>
            <?php
            if (smc_session()['default_setting']['sync_type'] != 2) {
                echo Forms::FloatingAddButton('4c0870', '#addProduct', CommonLanguage::getMessage('add_Product'));
            }
            ?>
            <div class="row">
                <div class="col-md-3">
                    <label><?php echo CommonLanguage::getMessage('status'); ?></label>
                    <select id="product_status" name="product_status" 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="2"><?php echo CommonLanguage::getMessage('disabled'); ?></option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label><?php echo CommonLanguage::getMessage('category_name'); ?></label>
                    <input type="hidden" class="full-width" name="current_category_id" multiple id="current_category_id" autocomplete="off" />
                </div>
                <div class="col-md-3 <?php echo $permissions->hasPermission('Branches') ? '':'hidden'; ?> ">
                    <label><?php echo CommonLanguage::getMessage('choose_branch') ?></label>
                    <input id="search_branch_id" type="hidden" class="full-width" name="search_branch_id"  >
                </div> 

                <div class="col-md-2">
                    <div><label><?php print CommonLanguage::getMessage('show_zero_qty'); ?></label></div>
                    <div><input type="checkbox" id="show_zero_qty" checked /></div>
                </div>

            </div>
            <div class="clearfix"></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>
                                <?php if ($permissions->hasPermission('print_bar_code') || $permissions->hasPermission('delete_multi_product')) { ?>
                                    <th class="text-center" style="width:15%"><input type="checkbox" class="prdt_check_all_td pull-left multi_delete" /></th>
                                <?php }
                                if (smc_session()['default_setting']['show_product_image_list'] == 1) {
                                ?>
                                    <th class="text-center" style="width:15%"><?php print CommonLanguage::getMessage('image'); ?></th>
                                <?php } ?>
                                <th class="text-center" style="width:15%"><?php print CommonLanguage::getMessage('barcode'); ?></th>
                                <th class="text-center" style="width:15%"><?php print CommonLanguage::getMessage('Code'); ?></th>

                                <?php if (smc_session()['default_setting']['activate_search_product_second_code'] == 1) { ?>
                                    <th><?php print CommonLanguage::getMessage('product_second_code') ?></th>
                                <?php } ?>
                                <th class="text-center" style="width:20%"><?php print CommonLanguage::getMessage('Item'); ?></th>
                                <?php if (smc_session()['default_setting']['show_price_product_list'] == 1) { ?>
                                    <th class="text-center" style="width:15%"><?php print CommonLanguage::getMessage('Price'); ?></th>
                                <?php } ?>
                                <th class="text-center" style="width:15%"><?php print CommonLanguage::getMessage('Category'); ?></th>
                                <th class="text-center" style="width:15%"><?php print CommonLanguage::getMessage('brand_name'); ?></th>
                                <th class="text-center" style="width:15%"><?php print CommonLanguage::getMessage('quantity'); ?></th>
                                <th class="text-center" style="width:15%">PLU</th>
                                <th class="text-center" style="width:15%"><?php print CommonLanguage::getMessage('status'); ?></th>

                                <th class="text-center no-print" style="width:15%"><?php print CommonLanguage::getMessage('Action'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>

                    </table>
                </div>
                <div class="col-md-12">

                    <?php if ($permissions->hasPermission('print_bar_code')) { ?>
                        <div class="col-md-2 pull-left">
                            <button class="btn btn-primary full-width" id="multi_barcode_print"><?php echo CommonLanguage::getMessage('print_multi_barcode') ?></button>
                        </div>

                    <?php }
                    if ($permissions->hasPermission('delete_multi_product')) { ?>
                        <div class="col-md-2 pull-left">
                            <button class="btn btn-primary full-width" id="delete_multi_product"><?php echo CommonLanguage::getMessage('Delete') ?></button>
                        </div>
                    <?php } ?>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="delete_modal" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header text-left">
                <h4 class="modal-title bold"><?php print CommonLanguage::getMessage('Confirm_Delete') ?></h4>
                <div id="delete_alert" class="hidden"></div>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-12 m-t-10">
                        <p><?php print CommonLanguage::getMessage('About_To_Delete') ?>&nbsp;</p>
                        <p><?php print CommonLanguage::getMessage('Proceed_Delete') ?></p>
                    </div>
                </div>
            </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-danger width-auto" id="delete_prod_btn"><?php print CommonLanguage::getMessage('delete') ?></button>
            </div>
        </div>
    </div>
</div>
<button type="" class="openFrame hidden" id="multi_barcode_frame" data-src="" />

<script>
    var title = <?php echo json_encode(CommonLanguage::getMessage('product_list')) ?>,
        Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')) ?>;

    var is_new = <?php echo json_encode($is_new) ?>;
    $(function() {
        build_select2($("#search_branch_id"), "xhr/CommonSearch?col_name=branch_name&col_id=branch_id&table=tbl_organization_branches",);

        var optns = {};
        if ($('.prdt_check_all_td').length > 0) {
            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],
                        "orderable": false
                    });
                },
            };
        }


        new Switchery($("#show_zero_qty").get(0), {
            color: $.Pages.getColor("primary")
        });
        var table = $('#tableWithSearch').DataTable();
        build_select2($("#current_category_id"), "xhr/CommonSearch?col_name=Cat_Name&col_id=Cat_ID&table=tbl_product_cat", 1);

        $('#tableWithSearch').on('page.dt', function() {
            var info = table.page.info();
        });
        $('#product_status,#current_category_id,#show_zero_qty,#search_branch_id').on('change', function() {
            RebuildDataTable(title, [0, 1, 2, 3], "InventoryAjax/listProductRequest", {
                Status_ID: $('#product_status').val(),
                category_id: $('#current_category_id').val(),
                show_zero_qty: $("#show_zero_qty").is(":checked") ? 1 : 0,
                search_branch_id: $('#search_branch_id').val()
            }, '', '', optns);
        })
        $("#search_branch_id").trigger("change");
        if (is_new)
            $('#addProduct').modal('show');
        $('#tableWithSearch').on('click', '.delete_product', function() {
            var entry_value = $(this).parents('div.Action').attr('data-id');
            IncludeDeleteModal(common_delete_modal, {
                Product_ID: entry_value
            }, function() {
                RebuildDataTable(title, [0, 1, 2, 3], "InventoryAjax/listProductRequest", {
                    Status_ID: $('#product_status').val(),
                    category_id: $('#current_category_id').val(),
                    show_zero_qty: $("#show_zero_qty").is(":checked") ? 1 : 0
                }, '', '', optns);
            }, "InventoryAjax/deleteProduct");
        });
        $('#tableWithSearch').on('click', '.disable_enable_item', function() {
            var status_id = $(this).attr('data-id'),
                target_item_value = $(this).parents('div.Action').attr('data-id');
            $('#current_status_id').val(status_id == 1 ? 0 : 1);
            $('#target_item_value').val(target_item_value);
            $('#target_item').val('stock_products');
            $('#target_item_id').val('Product_ID');
            status_id == 0 ? $('#enable-disable-modal .add-label,#enable-disable-modal .about_enable_item').removeClass('hidden') : $('#enable-disable-modal .edit-label,#enable-disable-modal .about_disable_item').removeClass('hidden');

        });
        $("#tableWithSearch").on("click", ".copy", function() {
            var product_id = $(this).parents('div.Action').attr('data-id');
            CommonViewById('InventoryAjax/getProductInfo', {
                    product_id: product_id
                },
                '#addProductLoader',
                function(response) {
                    var uom_conversions = response['uom_conversion'],
                        shelfs = response['shelfs'],
                        product_links = response['products_links'],
                        product_criteria = response['product_criteria'],
                        product_add_ons = response['product_add_ons'],
                        products_options = response['products_options'],
                        pricing_data = response['pricing_class'];
                    $('.Category_ID').val(response[0].Cat_ID).attr('data-select-name', response[0].Cat_Name)
                    $('#main_supplier_id').val(response[0].main_supplier_id).attr('data-select-name', response[0].main_supplier_name).trigger("change") 
                    build_select2($(".Category_ID"), "xhr/catSearch");
                    if (response[0].brand_name) {
                        $('#brand_id').val(response[0].brand_id).attr('data-select-name', response[0].brand_name)
                        build_select2($("#brand_id"), "xhr/CommonSearch?col_name=brand_name&col_id=brand_id&table=tbl_brand_products");
                    }
                    $('#UOM_ID').val(response[0].UOM_ID).attr('data-select-name', response[0].UOM_Name)
                    build_select2($("#UOM_ID"), "xhr/uomSearch");
                    $('#Product_Name').val(response[0].Product_Name);

                    $.each(pricing_data, function(index, value) {
                        $('.classes_price input.price_value[data-class=' + pricing_data[index]['Class_ID'] + ']').val(pricing_data[index]['Product_Price'])
                    });


                    var current_uom_conv_row = $("#UOMConForm .AddRow:eq(0)").clone();
                    if ($.type(uom_conversions) == 'object' && Object.keys(uom_conversions).length > 0) {
                        $("#UOMConForm .AddRow").remove();
                        $.each(uom_conversions, function(index, value) {
                            current_uom_conv_row = current_uom_conv_row == null ? $("#UOMConForm .AddRow:eq(0)").clone() : current_uom_conv_row;
                            var current_pricing_data = uom_conversions[index].price;
                            $(".select2-container", current_uom_conv_row).empty().remove();
                            $("input.conval", current_uom_conv_row).val(uom_conversions[index].conversion_amount);
                            $("input.code", current_uom_conv_row).val(uom_conversions[index].Bar_Code);
                            $("textarea.additional_barcodes", current_uom_conv_row).val(uom_conversions[index].additional_barcodes);
                            $("select[name=UOM_From]", current_uom_conv_row).val(uom_conversions[index].uom_from);
                            $("select[name=UOM_From]", current_uom_conv_row).select2();
                            $.each(current_pricing_data, function(index, value) {
                                $('.uom_price input.price_value[data-class=' + current_pricing_data[index]['Class_ID'] + ']', current_uom_conv_row).val(current_pricing_data[index]['Product_Price'])
                            });
                            $("#UOMConForm").append(current_uom_conv_row);
                            $('input[name=is_default_view_uom]').prop('checked', uom_conversions[index].is_default == 1 || response[0]['default_view_uom_id'] == uom_conversions[index].uom_from ? true : false);
                            $('input[name=is_default_sales_uom]').prop('checked', response[0].default_sales_uom == "0" ? false : true);
                            $('input[name=is_default_purchase_uom]').prop('checked', response[0].default_purchase_uom == "0" ? false : true);
                            $(".select2-container", current_uom_conv_row).show()
                            current_uom_conv_row = null
                        });
                    }
                    var product_link_in = product_links['in_items'],
                        product_link_out = product_links['out_items'],
                        product_link_in_row = $("#slide3 .InContainer .InItem:eq(0)").clone(),
                        product_link_out_row = $("#slide3 .OutContainer .OutItem:eq(0)").clone();
                    if (product_link_in.length > 0) {
                        $("#slide3 .InContainer .InItem").remove();
                        $.each(product_link_in, function(index, value) {
                            product_link_in_row = product_link_in_row == null ? $("#slide3 .InContainer .InItem:eq(0)").clone() : product_link_in_row;
                            $(".select2-container", product_link_in_row).empty().remove()
                            $('input.in_qty', product_link_in_row).val(product_link_in[index].current_quantity);
                            $('input[name=in_product]', product_link_in_row).val(product_link_in[index].sub_product_id).attr('data-select-name', product_link_in[index].Product_Name);
                            $('input[name=in_uom]', product_link_in_row).val(product_link_in[index].UOM_ID).attr('data-select-name', product_link_in[index].UOM_Name);
                            build_select2($("input[name=in_product]", product_link_in_row), ("xhr/ProductSearch"))
                            build_select2($("input[name=in_uom]", product_link_in_row), "xhr/productuomSearch?pid=" + product_link_in[index].sub_product_id)
                            $("#slide3 .InContainer").append(product_link_in_row);
                            $(".select2-container", product_link_in_row).show()
                            product_link_in_row = null
                        });

                    }
                    $('#link_note').val(response[0].link_note)
                    if (product_link_out.length > 0) {
                        $("#slide3 .OutContainer .OutItem").remove();
                        $.each(product_link_out, function(index, value) {
                            product_link_out_row = product_link_out_row == null ? $("#slide3 .OutContainer .OutItem:eq(0)").clone() : product_link_out_row;
                            $(".select2-container", product_link_out_row).empty().remove()
                            $('input.out_qty', product_link_out_row).val(product_link_out[index].current_quantity);
                            $('input[name=out_product]', product_link_out_row).val(product_link_out[index].sub_product_id).attr('data-select-name', product_link_out[index].Product_Name);
                            $('input[name=out_uom]', product_link_out_row).val(product_link_out[index].UOM_ID).attr('data-select-name', product_link_out[index].UOM_Name);
                            build_select2($("input[name=out_product]", product_link_out_row), ("xhr/ProductSearch"))
                            build_select2($("input[name=out_uom]", product_link_out_row), "xhr/productuomSearch?pid=" + product_link_out[index].sub_product_id)
                            $("#slide3 .OutContainer").append(product_link_out_row);
                            $(".select2-container", product_link_out_row).show()
                            product_link_out_row = null
                        });
                    }
                    product_op_row = $("#optional_out .op_out_row:eq(0)").clone();
                    if (products_options.length > 0) {
                        $("#optional_out .op_out_row ").remove();
                        $.each(products_options, function(index, value) {
                            product_op_row = product_op_row == null ? $("#optional_out .op_out_row:eq(0)").clone() : product_op_row;

                            $('input.optional_quantity', product_op_row).val(value.quantity);
                            $('input.op_required', product_op_row).prop("checked", value.is_required == 1 ? true : false);



                            var details_row = $('.op_detail_div  .op_detail_row:eq(0)', product_op_row).clone(),
                                details = value.details;
                            if (details.length > 0) {
                                $('.op_detail_div  .op_detail_row', product_op_row).remove();
                                $.each(details, function(index2, det_row) {
                                    details_row = details_row == null ? $('.op_detail_div  .op_detail_row:eq(0)', product_op_row).clone() : details_row;
                                    $(".select2-container", details_row).empty().remove()
                                    $('input[name=op_product]', details_row).val(det_row.sub_product_id).attr("data-select-name", det_row.product_name);
                                    build_select2($("input[name=op_product]", details_row), ("xhr/ProductSearch"))
                                    $('input[name=op_uom]', details_row).val(det_row.UOM_ID).attr("data-select-name", det_row.UOM_Name);
                                    build_select2($("input[name=op_uom]", details_row), ("xhr/productuomSearch?pid=" + det_row.sub_product_id))
                                    $('.op_detail_div', product_op_row).append(details_row);
                                    $('.op_detail_div .fa-minus-circle', product_op_row).css({
                                        "display": "inline"
                                    })
                                    $(".select2-container", details_row).show()
                                    details_row = null;
                                });
                            }



                            $("#optional_out").append(product_op_row);

                            product_op_row = null
                        });
                    }

                    var current_shelf_row = $("#slide4 .product_shelfs .shelfItem:eq(0)").clone();
                    if ($.type(shelfs) == 'object' && Object.keys(shelfs).length > 0) {
                        $("#slide4 .product_shelfs .shelfItem").remove();
                        $.each(shelfs, function(index, value) {
                            current_shelf_row = current_shelf_row == null ? $("#slide4 .product_shelfs .shelfItem:eq(0)").clone() : current_shelf_row;
                            $(".select2-container", current_shelf_row).empty().remove()
                            var selectedItems = shelfs[index].current_shelfs;
                            $('input[name=depot_id]', current_shelf_row).val(index).attr('data-select-name', shelfs[index].depot_name);
                            build_select2($("input[name=depot_id]", current_shelf_row), ("xhr/depotSearch"));
                            build_select2($("input[name=shelf_id]", current_shelf_row), "xhr/shelfdepotSearch?pid=" + index, 1);
                            $("input[name=shelf_id]", current_shelf_row).select2('val', []);
                            $("input[name=shelf_id]", current_shelf_row).data().select2.updateSelection(selectedItems);
                            $("#slide4 .product_shelfs").append(current_shelf_row);
                            $(".select2-container", current_shelf_row).show()
                            current_shelf_row = null
                        });
                    }

                    var current_product_criteria_row = $("#slide5 .AddCriteriaRow:eq(0)").clone();
                    if ($.type(product_criteria) == 'object' && Object.keys(product_criteria).length > 0) {
                        $("#slide5 .AddCriteriaRow").remove();
                        $.each(product_criteria, function(index, value) {
                            current_product_criteria_row = current_product_criteria_row == null ? $("#slide5 .AddCriteriaRow:eq(0)").clone() : current_product_criteria_row;
                            $(".select2-container", current_product_criteria_row).remove();
                            $('select[name=criteria_type]', current_product_criteria_row).val(product_criteria[index].criteria_type);
                            $('input[name=criteria_name]', current_product_criteria_row).val(product_criteria[index].criteria_name);
                            $('input[name=criteria_max_count]', current_product_criteria_row).val(product_criteria[index].criteria_max_count)
                            if (product_criteria[index].criteria_type == 1)
                                $('input[name=criteria_max_count]', current_product_criteria_row).removeClass('hidden')
                            else
                                $('input[name=criteria_max_count]', current_product_criteria_row).addClass('hidden')
                            $("select[name=criteria_type]", current_product_criteria_row).select2()

                            var criteria_details_row = $('.criteria_detail_divs .criteria-items .cr-row:eq(0)', current_product_criteria_row).clone(),
                                criteria_details = product_criteria[index].detail;
                            if (criteria_details.length > 0) {
                                $('.criteria_detail_divs .criteria-items .cr-row', current_product_criteria_row).remove();
                                $.each(criteria_details, function(index2, value) {
                                    criteria_details_row = criteria_details_row == null ? $('.criteria_detail_divs .criteria-items .cr-row:eq(0)', current_product_criteria_row).clone() : criteria_details_row;
                                    $('input[name=criteria_detail_name]', current_product_criteria_row).val(criteria_details[index2].criteria_detail_name);
                                    $('input[name=criteria_detail_price]', current_product_criteria_row).val(criteria_details[index2].criteria_detail_price);
                                    $('.criteria_detail_divs .criteria-items', current_product_criteria_row).append(criteria_details_row);
                                    $('.criteria-items .fa-minus-circle', current_product_criteria_row).css({
                                        "display": "inline"
                                    })
                                    criteria_details_row = null;
                                });
                            }

                            $("#slide5").append(current_product_criteria_row);
                            $('.AddButtons .fa-minus-circle', current_product_criteria_row).css({
                                "display": "inline"
                            })
                            $(".select2-container", current_product_criteria_row).show()
                            current_product_criteria_row = null
                        });
                    }

                    var current_add_ons_row = $("#slide6 .add_ons_divs .add-row:eq(0)").clone();
                    if (product_add_ons.length > 0) {
                        $("#slide6 .add_ons_divs .add-row").remove();
                        $.each(product_add_ons, function(index, value) {
                            current_add_ons_row = current_add_ons_row == null ? $("#slide6 .add_ons_divs .add-row:eq(0)").clone() : current_add_ons_row;
                            $(".select2-container", current_add_ons_row).remove();
                            $('select[name=add_ons_id]', current_add_ons_row).val(product_add_ons[index].add_ons_id);
                            $("input[name=product_add_ons_quantity]", current_add_ons_row).val(product_add_ons[index].product_add_ons_quantity);
                            $("select[name=add_ons_id]", current_add_ons_row).select2()
                            $("#slide6 .add_ons_divs").append(current_add_ons_row);
                            $(".select2-container", current_add_ons_row).show()
                            current_add_ons_row = null
                        });
                    }

                });

        });

        $("#tableWithSearch").on("click", "input.prdt_check_all_td", function(e) {
            var is_checked = $(this).is(":checked");
            var row = $("#tableWithSearch").dataTable().fnGetNodes();
            for (var i = 0; i < row.length; i++) {
                $(row[i]).find("input.prdt_check_input_td").prop("checked", is_checked);
            }
        });

        $("#multi_barcode_print").on("click", function() {
            var products = {
                pr: []
            };
            $("input.prdt_check_input_td:checked").each(function() {
                products.pr.push($(this).attr("data-id"));
            });
            if (products.length == 0)
                return;
            var myurl = 'Inventory/printBarCode';
            $('#multi_barcode_frame').attr('data-src', myurl + '?is_pop=1').attr("data-post-json", JSON.stringify(products));
            $('#multi_barcode_frame').trigger('click');
        });




        $("#delete_multi_product").on("click", function() {
            $("#delete_modal").modal("show");

        });
        $("#delete_prod_btn").on("click", function() {
            var products = [];
            $("input.prdt_check_input_td:checked").each(function() {
                products.push($(this).attr("data-id"));
            });
            if (products.length == 0)
                return;
            $.ajax({
                url: "InventoryAjax/multi_delete_product",
                method: "POST",
                data: {
                    product_ids: JSON.stringify(products)
                },
                complete: function(v1, v2) {
                    if (v2 == 'success') {
                        if (v1.responseText == 'ok') {
                            $("#delete_alert").removeClass('hidden');
                            $("#delete_alert").attr("class", "alert alert-success").html(Submitted_Successfully);
                        } else {
                            $("#delete_alert").removeClass('hidden');
                            $("#delete_alert").attr("class", "alert alert-danger").html(v1.responseText);
                        }
                        setTimeout(function() {
                            $("#delete_modal").modal("hide");
                            $("#delete_alert").addClass('hidden');
                        }, 3000);
                        RebuildDataTable(title, [0, 1, 2, 3], "InventoryAjax/listProductRequest", {
                            Status_ID: $('#product_status').val(),
                            category_id: $('#current_category_id').val(),
                            show_zero_qty: $("#show_zero_qty").is(":checked") ? 1 : 0
                        }, '', '', optns);

                    }
                }
            });
        });
    });
</script>
