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

$formname = 'Sale Entry';
$maindb = 'sale';
$accdb = 'actran';

$file = 'sale.php';
$grid = '';
$source = 'SL';
$type = "S";

$keyfld = "vouchno";
$trandbexist = 0;
$focusfld = "name";
$printfile = 'sale_pdf.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];

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

    $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) {

        $path = "images/Sales/";
        $filename1 = $mvouch . ".jpg";
        $img_file1 = $path . ($filename1);

        $image_ftype = pathinfo($img_file1, PATHINFO_EXTENSION);
        $size = $_FILES['image']['size'];

        // Restrict file size to 100KB (102400 bytes)
        if ($size <= 102400) {
            move_uploaded_file($_FILES["image"]["tmp_name"], $img_file1);
        } else {
            browse("Image size should be less than 100KB. Please try again.");
            header("refresh: 2; $file?mode=last");
            exit();
        }


        mysqli_query($conn, "LOCK TABLES `$maindb` WRITE, `accmast` WRITE, `$accdb` 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;

            $geninvn = mysqli_query($conn, "SELECT MAX(CAST(SUBSTRING_INDEX(invno,'-',-1) AS UNSIGNED)) AS maxinvno FROM `$maindb` WHERE type='$type'") or die(mysqli_error($conn));
            $row = mysqli_fetch_assoc($geninvn);
            $qinvno = (!empty($row['maxinvno'])) ? ($row['maxinvno'] + 1) : 1;

            $invprefix = "";
            if ($type == "A") {
                $invprefix = "GG";
            } elseif ($type == "S") {
                $invprefix = "GM";
            }

            $minvno = $invprefix . "-" . $qinvno;
        }


        ######################## 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;
            }

            $minus_amt = ($amount * -1);

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


        if ($addflag == 1) {
            mysqli_query($conn, "INSERT INTO `$maindb`(`vouchno`, `vouchdt`, `invno`, `party`, 
                                                       `type`, `qty`, `descrip`, `rate`, `amount`, `image`)
                                               VALUES ('$qvouch', '$vouchdt', '$minvno', '$party', 
                                                       '$type', '$qty', '$descrip', '$rate', '$amount', '$img_file1')") or die(mysqli_error($conn));
        } else {
            $mvouch = $qvouch;

            mysqli_query($conn, "UPDATE `$maindb` SET `vouchdt`='$vouchdt', `party`='$party', `type`='$type', `qty`='$qty', 
                                                      `descrip`='$descrip', `rate`='$rate', `amount`='$amount', `image`='$img_file1' 
                                                      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);

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

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

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

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

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

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

    .upload-btn-wrapper {
        position: relative;
        overflow: hidden;
        display: inline-block;
    }

    .skbtn {
        border: 2px solid gray;
        color: gray;
        background-color: white;
        width: 150px;
        height: 40px;
        border-radius: 8px;
        font-size: 15px;
        font-weight: bold;
        margin-left: 30px;
    }

    .upload-btn-wrapper input[type=file] {
        font-size: 100px;
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0;
    }

    .skimg {
        width: 100%;
        max-width: 300px;
        height: 200px;
        object-fit: cover;
        border-radius: 6px;
        box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
    }

    .skimg {
        cursor: pointer;
    }

    /* .skimg {
        width: 80%;
        height: auto;
        margin-left: 10px;
        margin-top: 30px;
        margin-bottom: 30px;
        border-radius: 6px;
        box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
    } */
</style>
</head>

<body>

    <form action='' method='POST' enctype="multipart/form-data">
        <!-- 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-2 col-md-2 col-sm-2 col-xs-2 pad text-right">
                                <label class="label-control marg">Challan No.</label>
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-2 col-xs-2 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-1 col-md-1 col-sm-2 col-xs-2 pad text-right">
                                <label class="label-control marg">Date</label>
                            </div>
                            <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4 pad">
                                <input type="date" name="vouchdt" id="vouchdt"
                                    value="<?php echo ($addflag != 1) ? $get['vouchdt'] : date('Y-m-d'); ?>" class="form-control form vouchdt focusfield" required autofocus>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2  text-right pad">
                                <label class="label-control marg">Customer</label>
                            </div>
                            <div class="col-lg-6 col-md-6 col-sm-8 col-xs-8 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-2 col-md-2 col-sm-2 col-xs-2 text-right pad ">
                                <label class="label-control marg">Type</label>
                            </div>
                            <div class="col-lg-2 col-md-2 col-sm-4 col-xs-4 pad">
                                <select id="type" name="type" class="select2 form-control form type" required>
                                    <?php
                                    $typeOptions = [
                                        'A' => 'Air',
                                        'S' => 'Sea'
                                    ];

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

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

                        <div class="row">
                            <div class="col-lg-1 col-md-1 col-sm-1 col-xs-1 pad"></div>
                            <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 text-center pad">
                                <label class="label-control marg"> Qty</label>
                            </div>
                            <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 text-left pad">
                                <label class="label-control marg"> Description</label>
                            </div>
                            <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 text-center pad">
                                <label class="label-control marg"> Rate</label>
                            </div>
                            <div class="col-lg-2 col-md-2 col-sm-1 col-xs-1 text-center pad">
                                <label class="label-control marg"> Amount</label>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-lg-1 col-md-1 col-sm-1 col-xs-1 pad"></div>
                            <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 pad">
                                <input type="number" name="qty" step="any" value="<?php echo ($addflag != 1) ? $get['qty'] : "0"; ?>" class="form-control form text-right qty">
                            </div>
                            <div class="col-lg-4 col-md-3 col-sm-4 col-xs-4 pad">
                                <input type="text" name="descrip" value="<?php echo ($addflag != 1) ? $get['descrip'] : ""; ?>" class="form-control form descrip">
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-2 col-xs-2 pad">
                                <input type="number" name="rate" step="any" value="<?php echo ($addflag != 1) ? $get['rate'] : "0"; ?>" class="form-control form text-right rate">
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-2 col-xs-2 pad">
                                <input type="number" name="amount" step="any" value="<?php echo ($addflag != 1) ? $get['amount'] : "0"; ?>" class="form-control form text-right amount" readonly tabindex="-1">
                            </div>
                        </div>

                        <hr>

                        <?php if ($addflag != 1) { ?>

                        <div class="row">
                            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 pad">
                                <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4 pad">
                                    <div class="upload-btn-wrapper">
                                        <button class="skbtn">Choose Image</button>
                                        <input type="file" class="form image" name="image" accept="image/*" />
                                    </div>
                                </div>
                                <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 pad">
                                    <img class="view1 skimg" src="<?php echo ($addflag != 1) ? $get['image'] . "?a=" . mt_rand() : "" ?>" alt="Image" />
                                </div>
                            </div>
                        </div>
                        <?php } ?>
                            

                    </div>

                    <div class="panel-footer">
                        <?php include("includes/buttons.php"); ?>
                    </div>
                </div>
            </div>
        </div>
    </form>

    <div class="modal fade" id="imgModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Image Preview</h4>
                </div>
                <div class="modal-body text-center">
                    <img id="fullImage" src="" style="max-width:100%;max-height:60vh;">
                </div>
            </div>
        </div>
    </div>

    <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">Pairs</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">Pairs</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="5%">Voucher</th>
                                    <th width="10%">Date</th>
                                    <th width="25%">Customer</th>
                                    <th width="10%">Mode</th>
                                    <th width="10%">Pairs</th>
                                    <th width="10%">Amount</th>
                                    <th width="2%">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>