<style>
    .select2-container.select2-container-multi {
        height: auto !important;
        overflow-x: hidden !important;
        overflow-y: scroll !important;
        max-height: 70px;
    }

    .panel-default {
        min-height: 70px;
    }

    #TopContainer {
        background: #ddd;
        padding: 12px 6px;
    }

    .DropDownForForms>.dropdown-menu {
        width: 100%;
        height: 200px;
        max-height: 200px;
        overflow-y: scroll;
    }

    .DropDownForForms>.dropdown-menu {
        height: auto;
        cursor: pointer;
        overflow-y: auto;
    }

    .DropDownForForms>button>input {
        position: absolute;
        left: 5;
        top: 0;
        width: 90%;
        cursor: pointer;
        -webkit-user-select: none;
        -moz-user-select: none;
        user-select: none;
        padding: 0;
        border: 0;
        background: transparent;
    }

    .dropdown-menu>li>a {

        color: #000 !Important;
        opacity: 1;
    }


    .control-label {
        font-size: 14px !important;
        color: rgb(70, 70, 70) !important;
        opacity: 1 !important;
    }

    .form-horizontal .form-group .control-label {
        white-space: nowrap;
    }

    .ValueSpan {
        height: 35px;
        display: block;
        padding: 6px 6px;
        font-size: 18px;
        font-family: "Segoe UI", Arial, sans-serif;
    }

    #tableWithSearch_filter,
    #tableWithSearch_length {
        display: none
    }

    #tableWithSearch th {
        color: #444;
        background: #ddd;
        text-align: center;
        border-top: 1px solid #4c0870;
    }

    #tableWithSearch td {
        text-align: center;
    }

    .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;
    }
</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(public_round_number(parseFloat(val + "")));
    }
</script>
<script src="<?php echo THEME_PATH; ?>/plugins/moment/moment.min.js"></script>
<div class="container-fluid container-fixed-lg">
    <div class="row">

        <div class="col-md-8 pull-right">
            <div class="col-md-4">
                <div class="input-daterange input-group" id="datepicker-range">
                    <input id="From_To_Date" type="text" class="form-control" name="From_To_Date">
                    <!--                <input type="text" class="input-sm form-control" id="From_Date" name="start">-->
                    <!--                <span class="input-group-addon bg-complete"><i class="fa fa-calendar"></i></span>-->
                    <!--                <input type="text" class="input-sm form-control" id="To_Date" name="end">-->
                </div>
            </div>
            <div class="col-md-4 ">
                <select id="TypeTrans" class="full-width Transaction" data-init-plugin="select2">
                    <option value="All"><?php print CommonLanguage::getMessage('All'); ?></option>
                    <option value="Credit"><?php print CommonLanguage::getMessage('credit'); ?></option>
                    <option value="Debit"><?php print CommonLanguage::getMessage('debit'); ?></option>
                </select>
            </div>
            <div class="col-md-4">

                <?php echo Forms::CurrencyDropDown(1, 'complete') ?>
            </div>
        </div>
        <br>
        <br>
        <div class="col-md-12">
            <div class="panel panel-default">

                <div id="TopContainer">

                    <div class="row Row1 callout callout-info col-md-5 col-xs-5 form-horizontal">
                        <div class="form-group">
                            <label for="fname" class="col-sm-4 control-label"><?php print CommonLanguage::getMessage('account_name'); ?>:</label>
                            <select id="Accounts_Array" class="full-width" multiple tabindex="-1" data-init-plugin="select2">
                                <?php for ($i = 0; $i < count($accounts); $i++) : ?>
                                    <option value=<?php echo $accounts[$i]['Account_Code'] ?>> <?php echo ($accounts[$i]['Account_Name'] . " - " . $accounts[$i]['Account_Code']) ?> </option>

                                <?php endfor ?>
                            </select>
                        </div>
                    </div>
                    <div class="row Row1 callout callout-info col-md-5 col-xs-5 form-horizontal pull-right" style="margin: 20px;">

                        <div class="form-group" style="padding:0;">
                            <label for="fname" class="col-sm-4 col-xs-4 control-label"><?php print CommonLanguage::getMessage('opening_balance'); ?></label>
                            <div class="col-sm-1 col-xs-3" style="margin-top: 6px; font-size: 20px;">
                                <span class="totalCurr"><?php echo $defCurrencySymbol; ?></span>
                            </div>
                            <div class="col-sm-7">
                                <span id="PreviousBalance" class="ValueSpan"> 0</span>
                            </div>
                        </div>
                        <div class="form-group" style="padding:0;">
                            <label for="fname" class="col-sm-4 col-xs-4 control-label"><?php print CommonLanguage::getMessage('current_balance'); ?></label>
                            <div class="col-sm-1 col-xs-3" style="margin-top: 6px; font-size: 20px;">
                                <span class="totalCurr"><?php echo $defCurrencySymbol; ?></span>
                            </div>
                            <div class="col-sm-7">
                                <span id="Current_Balance" class="ValueSpan"> 0</span>
                            </div>
                        </div>
                        <div class="form-group" style="padding:0;">
                            <label for="fname" class="col-sm-4 col-xs-4 control-label"><?php print CommonLanguage::getMessage('overall_balance'); ?></label>
                            <div class="col-sm-1 col-xs-3" style="margin-top: 6px; font-size: 20px;">
                                <span class="totalCurr"><?php echo $defCurrencySymbol; ?></span>
                            </div>
                            <div class="col-sm-7">
                                <span id="OverAll" class="ValueSpan">0</span>
                            </div>
                        </div>
                    </div>
                    <div style="clear:both"></div>
                </div>
                <div id="header"></div>
                <div class="box-body no-padding">
                    <table class="table table-hover" id="tableWithSearch">
                        <thead>
                            <tr>
                                <th><?php print CommonLanguage::getMessage('Date'); ?></th>
                                <th><?php print CommonLanguage::getMessage('jv'); ?>#</th>
                                <th><?php print CommonLanguage::getMessage('ref'); ?>#</th>
                                <th><?php print CommonLanguage::getMessage('Code'); ?></th>
                                <th style="min-width: 70px"><?php print CommonLanguage::getMessage('description'); ?></th>
                                <th><?php print CommonLanguage::getMessage('debit'); ?></th>
                                <th><?php print CommonLanguage::getMessage('credit'); ?></th>
                                <th><?php print CommonLanguage::getMessage('balance'); ?></th>
                                <th><?php print CommonLanguage::getMessage('overall_balance'); ?></th>
                            </tr>
                        </thead>
                        <tbody id="transactions">

                        </tbody>
                    </table>
                </div>
            </div>


        </div>
    </div>

