<!--
< ?php
//if($permissions->hasPermission('addStockCard')){
//include("Views/Stock/addStockCard.php");
//}
?>
-->
<style>
    .table thead tr >th{
        background-color: #4c0870;
        color:#fff;
    }
    .table thead tr th[class*='sorting_'] {
        color: #FFFFFF;
    }
    .panel.panel-default{
        border:1px solid #4c0870;
    }
    .bg-master-lighter {
        border:none;
        background-color:#fff;
        border-top:1px solid #ddd;  
    }
    .form-horizontal .form-group {
        border-bottom: 1px solid #4c0870;
    }
    .dataTables_wrapper .dataTables_paginate .paginate_button.current, .dataTables_wrapper .dataTables_paginate .paginate_button.current:hover,.dataTables_wrapper .dataTables_paginate .paginate_button:hover{
        color:#fff !important;
        border-radius: 50%;
        background: #ed9421!important;
        border-color: #4c0870
    }
    .dataTables_wrapper .dataTables_paginate .paginate_button.disabled:hover{
        color:#fff !important;
    }
.span_class{
    color:black;
}
.span_class:hover{
    color:#ed9421;
}

</style>
<script>
    function AddCommas(val) {
        val = parseFloat(val.toString()).toString();
        while (/(\d+)(\d{3})/.test(val.toString())) {
            val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
        }
        return val.replace(/\.0$|\.00$/, "") || "0";
    }
    function FixNumber(val) {
        return AddCommas(parseFloat(val + "").toFixed(2));
    }
</script>
<script src="<?php echo THEME_PATH; ?>/plugins/moment/moment.min.js"></script>
<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div id="ExpirySuccess" class="hidden"></div>
        <div class="panel-heading">
            <div class="panel-title"><?php print CommonLanguage::getMessage('Stock_Card'); ?></div>
        </div>
        <div class="row">
            <div class="col-md-5 form-group">


                <div class="col-md-12">
                    <label><?php echo CommonLanguage::getMessage('Date') ?></label>
                    <div class="input-daterange input-group" id="datepicker-range" style="width:100%">
                        <input id="From_To_Date" type="text" class="form-control" name="From_To_Date" >
                    </div>
                </div>
                <div class="col-md-6">
                    <label><?php echo CommonLanguage::getMessage('Category') ?></label>
                    <input class=" full-width " id="category_filter"  type="hidden" />
                </div>
                <div class="col-md-6  <?php echo smc_session()['default_setting']['activate_second_currency'] == 1 ? '':'hidden'; ?>">
                    <label><?php echo CommonLanguage::getMessage('currency') ?></label>
                    <select class="full-width" id="currency_id" data-init-plugin="select2">
                        <option value="1"> <?php echo smc_session()['local_currency_name'] . ' - ' . smc_session()['local_currency_symbol'] ?></option>
                        <option value="2"> <?php echo smc_session()['second_currency']['name'] . ' - ' . smc_session()['second_currency']['symbol'] ?></option>
                    </select>
                </div>
                <div class="col-md-12">
                    <label><?php echo CommonLanguage::getMessage('product') ?></label>
                    <input class=" full-width Product_ID" id="Product_ID" name="Product_ID" type="hidden" />
                </div>
                <div class="col-md-6">
                    <label><?php echo CommonLanguage::getMessage('Transaction_Type') ?></label>
                    <select id ="TypeTrans" class="full-width Transaction" data-init-plugin="select2" >
                        <option value="0"><?php print CommonLanguage::getMessage('All'); ?></option>
                        <?php foreach ($Trans_Type as $Type): ?>
                            <option value="<?php echo $Type['Transaction_Type_ID'] ?>"><?php echo $Type['Transaction_Type'] ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6">
                    <label><?php echo CommonLanguage::getMessage('Depot') ?></label>

                    <div class="input-daterange input-group"  style="width:100%">
                        <input id="depot_id" type="hidden" class="full-width" name="depot_id" >
                    </div>

                </div>
            </div>




            <div class="col-md-4">
                <img src="" class="Profile m-l-95"  style="width:50%;">

            </div>
            <div class="col-md-3">
                <h5> <?php print CommonLanguage::getMessage('product'); ?> : <span class="product"></span></h5>

                <h5> <?php print CommonLanguage::getMessage('system_qty'); ?> : <span class="qunatity"></span></h5>


                <h5> <?php print CommonLanguage::getMessage('report_qty'); ?> : <span class="stock"></span></h5>
                <?php if ($permissions->hasPermission('show_cost_balance_stock_card')) { ?>
                    <h5> <?php print CommonLanguage::getMessage('balance'); ?> : <span class="CurrencySymbol"><?php echo $Currency_Symbol; ?></span><span class="Cost"> </span></h5>
                <?php } ?>

            </div>
            <br>
            <hr>
            <div class="col-md-12">
                <div class="box-body no-padding">
                    <table class="table table-hover table-bordered" id="tableWithSearch">
                        <thead>
                            <tr>
                                <th class="text-center"><?php print CommonLanguage::getMessage('Transaction_Date') ?></th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('Transaction_Type') ?></th>
                                <?php if ($permissions->hasPermission('show_cost_balance_stock_card')) { ?>
                                <th class="text-center"><?php print CommonLanguage::getMessage('cost') ?>&nbsp;<span id="default_uom"></span></th>
                                <?php } ?>
                                <th class="text-center"><?php print CommonLanguage::getMessage('in') ?></th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('out') ?></th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('balance') ?></th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('Depot') ?></th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('employee') ?></th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('customer_supplier') ?></th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('record_nb') ?></th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('description') ?></th>
                                <!--<th class="text-center"><?php // print CommonLanguage::getMessage('Action')                 ?></th>-->
                            </tr>
                        </thead>
                        <tbody id="transactions">

                        </tbody>
                    </table>
                </div>
                <!--                < ?php echo Forms::FloatingAddButton('4c0870', '#add_StockCard', CommonLanguage::getMessage('Add')); ?>-->
            </div>
        </div>
    </div>
