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

$formname = 'Card Sale';
$maindb = 'cardsale';
$accdb = 'actran';

$printfile = "cardsale_print.php";
$file = 'cardsale.php';
$trandbexist = 0;
$grid = '';
$keyfld = "vouchno";
$keycond = "";
$source = "CDSL";

$focusfield = "name";

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

$zcono = $_SESSION["comp_" . $dbname];
$zyear = $_SESSION["tit_" . $dbname];
$zroot = $dbname;

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

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

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

    $a = 1;
    $id = $_POST["id"];
    $vouchno = $_POST["vouchno"];
    $qvouch = $_POST["vouchno"];

    $vouchdt = $_POST["vouchdt"];
    $rem1 = $_POST["rem1"];
    $rem2 = $_POST["rem2"];

    $billamt = $_POST["billamt"];

    $adduser = $_POST["adduser"];
    $adddate = $_POST["adddate"];
    $addtime = $_POST["addtime"];
    $edituser = $_POST["edituser"];
    $editdate = $_POST["editdate"];
    $edittime = $_POST["edittime"];

    $shift = $_POST["shift"];
    $setno = $_POST["setno"];
    $owner = $_POST["owner"];
    $trnflag = "D"; // for card

    $accode = $owner;

    if ($shift > 1) {
        $trndate = date('Y-m-d', strtotime($vouchdt . ' + 1 days'));
    } else {
        $trndate = $vouchdt;
    }

    $chkcomp = mysqli_query($conn, "SELECT * FROM $zroot.compyear WHERE cono = '$zcono' AND finyear = '$zyear' ") or die(mysqli_error($conn));
    $fetcomp = mysqli_fetch_assoc($chkcomp);
    $suppcode = $fetcomp["suppcode"];

    IF ($suppcode == 0) {
        browse('Supplier Code Empty In Year Creation');
        $a = 0;
    }

    IF ($owner != '') {
        $suppcard = 0;

        $chkacc = mysqli_query($conn, "SELECT suppcard FROM `accmast` where accode = '$owner' ") or die(mysqli_error($conn));
        $fetacc = mysqli_fetch_array($chkacc);
        browse(mysqli_num_rows($chkacc));

        if (mysqli_num_rows($chkacc) <= 0) {
            browse('Invalid Card A/c.');
            $a = 0;
        } ELSE {
            $suppcard = $fetacc['suppcard'];
        }
    } ELSE {
        browse("Card A/c. Cannot Be Empty");
        $a = 0;
    }

