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

$maindb = 'credmain';

$trandb = 'credoth';
$formname = 'Credit Note';

$accdb = 'actran';
$printfile = "crednote_print.php";
$file = 'crednote.php';
$trandbexist = 1;
$source = "CN";
$series = $_SESSION["society_" . $dbname];
$usertype = $_SESSION["usertype_" . $dbname];

$adduser = $_SESSION['username_' . $dbname];
date_default_timezone_set("Asia/Kolkata");
$adddate = date("Y-m-d");
$addtime = date("h:i:sa");
$zroot = $_SESSION["zdir"];

if (empty($series)) {
    browse("Invalid Society Credentials Forced Logout.");
    print '<script type="text/javascript">';
    print " top.window.location = 'index.php'";
    PRINT '</script>';
}

$keyfld = "vouchno";
$keycond = "and `series`= '$series'";




$admin = $_SESSION["admin_" . $dbname];
$zdb = $_SESSION["zdbyear_" . $dbname];

mysqli_select_db($conn, $zdb);

include("includes/vouchno_generate.php");
include("includes/prev&next.php");

if (isset($_POST["submit"])) {
    $a = 1;
    $vouchdt = trim($_POST["vouchdt"]);
    $party = trim($_POST["party"]);
    $billamt = trim($_POST["billamt"]);

    $rem1 = trim($_POST["rem1"]);
    $rem2 = trim($_POST["rem2"]);
    $count = $_POST["items"];

    $mvouch = $qvouch;


    $getparty = mysqli_query($conn, "SELECT `accode`,`name`, `flatno` FROM `accmast` WHERE `accode`='$party'")or die(mysqli_error($conn));
    $gparty = mysqli_fetch_array($getparty);
    $partyname = $gparty['name'];
    $flatno = $gparty['flatno'];

    if ($billamt <= 0) {
        browse("Bill Amount Cannot Be Zero");
        $a = 0;
    }

    if (empty($party)) {
        $a = 0;
        browse("Party Cannot Be Empty");
    }

//    browse($a);

    if ($a == 1) {

        if ($addflag == 1) {
            $gen1 = mysqli_query($conn, "SELECT MAX(vouchno) AS maxcode FROM `$maindb` where vouchno != '' LIMIT 0,1 ") or die(mysqli_error($conn));
            if (mysqli_num_rows($gen1) > 0) {
                $vvouch = mysqli_fetch_assoc($gen1);
                $qvouch = $vvouch["maxcode"] + 1;
            } else {
                $qvouch = '1';
            }

            $mlen = strlen($qvouch);
            $mvouch = str_repeat("0", 6 - $mlen) . $qvouch;
        }


        mysqli_query($conn, "LOCK TABLES `$maindb` WRITE, `$trandb` WRITE, `item` WRITE, `$stkdb` WRITE, `$accdb` WRITE, `inttran` WRITE,$zroot.`billingcycle` WRITE, $zroot.`company` WRITE");

        mysqli_query($conn, "DELETE FROM `$trandb` WHERE vouchno='$mvouch' $keycond") or die(mysqli_error($conn));
        mysqli_query($conn, "DELETE FROM `$accdb` WHERE `vouchno` = '$mvouch' AND `source` = '$source' $keycond") OR die(mysqli_error($conn));

        $chk = 0;
        for ($i = 0; $i <= $count; $i++) {


            $msrno = $_POST["srno_$i"];
            $debparty = $_POST["debparty_$i"];
            $amt = $_POST["amount_$i"];
            $mamt = $_POST["amount_$i"] * -1;

            
            if (!empty($debparty) && !empty($amt)) {
                $chk++;
                mysqli_query($conn, "INSERT INTO `$trandb`(series, vouchno, vouchdt, srno, debparty, amount)
                            VALUES('$series','$mvouch', '$vouchdt', '$msrno', '$debparty', '$amt')") or die(mysqli_error($conn));


                $getparty1 = mysqli_query($conn, "SELECT `accode`,`name`,grpcode FROM `accmast` WHERE `accode`='$debparty'")or die(mysqli_error($conn));
                $gparty1 = mysqli_fetch_array($getparty1);
                $dbpartygrp = $gparty1['grpcode'];

                mysqli_query($conn, "INSERT INTO `$accdb`(series, date, vouchno, source, trnno, accode, grpcode, amount)
                    VALUES ('$series','$vouchdt','$mvouch', '$source', '001', '$debparty','$dbpartygrp', '$mamt')");
            }
            
        }

        if ($chk == 0) {
            $billamt = 0;
            browse('Entry Will Not Be Saved. Description Cannot Be Empty');
            header("refresh: 1; $file?mode=last");
            return false;
        }
######################### STOCK PART ####################################################
############################### Accounts Part ######################################################
//        IF ($chkledg == 1) {
        if ($billamt > 0) {
            $minus_amt = ($billamt * -1);
// sale part


            for ($i = 0; $i <= $count; $i++) {


                $msrno = $_POST["srno_$i"];
                $debparty = $_POST["debparty_$i"];
            }

// party part
            mysqli_query($conn, "INSERT INTO `$accdb`(series, date, vouchno, source, trnno, accode, grpcode, amount)
                     VALUES ('$series','$vouchdt','$mvouch', '$source', '002', '$party','010', '$billamt')");

            mysqli_query($conn, "DELETE FROM `inttran` WHERE vouchno='$mvouch' AND `source`='$source' $keycond") or die(mysqli_error($conn));

            //            interst part start


            $gmember = mysqli_query($conn, "SELECT  `interest` FROM `accmast` Where `accode`='$party'") or die(mysqli_error($conn));
            $fmember = mysqli_fetch_assoc($gmember);
            $intopen = $fmember['interest'];

            $gint = mysqli_query($conn, "SELECT sum(amount) as amt FROM `actran` WHERE `accode`='$party'
                                and date < '$vouchdt' and `source` ='INT' ") or die(mysqli_error($conn));
            $fint = mysqli_fetch_array($gint);
            $intacc = $fint['amt'] * -1;

            $gint2 = mysqli_query($conn, "SELECT sum(amount) as amt FROM `inttran` WHERE `accode`='$party'
                                and date < '$vouchdt'") or die(mysqli_error($conn));
            $fint2 = mysqli_fetch_array($gint2);
            $intpaid = $fint2['amt'];


            $totint = $intopen + $intacc - $intpaid;

            if ($totint > 0) {
                if ($billamt >= $totint) {
                    $paidint = $totint;
                } else {
                    $paidint = $billamt;
                }
                $getsoc = mysqli_query($conn, "SELECT * FROM $zroot.`company` WHERE `code` = '$series' ") or die(mysqli_error($conn));
                $fetsoc = mysqli_fetch_array($getsoc);
                $billcycle = $fetsoc['billcycle'];
                $curmon = date('m', strtotime($vouchdt));
                if ($curmon == 12) {
                    $nextmon = 1;
                } else {
                    $nextmon = $curmon + 1;
                }
                $gbilcode = mysqli_query($conn, "SELECT checkdate,descrip FROM $zroot.`billingcycle` Where `billcycle`='$billcycle' and `code` = '$nextmon' ") or die(mysqli_error($conn));
                $fetbilcode = mysqli_fetch_array($gbilcode);

                $chkdate = date("Y", strtotime($vouchdt));

                $chkdt = $fetbilcode['checkdate'] . $chkdate;

                $checkdate = date("Y-m-d", strtotime($chkdt));
                mysqli_query($conn, "INSERT INTO `inttran`(series, date, vouchno, source, flatno, trnno, accode, bankinit, grpcode, amount, chqno,
                                              chqdate,`recpno`,`clrdate`)
                     VALUES ('$society','$checkdate','$mvouch', '$source','$flatno', '001', '$party', '$binit', '$pgrp', '$paidint','$chqno', '$chqdate',
                             '$recpno','$checkdate')") or die(mysqli_error($conn));
            }


//            interst part endF
            if ($addflag == 1) {
                mysqli_query($conn, "INSERT INTO `$maindb`(vouchno, `series`, `vouchdt`, `accode`,   `billamt`, `rem1`, `rem2`, adduser, adddate, addtime)
                                          VALUES('$mvouch', '$series', '$vouchdt', '$party',  '$billamt', '$rem1', '$rem2','$adduser', '$adddate', '$addtime')") or die(mysqli_error($conn));
            } else {
                $editdate = date("Y-m-d");
                $edittime = date("h:i:sa");

                mysqli_query($conn, "UPDATE `$maindb` SET  `accode`='$party', `vouchdt`='$vouchdt', `edituser`='$adduser',`edittime`='$edittime',`editdate`='$editdate',
                        `billamt`='$billamt', `rem1`='$rem1', `rem2`='$rem2'  WHERE vouchno = '$mvouch' $keycond ") or die(mysqli_error($conn));
            }
        }

        mysqli_query($conn, "UNLOCK TABLES")or die(mysqli_error($conn));
        if ($addflag == 1) {
            insmess();
            header("refresh: 1; $file?mode=true&$keyfld=$mvouch");
        } else {
            updmess();
            header("refresh: 1; $file?mode=edit&$keyfld=$mvouch");
        }
    }
}


if ($addflag != 1) {

    $getvouch = '';
    if ($addflag == 0) {
        $getvouch = $_GET[$keyfld];
    } else {
        $getvouch = $qvouch;
    }
//    browse($getvouch);

    $result = mysqli_query($conn, "SELECT *,DATE_FORMAT(`editdate`,'%d-%m-%Y') as editdate, DATE_FORMAT(`adddate` ,'%d-%m-%Y')AS adddate  FROM `$maindb` WHERE $keyfld='$getvouch'  ") or die(mysqli_error($conn));
    $get = mysqli_fetch_array($result);

    $getparty = mysqli_query($conn, "SELECT `accode`,`name`, `flatno` FROM `accmast` WHERE `accode`= '$get[accode]' ") or die(mysqli_error($conn));
    $lparty = mysqli_fetch_array($getparty);
}

$senable = "";
$cenable = "";

if (isset($_GET["delete"])) {
    mysqli_query($conn, "LOCK TABLES `$maindb` WRITE, `$trandb` WRITE,  `$accdb` WRITE, inttran WRITE")or die(mysqli_error($conn));

    $delcond2 = " vouchno = '$_GET[vouchno]' and series ='$series'";
    $delcond = " source = '$source' and vouchno = '$_GET[vouchno]' and series ='$series'";

    delnew($zdb, "$maindb", "$delcond2", "$file?mode=last");
    delnew($zdb, "$trandb", "$delcond2", "$file?mode=last");
    delnew($zdb, "$accdb", "$delcond", "$file?mode=last");
    delnew($zdb, "inttran", "$delcond", "$file?mode=last");
}

include("includes/linkshead.php");
?>
<script src="MyScript/crednote.js?A=<?= mt_rand(); ?>" type="text/javascript"></script>
<script src="MyScript/crednote_search.js" type="text/javascript"></script>
<script src="MyScript/search_item.js?A=<?= mt_rand(); ?>" type="text/javascript"></script>
</head>
<body>
    <form action='' method='POST'>
        <div class="col-lg-3 pad text-center" id="overlay_form" style="display:none;z-index:999;">
            <button type="button" id="close_form" style="float: right;font-weight: bold;font-size: 18px;color:red;" ><i class="fa fa-close"></i></button>
            <div style='width:100%;' id='browdata'>
            </div>
        </div>
        <!-- Default box -->
        <div>
            <div class="col-lg-10 col-md-8 col-sm-12 col-xs-12  pad">
                <div class="panel panel-default">
                    <div class="row" style="background-color:#F5F5F5">
                        <div class="col-lg-3" style="color:#64CCFC"><h4><?php Echo $formname; ?></h4></div>
                        <?php if ($usertype == 1) { ?>

                            <div class="col-lg-3"><label class=" marg" style="color:green;font-size: 14px">&nbsp;<?php Echo $get["adduser"]; ?></label><br>
                                <?php if ($get["edituser"] != '') { ?>
                                    <label class="marg" style="color:red;font-size: 14px"><?php Echo $get["edituser"]; ?></label>
                                <? } ?>
                            </div>
                            <div class="col-lg-2"><label class=" marg" style="color:green;font-size: 14px"><?php Echo $get["adddate"]; ?></label>
                                <?php if ($get["editdate"] != '00-00-0000') { ?>
                                    <label class="marg" style="color:red;font-size: 14px"><?php Echo $get["editdate"]; ?></label>
                                <? } ?>
                            </div>
                            <div class="col-lg-1"><label class="marg" style="color:green;font-size: 14px"><?php Echo $get["addtime"]; ?></label>
                                <?php if ($get["edittime"] != '00:00:00') { ?>
                                    <label class=" marg" style="color:red;font-size: 14px"><?php Echo $get["edittime"]; ?></label>
                                <? } ?>
                            </div>
                        <? } ?>
                    </div>
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-lg-1 col-md-3 col-sm-3 col-xs-3 text-right pad">
                                <label class="label-control marg">Voucher</label>
                            </div>
                            <div class="col-lg-1 col-md-8 col-sm-8 col-xs-8 pad">
                                <input type="text" class="form-control form vouchno" name="vouchno" value="<?php Echo ($addflag != 1) ? $get["vouchno"] : " $qvouch"; ?>" required readonly>
                                <input type="hidden" class="form-control form addflg" name="addflg" value="<?php Echo ($addflag != 1) ? $addflag : " $addflag"; ?>" >
                            </div>
                            <div class="col-lg-1 col-md-3 col-sm-3 col-xs-3 text-right pad">
                                <label class="label-control marg">Date</label>
                            </div>
                            <div class="col-lg-2 col-md-8 col-sm-8 col-xs-8 pad">
                                <input type="date" class="form-control form" name="vouchdt" value="<?php Echo ($addflag != 1) ? $get["vouchdt"] : date("Y-m-d"); ?>" autofocus >
                            </div>
                            <div class="col-lg-1 col-md-3 col-sm-3 col-xs-3 text-right">
                                <label class="label-control marg">Flat</label>
                            </div>
                            <div class="col-lg-1 col-md-3 col-sm-3 col-xs-3 pad">
                                <input type="text" name="flatno" value="<?php echo ($addflag != 1) ? $lparty['flatno'] : ""; ?>" class="form-control form flatno" >
                            </div>
                            <div class="col-lg-1 col-md-3 col-sm-3 col-xs-3 text-right pad">
                                <label class="label-control marg">Member</label>
                            </div>
                            <div class="col-lg-4 col-md-8 col-sm-8 col-xs-8 pad">
                                <select name="party" class="form-control form member select2" id="party" style='width:90%' required>
                                    <option value="<?php echo ($addflag != 1) ? $lparty['accode'] : " "; ?>"><?php echo ($addflag != 1) ? $lparty['name'] : " "; ?></option>
                                    <?php
                                    $mown2 = mysqli_query($conn, "SELECT `accode`, `name` FROM `accmast` WHERE grpcode = '010'
                                                         ORDER BY name") or die(mysqli_error($conn));
                                    while ($trow2 = mysqli_fetch_array($mown2)) {
                                        echo "<option value='$trow2[accode]'>$trow2[name]</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <!--</div>-->
                    <!--            </div>
                                <div class="col-lg-8 col-md-8 col-sm-12 col-xs-12 pad goodsReturn">-->
                    <!--<div class="panel panel-default">-->
                    <div class="panel-heading">
                        <div class="actions pull-right">
                            <!--<i class="fa fa-chevron-down"></i>-->
                        </div>
                    </div>
                    <div class="panel-body">
                        <div class="table-responsive">
                            <table class="table-striped table-condensed table-bordered" width="100%">
                                <thead  class="mySearchTr">
                                    <tr> 
                                        <th style="width: 5%"></th>
                                        <th style="width: 5%">#</th>
                                        <th style="width: 70%">Description</th>
                                        <th class="text-right" style="width: 20%">Amount</th>                                    
                                    </tr> 
                                </thead>
                                <tbody class="tbody">
                                    <?php
                                    if ($addflag != 1) {

                                        $qry = mysqli_query($conn, "SELECT * FROM  `$trandb` WHERE vouchno='$getvouch' $keycond ORDER BY srno") or die(mysqli_error($conn));
                                        $ctr = 0;
                                        while ($row = mysqli_fetch_array($qry)) {

                                            $gdeb = mysqli_query($conn, "SELECT accode,name FROM `accmast` where `accode`='$row[debparty]' order by name")or die(mysqli_error($conn));
                                            $fitem = mysqli_fetch_array($gdeb);

                                            echo "<tr>";
                                            Echo "<td><i class='fa fa-close remove' style='display:none;'></i></td>";
                                            echo "<td><input type='text' size='6' maxlength='6' name='srno_" . $ctr . "' class='srno form-control  form' value='$row[srno]'></td>";
                                            echo "<td>";
                                            Echo "<select class='form-control form debparty select2' name='debparty_$ctr' style='width:100%'>";
                                            Echo "<option value='$fitem[accode]'>$fitem[name]</option>";
                                            $gitem = mysqli_query($conn, "SELECT `accode`,`name` FROM `accmast` WHERE `active`='1' and `grpcode`!='$get[accode]' and `grpcode`!='001' and`grpcode`!='002' $keycond order by name")or die(mysqli_error($conn));
                                            while ($item = mysqli_fetch_array($gitem)) {
                                                Echo "<option value='$item[accode]'>$item[name]</option>";
                                            }
                                            Echo "</select>";
                                            echo "</td>";
                                            echo "<td><input type='text' name='amount_$ctr' class='amtoth form-control form text-right' value='$row[amount]' ></td>";
                                            echo "</tr>";
                                            $ctr++;
                                        }
                                    } else {
                                        $pctr = 0;
                                        $yctr = 0;
                                        $yctr++;
                                        ?>
                                        <tr>                                    
                                            <td><i class="fa fa-close remove"></td>
                                            <td><input type='text' name='srno_0' class='srno form-control form ' value='1'></td>
                                            <td><select class="form-control form debparty select2" name="debparty_0" style='width:100%'>
                                                    <option value=""></option>
                                                    <?php
                                                    $gitem = mysqli_query($conn, "SELECT * FROM `accmast` where `grpcode`!='001' and`grpcode`!='002' order by name")or die(mysqli_error($conn));
                                                    while ($item = mysqli_fetch_array($gitem)) {
                                                        Echo "<option value='$item[accode]'>$item[name]</option>";
                                                    }
                                                    ?>
                                                </select></td>
                                            <td><input type='text' name='amount_0' class='amtoth form-control form text-right' value='' ></td> 
                                        </tr>
                                        <?php
                                        $pctr++;
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                        <div class="col-lg-12 pad">
                            <button type="button" class="btn btn-primary btn-square form"  id="addnewoth">
                                <i class="fa fa-plus" data-toggle='tooltip' title='Add Row'></i>    
                            </button>
                            <input type="hidden" id="items" name="items" value="<?php Echo ($addflag != 1) ? $ctr : 1; ?>" >
                        </div>
                    </div>
                    <!--</div>-->
                    <!--            </div>
                                <div class="col-lg-8 col-md-8 col-sm-12 col-xs-12 pad">-->
                    <!--<div class="panel panel-default">-->
                    <div class="panel-heading">
                        <div class="actions pull-right">
                            <!--<i class="fa fa-chevron-down"></i>-->
                        </div>
                    </div>
                    <div class="panel-body">
                        <div class="col-lg-12 col-xs-12 pad">
                            <div class="col-lg-8 col-xs-12 pad">
                                <div class="col-lg-12 col-xs-12 pad">
                                    <div class="col-lg-2 pad text-right">
                                        <label class="label-control marg">Narration</label>
                                    </div>
                                    <div class="col-lg-10 pad">
                                        <input type="text" name="rem1" class="form-control form rem1" value="<? Echo ($addflag != 1) ? $get["rem1"] : ""; ?>">
                                    </div>
                                </div>
                                <div class="col-lg-12 col-xs-12 pad">
                                    <div class="col-lg-2 pad text-right"></div>
                                    <div class="col-lg-10 pad">
                                        <input type="text" name="rem2" class="form-control form rem2" value="<? Echo ($addflag != 1) ? $get["rem2"] : ""; ?>">
                                    </div>
                                </div>
                            </div>


                            <div class="col-lg-4 col-xs-12 pad">
                                <div class="col-lg-12 col-xs-12 pad">
                                    <!--<div class="col-lg-3 pad"></div>-->
                                    <!--<div class="col-lg-3 pad"></div>-->
                                    <div class="col-lg-6 pad text-right">
                                        <label class="label-control marg">Total (Rs.)</label>
                                    </div>
                                    <div class="col-lg-6 pad">
                                        <input type="text" name="billamt"  class="form-control form text-right obillamt" value="<?php echo ($addflag != 1) ? $get['billamt'] : ""; ?>" readonly>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-10 col-md-8 col-sm-12 col-xs-12 pad">
                <div class="panel panel-default">
                    <div class="panel-body">
                        <?php include("includes/buttons.php"); ?>
                    </div>
                </div>
            </div>
        </div>
    </form>
    <div class="modal fade bs-example-modal-lg searchModal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button class="close" data-dismiss="modal"><span>&times;</span></button>
                    <h4 class="modal-title" id="myLargeModalLabel">Search <? Echo $formname; ?></h4>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-lg-2">
                            <select class="form-control sfield">
                                <option value="1">Voucher</option>
                                <option value="2">Date</option>
                                <option value="3">Member</option>
                                <option value="4">Bill Amount</option>
                            </select>
                        </div>
                        <div class="col-lg-2">
                            <select class="form-control soperator">
                                <option value="">Type of Search</option>
                                <option value="%">Like</option>
                                <option value="=">Exactly</option>
                            </select>
                        </div>
                        <div class="col-lg-2">
                            <select class="form-control sortBy">
                                <option value="">Sort By</option>
                                <option value="1">Voucher</option>
                                <option value="2">Date</option>
                                <option value="3">Member</option>
                                <option value="4">Bill Amount</option>

                            </select> 
                        </div>
                        <div class="col-lg-2">
                            <select class="form-control orderAs">
                                <option value="desc">Desc</option>
                                <option value="asc">Asc</option>
                            </select>
                        </div>
                        <div class="col-lg-2">
                            <input type="text" value="" class="form-control ssearch" placeholder="Search Here">
                        </div>
                        <div class="col-lg-2">
                            <input type="button" style="color: black; background-color:#F17B25;" class="btn btn-primary sload" value="Search" >
                        </div>
                    </div>
                    <div class="col-lg-12 sloader text-center">
                        <!--<img src="images/search.gif" alt="loading">-->       
                    </div>
                    <div class="col-lg-12 snoRecord text-center">
                        <h3>NO RECORDS FOUND</h3>
                    </div>
                    <div class="table-responsive" style="max-height: 400px;overflow: auto;">
                        <table id="" class="table table-striped table-condensed table-bordered" width="100%">
                            <thead>
                                <tr style="background-color:#EFE4B0;">
                                    <th style="color: black;" width="10%">Vouchno</th>
                                    <th style="color: black;" width="10%">Date</th>
                                    <th style="color: black;" width="60%">Member</th>
                                    <th style="color: black;" width="10%">Bill Amount</th>
                                    <th style="color: black;" width="10%">Action</th>
                                </tr>
                            </thead>
                            <tbody class="sTbody">
                            </tbody>
                        </table>
                    </div>
                    <div class="row">
                        <div class="col-xs-12 text-right search-action-bar">
                            <input type="button" style="color: black; background-color:#EFE4B0;"  class="btn btn-primary sprev" value="Previous">
                            <input type="button" style="color: black; background-color:#EFE4B0;"  class="btn btn-primary snext" value="Next">
                        </div>
                    </div>
                </div>
                <div class="modal-footer"></div>
            </div>
        </div>
    </div>

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