</div>
<script>

    var year = <?php echo json_encode($year) ?>,
            start_date = <?php echo json_encode($start_date) ?>,
            end_date = <?php echo json_encode(smc_session()['end_date']) ?>,
            show_cost_balance = <?php echo json_encode($permissions->hasPermission('show_cost_balance_stock_card')) ?>,
            currencySymbol = <?php echo json_encode($Currency_Symbol) ?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            Edit = <?php echo json_encode(CommonLanguage::getMessage('Edit')); ?>,
            loader = '<div id="IsBusy" style="position:absolute;left:0;right:0;top:-230px;height:100%;background:rgba(255,255,255,0.9);opacity:1"><img class="image-responsive-height demo-mw-50" src="img/demo/progress.svg" alt="Progress" style="position: absolute;left: 50%;top: 50%;margin: -25px 0 0 -25px;" /></div>';
    $(document).ready(function () {
//        CallAjaxFunction();
        build_select2($("#Product_ID"), "xhr/ProductSearch")
        build_select2($("#category_filter"), "xhr/catSearch")
        build_select2($("#depot_id"), "xhr/depotSearch")

        $("#category_filter").on("change", function () {
            $("#Product_ID").val("").attr("data-select-name", "")
            build_select2($("#Product_ID"), ("xhr/ProductSearch?cat=" + $("#category_filter").val()))
        })

        //        $("#Material_Category_ID").on("change", function () {
        //            var Type = $(this).data("TypeListTarget"),
        //                    Catolder = $("#s2id_" + $(this).attr("id"));
        //            $("#s2id_Product_ID").append("<div class='LoadingCities' style='position:absolute;left:0;top:0;width:100%;height:100%;background:rgba(180,180,180,0.5);text-align:center'><img style='height:25px;margin-top:5px;' src='img/demo/progress.svg' /></div>")
        //            Catolder.append("<div class='LoadingCities' style='position:absolute;left:0;top:0;width:100%;height:100%;background:rgba(180,180,180,0.5);text-align:center'></div>")
        //            $.ajax({
        //                url: "StockAjax/StockDashboardAjax",
        //                dataType: "json",
        //                data: {Material_Category_ID: $(this).val()},
        //                complete: function (v, vv) {
        //                    $("#Product_ID").select2("destroy").empty()
        //                    if (vv == "success") {
        //                        var ToBeAdded = "";
        //                        for (var x = 0; x < v.responseJSON.length; x++) {
        //                            ToBeAdded += "<option value='" + v.responseJSON[x]["ID"] + "'>" + v.responseJSON[x]["Code"] + "-" + v.responseJSON[x]["Name"] + "</option>"
        //                        }
        //                        $("#Product_ID").html(ToBeAdded);
        //                    }
        //                    $("#Product_ID").select2();
        //                    $(">.LoadingCities", Catolder).remove()
        //                }
        //            })
        //        }).data("MyModuleListTarget", "#Module_ID").trigger("change")


        //        $("body").addClass("NoSearch")
        //        $("body .search-link[data-toggle='search']").html("<i class='pg-search'></i>Click here to <span class='bold'>search</span>")
        $("input[name=From_To_Date]").daterangepicker({
            locale: {
                format: 'YYYY-MM-DD'
            }, ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            startDate: start_date,
            endDate: end_date
        }, function (start, end, label) {
            window.startDate = start.format("YYYY-MM-DD"),
                    window.endDate = end.format("YYYY-MM-DD")
        });
        $("#depot_id,#currency_id").on("change", function () {
            setTimeout(function () {
                CallAjaxFunction()
            }, 800)
            load();
        })
        $('.Product_ID,#TypeTrans,#From_To_Date').on("change", function () {
            if ($("input.Product_ID").val() != '') {
                setTimeout(function () {
                    CallAjaxFunction()
                }, 800)
                load();
            } else {
                $(".product").empty();
                $(".qunatity").empty();
                $(".stock").empty();
                $(".Cost").empty();
                $('#tableWithSearch').DataTable().destroy();
                $("#tableWithSearch tbody").empty();

            }

        })



    })






    function CallAjaxFunction() {

        var depot_name = $('#depot_id').select2('data');
        if (depot_name) {
            depot_name = depot_name.text;
        } else {
            depot_name = '';
        }

        var CurrentData = {
            From_Date: window.startDate ? window.startDate : start_date,
            To_Date: window.endDate ? window.endDate : end_date,
            Category_ID: $("#category_filter").val() ? $("#category_filter").val() : 0,
            Product_ID: $("input.Product_ID").val(),
            Type: $("#TypeTrans").val(),
            depot_id: $("#depot_id").val(),
            currency_id: $("#currency_id").val()
        }


        $('#tableWithSearch').DataTable().destroy();
        $("#tableWithSearch tbody").empty();
        $.ajax({
            url: "StockAjax/StockCardAjax",
            method: "POST",
            data: CurrentData,
            dataType: 'json',
            complete: function (v1, v2) {
                if (v2 == "success") {
                    var available_types = ["1", "2", "4", "8", "9", "11", "12", "13", "14"];


                    var img = v1.responseJSON[1],
                            Data = v1.responseJSON[0],
                            l = (Object.keys(Data['details']).length);
                    //                        console.log(Data)
                    $('.Profile').attr("src", img);
                      $(".product").empty().html('');
                            $(".qunatity").empty().html('0');
                            $(".stock").empty().html('0');
                            $(".Cost").empty().html(' ' + FixNumber(Data['Cost']));
                            $(".CurrencySymbol").text('')
                            $("#default_uom").text('')
                    for (var i = 0; i < l; i++) {
//                        console.log(Data)
//                        console.log(row)
//                        console.log(row['Transaction_Type_ID'])
                        var row = Data['details'][i];
                        var data_source = (row['Transaction_Type_ID'] == 2 || row['Transaction_Type_ID'] == 11) ?
                                "Inventory/ViewInvoice/" + row['main_id'] + "/" + row['is_actual'] + "?is_pop=1" :
                                (row['Transaction_Type_ID'] == 1 || row['Transaction_Type_ID'] == 12 ?
                                        "Inventory/ViewInvoice/vendor/" + row['main_id'] + "/" + row['is_actual'] + "?is_pop=1" :
                                        ((row['Transaction_Type_ID'] == 8 || row['Transaction_Type_ID'] == 13)
                                                ? "Inventory/ViewReturnDebit/vendor/" + row['main_id'] + "?is_pop=1" :
                                                (row['Transaction_Type_ID'] == 9 || row['Transaction_Type_ID'] == 14 ? "Inventory/ViewReturnDebit/" + row['main_id'] + "?is_pop=1" : "Stock/TransferGoods/" + row['main_id'])));
                        //                                            console.log(FixNumber(Data['General']['Total_Quantity']))
                        if (i == 0) {
                            $(".product").empty().html(row['CODE'] + ' - ' + row['NAME']);
                            $(".qunatity").empty().html(FixNumber(row['total_qty_def_view']) + ' ' + row['default_view_uom']);
                            $(".stock").empty().html(FixNumber(Data['Amount_Per_Stock']) + ' ' + row['default_view_uom']);
                            $(".Cost").empty().html(' ' + FixNumber(Data['Cost']));
                            $(".CurrencySymbol").text(Data['Currency_Symbol'])
                            $("#default_uom").text('('+Data['default_view_uom']+')')
                        }
                        var content = $.inArray(row['Transaction_Type_ID'], available_types) == -1 ? row['Transaction_Type'] : '<a class="span_class" data-src="' + data_source + '" class="openFrame"><span>' + row['Transaction_Type'] + '</span></a>';
                        var TR = $('<tr data-id=' + row['Transaction_ID'] + '><td class="text-center">' + row['Transaction_Date'] + '</td>' +
                                '<td class="text-center">' + content + '</td>' + (show_cost_balance ?
                                        '<td class="text-center">' + FixNumber(($("#currency_id").val() == 1 ? row['Unit_Cost'] : (row['second_currency_cost'])) * row['uom_rate']) + ' ' + row['Currency_Symbol'] + '</td>' : '') +
                                '<td class="text-center">' + (row['Operation_Type'] == '+' ? row['Cur_Quantity'] : '') + '</td>' +
                                '<td class="text-center">' + (row['Operation_Type'] == '-' ? row['Cur_Quantity'] : '') + '</td>' +
                                '<td class="text-center">' + FixNumber(row['Balance']) + ' ' + row['default_view_uom'] + '</td>' +
                                '<td class="text-center">' + row['Depot_Name'] + '</td>' +
                                '<td class="text-center">' + row['Employee_Name'] + '</td>' +
                                '<td class="text-center">' + (row['Customer_Name'] != '' ? row['Customer_Name'] : (row['Supplier_Name'] != '' ? row['Supplier_Name'] : '')) + '</td>' +
                                '<td class="text-center">' + row['main_nb'] + '</td>' +
                                '<td class="text-center">' + row['trans_note'] + '</td>' +
                                //                                '<td class="text-center "><span class="ExpiryDate">' + row['Expiry_Date'] + '</span></td>' +
                                //                                '<td class="text-center"><button class="text-center btn bg-complete-darker" style ="color:#FFF" id="editTrans">' + Edit + '</button></td>' +
                                '</tr>');
                        $("#tableWithSearch").append(TR)
                    }

                    RebuildDataTable('Stock Card' + '<br/>' + depot_name, [], '', [], '', [], {bSort: false})
                    //                    RebuildTable()
                    //                    ReloadScroll()

                }
            }
        })
    }

    function load() {
        $("#tableWithSearch").append(loader);
        setTimeout(function () {
            $("#IsBusy").remove();
        }, 800)
    }




</script>