//    browse($owner);
//    browse($suppcard);


    $mvouch = $qvouch;

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

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


        //**************************************************        auto cash Entry Start  ***************************************

        $mcashvouch = $_POST["cashvouch"];
        $recpamt = $billamt;
        $cashamt = $billamt;

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

        $genrecp = mysqli_query($conn, "SELECT vouchno,recpno FROM `cashpay` where `vouchno` = '$mcashvouch' ") or die(mysqli_error($conn));
        if (mysqli_num_rows($genrecp) > 0) {
            $fetrecp = mysqli_fetch_array($genrecp);
            $mrecpno = $fetrecp['recpno'];
            $mcashvouch = $fetrecp['vouchno'];
        } else {
            $gen2 = mysqli_query($conn, "SELECT MAX(recpno) AS maxcode FROM `cashpay` where bankname = '3' LIMIT 0,1 ") or die(mysqli_error($conn));
            if (mysqli_num_rows($gen2) > 0) {
                $gvouch = mysqli_fetch_assoc($gen2);
                $mrecpno1 = $gvouch["maxcode"] + 1;
            } else {
                $mrecpno1 = '1';
            }
            $mrecpno = $mrecpno1;
        }

        mysqli_query($conn, "DELETE FROM `cashpay` WHERE `$keyfld`='$mcashvouch' ") or die(mysqli_error($conn));

        mysqli_query($conn, "INSERT INTO `cashpay`( vouchno ,`vouchdt`, `bankname`, `bankinit`, `recpno`, `party`,`amount`, `shift`,`remark1`,`remark2`,`trnflag`)
                                       Values ('$mcashvouch', '$vouchdt', '3', 'COH', '$mrecpno','$accode', '$cashamt', '$shift', '','', '$trnflag')") or die(mysqli_error($conn));

        $minus_amt = ($cashamt * -1);

        mysqli_query($conn, "DELETE FROM `$accdb` WHERE `$keyfld`='$mcashvouch' and `source` = 'CP' $keycond") or die(mysqli_error($conn));

        // cash part  
        mysqli_query($conn, "INSERT INTO `$accdb`(date, vouchno, recpno, source, trnno, bankinit, accode, grpcode, amount, drawbank, shift, trnflag)
                                 VALUES ('$trndate', '$mcashvouch', '$mrecpno', 'CP', '001', 'COH', '3','002', '$cashamt', '$setno', '$shift', '$trnflag')") or die(mysqli_error($conn));

        // party part
        mysqli_query($conn, "INSERT INTO `$accdb`(date, vouchno, recpno, source, trnno, bankinit, accode, grpcode, amount, drawbank, shift, trnflag)
                                 VALUES ('$trndate', '$mcashvouch', '$mrecpno', 'CP', '002', 'COH', '$accode', '010', '$minus_amt', '$setno', '$shift', 'D')") or die(mysqli_error($conn));



        ############################### Accounts Part ######################################################

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

        if ($suppcard > 0) {
            $minus_amt = ($billamt * -1);

            // sale part
            mysqli_query($conn, "INSERT INTO `$accdb`(date, vouchno, source, trnno, accode, grpcode, amount, drawbank, shift, trnflag)
                                              VALUES ('$trndate','$mvouch', '$source', '001', '$owner','010', '$billamt', 
                                                      '$setno', '$shift', '$trnflag') ") or die(mysqli_error($conn));

            // party part
            mysqli_query($conn, "INSERT INTO `$accdb`(date, vouchno, source, trnno, accode, grpcode, amount, drawbank, shift, trnflag)
                                              VALUES ('$trndate','$mvouch', '$source', '002', '$suppcode', '009', '$minus_amt',
                                                      '$setno', '$shift', '$trnflag') ") or die(mysqli_error($conn));
        }

        ############################## MAIN  ######################################################


        if ($addflag == 1) {
            mysqli_query($conn, "INSERT INTO `$maindb`(`vouchno`,`vouchdt`,`rem1`, `rem2`,`billamt`,`adduser`, `adddate`, `addtime`, 
                                                        `edituser`,`editdate`,`edittime`,`shift`,`setno`,`owner`, `cashvouch`)
                                                VALUES('$mvouch','$vouchdt','$rem1','$rem2','$billamt','$adduser','$adddate','$addtime',
                                                        '$edituser','$editdate','$edittime','$shift','$setno','$owner', '$cashvouch')") or die(mysqli_error($conn));
            insmess();
            $mvouch = $qvouch; //1
            header("refresh: 1; $file?$keyfld=$mvouch&mode=last");
        } else {
            $mvouch = $qvouch; //1
            $editdate = date("Y-m-d");
            $edittime = date("h:i:sa");
            mysqli_query($conn, "UPDATE `$maindb` SET `vouchdt`='$vouchdt',`shift`='$shift',`setno`='$setno',`owner`='$owner', `billamt`='$billamt',
                                         `cashvouch` = '$cashvouch', `rem1`='$rem1', `rem2`='$rem2', `edituser`='$edituser', `editdate`='$editdate', `edittime`='$edittime', 
                                         `adduser`='$adduser', `adddate`='$adddate', `addtime`='$addtime' WHERE `vouchno` = '$mvouch' ") or die(mysqli_error($conn));
            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 *,DATE_FORMAT(`adddate`, '%d-%m-%Y') as addt, DATE_FORMAT(`editdate`, '%d-%m-%Y') as eddt FROM `$maindb` WHERE $keyfld='$getvouch'") or die(mysqli_error($conn));
    $get = mysqli_fetch_array($result);
    $delcsh = $get['cashvouch'];

    $getparty = mysqli_query($conn, "SELECT `accode`,`name` FROM `accmast` WHERE `accode`= '$get[owner]'") 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, `$trandb2` WRITE, `$stkdb` WRITE, `$accdb` WRITE, `cashpay` WRITE, `accmast` WRITE")or die(mysqli_error($conn));

    $delcond = " source = '$source' and vouchno = '$_GET[vouchno]'";
    $delcond1 = " source = 'CR' and vouchno = '$delcsh'";
    $delcond2 = " vouchno = '$_GET[vouchno]'";
    $delcond3 = " vouchno = '$delcsh'  ";

    delnew($zdb, "$maindb", "$delcond2", "$file?mode=last");
    delnew($zdb, "$accdb", "$delcond", "$file?mode=last");
    delnew($zdb, "$accdb", "$delcond1", "$file?mode=last");
    delnew($zdb, "cashpay", "$delcond3", "$file?mode=last");

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

include("includes/linkshead.php");
?>
<script src="MyScript/cardsale_search.js" type="text/javascript"></script>
</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'>
        <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-12 col-md-12 col-sm-12 col-xs-12 pad">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <?php include("includes/usermention.php");
                        ?>
                        <div class="heading-elements">

                        </div>
                        <a class="heading-elements-toggle"><i class="icon-menu"></i></a>
                    </div>

                    <!--                    <div class="panel-heading" style="height:40px">
                                            <div class="col-lg-10 col-md-10 col-sm-10 col-xs-12">
                                                <h3 class="panel-title" style="color:black"><a class="myPrint"><?php echo $formname; ?></a></h3>
                                            </div>
                                            <div class="col-lg-2 col-md-2 col-sm-2 col-xs-12">
                                                <input type="date" value="<?= $zStartDate ?>" style="width: 1px;border: none" class="zstdate">
                                                <input type="date" value="<?= $zEndDate ?>" style="width: 1px;border: none" class="zenddate">
                                                <h4 class="panel-title" style="float:right"><b><?php echo $get['username'] ?></b></h4>
                                            </div>
                    
                                        </div>-->
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-lg-1 col-md-2 col-sm-2 col-xs-2 text-right pad">
                                <label class="label-control marg" >Voucher</label>
                            </div>
                            <div class="col-lg-1 col-md-2 col-sm-2 col-xs-2 pad">
                                <input type="text" name="vouchno" class="form-control form vouchno" id="vouchno" value="<?php echo ($addflag != 1) ? $get['vouchno'] : $qvouch ?>" >
                                <input type="hidden" name="voucher" class="form-control form voucher" value="<?php echo ($addflag != 1) ? $get['voucher'] : '' ?>" tabindex="-1" readonly required>
                                <input type="hidden" name="monno" class="form-control form monno" value="<?php echo ($addflag != 1) ? $get['monno'] : '' ?>" >
                                <input type="hidden" class="form-control addflag" value="<?php echo $addflag ?>" >
                                <input type="hidden" name="source" class="form-control form source" value="<?= $source; ?>" id="source">
                                <input type="hidden" class="form-control form" name="cashvouch" value="<?php Echo ($addflag != 1) ? $get["cashvouch"] : ""; ?>" >
                                <input type="hidden" class="form-control form canc_flag" name="" value="<?php Echo ($addflag != 1) ? $get["canc_flag"] : ""; ?>" >
                            </div>
                            <div class="col-lg-1 col-md-1 col-sm-2 col-xs-3 text-right pad">
                                <label class="label-control marg" >Date</label>
                            </div>
                            <div class="col-lg-1 col-md-1 col-sm-3 col-xs-4 pad">
                                <input type="date" class="form-control form vouchdt focusfield" name="vouchdt"  value="<?php Echo ($addflag != 1) ? $get["vouchdt"] : date("Y-m-d"); ?>" autofocus required>
                            </div>
                            <div class="col-lg-1 col-md-1 col-sm-2 col-xs-2 text-right pad">
                                <label class="label-control marg " >Shift</label>
                            </div>
                            <div class="col-lg-1 col-md-1 col-sm-3 col-xs-4 pad">
                                <select name="shift" id="shift" class="form-control form select2 " required>
                                    <option value="<?php echo ($addflag != 1) ? $get['shift'] : ""; ?>"><?php echo ($addflag != 1) ? $get['shift'] : ""; ?></option>
                                    <?php
                                    $getshift = mysqli_query($conn, "SELECT  `shift`  FROM shift WHERE shift != '' ") or die(mysqli_error($conn));
                                    while ($trow = mysqli_fetch_array($getshift)) {
                                        echo "<option value='$trow[shift]'>$trow[shift]</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>     

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

                        <div class="row">
                            <div class="col-lg-1 col-md-1 col-sm-2 col-xs-2  pad text-right">
                                <label class="label-control marg">A/C No.</label>
                            </div>
                            <div class="col-lg-3 col-md-3 col-sm-7 col-xs-9  pad">
                                <select name="owner" class="form-control form  select2 owner" required>
                                    <option value="<?php echo ($addflag != 1) ? $lparty['accode'] : ""; ?>"><?php echo ($addflag != 1) ? $lparty['name'] : ""; ?></option>
                                    <?php
                                    $getcust = mysqli_query($conn, "SELECT accode,name FROM accmast WHERE grpcode = '010' and credcard = 1 GROUP BY name ") or die(mysqli_error($conn));
                                    while ($trow = mysqli_fetch_array($getcust)) {
                                        echo "<option value='$trow[accode]'>$trow[name]</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-1 col-md-1 col-sm-2 col-xs-2  pad text-right">
                                <label class="label-control marg">Amount</label>
                            </div>
                            <div class="col-lg-1 col-md-2 col-sm-3 col-xs-3  pad">
                                <input type="text" name="billamt" class="form-control form text-right billamt" value="<?php echo ($addflag != 1) ? $get['billamt'] : ""; ?>"/>
                            </div>  
                        </div>

                        <div class="row">
                            <div class="col-lg-1 col-md-1 col-sm-2 col-xs-3 text-right pad">
                                <label class="label-control marg">Remarks</label>
                            </div>
                            <div class="col-lg-4 col-md-4 col-sm-9 col-xs-9  pad">
                                <input type="text" class="form-control form " name="rem1" value="<?php Echo ($addflag != 1) ? $get["rem1"] : ""; ?>" >
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-1 col-md-1 col-sm-2 col-xs-3 text-right pad">
                                <label class="label-control marg"></label>
                            </div>
                            <div class="col-lg-4 col-md-4 col-sm-9 col-xs-9  pad">
                                <input type="text" class="form-control form" name="rem2" value="<?php Echo ($addflag != 1) ? $get["rem2"] : ""; ?>">
                            </div>
                        </div>



                    </div>

                    <div class="panel-footer">
                        <?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 No</option>
                                <option value="2">Voucher Date</option>
                                <option value="3">Party Name</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">Voucher Date</option>
                                <option value="3">Party Name</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 class="mySearchTr">
                                <tr>
                                    <th width="10%">Voucher</th>
                                    <th width="15%">Date</th>
                                    <th width="35%">Name</th>
                                    <th width="15%">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>
