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

$formname = 'Purchase & Sale Entry';
$maindb = 'purchsale';
$accdb = 'actran';
$billdb = 'billsett';

$file = 'purchsale.php';
$grid = '';
$source = 'PUSL';
$type = "S";

$keyfld = "vouchno";
$trandbexist = 0;
$focusfld = "name";
$printfile = 'pursalereg.php';
//$printfile = 'cashr_voucher.php';
$usertype = $_SESSION["usertype"];
$username = $_SESSION["username_" . $dbname];
$salelock = $_SESSION["salelock"];

$admin = $_SESSION["admin_" . $dbname];
$zdb = $_SESSION["zdbyear_" . $dbname];
$zyear = right($zdb, 4);
$zStartDate = getzdates($zyear, 'S');
$zEndDate = getzdates($zyear, 'E');
date_default_timezone_set('Asia/Kolkata');
$adduser = $_SESSION['username_' . $dbname];
$adddate = date("Y-m-d");
$addtime = date("h:i:sa");
mysqli_select_db($conn, $zdb);
include("includes/vouchno_generate.php");
include("includes/prev&next.php");

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

    $a = 1;
    $username = $_SESSION["username_" . $dbname];

    $vouchdt = $_POST["vouchdt"];
    $qvouch = $_POST["vouchno"];

    // browse($qvouch);
    $mvouch = $qvouch;

    foreach ($_POST as $key => $value) {
        $exclude_fld = ["test"];
        if (in_array($key, $exclude_fld)) {
            continue;
        }
        $$key = $value;
        // echo "Field ".htmlspecialchars($key)." is ".htmlspecialchars($value)."<br>";
    }


    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"];
        ######################## ACCOUNTS PART ######################################
        mysqli_query($conn, "DELETE FROM `$accdb` WHERE vouchno='$mvouch' AND `source`='$source'") or die(mysqli_error($conn));

