
<style>
    .panel-default{
        min-height:550px;
    }
    #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;
    }
    #ledgerTable_filter,#ledgerTable_length{
        display: none
    }
    #ledgerTable th{
        color: #444;
        background: #ddd;
        text-align: center;
        border-top: 1px solid #4c0870;
    }
    #ledgerTable 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;
    }
     @media print{
        .print-only{
            display:block;
        }
        h4{
            font-size: 25px !important;
            line-height: 23px !important;
        }
       
        .table thead tr th,.table tbody tr td{
              border:2px solid #000 !important;
        }
        .table-bordered{
            border:2px solid #000 !important;
        }
        .table thead tr >th,.table tbody tr td{
            font-size: 1.3em !important;
        }
      
    }
</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">
    <div class="row">

        <div class="col-md-12 pull-right">
            <div class="col-md-2">
                <label><?php echo CommonLanguage::getMessage('Type'); ?></label>
                <select id="transaction_type" class="full-width" multiple data-init-plugin="select2">
                    <option value="inv"><?php echo CommonLanguage::getMessage('invoice') ?></option>
                    <option value="pur"><?php echo CommonLanguage::getMessage('purchase') ?></option>
                    <option value="pay"><?php echo CommonLanguage::getMessage('payment') ?></option>
                    <option value="rec"><?php echo CommonLanguage::getMessage('receipt') ?></option>

                </select>
            </div>
            <div class="col-md-2">
                <label><?php echo CommonLanguage::getMessage('users'); ?></label>
                <select  id="users"  class="full-width Account_Code " multiple data-init-plugin="select2">
                    <?php foreach ($users as $user): ?>
                        <option value="<?php echo $user['User_ID']; ?>"><?php echo $user['User_Name']; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label><?php echo CommonLanguage::getMessage('range_date'); ?></label>
                <div class="full-width input-daterange input-group" id="datepicker-range">
                    <input id="From_To_Date" type="text" class="form-control" name="From_To_Date" >
                </div>
            </div>
            <div class="col-md-2 ">
                <label><?php echo CommonLanguage::getMessage('Transaction_Type'); ?></label>
                <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-3">
                <label><?php echo CommonLanguage::getMessage('Currency'); ?></label>
                <?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>
                            <div class="col-sm-8 col-xs-8">
                                <input type="text" id="Account_Name" class="form-control" name="Account_Name" required="" aria-required="true">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="fname" class="col-sm-4 control-label"><?php print CommonLanguage::getMessage('account_number'); ?></label>
                            <div class="col-sm-8">
                                <input type="text" id="Account_Number"  class="form-control" name="Account_Number" required="" aria-required="true">
                            </div>
                        </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 class="box-body no-padding">
                    <table class="table table-hover" id="ledgerTable">
                        <thead>
                            <tr>
                                <th><?php print CommonLanguage::getMessage('Date'); ?></th>
                                <th><?php print CommonLanguage::getMessage('jv'); ?>#</th>
                                <th><?php print CommonLanguage::getMessage('ref'); ?>#</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>

            <nav class="navbar navbar-default bg-master-lighter sm-padding-10" role="navigation">
                <div class="container-fluid">
                    <div class="collapse navbar-collapse" id="sub-nav">
                        <div class="row"> 
                            <div class="col-sm-4 ">
                                <ul class="nav navbar-nav navbar-center">


                                    <li><a href="#"  title="Print" data-toggle="tooltip" class="PrintThisTableButton" data-currency="<?php echo $defCurrencyName ?>" data-table="#ledgerTable" data-date="<?php echo 'From : ' . ($today) . ' To : ' . ($today) ?>" data-title="GENERAL LEDGER"><i class="fa fa-print"></i></a></li>
                                    <!--                                    <li><a href="#" data-toggle="tooltip" data-placement="top" title="Download"><i class="fa fa-download"></i></a></li>-->
                                </ul>
                            </div>
                            <div class="col-sm-4 pull-right">
                                <ul class="nav navbar-nav navbar-right">
                                    <li>
                                        <a href="#" class="p-r-10" data-download-pdf="#ledgerTable" data-landscape="" data-title="General Ledger"><img width="25" height="25" alt="" class="icon-pdf" data-src-retina="<?php echo SITE_LINK; ?>img/invoice/pdf2x.png" data-src="<?php echo SITE_LINK; ?>img/invoice/pdf2x.png" src="<?php echo SITE_LINK; ?>img/invoice/pdf2x.png"></a>
                                    </li>
                                    <li>
                                        <a href="#" class="p-r-10"><img width="25" height="25" alt="" class="icon-image" data-src-retina="<?php echo SITE_LINK; ?>img/invoice/image2x.png" data-src="<?php echo SITE_LINK; ?>img/invoice/image2x.png" src="<?php echo SITE_LINK; ?>img/invoice/image2x.png"></a>
                                    </li>
                                    <li>
                                        <a href="#" class="p-r-10"><img width="25" height="25" alt="" class="icon-doc" data-src-retina="<?php echo SITE_LINK; ?>img/invoice/doc2x.png" data-src="<?php echo SITE_LINK; ?>img/invoice/doc2x.png" src="<?php echo SITE_LINK; ?>img/invoice/doc2x.png"></a>
                                    </li>
                                    <li><a href="#" class="p-r-10" onclick="$.Pages.setFullScreen(document.querySelector('html'));return false"><i class="fa fa-expand"></i></a></li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </nav>
        </div>
    </div>

