<div class="content-wrapper">
  
    <div class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col">
                    <div class="card card-primary card-outline">
                        <div class="card-header">
                            <h5 class="m-0">Create <?php echo $pageTitle; ?> <a href="<?php echo site_url("accounts/vouchers/listvouchers"); ?>" class="btn btn-sm btn-warning float-right"><i class="nav-icon fas fa-times"></i> Cancel <?php echo $pageTitle; ?></a></h5>
                        </div>
                        <div class="card-body">
                            <form method=POST action="" enctype="multipart/form-data" name="tbl_accounts">
                                <div class="row">
                                    <div class="col-3">
                                        <fieldset>
                                            <legend>Transaction Date</legend><input type="text" class="form-control nepaliDatePicker" id="voucher_date" value="<?php echo NepaliDate(); ?>" name="voucher_date">
                                        </fieldset>
                                    </div>
                                    <div class="col-3">
                                        <fieldset>

                                            <legend><span id="selectedAccountName"></span> Balance</legend><span id="selectedAccountBalance" style="padding: 6px 0px;    display: inline-block;    text-align: right;    width: 100%;">Choose A/C First</span>
                                        </fieldset>
                                    </div>
                                    <div class="col-3 offset-3">
                                        <fieldset>
                                            <legend>Voucher #</legend><input type="text" readonly class="form-control" id="voucher_no" value="<?php echo generateVoucherNo(); ?>" name="voucher_no">
                                        </fieldset>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col">
                                        <fieldset>
                                            <legend>Enter Transaction</legend>
                                            <table id="EntryTable" class="table order-list">
                                                <thead>
                                                    <tr>
                                                        <td class="col-4">Account</td>
                                                        <td class="col-5">Narration</td>
                                                        <td class="col-1">Debit</td>
                                                        <td class="col-1">Credit</td>
                                                        <td class="col-1"></td>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                        <td> <?php $this->myaccounts->showAccountsCombo("account_id", "", "account_id", "status=1", $default = "", $CSSclass = ""); ?> </td>
                                                        <td> <input type="text" name="narration" id="narration" class="form-control" /> </td>
                                                        <td> <input type="text" name="debit" id="debit" value="0" class="form-control" /> </td>
                                                        <td> <input type="text" name="credit" id="credit" value="0" class="form-control" /> </td>
                                                        <td> <input type="button" class="btn btn-primary full-width" id="addrow" value="Add" /> </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                            <div id="errorBox" class="alert alert-secondary hidden" role="alert">
                                                <h5></h5>
                                            </div>
                                        </fieldset>
                                        <div class="card card-success card-outline mt-4">
                                            <div class="card-header">Transaction List </div>
                                            <div class="card-body">
                                                <table id="myTable" class=" table order-list table-striped table-bordered">
                                                    <thead>
                                                        <tr>
                                                            <td>Account</td>
                                                            <td>Narration</td>
                                                            <td>Debit</td>
                                                            <td>Credit</td>
                                                        </tr>
                                                    </thead>
                                                    <tbody> </tbody>
                                                    <tfoot>
                                                        <tr>
                                                            <th colspan="2" class="text-right">Total</th>
                                                            <td>
                                                                <div id="debitTotal"></div>
                                                            </td>
                                                            <td>
                                                                <div id="creditTotal"></div>
                                                            </td>
                                                            <td>
                                                                <div class="bold-text" id="balance"></div>
                                                            </td>
                                                        </tr>
                                                    </tfoot>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <!--COL START-->
                                    <div class="col">
                                        <div class="form-group"> <label for="remarks">Remarks</label> <textarea class="form-control" id="remarks" name="remarks"></textarea> </div>
                                    </div>
                                    <!--COL END-->
                                </div> <button class="btn btn-primary" type="submit" id="saveButton" name="submit">Save Voucher</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    $(document).ready(function() {
        $("#account_id").change(function(e) {
                var account_id = this.value;
                $.ajax({
                        url: "<?php echo site_url("accounts/Ledger/getaccountbalance/"); ?>" + account_id,
                        async: false,
                        dataType:"json",
                        success: function(data) {
                            $("#selectedAccountName").html(data.account_name);
                            $("#selectedAccountBalance").html(data.Balance);
                        }
                    });

        });
    var counter = 0; $("#addrow").on("click", function() {
        var msg = "Transaction Row Added !!";
        if ($("#account_id").val() != "") {
            if (!isAccountAdded($("#account_id").val())) {
                if ($("#narration").val() != "") {
                    var debit = ($.isNumeric($("#debit").val()) ? $("#debit").val() : 0);
                    var credit = ($.isNumeric($("#credit").val()) ? $("#credit").val() : 0);
                    if ($.isNumeric(debit) && $.isNumeric(credit)) {
                        if (debit > 0 || credit > 0) {
                            addRow()
                        } else {
                            msg = "Either debit side or credit side must contain some value";
                        }
                    } else {
                        msg = "Non numberic value entered in debit side or credit side. ";
                    }
                } else {
                    msg = "Narration can't be empty!";
                }
            } else {
                msg = "Account already added in transactions";
            }
        } else {
            msg = "Account Head Not Selected!";
        }
        $("#errorBox h5").html(msg);
        $("#errorBox").fadeTo(2000, 500).slideUp(500, function() {
            $("#errorBox").slideUp(500);
        });
    }); $("table.order-list").on("click", ".ibtnDel", function(event) {
        $(this).closest("tr").remove();
        calculateTotals();
    });
    });

    function isAccountAdded(account_id) {
        var arr = $('input[name="account_id[]"]').map(function() {
            return this.value;
        }).get();
        console.log(arr);
        if ($.inArray(account_id, arr) >= 0) return true;
        else return false;
    }

    function addRow() {
        var newRow = $("<tr>");
        var cols = "";
        cols += '<td><input type="hidden" class="form-control" name="account_ids[]" value="' + $("#account_id").val() + '"/><input type="text" readonly class="form-control" name="account_name[]" value="' + $("#account_id option:selected").text() + '"/></td>';
        cols += '<td><input type="text" readonly class="form-control" name="narration[]" value="' + $("#narration").val() + '"/></td>';
        cols += '<td><input type="text" readonly class="form-control" name="debit[]" value="' + ($.isNumeric($("#debit").val()) ? $("#debit").val() : 0) + '"/></td>';
        cols += '<td><input type="text" readonly class="form-control" name="credit[]" value="' + ($.isNumeric($("#credit").val()) ? $("#credit").val() : 0) + '"/></td>';
        cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger "  value="Delete"></td>';
        newRow.append(cols);
        $("#myTable.order-list").append(newRow);
        calculateTotals();
    }

    function calculateTotals() {
        var debitTotal = 0;
        var creditTotal = 0;
        var balance = 0;
        $("table.order-list").find('input[name^="debit[]"]').each(function() {
            debitTotal += +$(this).val();
        });
        $("table.order-list").find('input[name^="credit[]"]').each(function() {
            creditTotal += +$(this).val();
        });
        balance = Number(debitTotal) - Number(creditTotal);
        roundbalance=balance.toFixed(2);
    
        $("#debit").val(0);
        $("#credit").val(0);
        $("#debitTotal").text(debitTotal.toFixed(2));
        $("#creditTotal").text(creditTotal.toFixed(2));
        $("#balance").text(balance.toFixed(2));
        if (roundbalance !=0) {
              $("#saveButton").prop("disabled", true);
        } else {
             
            $("#saveButton").prop("disabled", false);
        }
    }
    $("#saveButton").prop("disabled", true);
</script>