</div>


<script type="text/javascript">
    var TotalLang = <?php echo json_encode(CommonLanguage::getMessage('total')); ?>;
    var today = <?php echo json_encode($today) ?>,
        fromdate = <?php echo json_encode($from_day) ?>,
        is_actual = <?php echo json_encode($Is_Actual) ?>;
    var general_ledger = <?php echo json_encode(CommonLanguage::getMessage('general_ledger')); ?>;




    $(document).ready(function() {

        $("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'
            },
            startDate: fromdate

        }, function(start, end, label) {
            window.startDate = start.format("YYYY-MM-DD"),
                window.endDate = end.format("YYYY-MM-DD")

        });
        $(".applyBtn").on("click", function() {
            AjaxCall();

        })
        $("#Accounts_Array").on("change", function() {
            AjaxCall();
        })


        $("#CurrencyDropDown .dropdown-menu li").click(function() {
            setTimeout(function() {

                AjaxCall();
            }, 1000)
        })
        $(".Transaction").on("change", function() {

            setTimeout(function() {

                AjaxCall();
            }, 1000)
        })

        $("#Account_Name").autocomplete({
            source: "xhr/ajaxTransaction",
            minLength: 1,
            select: function(event, ui) {
                var id = ui.item.id;
                var code = ui.item.code;
                $('#Account_Name').val(ui.item.value);
                $("#Account_Number").attr("value", code);
                AjaxCall();
            }
        }).autocomplete("instance")._renderItem = function(ul, item) {
            var $LI = $("<li>").html("<table style='height:24px;' cellspacing='0' cellpadding='0'><tr><td><strong>" + item.label + "</strong></td></tr></table>").appendTo(ul);
            return $LI
        }
        $("#Account_Name").autocomplete("instance")._resizeMenu = function(ul, items) {
            this.menu.element.outerWidth($("#Account_Name").width() + parseFloat($("#Account_Name").css("padding-left")) + parseFloat($("#Account_Name").css("padding-right")) + 300);
        }
    });

    function FixFloatVal(what) {
        return what.replace(/\.0$|\.00$|\.000$/, "");
    }

    function AjaxCall() {

        var From_Date = $("input[name=daterangepicker_start]").val() ? $("input[name=daterangepicker_start]").val() : fromdate,
            To_Date = $("input[name=daterangepicker_end]").val() ? $("input[name=daterangepicker_end]").val() : today,
            Type = $("#TypeTrans").val(),
            code = $("#Accounts_Array").val(),
            Currency_ID = (parseInt($("#CurrencyDropDown button input").val()));


        //        $('#tableWithSearch').DataTable().destroy();
        //        $("#tableWithSearch  tbody").empty()
        var AccountNumber = code || 0 // nt exists just for texting
        $.ajax({
            url: 'ACCAjax/ledgerAjax?Account_Number=' + AccountNumber + '&From_Date=' + From_Date + '&To_Date=' + To_Date + '&Currency_ID=' + Currency_ID + '&Type=' + Type + '&actual=' + is_actual,
            method: 'GET',
            dataType: 'json',
            data: {
                from_multi_accounts: 'yes'
            },
            complete: function(data, vv) {
                $('#tableWithSearch').DataTable().destroy()
                $('#tableWithSearch tbody').empty()
                var results = data.responseJSON;

                var results = $.map(
                    data.responseJSON,
                    function(el) {
                        return el;
                    }
                );
                var final_results = results[results.length - 1];



                var total_debit = final_results['Debit'];
                var total_credit = final_results['Credit'];
                var Current_Balance = final_results['Current_Balance'];
                var All_Balance = final_results['All_Balance'];
                var Prev_Balance = final_results['Prev_Balance'];
                var Currency = results[results.length - 3];
                var Default_Currency = Currency['Currency_Symbol'];

                $("#PreviousBalance").html(AddCommas(public_round_number(parseFloat(Prev_Balance + ""))));
                $("#Current_Balance").html(AddCommas(public_round_number(parseFloat(Current_Balance + ""))));
                $("#OverAll").html(AddCommas(public_round_number(parseFloat(All_Balance + ""))));

                $('.totalCurr').html(Default_Currency)



                //                if(results.length <= 2)
                //                    $("#tableWithSearch > tbody").append($('<tr class="odd"><td style="display:none"></td><td style="display:none"></td><td style="display:none"></td><td style="display:none"></td><td style="display:none"></td><td style="display:none"></td><td style="display:none"></td><td style="display:none"></td><td valign="top" colspan="9" class="dataTables_empty PrintThisTable">No data available in table</td></tr>'));

                if (results.length > 2) {
                    for (var i = 0; i < (results.length) - 3; i++) {
                        var transactions = "<tr>" +
                            "<td>" + results[i]["Transaction_Date"] + "</td>" +
                            "<td>" + results[i]["JV_ID"] + "</td>" +
                            "<td>" + results[i]["Ref_ID"] + "</td>" +
                            "<td>" + results[i]["Transaction_Account"] + "</td>" +
                            "<td>" + results[i]["Transaction_Description"] + "</td>";

                        if (results[i]["JV_ID"] == "--") {
                            transactions += "<td>" + results[i]["Debit"] + "</td>" +
                                "<td>" + results[i]["Credit"] + "</td>";
                        } else {
                            transactions += "<td>" + Default_Currency + " " + AddCommas(public_round_number(parseFloat(results[i]["Debit"] + ""))) + "</td>" +
                                "<td>" + Default_Currency + " " + AddCommas(public_round_number(parseFloat(results[i]["Credit"] + ""))) + "</td>";
                        }

                        transactions += "<td>" + Default_Currency + " " + AddCommas(public_round_number(parseFloat(results[i]['Current_Balance'] + ""))) + "</td>" +
                            "<td>" + Default_Currency + " " + AddCommas(public_round_number(parseFloat(results[i]["All_Balance"] + ""))) + "</td>" +
                            "</tr>";
                        $("#tableWithSearch tbody").append(transactions);

                    }
                    var finaltr = $("<tr style='color:#4c0870;'><td style='display:none'>z</td><td></td><td></td><td></td><td style='font-size: 1.3em' class='bold'>" + TotalLang + "</td><td style='font-size: 1.3em' class='bold'>" + Default_Currency + ' ' + AddCommas(public_round_number(parseFloat(total_debit + ""))) + "</td><td style='font-size: 1.3em' class='bold'>" + Default_Currency + ' ' + AddCommas(public_round_number(parseFloat(total_credit + ""))) + "</td><td style='font-size: 1.3em' class='bold'>" + Default_Currency + ' ' + AddCommas(public_round_number(parseFloat(Current_Balance + ""))) + "</td><td style='font-size: 1.3em' class='bold'>" + Default_Currency + ' ' + AddCommas(public_round_number(parseFloat(All_Balance + ""))) + "</td></tr>");
                    $("#tableWithSearch > tbody:last").append(finaltr)

                    $(".PrintThisTableButton").attr({
                        "data-Account": $('#Account_Name').val(),
                        "data-title": "General Ledger",
                        "data-balance": Default_Currency + ' ' + AddCommas(public_round_number(parseFloat(All_Balance + ""))),
                        "data-debit": Default_Currency + ' ' + AddCommas(public_round_number(parseFloat(total_debit + ""))),
                        "data-credit": Default_Currency + ' ' + AddCommas(public_round_number(parseFloat(total_credit + ""))),
                        "data-currency": $("#CurrencyDropDown > button>span").html(),
                        "data-table": "#tableWithSearch",
                        "data-date": 'From :' + (From_Date) + ' To :' + (To_Date),
                        "data-Old": Default_Currency + ' ' + AddCommas(public_round_number(parseFloat(Prev_Balance + ""))),
                        "data-current": Default_Currency + ' ' + AddCommas(public_round_number(parseFloat(Current_Balance + "")))
                    })
                    $("[data-download-pdf]").attr({
                        "data-Account": $('#Account_Name').val(),
                        "data-title": "General Ledger",
                        "data-balance": Default_Currency + ' ' + AddCommas(public_round_number(parseFloat(All_Balance + ""))),
                        "data-debit": Default_Currency + ' ' + AddCommas(public_round_number(parseFloat(total_debit + ""))),
                        "data-credit": Default_Currency + ' ' + AddCommas(public_round_number(parseFloat(total_credit + ""))),
                        "data-currency": $("#CurrencyDropDown > button>span").html(),
                        "data-table": "#tableWithSearch",
                        "data-date": 'From :' + (From_Date) + ' To :' + (To_Date),
                        "data-Old": Default_Currency + ' ' + AddCommas(public_round_number(parseFloat(Prev_Balance + ""))),
                        "data-current": Default_Currency + ' ' + AddCommas(public_round_number(parseFloat(Current_Balance + "")))
                    })
                }
                RebuildTable()
                ReloadScroll()
            }
        });
    }

    function RebuildTable() {
        //        $('#tableWithSearch').dataTable();
        var message = datatable_header;
        var Accounts_Array = $("#Accounts_Array").val();
        var accounts_code = '';
        for (let index = 0; index < Accounts_Array.length; index++) {
            accounts_code += Accounts_Array[index]+',';
        }
        accounts_code = accounts_code.slice(0, -1)
        $.ajax({
            url: 'ACCAjax/getAccountName',
            method: 'GET',
            data: {
                data: accounts_code
            },
            dataType: 'json',
            complete: function(data, vv) {
                var multi_accounts_name = data.responseJSON[0];

                //
                var msg = '<br/> <div style="width: 100%;"> <table style="width: 100%;" border="0"> <tr style="width: 100%;"> <td rowspan="2" style="width: 50%;"><strong>Acc. Name:&nbsp' + multi_accounts_name + '</strong> </td> <td style="width: 50%;text-align: center;"><strong>Currency:&nbsp' + $('#CurrencyDropDown button span').text() + '</strong></td> </tr> <tr style="width: 100%;"> <td style="text-align: center;"><strong>Date:&nbsp' + window.startDate + '-' + window.endDate + '</strong></td> </tr> </table> </div> <style type="text/css"> @media print { .table tbody tr:last-child, .table tbody tr:nth-last-child(2) { font-weight: bold !important; } } </style>';

                message = message.replace('[[msg]]',msg);
                $('#tableWithSearch').dataTable({
                    "aaSorting": [],
                    "bSort": false,
                    dom: 'Bfrtip',
                    "pagingType": "full_numbers",
                    buttons: [{
                            extend: 'excelHtml5',
                            exportOptions: {
                                "columns": [0, 2, 3, 4, 5, 6, 7]
                            },
                            title: general_ledger,
                            text: '<i class="fa fa-file-excel-o"></i> Excel'

                        },
                        {
                            extend: 'pdfHtml5',
                            exportOptions: {
                                "columns": [0, 2, 3, 4, 5, 6, 7]
                            },
                            title: general_ledger,
                            text: '<i class="fa fa-file-pdf-o"></i> Pdf',
                            "sCharSet": 'utf-8',
                            //                    message: 'Account Name: '+$('#Account_Name').attr('data-name')+'\nAccount Code: '+$("#Account_Number").attr("data-nb")+'\nFrom: '+fromdate+'\nTo: '+today+'\nCurrency: '+$("#CurrencyDropDown button span").text(),

                        },
                        {
                            extend: 'print',
                            /* here we set header ?*/
                            message: message+'<br><br><br>',
                            text: '<i class="fa fa-print"></i> Print',
                            exportOptions: {
                                "columns": [0, 2, 3, 4, 5, 6, 7]
                            },
                            title: general_ledger
                        }
                    ],
                });
            }
        });



    }
</script>