<?php
ob_start();
ini_set('display_errors', 1);
error_reporting(E_ERROR);
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include('includes/function.php');
header('Content-Type: text/html; charset=utf-8');
//mysqli_query($conn, "SET NAMES 'utf8'");
//mysqli_query($conn, 'SET CHARACTER SET utf8');
mysqli_set_charset($conn, "utf8mb4");

$formname = 'List Upload';

$trandbexist = 0;
$keyfld = "vouchno";
$focusfield = "name";
$mgrpcode = '';
$keycond1 = "";
date_default_timezone_set("Asia/Kolkata");
$editdate = date("Y-m-d");
$edittime = date("h:i:sa");
$adduser = $_SESSION['username_' . $dbname];
date_default_timezone_set("Asia/Kolkata");
$adddate = date("Y-m-d");
$addtime = date("h:i:sa");
$stkdb = "transacn";
$para = $_GET["para"];
$username = $_SESSION["username_" . $dbname];
$admin = $_SESSION["admin_" . $dbname];
$zdb = $_SESSION["zdbyear_" . $dbname];
$zroot = $_SESSION["zdbroot"];
mysqli_select_db($conn, $zdb);
$source = "OL";
$maindb = 'onlmain';
$trandb = 'onltran';

if (isset($_POST["submit"])) {
    $vouchdt = date("Y-m-d");

    $a = 1;

    foreach ($_POST as $key => $value) {
        $exclude_fld = ["addfg", "submit", "vouchno"];
        if (in_array($key, $exclude_fld)) {
            continue;
        }
        $$key = $value;
    }

    $mvouch = $qvouch;

    if ($a == 1) {



        $gen1 = mysqli_query($conn, "SELECT vouchno AS maxcode FROM `$maindb` where vouchno != '' order by vouchno desc 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;

        mysqli_query($conn, "DELETE FROM `$trandb` WHERE vouchno='$mvouch' ") or die(mysqli_error($conn));
        mysqli_query($conn, "DELETE FROM `rejtran` WHERE vouchno='$mvouch' ") or die(mysqli_error($conn));
        $cnt = 0;
        $cntamt = 0;
        mysqli_query($conn, "DELETE FROM `$stkdb` WHERE `vouchno`='$mvouch' AND `source`='$source' ") or die(mysqli_error($conn));

        // Insert new transaction items
        $count = $_POST["items"];
        for ($i = 0; $i < $count; $i++) {
            $msrno = $_POST["srno_$i"];
            $group = $source . $mvouch;
            $rwcnt = $_POST["rwcnt_$i"];
            if ($rwcnt > 0) {

                $h = 0;
                for ($k = 0; $k <= $rwcnt; $k++) {
                    $sz = 'sz' . $k;
                    $val = $_POST["tnfld_" . $k . "_" . $i];
                    $$sz = $val;
                }

                $mno = 0;
                $sz0 = mysqli_real_escape_string($conn, $sz0);

                $chkitem = mysqli_query($conn, "Select a.name,a.barcode,a.batch,a.bbf,a.type,b.* from product a, prodtran b where a.code = b.code and trim(b.`lineitem`)=trim('$sz0') ");
//                SIR SAID TO CHANGE CONDITION FROM 'LIKE' TO '=' ON 05-06-2025
//                $chkitem = mysqli_query($conn, "Select a.name,a.batch,a.bbf,a.type,b.* from product a, prodtran b where a.code = b.code and b.`lineitem` LIKE '%$sz0%' ");
                if (!empty($chkitem)) {
                    $mno = mysqli_num_rows($chkitem);
                }
                if ($mno > 0) {
                    $fitem = mysqli_fetch_array($chkitem);
                    $cnt++;
                    $mitem = $fitem['code'];
                    $type = $fitem['type'];
                    $bf = $fitem["bbf"];
                    $batch = $fitem["batch"];
                    $pouch = $fitem["pouch"];
                    $stkunit = $fitem["stkunit"];
                    $barcode = $fitem["barcode"];
                    $bbfmon = date('m', strtotime("+" . $bf . " months", strtotime($vouchdt)));
                    $bbfyear = date('Y', strtotime("+" . $bf . " months", strtotime($vouchdt)));
                    $weight = $fitem["weight"];


                    $qty = $sz1;

                    
                    $chars = preg_replace('/[^a-zA-Z]/', '', $weight);
                    if (strtoupper($chars) == 'G') {
                        $weignum = floatval($weight / 1000);
                    } else {
                        $weignum = floatval($weight);
                    }
                    if ($stkunit == 1) {
                        $stkqty = $qty * $weignum * 1000 * -1;
                        $mqty = $qty * $weignum * 1000;
                    } else {
                        $stkqty = $qty * $weignum * -1;
                        $mqty = $qty * $weignum;
                    }
                    $minqty = $qty * $weignum * -1;

                    $aqty = 0;
                    $stkqty = 0;
                    $actqty = $mqty;
                    $batchno = $batch;
                    
                    $prodtype = $fitem['type'];
                    if ($prodtype == "Organic") {
                        $stkdate = "2025-11-18";
                    } else {
                        $stkdate = "2026-01-14";
                    }

                    if ($vouchdt > $stkdate) {
                        $getstk = mysqli_query($conn, "SELECT itemcode, batch, sum(stkqty) as tqty FROM `transacn` WHERE `itemcode` =  '$mitem' 
                                                   GROUP BY itemcode, batch having sum(stkqty) > 0  ") or die(mysqli_error($conn));
                        if (mysqli_num_rows($getstk) > 0) {
                            $batchno = "";
                            $sqty = 0;
                            $pqty = $mqty;
                            while ($fetstk = mysqli_fetch_array($getstk)) {
                                $batchno = $fetstk['batch'];
                                $tsqty = $fetstk['tqty'];

                                if ($mqty <= $tsqty) {
                                    $stqty = $mqty * -1;
                                    if ($stkunit == 1) {
                                        $minqty = $stqty / 1000;
                                    } else {
                                        $minqty = $stqty;
                                    }

                                    $nsrno++;
                                    mysqli_query($conn, "INSERT INTO `$stkdb`(`srno`, `yearno`, `vouchno`, `vouchdt`, `barcode`, `itemcode`,  `cartqty`,
                                                  `qty`, `source`, `group` , `ordno`,`unit`,`stkqty`, batch)
                            VALUES('$cnt', '$myyear', '$mvouch', '$vouchdt','$barcode', '$mitem',  '$cartqty',
                                   '$minqty', '$source', '$group','1', '$stkunit','$stqty', '$batchno')") or die(mysqli_error($conn));

                                    $aqty = $aqty + $mqty;
                                    $mqty = $mqty - $fetstk['tqty'];
                                    break;
                                } else {

                                    $nsrno++;
                                    $stqty = $fetstk['tqty'] * -1;
                                    if ($stkunit == 1) {
                                        $minqty = $stqty / 1000;
                                    } else {
                                        $minqty = $stqty;
                                    }
                                    mysqli_query($conn, "INSERT INTO `$stkdb`(`srno`, `yearno`, `vouchno`, `vouchdt`, `barcode`, `itemcode`,  `cartqty`,
                                                  `qty`, `source`, `group` , `ordno`,`unit`,`stkqty`, `batch`)
                            VALUES('$cnt', '$myyear', '$mvouch', '$vouchdt','$barcode', '$mitem',  '$cartqty',
                                   '$minqty', '$source', '$group','1', '$stkunit','$stqty', '$batchno')") or die(mysqli_error($conn));

                                    $aqty = $aqty + $fetstk['tqty'];
                                    $mqty = $mqty - $fetstk['tqty'];
                                }
                            }
                        } else {
                            $stqty = $mqty * -1;
                            $nsrno++;
                            mysqli_query($conn, "INSERT INTO `$stkdb`(`srno`, `yearno`, `vouchno`, `vouchdt`, `barcode`, `itemcode`,  `cartqty`,
                                                  `qty`, `source`, `group` , `ordno`,`unit`,`stkqty`, `batch`)
                            VALUES('$cnt', '$myyear', '$mvouch', '$vouchdt','$barcode', '$mitem',  '$cartqty',
                                   '$minqty', '$source', '$group','1', '$stkunit','$stqty', '$batchno')") or die(mysqli_error($conn));

                            $aqty = $aqty + $mqty;
                        }

                        if ($aqty != $actqty) {
                            $stkqty = $actqty - $aqty;

                            $stqty = $stkqty * -1;
                            $nsrno++;
                            mysqli_query($conn, "INSERT INTO `$stkdb`(`srno`, `yearno`, `vouchno`, `vouchdt`, `barcode`, `itemcode`,  `cartqty`,
                                                  `qty`, `source`, `group` , `ordno`,`unit`,`stkqty`, `batch`)
                            VALUES('$cnt', '$myyear', '$mvouch', '$vouchdt','$barcode', '$mitem',  '$cartqty',
                                   '$minqty', '$source', '$group','1', '$stkunit','$stqty', '$batchno')") or die(mysqli_error($conn));

                            $aqty = $aqty + $mqty;
                            //                    browse("Not Mactched");
                        }

                        if ($pouch > 0) {
                            $mitemcode = mysqli_query($conn, "SELECT `code`,`barcode` FROM `product` WHERE `code`='$pouch'") or die(mysqli_error($conn));
                            $icode = mysqli_fetch_array($mitemcode);
                            $pbarcode = $icode['barcode'];
                            $pcqty = $qty * -1;
                            mysqli_query($conn, "INSERT INTO `$stkdb`(`srno`, `yearno`, `vouchno`, `vouchdt`, `barcode`, `itemcode`,
                                                  `qty`, `source`, `group` , `ordno`,`unit`,`stkqty`)
                            VALUES('$cnt', '$myyear', '$mvouch', '$vouchdt','$pbarcode', '$pouch', 
                                   '$pcqty', '$source', '$group','1', '$stkunit','$pcqty')") or die(mysqli_error($conn));
                        }
                        $ttqty += $qty;
                    }

                    mysqli_query($conn, "INSERT INTO `$trandb`(`vouchno`, `vouchdt`, `srno`, `itemcode`, `unitgm`, `qty`, `type`, `batchno`, `bbfmon`, `bbfyear`, `weight`)
                                                                      VALUES('$mvouch', '$vouchdt', '$cnt', '$mitem', '$unit', '$qty', '$type', '$batchno', '$bbfmon', '$bbfyear', '$weight')") or die(mysqli_error($conn));
                } else {
                    mysqli_query($conn, "INSERT INTO `rejtran`(`vouchno`, `lineitem`, `qty`)
                                                                      VALUES('$mvouch', '$sz0', '$sz1')") or die(mysqli_error($conn));
                }
            }
        }




//            echo "Data successfully inserted!";
//        if ($addflag == 1) {
        $insert_fields .= "`vouchno`, `vouchdt`, `rem1`,`ttotqty`";
        $insert_values .= "'$mvouch', '$adddate', 'Auto From Excel of Zenstores','$ttqty'";
        $insert_qry = "INSERT INTO $maindb ($insert_fields) VALUES ($insert_values)";
        mysqli_query($conn, $insert_qry) or die(mysqli_error($conn));

        $mvouch = $qvouch;
        header("refresh: 1; onlent.php?mode=edit&vouchno=$mvouch");
//        }
    }
}


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

include("includes/linkshead.php");
?>
<script type="text/javascript">
    $(document).ready(function () {


        $("#loaderBackground, #uploadLoader").hide();
        $("body").on("click", '#upload', uploadCsv);
        $("body").on("click", ".remove", remove);

        function uploadCsv() {
            var file_data = $('#file-5').prop('files')[0];
            event.preventDefault();
            var form_data = new FormData();
            form_data.append('file', file_data);
            $("#loaderBackground, #uploadLoader").show();
            $.ajax({
                url: 'showuploaddata.php',
                dataType: 'html',
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,
                type: 'post',
                success: function (response) {
                    $('.tbody').html(response);
                    $('.tabcss').attr("style", "");
                }
            });
//        }
        }
        function remove() {
            $(this).closest("tr").remove();
            //        caltran();
        }

    })
</script>
<style>

</style>

<meta charset="UTF-8">
</head>
<body>
    <form action='' method='POST' enctype="multipart/form-data" accept-charset="utf-8">

        <div class="panel-heading">
            <h3 class="panel-title">&nbsp;&nbsp;<?php Echo $formname; ?></h3>
        </div>

        <!-- COMPANY -->

        <div class="row">
            <div class = "col-lg-2">
                <?php
//                echo ' <input type="button"  name="excel" class="btn btn-primary pull-right" style="background-color:#78909C;color: #fff;align:left" value="Upload Format" onclick="window.open(\'candupd_format.php?vouchno=' . $getvouch . '\',\'popUpWindow\',\'height=800,width=950,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes\');">';
                ?>
            </div>
            <div class = "col-lg-2 text-center">
                <input type="file" name="file-5[]" id="file-5" class="inputfile inputfile-4" data-multiple-caption="{count} files selected" accept=".csv">
            </div>
            <div class = "col-lg-2">
                <input  id="upload" type="button" class="btn btn-pad btn-square btn-square" style="background-color:#05B2EA;color:#fff; " value="Proceed">

                                    <!--<label for="file-5"><figure><svg xmlns="http://www.w3.org/2000/svg" width="20" height="17" viewBox="0 0 20 17"><path d="M10 0l-5.2 4.9h3.3v5.1h3.8v-5.1h3.3l-5.2-4.9zm9.3 11.5l-3.2-2.1h-2l3.4 2.6h-3.5c-.1 0-.2.1-.2.1l-.8 2.3h-6l-.8-2.2c-.1-.1-.1-.2-.2-.2h-3.6l3.4-2.6h-2l-3.2 2.1c-.4.3-.7 1-.6 1.5l.6 3.1c.1.5.7.9 1.2.9h16.3c.6 0 1.1-.4 1.3-.9l.6-3.1c.1-.5-.2-1.2-.7-1.5z"/></svg></figure> <span>Choose a file&hellip;</span></label>-->
            </div>
        </div>


        <!-- SELECTION LIST TABLE -->

        <h5><b>Item List</b></h5>
        <div class="table-responsive tbody" style="overflow-y: scroll;height: 550px">

        </div> 
        <!--<button class="btn" type="button" id="addnew">Add More</button>-->



        <!-- SUBMIT & CANCEL -->
        <div class="row mt-3">
            <div class="col text-center">
                <button id='submit' type='submit' name='submit' value='<?php echo ($addflag == 0) ? "Update" : "Save"; ?>' class="btn btn-pad btn-square " style="background-color:#008D4C; ">
                    <i class="fa fa-check" style="color:#ffffff"></i>
                </button>

                <button id='cancel' type="button" class="btn btn-pad btn-square " style="background-color:#39CCCC; "  onClick="window.location.href = '<?= $file . "?mode=last" . $para; ?>'">
                    <i class="fa fa-times" style="color:#ffffff"></i>
                </button>
            </div>
        </div>


    </form>
    <?php include("includes/linksfoot.php"); ?>
</body>
</html>