</div>


<script type="text/javascript">
    var TotalLang = <?php echo json_encode(CommonLanguage::getMessage('total')); ?>;
    var general_ledger = <?php echo json_encode(CommonLanguage::getMessage('general_ledger')); ?>;
    var today = <?php echo json_encode($today) ?>,
            fromdate = <?php echo json_encode($from_day) ?>,
            is_actual = <?php echo json_encode($is_actual) ?>,
            Ismatch = <?php echo json_encode($Ismatches) ?>,
            code = <?php echo json_encode($Account_ID) ?>,
            account_name = <?php echo json_encode($account_name) ?>;
    var org_name = org_head[0]['Organization_Legal_Name'],
            org_phone = org_head[0]['Organization_Phone'],
            org_email = org_head[0]['Organization_Email'],
            org_address = org_head[0]['Name'] + '-' + org_head[0]['Organization_Province'];
    if (!is_actual) {
        $("#transactions").on("click", ".desc", function () {
            var link_id = $(this).parents("tr").attr("data-id"),
                    link_type = $(this).parents("tr").attr("data-type"),
                    link_prefix = $(this).parents("tr").attr("data-prefix"),
                    url = site_link;
            if (link_type == 'inv') {
                url = url + "Inventory/ViewInvoice/" + link_id + "/0?is_pop=1";
            } else if (link_type == 'pur') {
                url = url + "Inventory/ViewInvoice/vendor/" + link_id + "/0?is_pop=1";
            } else if (link_type == 'pay') {
                url = url + "ACC/ViewReceipt/" + link_id + "/" + link_prefix + "?is_pop=1";
            } else if (link_type == 'rec') {
                url = url + "ACC/ViewReceipt/Receipt/" + link_id + "/" + link_prefix + "?is_pop=1";
            }
            $('#frameModal').on('show.bs.modal', function () {
                $('iframe', $(this)).attr("src", url);

            });
            $('#frameModal').modal("show")
        })
    }
    $(document).ready(function () {
        $("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")
            AjaxCall();
        });
