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

$formname = 'Sale Claim';
$maindb = 'slclaim';
$accdb = 'actran';

$file = 'slclaim.php';
$source = 'SCL';

$keyfld = "vouchno";
$trandbexist = 0;
$focusfld = "name";
$printfile = 'pursalereg.php';
$usertype = $_SESSION["usertype"];

$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];

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, `cashpay` 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;
        }

        
        ######################## auto cash Entry Start ######################################

        $mcashvouch = $_POST["cashvouch"];

        if ($type != 'R') {
            if ($mcashvouch == '0' || $mcashvouch == '') {
                $gen1 = mysqli_query($conn, "SELECT MAX(vouchno+0) 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;
            }   

            if ($type == "C") {
                $bankname = 3;
            }
            
            $getbankinit = mysqli_query($conn, "SELECT grpcode, bankinit FROM `accmast` WHERE `accode` = '$bankname'") or die(mysqli_error($conn));
            $bankinit = mysqli_fetch_array($getbankinit);
            $binit = $bankinit['bankinit'];
            $bgrp = $bankinit['grpcode'];

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

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

            $minus_amt = ($amount * -1);

            // cash part
            mysqli_query($conn, "INSERT INTO `$accdb`(date, vouchno, source, trnno, bankinit, accode, grpcode, amount)
                                                VALUES ('$vouchdt', '$mcashvouch', 'CP', '001', '$binit', '$bankname', '$bgrp', '$minus_amt')") or die(mysqli_error($conn));

            // party part
            mysqli_query($conn, "INSERT INTO `$accdb`(date, vouchno, source, trnno, accode, grpcode, amount)
                                                VALUES ('$vouchdt', '$mcashvouch', 'CP', '002', '$party', '010', '$amount')") or die(mysqli_error($conn));

            mysqli_query($conn, "INSERT INTO `cashpay`( vouchno ,`vouchdt`, `bankname`, `bankinit`, `party`, `type`, `amount`, trnflag)
                                           Values ('$mcashvouch', '$vouchdt', '$bankname', '$binit', '$party', '$type', '$amount', 'S')") or die(mysqli_error($conn));
        } else {
            mysqli_query($conn, "DELETE FROM `cashpay` WHERE `$keyfld`='$mcashvouch' ") or die(mysqli_error($conn));
            mysqli_query($conn, "DELETE FROM `actran` WHERE `$keyfld`='$mcashvouch' AND `source`='CP' ") or die(mysqli_error($conn));
            $mcashvouch = "";
        }

        ######################## auto cash Entry End ######################################

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

        if ($amount > 0) {

            if ($type == "R") {
                $purcode = 15;
            } else {
                $purcode = 14;
            }

            $getbankinit = mysqli_query($conn, "SELECT bankinit FROM `accmast` WHERE `accode` = '$bankname'") or die(mysqli_error($conn));
            $bankinit = mysqli_fetch_array($getbankinit);
            $binit = $bankinit['bankinit'];

            $minus_amt = ($amount * -1);

            // sale part
            mysqli_query($conn, "INSERT INTO `$accdb`(date, vouchno, source, trnno, bankinit, accode, grpcode, amount)
                                            VALUES ('$vouchdt', '$mvouch', '$source', '001', '$binit', '$purcode', '005', '$minus_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', '$party', '010', '$amount')") or die(mysqli_error($conn));
        }


        if ($addflag == 1) {
            mysqli_query($conn, "INSERT INTO `$maindb`(`vouchno`, `vouchdt`, `bankname`, `bankinit`, `party`, `type`, `pairs`, `amount`, `remark`, cashvouch)
                                               VALUES ('$qvouch', '$vouchdt', '$bankname', '$binit', '$party', '$type', '$pairs', '$amount', '$remark', '$mcashvouch')") or die(mysqli_error($conn));
        } else {
            $mvouch = $qvouch;

            mysqli_query($conn, "UPDATE `$maindb` SET vouchdt='$vouchdt', `party`='$party', `bankname`='$bankname', `bankinit`='$binit',
                                                      `type`='$type', `amount`='$amount',`remark`='$puramt' , cashvouch='$mcashvouch'
                                                      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);
    
    $delcsh = $get['cashvouch'];

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

    $getbank = mysqli_query($conn, "SELECT * FROM `accmast` WHERE `accode` = '$get[bankname]' ") or die(mysqli_error($conn));
    $banknm = mysqli_fetch_array($getbank);

}

/* DELETE */
if (isset($_GET["delete"])) {
    mysqli_query($conn, "LOCK TABLES `$maindb` WRITE, `accmast` WRITE, `$accdb` WRITE, `cashpay` WRITE") or die(mysqli_error($conn));
   
    $delcond = " source = '$source' and vouchno = '$_GET[vouchno]' ";
    $delcond3 = " vouchno = '$delcsh'  ";
    $delcond4 = " source = 'CP' and vouchno = '$delcsh'";

    delete($zdb, "$maindb", "$keyfld", $_GET[$keyfld], "$file?mode=last");
    delnew($zdb, "$accdb", "$delcond", "$file?mode=last");
    delnew($zdb, "cashpay", "$delcond3", "$file?mode=last");
    delnew($zdb, "$accdb", "$delcond4", "$file?mode=last");

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

include("includes/linkshead.php");
?>

<script src="MyScript/slclaim_search.js?b=<?= mt_rand() ?>" type="text/javascript"></script>
<script src="MyScript/sale.js?a=<?= mt_rand() ?>" 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;
    }

    .bgpurch {
        background-color: #8fcccc;
    }

    .row {
        width: 100%;
        margin-right: 0px;
        margin-left: 0px;
    }
</style>
</head>

<body>

    <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">
                        <h3 class="panel-title" style="color:#78909C"><a class="myPrint"><?php echo $formname; ?></a></h3>
                    </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 marg">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" value="<?php echo ($addflag != 1) ? $get['vouchno'] : $qvouch; ?>" class="form-control form" readonly>
                                <input type="hidden" class="form-control form" name="cashvouch" value="<?php echo ($addflag != 1) ? $get["cashvouch"] : ""; ?>">
                            </div>

                            <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2  text-right">
                                <label class="label-control marg">Date</label>
                            </div>
                            <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 pad">
                                <input type="date" name="vouchdt" id="vouchdt" value="<?php echo ($addflag != 1) ? $get['vouchdt'] : date('Y-m-d'); ?>" class="form-control form vouchdt" required autofocus>
                            </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 marg">Customer</label>
                            </div>
                            <div class="col-lg-6 col-md-6 col-sm-7 col-xs-7 pad">
                                <select id="party" name="party" class="form-control form party 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 = '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">
                            <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3 text-right pad">
                                <label class="label-control marg">Mode</label>
                            </div>
                            <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 pad">
                                <select id="type" name="type" class="select2 form-control form type" required>
                                    <?php
                                    $typeOptions = [
                                        'R' => 'Credit',
                                        'U' => 'UPI / Bank',
                                        'C' => 'Cash'
                                    ];

                                    foreach ($typeOptions as $value => $label) {
                                        $selected = ($get['type'] == $value) ? 'selected' : '';
                                        echo "<option value=\"$value\" $selected>$label</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>

                        <div class="row showcashbank">
                            <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3 text-right">
                                <label class="label-control marg">Bank</label>
                            </div>
                            <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 pad">
                                <select id="bankname" name="bankname" class="form-control form select2 bankname" style="width:100%">
                                    <option value="<?php echo ($addflag != 1) ? $banknm['accode'] : ""; ?>"><?php echo ($addflag != 1) ? $banknm['name'] : ""; ?></option>
                                    <?php
                                    $mown1 = mysqli_query($conn, "SELECT accode, `name` FROM `accmast` WHERE accode != '3' AND (`grpcode` = '002' or grpcode = '001') ") 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-4 col-xs-4 text-right">
                                <label class="label-control marg"> Pairs</label>
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-6 col-xs-6 pad">
                                <input type="number" name="pairs" step="any"
                                    value="<?php echo ($addflag != 1) ? $get['pairs'] : "0"; ?>"
                                    class="form-control form text-right pairs">
                            </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 marg"> Amount</label>
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-6 col-xs-6 pad">
                                <input type="number" name="amount" step="any" value="<?php echo ($addflag != 1) ? $get['amount'] : "0"; ?>" class="form-control form text-right amount">
                            </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">
                    <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="">Sort By</option>
                                <option value="1">Voucher</option>
                                <option value="2">Date</option>
                                <option value="3">Customer</option>
                                <!-- <option value="4">Mode</option> -->
                                <option value="5">Amount</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</option>
                                <option value="2">Date</option>
                                <option value="3">Customer</option>
                                <!-- <option value="4">Mode</option> -->
                                <option value="5">Amount</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="3%">Voucher</th>
                                    <th width="5%">Date</th>
                                    <th width="25%">Customer</th>
                                    <th width="5%">Mode</th>
                                    <th width="5%">Amount</th>
                                    <th width="5%">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>