//
        if ($puramt > 0) {
//            browse('suf');
            $sminus_amt = ($puramt * -1);
            $purcode = 12;


            $qrygrp = mysqli_query($conn, "select `grpcode` from accmast where `accode` = '$supplier'") or die(mysqli_error($conn));
            $fetgrp = mysqli_fetch_array($qrygrp);
            $pgrp = $fetgrp['grpcode'];

            mysqli_query($conn, "INSERT INTO `$accdb`( date, vouchno, source, trnno, accode, grpcode, amount)
                    VALUES ('$vouchdt','$mvouch', '$source', '001', '$purcode','004', '$sminus_amt')") or die(mysqli_error($conn));
            // party part
            mysqli_query($conn, "INSERT INTO `$accdb`( date, vouchno, source, trnno, accode, grpcode, amount)
                     VALUES ( '$vouchdt','$mvouch', '$source', '002', '$supplier','$pgrp', '$puramt')") or die(mysqli_error($conn));
        }
        
        if ($saleamt > 0) {
//            browse('suf');
            $cminus_amt = ($saleamt * -1);
            $purcode = 15;


            $qrygrp = mysqli_query($conn, "select `grpcode` from accmast where `accode` = '$customer'") or die(mysqli_error($conn));
            $fetgrp = mysqli_fetch_array($qrygrp);
            $pgrp = $fetgrp['grpcode'];

            mysqli_query($conn, "INSERT INTO `$accdb`( date, vouchno, source, trnno, accode, grpcode, amount)
                    VALUES ('$vouchdt','$mvouch', '$source', '003', '$purcode','004', '$saleamt')") or die(mysqli_error($conn));
            // party part
            mysqli_query($conn, "INSERT INTO `$accdb`( date, vouchno, source, trnno, accode, grpcode, amount)
                     VALUES ( '$vouchdt','$mvouch', '$source', '004', '$customer','$pgrp', '$cminus_amt')") or die(mysqli_error($conn));
        }


        if ($addflag == 1) {
            mysqli_query($conn, "INSERT INTO `purchsale`(`vouchno`, `vouchdt`, `supplier`, `purrate`, `purqty`, `puramt`, `customer`, `salerate`, `saleamt`, `diffamt`)
                                       Values ('$qvouch', '$vouchdt', '$supplier', '$purrate', '$purqty', '$puramt', '$customer', '$salerate','$saleamt', '$diffamt')") or die(mysqli_error($conn));
        } else {
            $mvouch = $qvouch;
            $editdate = date("Y-m-d");
            $edittime = date("h:i:sa");
            mysqli_query($conn, "UPDATE `$maindb` SET  vouchdt='$vouchdt', `supplier`='$supplier',`purrate`='$purrate',
                                                      `purqty`='$purqty',`puramt`='$puramt',`customer`='$customer',
                                                      `salerate`='$salerate',`saleamt`='$saleamt',`diffamt`='$diffamt'
                                                      where vouchno = '$mvouch' ") or die(mysqli_error($conn));
        }

        mysqli_query($conn, "UNLOCK TABLES");

        if ($addflag == 1) {
            insmess();
            header("refresh: 1; $file?$keyfld=$mvouch&mode=last");
        } 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);

    $getsupp = mysqli_query($conn, "SELECT * FROM `accmast` WHERE `accode` = '$get[supplier]'");
    $fetsupp = mysqli_fetch_array($getsupp);

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

/* DELETE */
if (isset($_GET["delete"])) {
    mysqli_query($conn, "LOCK TABLES `$maindb` WRITE, `accmast` WRITE, `$accdb` WRITE, `billsett` 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, "billsett", "$delsett", "$file?mode=last");


    mysqli_query($conn, "UNLOCK TABLES");
}

include("includes/linkshead.php");
?>
<script src="MyScript/purchsale.js" type="text/javascript"></script>
<!--<script src="MyScript/cashrecp_search.js" type="text/javascript"></script>-->

<script src="MyScript/checkdate.js" type="text/javascript"></script>
<script src="MyScript/shortkeys.js" type="text/javascript"></script>
<style type="text/css">
    .bgsale{
        background-color:#e3f2e1;
        /*padding: 1%;*/
    }
    .bgpurch{
        background-color:#8fcccc;
        /*padding: 1%;*/

    }
    .row{
        width:100%;
        margin-right: 0px; 
        margin-left: 0px;
    }
</style>
</head>
<body>
    <!--    <div id="preloader" class="col-lg-12 text-center">
            <h3 class="text-center">Loading</h3>
            <div id="status">&nbsp;</div>
        </div>-->
    <form action='' method='POST'>
        <!-- Default box -->
        <div class="row">
            <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 pad">
                <div class="panel panel-default">
                    <div class="panel-heading" style="height:60px">
                        <div class="col-lg-6 col-md-10 col-sm-10  col-xs-10">
                            <h3 class="panel-title" style="color:#78909C"><a class="myPrint"><?php echo $formname; ?></a></h3>
                        </div>
                        <div class="col-lg-6 col-md-2 col-sm-2 text-right col-xs-2">
                            <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="date" value="<?= $salelock ?>" style="width: 1px;border: none" class="salelock">
                            <?php
                            $useadd = $edituser = '';
                            if ($get['username'] != '' || $get['adduser'] != '') {
                                if ($get['adduser'] != '') {
                                    $addt = date("d-m-Y", strtotime($get['adddate']));
                                    $useradd = "<h4 class='panel-title' style='float:right;color:green'>" . $get['adduser'] . "&nbsp;&nbsp;&nbsp;" . $addt . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $get['addtime'] . "</h4>";
                                } else {
                                    $addt = date("d-m-Y", strtotime($get['adddate']));
                                    $useradd = "<h4 class='panel-title' style='color:green'>" . $get['username'] . "</h4>";
                                }
                            }
                            if ($get['edituser'] != '') {
                                $editdt = date("d-m-Y", strtotime($get['editdate']));

                                $edituser = "<h4 class='panel-title' style='float:right;color:orange'>" . $get['edituser'] . "&nbsp;&nbsp;&nbsp;" . $editdt . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $get['edittime'] . "</h4>";
                            }
                            if ($get['adduser'] != '' && $get['edituser'] != '') {
                                $user = $useradd . "<br>" . $edituser;
                            } else {
                                $user = $useradd . $edituser;
                            }
                            if ($usertype == 1) {
                                ?>
                                <label class="marg" style="">&nbsp;<?php echo $user; ?></label>
                            <? } else { ?>
                                <label class="marg" style="">&nbsp;<?php echo $get['adduser']; ?></label>
                            <? } ?>
                        </div>
                    </div>

                    <div class="panel-body">
                        <div class="row">
                            <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4  text-right">
                                <label class="label-control">Voucher</label>
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-6 col-xs-6 pad"> 
                                <input type="text" name="vouchno" id="vouchno"  placeholder="vouchno" value="<?php echo ($addflag != 1) ? $get['vouchno'] : $qvouch; ?>" class="form-control form"  readonly>


                            </div>
                        </div>
                        <div class="row">

                            <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4  text-right">
                                <label class="label-control">Date</label>
                            </div>
                            <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 pad"> 
                                <input type="date" name="vouchdt"   placeholder="date" value="<?php echo ($addflag != 1) ? $get['vouchdt'] : date('Y-m-d'); ?>" class="form-control form vouchdt" required autofocus="autofocus">
                            </div>
                            <!--                            <div class="col-lg-2 col-md-2 col-sm-8 col-xs-8 pad">
                                                            <a class="btn btn-primary" href="cashr_voucher.php?vouchno=<?= $qvouch; ?>" target="_blank" tabindex="-1">Voucher</a>
                                                        </div>-->
                        </div>
                        <div class="row">
                            <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4 text-right">
                                <label class="label-control"> Qty.</label>
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-6 col-xs-6 pad"> 
                                <input type="number" name="purqty" placeholder="purqty" step="any" value="<?php echo ($addflag != 1) ? $get['purqty'] : "0"; ?>" class="form-control form text-right purqty">
                            </div>
                        </div>

                        <div class="row bgpurch">
                            <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4 text-right">
                                <label class="label-control">Supplier</label>
                            </div>
                            <div class="col-lg-6 col-md-8 col-sm-8 col-xs-8   pad"> 
                                <select id="bankname" name="supplier"  class="form-control form select2">
                                    <option value="<?php echo ($addflag != 1) ? $fetsupp['accode'] : " "; ?>"><?php echo ($addflag != 1) ? $fetsupp['name'] : " "; ?></option>
                                    <?php
                                    $mown1 = mysqli_query($conn, "SELECT accode, `name` FROM `accmast` where `grpcode` = '009' or grpcode = '010' ") 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 bgpurch">

                            <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4 text-right">
                                <label class="label-control"> Purchase Rate</label>
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-6 col-xs-6 pad"> 
                                <input type="number" name="purrate" placeholder="purrate" step="any" value="<?php echo ($addflag != 1) ? $get['purrate'] : "0"; ?>" class="form-control text-right form purrate">
                            </div>
                        </div>
                        <div class="row bgpurch">
                            <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4 text-right">
                                <label class="label-control"> Purchase Amount</label>
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-6 col-xs-6 pad"> 
                                <input type="number" name="puramt" placeholder="puramt" step="any" value="<?php echo ($addflag != 1) ? $get['puramt'] : "0"; ?>" class="form-control form text-right puramt" readonly>
                            </div>

                        </div>

                        <br>
                        <div class="row bgsale" style="padding:1%">
                            <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4  text-right">
                                <label class="label-control">Customer</label>
                            </div>
                            <div class="col-lg-6 col-md-6 col-sm-7 col-xs-7 pad"> 
                                <select id="party" name="customer" class="form-control form select2">
                                    <option value="<?php echo ($addflag != 1) ? $gtpt['accode'] : " "; ?>"><?php echo ($addflag != 1) ? $gtpt['name'] : " "; ?></option>
                                    <?php
                                    $mown = mysqli_query($conn, "SELECT * FROM `accmast` where `grpcode` = '009' or grpcode = '010' order by `name`") or die(mysqli_error($conn));
                                    while ($trow = mysqli_fetch_array($mown)) {
                                        echo "<option value=$trow[accode]>$trow[name]</option>";
                                    }
                                    ?>
                                </select>
                            </div> 
                        </div>
                        <div class="row bgsale">
                            <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4 text-right">
                                <label class="label-control"> Sale Rate</label>
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-6 col-xs-6 pad"> 
                                <input type="number" name="salerate" placeholder="salerate" step="any" value="<?php echo ($addflag != 1) ? $get['salerate'] : "0"; ?>" class="form-control form text-right salerate">
                            </div>
                        </div>
                        <div class="row bgsale">

                            <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4 text-right">
                                <label class="label-control"> Sale Amount</label>
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-6 col-xs-6 pad"> 
                                <input type="number" name="saleamt" placeholder="saleamt" step="any" value="<?php echo ($addflag != 1) ? $get['saleamt'] : "0"; ?>" class="form-control form text-right saleamt" readonly>
                            </div>

                        </div>
                        <br>
                        <div class="row">
                            <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4 text-right">
                                <label class="control-label">Difference Amount</label>
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-6 col-xs-6 pad"> 
                                <input type="number" step="any" name="diffamt" id="diffamt" placeholder="diffamt" value="<?php echo ($addflag != 1) ? $get['diffamt'] : ''; ?>" class="form-control form text-right numeric diffamt" style="background-color:#fcfbb3;color:red">
                            </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>
                                                <div class="row">
                                                    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3 text-right pad">
                                                    </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 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">
                    <input type="hidden" value="<?php Echo $file ?>" class="form-control file">
                    <div class="row">
                        <div class="col-lg-2">
                            <select class="form-control sfield">
                                <option value="1">Voucher No.</option>
                                <option value="2">Date</option>
                                <option value="3">Supplier</option>
                                <option value="4">Customer</option>
                                <!--<option value="6">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 No.</option>
                                <option value="2">Date</option>
                                <option value="3">Supplier</option>
                                <option value="4">Customer</option>
                                <!--<option value="6">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" 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 class="mySearchTr">
                                    <th width="15%">Voucher No.</th>
                                    <th width="15%">Date</th>
                                    <th width="25%">Supplier</th>
                                    <th width="14%">Purchase Amount</th>
                                    <th width="25%">Customer</th>
                                    <th width="14%">Sale Amount</th>
                                    <th width="14%">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"  class="btn btn-primary sprev" value="Previous">
                            <input type="button"  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>