//                        $(".applyBtn").on("click",function(){
//
//
//
//                            AjaxCall();
//
//                        })
        if (Ismatch) {
            var x = account_name + ' - ' + code;
            $("#Account_Number").attr("value", code)
            $("#Account_Name").attr("value", x)
            $(window).on("load", function () {
                AjaxCall();
            })
        }
        $("#CurrencyDropDown .dropdown-menu li").click(function () {
            setTimeout(function () {
                AjaxCall();
            }, 300)
        })
        $(".Transaction,#transaction_type,#users").on("change", function () {
            setTimeout(function () {
                AjaxCall();
            }, 300)
        })

        $("#Account_Name").autocomplete({
            source: "xhr/ajaxTransaction",
            minLength: 1,
            select: function (event, ui) {
                var id = ui.item.id;
                var code = ui.item.code;
                $('#Account_Name').attr('data-name', ui.item.value.split('-')[0]);
                $('#Account_Name').val(ui.item.value);
                $("#Account_Number").attr("value", code);
                $("#Account_Number").attr("data-nb", 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")));
//                            this.menu.element.outerWidth($("#Account_Name").width()-295 + 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,
                code = $("#Account_Number").attr("value"),
                Type = $("#TypeTrans").val(),
                Currency_ID = (parseInt($("#CurrencyDropDown button input").val()));
        $('#ledgerTable').DataTable().destroy();
        $("#ledgerTable  tbody").empty()
        var AccountNumber = code || 0
        var DataArr = {
            Account_Number: AccountNumber,
            From_Date: From_Date,
            To_Date: To_Date,
            Currency_ID: Currency_ID,
            Type: Type,
            actual: is_actual,
            users: $("#users").val(),
            trans_type: $("#transaction_type").val()

        }
        $.ajax({
            url: 'ACCAjax/ledgerAjax',
            method: 'GET',
            data: DataArr,
            dataType: 'json',
            complete: function (data, vv) {
                $('#ledgerTable 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 - 2];
                console.log(Currency)
                var Default_Currency = Currency['Currency_Symbol'];
                $("#PreviousBalance").html(AddCommas(parseFloat(Prev_Balance + "").toFixed(2)));
                $("#Current_Balance").html(AddCommas(parseFloat(Current_Balance + "").toFixed(2)));
                $("#OverAll").html(AddCommas(parseFloat(All_Balance + "").toFixed(2)));

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



//                if(results.length <= 2)
//                    $("#ledgerTable > 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) - 2; i++) {
                        var transactions = "<tr data-id='" + results[i]['main_id'] + "' data-type='" + results[i]['main_type'] + "' data-prefix = '" + results[i]['serial_prefix'] + "'>" +
                                "<td>" + results[i]["Transaction_Date"] + "</td>" +
                                "<td>" + results[i]["JV_ID"] + "</td>" +
                                "<td>" + results[i]["Ref_ID"] + "</td>" +
                                "<td class='desc' " + (is_actual ? '' : "style='cursor:pointer'>") + 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(parseFloat(results[i]["Debit"] + "").toFixed(2)) + "</td>" +
                                    "<td>" + Default_Currency + " " + AddCommas(parseFloat(results[i]["Credit"] + "").toFixed(2)) + "</td>";
                        }

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

                    }
                    var finaltr = $("<tr style='color:#4c0870;'><td>&nbsp;</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(parseFloat(total_debit + "").toFixed(2)) + "</td><td style='font-size: 1.3em' class='bold'>" + Default_Currency + ' ' + AddCommas(parseFloat(total_credit + "").toFixed(2)) + "</td><td style='font-size: 1.3em' class='bold'>" + Default_Currency + ' ' + AddCommas(parseFloat(Current_Balance + "").toFixed(2)) + "</td><td style='font-size: 1.3em' class='bold'>" + Default_Currency + ' ' + AddCommas(parseFloat(All_Balance + "").toFixed(2)) + "</td></tr>");
                    $("#ledgerTable > tbody:last").append(finaltr)

                    $(".PrintThisTableButton").attr({"data-Account": $('#Account_Name').val(), "data-title": "General Ledger", "data-balance": Default_Currency + ' ' + AddCommas(parseFloat(All_Balance + "").toFixed(2)), "data-debit": Default_Currency + ' ' + AddCommas(parseFloat(total_debit + "").toFixed(2)), "data-credit": Default_Currency + ' ' + AddCommas(parseFloat(total_credit + "").toFixed(2)), "data-currency": $("#CurrencyDropDown > button>span").html(), "data-table": "#ledgerTable", "data-date": 'From :' + (From_Date) + ' To :' + (To_Date), "data-Old": Default_Currency + ' ' + AddCommas(parseFloat(Prev_Balance + "").toFixed(2)), "data-current": Default_Currency + ' ' + AddCommas(parseFloat(Current_Balance + "").toFixed(2))})
                    $("[data-download-pdf]").attr({"data-Account": $('#Account_Name').val(), "data-title": "General Ledger", "data-balance": Default_Currency + ' ' + AddCommas(parseFloat(All_Balance + "").toFixed(2)), "data-debit": Default_Currency + ' ' + AddCommas(parseFloat(total_debit + "").toFixed(2)), "data-credit": Default_Currency + ' ' + AddCommas(parseFloat(total_credit + "").toFixed(2)), "data-currency": $("#CurrencyDropDown > button>span").html(), "data-table": "#ledgerTable", "data-date": 'From :' + (From_Date) + ' To :' + (To_Date), "data-Old": Default_Currency + ' ' + AddCommas(parseFloat(Prev_Balance + "").toFixed(2)), "data-current": Default_Currency + ' ' + AddCommas(parseFloat(Current_Balance + "").toFixed(2))})
                }
                RebuildTable()
            }
        });
    }
    function RebuildTable() {
        $('#ledgerTable').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',
                    message: '',
                    text: '<i class="fa fa-print"></i> Print',
                    exportOptions: {"columns": [0, 2, 3, 4, 5, 6, 7]},
                    title:'',
                    customize: function (win) {
                        $(win.document.body)
                                .css('font-size', '50px')
                                .prepend(
                                        '<div class="col-xs-4" style="margin-bottom:30px">' +
                                        '<h4>' + org_name + '</h4>' +
                                        '<h4>Tires, Batteries</h4>' +
                                        '<h4>' + org_phone + '</h4>' +
                                        '<h4>' + org_email + '</h4>' +
                                        '<h4>' + org_address + '</h4></div>' +
                                        '<div class="col-xs-3"><img src="' + window.site_link + 'img/logo_white.png" style="margin-bottom:20px;width:150px;heigth:150px;position:absolute;opacity:0.5; top:0; " />'+
                                        '</div><div class="col-xs-5">' +
                                        '<h4>Account Name:&nbsp' + $('#Account_Name').attr('data-name') + '</h4><h4>Date:&nbsp' + fromdate + ' - To:&nbsp' + today + '</h4>' +
                                        '<div>'
                                        );

                        $(win.document.body).find('table')
                                .addClass('compact')
                                .css({
                                    'padding-top': '60px'
                                });
                    }
                }],
        });

    }




</script>
