<?php
ob_start();

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

$formname = 'Sale (Only Amt.)';
$maindb = 'saleamt';
$accdb = 'actran';
$billdb = 'billsett';

$file = 'saleamt.php';
$grid = '';
$source = 'SLAM';
$keyfld = "vouchno";
$trandbexist = 0;
$focusfld = "name";
$printfile = 'saleamt_pdf.php';
$type = "SLAM";
$admin = $_SESSION["admin_" . $dbname];
$zdb = $_SESSION["zdbyear_" . $dbname];

$zyear = right($zdb, 4);
$zStartDate = getzdates($zyear, 'S');
$zEndDate = getzdates($zyear, 'E');

mysqli_select_db($conn, $zdb);
include("includes/vouchno_generate.php");
include("includes/prev&next.php");

if (isset($_POST["submit"])) {

    $a = 1;
    $vouchdt = $_POST["vouchdt"];
    $party = $_POST["party"];
    $amount = $_POST["amount"];
    $recpno = $_POST["recpno"];
    $remark1 = $_POST["remark1"];
    $remark2 = $_POST["remark2"];
    $logdate = $_POST["logdate"];

    // browse($qvouch);
    $mvouch = $qvouch;
    $counter = $_POST["counter"];

    if ($a == 1) {
        mysqli_query($conn, "LOCK TABLES `$maindb` WRITE, `accmast` WRITE, `$accdb` WRITE, $billdb WRITE") or die(mysqli_error($conn));

        if ($addflag == 1) {
            $gen1 = mysqli_query($conn, "SELECT MAX(vouchno) AS maxcode FROM `$maindb` 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';
            }
            $mvouch = $qvouch;
        }

        $in = mysqli_query($conn, "SELECT * FROM accmast WHERE accode='$bankname'") or die(mysqli_error($conn));
        $getinit = mysqli_fetch_array($in);
        $bankinit = $getinit["bankinit"];

        $gr = mysqli_query($conn, "SELECT * FROM accmast WHERE accode='$party'") or die(mysqli_error($conn));
        $grp = mysqli_fetch_array($gr);
        $pgrp = $grp["grpcode"];

        #########################START BILL SETTLEMENT###############################################

        $billflag = $_POST["billflag"];

        if ($billflag == 1) {
            $counter = $_POST["counter"];

            mysqli_query($conn, "DELETE FROM `$billdb` WHERE `bnkvouch` = '$mvouch' AND `source` = '$source'") OR die(mysqli_error($conn));
            $billstr2 = 'Adjusted For Bill No. ';
            for ($i = 0; $i <= $counter; $i++) {
                $myearno = $_POST["yearno_" . $i];
                $mvouchno = $_POST["vouchno_" . $i];
                $mbillno = $_POST["billno_" . $i];
                $msetoff = $_POST["setoff_" . $i];
                $mdays = $_POST["days_" . $i];
                $mbillsrc = $_POST["billsrc_" . $i];
                $mbilldate = $_POST["billdate_" . $i];

                if (!empty($msetoff)) {
                    mysqli_query($conn, "INSERT INTO `billsett`(`yearno`, `type`, `vouchno`, `billno`, `setoff`, `party`, `source`, `bnkvouch`, `bankinit`, nodays, billsrc, bnkdate, billdate)
                                VALUES('$myearno', 'P', '$mvouchno', '$mbillno', '$msetoff', '$party', '$source', '$mvouch', '$bankinit', '$mdays', '$mbillsrc', '$vouchdt', '$mbilldate')") or die(mysqli_error($conn));
                    $billstr2 = $billstr2 . $mbillno . ",";
                }
            }
            $remark1 = $billstr2;
        }
        ######################## ACCOUNTS PART ######################################

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

        if ($amount > 0) {


            $samtmin = $amount * -1;
//            $gstmin = $gstamt * -1;
            // sale part
            mysqli_query($conn, "INSERT INTO `$accdb`(date, vouchno, source, trnno, accode, grpcode, amount)
                    VALUES ('$vouchdt','$mvouch', '$source', '001', '$salecode','005', '$amount')");
            // party part
            mysqli_query($conn, "INSERT INTO `$accdb`(date, vouchno, source, trnno, accode, grpcode, amount)
                     VALUES ('$vouchdt','$mvouch', '$source', '002', '$party','010', '$samtmin')");
        }

        if ($addflag == 1) {
            mysqli_query($conn, "INSERT INTO `$maindb`( vouchno ,`vouchdt`, `party`,`amount`,`remark1`,`remark2`,`type`,logdate,recpno)
                                       Values ('$qvouch', '$vouchdt', '$party','$amount','$remark1','$remark2','S','$logdate', '$recpno')") or die(mysqli_error($conn));
        } else {
            mysqli_query($conn, "UPDATE `$maindb` SET   vouchdt='$vouchdt', `recpno`='$recpno', `party`='$party', amount='$amount', 
                                        `remark1`='$remark1', `remark2`='$remark2',`type`='S', logdate='$logdate' where vouchno = '$mvouch' ") or die(mysqli_error($conn));
        }
        mysqli_query($conn, "UNLOCK TABLES");

        if ($addflag == 1) {
//            insmess();
            header("refresh: 1; $file?$keyfld=$mvouch&mode=edit");
        } else {
//            updmess();
            header("refresh: 1; $file?$keyfld=$mvouch&mode=edit");
        }
    }
}

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

    $result = mysqli_query($conn, "SELECT * FROM `$maindb` WHERE $keyfld='$getvouch'") or die(mysqli_error($conn));
    $get = mysqli_fetch_array($result);

    $getparty = mysqli_query($conn, "SELECT * FROM `accmast` WHERE `accode` = '$get[party]'");
    $gtpt = mysqli_fetch_array($getparty);

    $result2 = mysqli_query($conn, "SELECT * FROM `billsett` WHERE source = '$source' and bnkvouch = '$getvouch'") or die(mysqli_error($conn));
}

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

/* DELETE */
if (isset($_GET["delete"])) {
    mysqli_query($conn, "LOCK TABLES `$maindb` WRITE, `accmast` WRITE, `$accdb` WRITE,$billdb WRITE ") or die(mysqli_error($conn));

    delete($zdb, "$maindb", "$keyfld", $_GET[$keyfld], "$file?mode=last");
    $delsett = " source = '$source' AND bnkvouch = '$_GET[vouchno]'";
    $delcond = " source = '$source' and vouchno = '$_GET[vouchno]' ";
    delnew($zdb, "$accdb", "$delcond", "$file?mode=last");
    delnew($zdb, "$billdb", "$delcond", "$file?mode=last");
    mysqli_query($conn, "UNLOCK TABLES");
}

include("includes/linkshead.php");
?>
<script src="MyScript/checkdate.js" type="text/javascript"></script>
<script src="MyScript/shortkeys.js" type="text/javascript"></script>
<script src="MyScript/saleamt.js" type="text/javascript"></script>
</head>
<body>

    <form action='' method='POST'>
        <!-- Default box -->
        <div class="row">
            <div class="col-lg-5">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title"><?php Echo $formname; ?></h3>
                        <div class="actions pull-right">
                            <i class="fa fa-chevron-down"></i>
                            <i class="fa fa-times"></i>
                        </div>
                    </div>
                    <input type="date" value="<?= $zStartDate ?>" style="width: 1px;border: none" class="zstdate">
                    <input type="date" value="<?= $zEndDate ?>" style="width: 1px;border: none" class="zenddate">
                    <input type="hidden" class="logdate" name="logdate" value="<?php Echo ($addflag != 1) ? $get["logdate"] : ""; ?>" readonly style="">
                    <input type="hidden" class="form-control form billflag" name="billflag" value="0">
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3 text-right pad">
                                <label class="label-control marg">Voucher No.</label>
                            </div>
                            <div class="col-lg-2 col-md-2 col-sm-8 col-xs-8 pad">
                                <input type="hidden" style="" name="shrtbtn" class="shrtbtn" value="<?php Echo ($addflag != 1) ? "" : "1"; ?>">
                                <input type="text" class="form-control form vouchno" name="vouchno" id="vouchno" value="<?php Echo ($addflag != 1) ? $get["vouchno"] : "$qvouch"; ?>" required readonly>
                                <input type="hidden" class="form-control form trnflag" name="trnflag" value="<?php Echo ($addflag != 1) ? $get["trnflag"] : ""; ?>" readonly>
                            </div>
                            <div class="col-lg-1 col-md-2 col-sm-3 col-xs-3 text-right pad">
                                <label class="label-control marg">Date</label>
                            </div>
                            <div class="col-lg-4 col-md-3 col-sm-8 col-xs-8 pad">
                                <input type="date" class="form-control form vouchdt focusfield" name="vouchdt" id="vouchdt" value="<?php Echo ($addflag != 1) ? $get["vouchdt"] : date("Y-m-d"); ?>" required>
                            </div>
                        </div>


                        <div class="row">
                            <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3 text-right pad">
                                <label class="label-control marg">Party</label>
                            </div>
                            <div class="col-lg-7 col-md-7 col-sm-8 col-xs-8 pad">
                                <select id="party" name="party" class="select2 form-control party form" required>
                                    <option value="<?php echo ($addflag != 1) ? $gtpt['accode'] : ""; ?>"><?php echo ($addflag != 1) ? $gtpt['name'] : ""; ?></option>
                                    <?php
                                    $mown1 = mysqli_query($conn, "SELECT * FROM `accmast` where (grpcode = '006' OR grpcode = '039') order by `name`") or die(mysqli_error($conn));
                                    while ($trow1 = mysqli_fetch_array($mown1)) {
                                        echo "<option value=$trow1[accode]>$trow1[name]</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3 text-right pad">
                                <label class="label-control marg">Invoice No.</label>
                            </div>
                            <div class="col-lg-3 col-md-3 col-sm-8 col-xs-8 pad">
                                <input type="text" name="recpno" value="<?php echo ($addflag != 1) ? $get['recpno'] : ""; ?>" class="form-control form">                                    
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3 text-right pad">
                                <label class="label-control marg">Amount</label>
                            </div>
                            <div class="col-lg-3 col-md-3 col-sm-8 col-xs-8 pad" >
                                <input type="text" name="amount" id="amount" value="<?php echo ($addflag != 1) ? $get['amount'] : ''; ?>" class="form-control form text-right">
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3 text-right pad">
                                <label class="label-control marg">Remark</label>
                            </div>
                            <div class="col-lg-7 col-md-7 col-sm-8 col-xs-8 pad">
                                <input type="text" name="remark1" value="<?php echo ($addflag != 1) ? $get['remark1'] : ''; ?>" class="form-control form remark1" >
                            </div>
                        </div>

                        <?php
                        if ($get['remark2'] != '') {
                            $billstr = $get['remark2'];
                        } else {
                            if (!empty($result2)) {

                                $count = mysqli_num_rows($result2);
                                $no = 1;
                                $billstri = '';
                                if ($count > 0) {
                                    $billstr2 = 'Adjusted For Bill No. ';

                                    while ($row2 = mysqli_fetch_array($result2)) {
                                        $bbno = $row2['billno'];
                                        $billstri = $billstri . $bbno . ",";
                                    }
                                }
                            }

                            $billstr = $billstr2 . " " . $billstri;
                        }
//                        
                        ?>
                        <div class="row">
                            <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3 text-right pad">
                                <label class="label-control marg"></label>
                            </div>
                            <div class="col-lg-7 col-md-7 col-sm-8 col-xs-8 pad">
                                <input type="text" name="remark2" value="<?php echo ($addflag != 1) ? $billstr : ''; ?>" class="form-control form remark2" >
                            </div>
                        </div>
                    </div>
                    <div class="panel-footer">
                        <?php include("includes/buttons.php"); ?>
                    </div>
                </div>
            </div>
            <div class="modal fade " tabindex="" id="settmodal" 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">Bill Settlement</h4>
                        </div>
                        <div class="modal-body">
                            <div class=" table-responsive">
                                <div class="toolbar">
                                    <div class="row">
                                        <div class="col-lg-2"><label class="label-control marg" style="color:red">Total Remain</label></div>
                                        <div class="col-lg-2"><input type="text" id="remain" name="remain" class="form-control" readonly style=""></div>
                                        <div class="col-lg-2"><label class="label-control marg" style="color:blue">Total Setoff</label></div>
                                        <div class="col-lg-2"><input type="text" id="totsetoff" name="totsetoff" class="form-control" readonly style=""></div>
                                        <!--<div class="col-lg-2"><input id="submit" type='submit' name='submit' value='<?php // echo ($addflag == 0) ? "Update" : "Save";                                 ?>' class="btn btn-primary"></div>-->
                                        <?php
//                                    if (!isset($_GET["method"])) {
                                        ?>
                                        <!--<div class="col-lg-2"><input type='button' name='exit' value='Exit' class="btn btn-danger" onClick="window.location.href = '<?php echo $grid; ?>'"></div>-->
                                        <?php // }    ?>
                                    </div>
                                </div>
                                </header>
                                <div id="div-2" class="accordion-body collapse in body">
                                    <div style="max-height:300px;overflow: auto; border: 0px solid;">
                                        <div id="data"></div>  
                                    </div>
                                </div>    
                            </div>
                        </div>
                        <div class="modal-footer"></div>
                    </div>
                </div>
            </div>
        </div>
    </form>
    <div class="modal fade bs-example-modal-lg" 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=" table-responsive">
                        <table id="example1" class="table table-striped">
                            <thead>
                                <tr class="mySearchTr">
                                    <th>Voucher</th>
                                    <th>Date</th>
<!--                                    <th>Cash Name</th>-->
                                    <th>Supplier</th>
                                    <th>Amount</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                if ($addflag != 1) {
                                    $srchresult = mysqli_query($conn, "SELECT *,Date_Format(`vouchdt` , '%d/%m/%Y') as mydt FROM `$maindb`") or die(mysqli_error($conn));
                                    while ($row = mysqli_fetch_array($srchresult)) {
                                        $gparty = mysqli_query($conn, "SELECT * FROM `accmast` WHERE `accode` = '$row[party]'");
                                        $gtpt1 = mysqli_fetch_array($gparty);

                                        echo "<tr class='clickable-row' data-href='$file?mode=edit&$keyfld=$row[$keyfld]'>";
                                        echo "<td align='left'>$row[vouchno]</td>";
                                        echo "<td align='left'>$row[mydt]</td>";
                                        echo "<td align='left'>$gtpt1[name]</td>";
                                        echo "<td align='left'>$row[amount]</td>";
                                        echo "<td align='left'><a href=\"$file?mode=edit&$keyfld=$row[$keyfld]\"><i class='fa fa-pencil' style='font-size:1.3em;color:#00C0EF;cursor:pointer;'></i></a></td>";
                                        echo "</tr>";
                                    }
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer"></div>
            </div>
        </div>
    </div>
    <?php include("includes/linksfoot.php"); ?>
</body>
</html>
