<?php
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include('includes/function.php');

$formname = 'Opening Balance ';
$maindb = 'accmast';
$file = 'openbal.php?mode=last&form=openbal';
$series = $_SESSION["society_" . $dbname];
$zdb = $_SESSION["zdbyear_" . $dbname];

mysqli_select_db($conn, $zdb);

if (isset($_GET["mode"]) == "true") {
    $addflag = 1;
} else {
    $addflag = 0;
}

if (isset($_POST['submit'])) {
    $savetype = $_POST['savetype'];
    $totdebit = $_POST["totdebit"];
    $totcredit = $_POST["totcredit"];

    $count = $_POST["count"];
    $mcount = $_POST["mcount"];

    if ($savetype == 1) {

        for ($i = 0; $i <= $mcount; $i++) {
            $accode = $_POST['accode_' . $i];
            $prinamt = $_POST['prinamt_' . $i];
            $advance = $_POST['advance_' . $i];
            $interest = $_POST['interest_' . $i];
            $latefee = $_POST['latefee_' . $i];
            $openbal = $_POST['openbal_' . $i];
            $dc = $_POST['dc_' . $i];

            mysqli_query($conn, "UPDATE `$maindb` SET `prinamt`='$prinamt', `advance`='$advance', `interest`='$interest', `latefee`='$latefee',`openbal`='$openbal',
                    `dc`='$dc' WHERE accode='$accode' and `series`='$series'") or die(mysqli_error($conn));
        }
    }

    if ($savetype == 2) {


        for ($i = 0; $i <= $count; $i++) {
            $accode = $_POST['accode_' . $i];
            $debit = $_POST['debit_' . $i];
            $credit = $_POST['credit_' . $i];

            if ($debit > 0) {
                $mopenbal = $debit;
                $mdc = "D";
            } else {
                if ($credit > 0) {
                    $mopenbal = $credit;
                    $mdc = "C";
                } else {
                    $mopenbal = 0.00;
                }
            }


            mysqli_query($conn, "UPDATE `$maindb` SET openbal='$mopenbal', `dc`='$mdc' WHERE accode='$accode' and `series` = '$series'") or die(mysqli_error($conn));
        }
    }

    updmess();
    header("refresh: 1; $file");
}
$result = mysqli_query($conn, "SELECT `accode`,`name`,`dc`,`openbal`,`floor`,`wing`,`flatno`,`prinamt`,`advance`,`interest`,`latefee` FROM `accmast`
                       WHERE `grpcode`='010' and `series`='$series' ORDER BY name") or die(mysqli_error($conn));

include("includes/linkshead.php");
?>
<style>
    .floatingHeader {
        position: fixed;
        top: 0;
        visibility: hidden;
        background-color: #037D95;
    }

    .persist-header {
        width: 1260px;
    }
</style>
<script>
    $(document).ready(function () {
        $('#data').on('keyup focus', '.prinamt, .advance,.interest,.latefee', calculateSum);
        $('#data').on('keyup focus', '.cal, .cal2', calculatecal);
        $('body').on('click', '.sbutton', filter);
        $('body').on('change focus', '#cmbtype', loadmain);


        $(document).keydown(function (event) {
            //19 for Mac Command+S
            if (!(String.fromCharCode(event.which).toLowerCase() == 's' && event.altKey) && !(event.which == 19))
                return true;
            //alert("Ctrl-s pressed");
            $("#submit").click();
            event.preventDefault();
            return false;
        });


        function loadmain() {
            var cmbtype = $('#cmbtype').val();
            var stype = $('.stype').val(),
                    sterm = $('#sterm').val();
            

            if (cmbtype == 2) {
                $.ajax({
                    type: "GET",
                    url: "opnbalall.php",
                    data: {
                        code: cmbtype,
                        stype: stype,
                        sterm: sterm
                    },
                    success: function (result) {
                        $("#data").html(result);
                        //                        $('.divmem').hide();
                        calculatecal();
                    }

                });
            } else {
                $.get("opnbalsrch.php", function (data) {
                    //                    $('.divmem').show();
                    $("#data").html(data);
                });
            }
        }

        function calculatecal() {
            var dsum = 0;
            $(".cal").each(function () {
                if (!isNaN(this.value) && this.value.length != 0) {
                    dsum += parseFloat(this.value);
                }
            });
            $("#totdebit").val(dsum.toFixed(2));


            var csum = 0;
            $(".cal2").each(function () {
                if (!isNaN(this.value) && this.value.length != 0) {
                    csum += parseFloat(this.value);
                }
            });
            $("#totcredit").val(csum.toFixed(2));

            var diff = dsum - csum;
            $("#Difference").val(diff.toFixed(2));

            var $row = $(this).closest("tr");
            var mname = $row.find('.cal').val();
            var mname2 = $row.find('.cal2').val();

            if (mname != "" || mname != 0) {
                $($row.find('.cal2')).attr("readonly", true);
            } else {
                $($row.find('.cal2')).removeAttr("readonly");
            }


            if (mname2 != "" || mname2 != 0) {
                $($row.find('.cal')).attr("readonly", true);
            } else {
                $($row.find('.cal')).removeAttr("readonly");
            }

        }

        function calculateSum() {
            var $row = $(this).closest("tr"),
                    openbal = 0,
                    openamt = 0,
                    prinamt = $row.find('.prinamt').val(),
                    interest = $row.find('.interest').val(),
                    //                    latefee = $row.find('.latefee').val(),
                    advance = $row.find('.advance').val();
            //            openbal = parseFloat(prinamt) + parseFloat(interest) + parseFloat(latefee) - parseFloat(advance),
            openbal = parseFloat(prinamt) + parseFloat(interest) - parseFloat(advance),
                    openamt = Math.abs(openbal);
            $row.find(".openbal").val(openamt);
            //            if (latefee > 0) {
            //                $($row.find('.advance')).attr("readonly", true);
            //                $row.find('.advance').val(0);
            //            } else {
            //                $($row.find('.advance')).removeAttr("readonly");
            //            }

            if (openbal > 0) {
                $row.find('.dc').val('D');
            } else {
                $row.find('.dc').val('C');
            }

        }

        function filter() {
            var stype = $('.stype').val(),
                    sterm = $('#sterm').val();
            var cmbtype = $('#cmbtype').val();
            if (cmbtype == 2) {
                $.ajax({
                    type: "GET",
                    url: "opnbalall.php",
                    data: {
                        stype: stype,
                        sterm: sterm
                    },
                    success: function (result) {
                        $("#data").html(result);
                    }
                });

            } else {
                $.ajax({
                    type: "GET",
                    url: "opnbalsrch.php",
                    data: {
                        stype: stype,
                        sterm: sterm
                    },
                    success: function (result) {
                        $("#data").html(result);
                    }
                });
            }

        }

        $("#cmbord").change(function () {
            var cmbord = $('#cmbord').val();
            var cmbtype = $('#cmbtype').val();
            if (cmbtype == 2) {
                $.ajax({
                    type: "GET",
                    url: "opnbalall.php",
                    data: {
                        code: cmbord
                    },
                    success: function (result) {
                        $("#data").html(result);
                        //                        $('.divmem').hide();
                    }

                });
            } else {
                $.ajax({
                    type: "GET",
                    url: "opnbalsrch.php",
                    data: {
                        code: cmbord
                    },
                    success: function (result) {
                        $("#data").html(result);
                    }
                });
            }

        });

        $('#submit').click(function () {
            $('#bill').submit();
        });
    });
    $(document).keydown(function (event) {
        //19 for Mac Command+S
        if (!(String.fromCharCode(event.which).toLowerCase() == 's' && event.ctrlKey) && !(event.which == 19))
            return true;
        //alert("Ctrl-s pressed");
        $("#submit").click();
        event.preventDefault();
        return false;
    });
</script>
<script>
    function UpdateTableHeaders() {
        $(".persist-area").each(function () {

            var el = $(this),
                    offset = el.offset(),
                    scrollTop = $(window).scrollTop(),
                    floatingHeader = $(".floatingHeader", this)

            if ((scrollTop > offset.top) && (scrollTop < offset.top + el.height())) {
                floatingHeader.css({
                    "visibility": "visible"
                });
            } else {
                floatingHeader.css({
                    "visibility": "hidden"
                });
            }
            ;
        });
    }

    // DOM Ready
    $(function () {

        var clonedHeaderRow;

        $(".persist-area").each(function () {
            clonedHeaderRow = $(".persist-header", this);
            clonedHeaderRow
                    .before(clonedHeaderRow.clone())
                    .css("width", clonedHeaderRow.width())
                    .addClass("floatingHeader");

        });

        $(window)
                .scroll(UpdateTableHeaders)
                .trigger("scroll");

    });
</script>

<body>
    <!-- main content start-->


    <div class="panel panel-widget forms-panel my-div width col-lg-12">
        <form name="" class="validation" id="form" action="" method="post">
            <div class="forms">
                <div class="form-grids widget-shadow" data-example-id="basic-forms">
                    <div class="form-title">
                        <h4><?php echo $formname ?></h4>
                    </div>

                    <div class="row">
                        <div class="form-body">
                            <label class="col-sm-5 control-label text-right" style="color: #F58484;font-size: 21px"><b>SELECT ACCOUNT</b></label>
                            <div class="col-sm-2">
                                <select id="cmbtype" name="savetype" style="height:35px;" class="cmbtype form-control" autofocus>
                                    <option value="1">Members</option>
                                    <option value="2">Other Accounts</option>
                                </select>
                            </div>
                            <label class="col-sm-5 control-label " style="color: #F58484;font-size: 21px;"><b>CTRL+S - SAVE</b></label>
                        </div>
                    </div>
                    <br>
                    <div class="form-group has-error ">
                        <label class="col-sm-1 control-label text-right">Order By</label>
                        <div class="col-sm-2">
                            <select id="cmbord" name="cmbord" style="height:35px;" class="cmbord form-control">
                                <option value=""></option>
                                <option value="1" selected="">Name</option>
                                <option value="2">Wing/Flat No.</option>
                            </select>
                        </div>
                        <label class="col-sm-1 control-label text-right">Search By</label>
                        <div class="col-sm-2">
                            <select id="stype" name="stype" style="height:35px;" class="stype form-control">
                                <option value="1">Name</option>
                                <option value="2">Flat No.</option>
                                <option value="3">Wing</option>
                            </select>
                        </div>
                        <div class="col-sm-3">
                            <input type="text" id="sterm" class="sterm form-control" style="height: 35px" value="">
                        </div>
                        <div class="col-sm-1">
                            <input type="button" class="btn btn-primary sbutton " style="height: 35px" value="Search">
                        </div>
                    </div>
                </div>
            </div>
            <br>
            <div class="row">
                <div style="overflow: auto; border: 0px ;">
                    <div style="float:left;">
                        <div id='data' style="margin-right: 47px;margin-left: 41px;">
                        </div>
                    </div>
                </div>
            </div>

            <div style="overflow: auto;">
                <table class="table-condensed" style="margin: 0 auto;">
                    <tr>
                        <td class="buttonform tooltip-bottom" id="ssubmit" style="display: <? echo $savedisabled ?>" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="Save Record">
                            <button id='submit' type='submit' name='submit' value='<?php echo ($addflag == 0) ? "Update" : "Save"; ?>' class="btn btn-pad btn-square " style="background-color:#008D4C; ">
                                <i class="fa fa-check" style="color:#ffffff"></i>
                            </button>
                        </td>
                        <td class=" buttonform tooltip-bottom" id="hexit" style="display: <? echo $exitdisabled ?>" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="Exit">
                            <button id='exit' type="button" class="btn btn-pad btn-square " style="background-color:#cccccc; " onClick="window.location.href = '<?= 'default.php' ?>'">
                                <i class="fa fa-power-off" style="color:red"></i>
                            </button>
                        </td>
                    </tr>
                </table>
            </div>
            <div class="row">
                <div style="overflow: auto; border: 0px ;">
                    <div style="float:left;">
                        <div id='data' style="margin-right: 47px;margin-left: 41px;"></div>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <?php
    include("includes/linksfoot.php");
    //include("includes/valid.php");
    ?>
</body>

</html>