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

ini_set("display_errors",1);
error_reporting(E_ERROR);

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

mysqli_select_db($conn, $zdb);

$formname = 'Itemwise Stock';
$zroot = $_SESSION["zdbroot"];

$maindb = 'product';
$trandb = 'transacn';

$grid = 'stock.php';

$getprevyear = mysqli_query($conn, "SELECT cono, finyear FROM $zroot.`compyear` where `cono`='$compcd' 
                            and `finyear`!='$myyear' ORDER BY `lastdate` DESC LIMIT 0,1 ") or die(mysqli_error($conn));
$showprevyear = mysqli_fetch_array($getprevyear);
$prevyear = $showprevyear['finyear'];


$olddb = $zroot1 . $compcd . '_' . $prevyear;


$giname = trim($_POST["itemname"]);
$gbrcd = trim($_POST["itemcode"]);
$gnm = $_POST["name"];
$gname = trim($_POST["itemgrp"]);
$gprodtype = trim($_POST["prodtype"]);
$gsubgrp = trim($_POST["subgrp"]);
$prnval = trim($_POST["prnval"]);
$stockval = trim($_POST["stockval"]);
$gperc = trim($_POST["gperc"]);

$prnzero = trim($_POST["prnzero"]);

$brcond = "";
$ncond = "";
$ncond = "";
$gcond = "";
$subcond = "";
$gperccond = "";
$gprodcond = "";

if (!empty($_POST["itemcode"])) {
    $brcond = " and b.`barcode` = '$gbrcd' ";
}

$itcond = "";
if (!empty($_POST["itemname"])) {
    $itcond = " and b.`name` like '%$giname%' ";
}

$godown = trim($_POST["godown"]);

$godowncond = "";
if (!empty($_POST["godown"])) {
    $godowncond = " and a.`godown` = '$godown' ";
}

if (!empty($_POST["name"])) {
    $ncond = " and b.`code` = '$gnm' ";
}

if (!empty($_POST["itemgrp"])) {
    $gcond = " and a.barcode in (select barcode from product where `prodgrp` = '$gname' ) ";
}

//    if (!empty($_POST["prodtype"])) {
//        $gprodcond = " and `prodtype` = '$gprodtype' ";
//    }
//
//    if (!empty($_POST["subgrp"])) {
//        $subcond = " and `itemsubgrp` = '$gsubgrp' ";
//    }
//
//    if (!empty($_POST["gsttype"])) {
//        $gperccond = " and `gstperc` = '$gperc' ";
//    }

if (empty($_POST["frmdt"])) {
    browse("FROM DATE CANNOT BE EMPTY");
    header("refresh:1; $grid");
}
if (empty($_POST["todt"])) {
    browse("TO DATE CANNOT BE EMPTY");
    header("refresh:1; $grid");
}

$forclosestk = trim($_POST["forclosestk"]);

$mfrmdate = trim($_POST["frmdt"]);
$mtodate = trim($_POST["todt"]);

if ($forclosestk > 0) {
    mysqli_query($conn, "drop temporary table if exists stkdbf ") or die(mysqli_error($conn));
    mysqli_query($conn, "create temporary table stkdbf
                            SELECT sum(a.qty) as sqty, a.godown, a.barcode, b.cost, sum(a.qty * b.cost) as closstk FROM transacn a, $maindb b 
                                   WHERE a.vouchdt <= '$mtodate' and a.itemcode = b.code group by a.itemcode, a.size, a.godown ") or die(mysqli_error($conn));

    $getstk = mysqli_query($conn, "SELECT sum(closstk) as clstk FROM `stkdbf` ") or die(mysqli_error($conn));
    $fetstk = mysqli_fetch_object($getstk);
    $grval = $fetstk->clstk;

    mysqli_query($conn, "update accmast set currbal = '$grval', currdc = 'D' WHERE accode = '23' ") or die(mysqli_error($conn));

    browse('Calculation of Closing Stock Completed.');
    die();
    //    echo "<script>
//            window.close();
//            </script>";
} else {
    //    mysqli_query($conn, "drop temporary table if exists proddbf ") or die(mysqli_error($conn));
//    mysqli_query($conn, "create temporary table proddbf
//                            SELECT * FROM `$maindb` WHERE code != '' $ncond $brcond $subcond $itcond $gcond ") or die(mysqli_error($conn));

    // mysqli_query($conn, "drop temporary table if exists stkdbf ") or die(mysqli_error($conn));
    // mysqli_query($conn, "create temporary table stkdbf
    //                         SELECT sum(a.qty) as sqty, a.godown, a.barcode,a.size, b.name, b.cost,b.rate FROM transacn a, $maindb b 
    //                                WHERE a.vouchdt >= '$mfrmdate' AND a.vouchdt <= '$mtodate' and a.qty > 0 
    //                                and a.barcode = b.barcode $godowncond $ncond $brcond $subcond $itcond $gcond group by a.barcode,a.size,a.godown ") or die(mysqli_error($conn));

    // mysqli_query($conn, "drop temporary table if exists stkdbfles ") or die(mysqli_error($conn));
    // mysqli_query($conn, "create temporary table stkdbfles
    //                         SELECT sum(a.qty) as sqty, a.godown, a.barcode,a.size, b.name, b.cost,b.rate FROM transacn a, $maindb b 
    //                                WHERE a.vouchdt >= '$mfrmdate' AND a.vouchdt <= '$mtodate' and a.qty < 0
    //                                and a.barcode = b.barcode  $godowncond $ncond $brcond $subcond $itcond $gcond group by a.barcode,a.size,a.godown") or die(mysqli_error($conn));

    // mysqli_query($conn, "drop temporary table if exists stkopen ") or die(mysqli_error($conn));
    // mysqli_query($conn, "create temporary table stkopen
    //                         SELECT sum(a.qty) as oqty, a.godown, a.barcode,a.size, b.name, b.cost, b.rate FROM transacn a, $maindb b 
    //                                WHERE a.vouchdt < '$mfrmdate' and a.barcode = b.barcode $godowncond  $ncond $brcond $subcond $itcond $gcond 
    //                                group by a.barcode,a.size,a.godown ") or die(mysqli_error($conn));

    // $getitem = mysqli_query($conn, "SELECT a.* from (SELECT * FROM `stkdbf` 
    //                                              union
    //                                              SELECT * FROM `stkdbfles` 
    //                                              union
    //                                              Select * from stkopen )  a group by barcode,size,godown order by size,godown") or die(mysqli_error($conn));
    $getitem = mysqli_query($conn, "SELECT  a.barcode, b.name, a.size, a.godown, b.cost, b.rate,
                                            SUM(CASE WHEN a.vouchdt < '$mfrmdate' THEN a.qty ELSE 0 END) AS openqty,
                                            SUM(CASE WHEN a.vouchdt >= '$mfrmdate' AND a.vouchdt <= '$mtodate' AND a.qty > 0 
                                                THEN a.qty ELSE 0 END) AS purqty,
                                            SUM(CASE WHEN a.vouchdt >= '$mfrmdate' AND a.vouchdt <= '$mtodate' AND a.qty < 0 
                                                THEN a.qty ELSE 0 END) * -1 AS saleqty

                                            FROM transacn a LEFT JOIN product b ON a.itemcode = b.code
                                            WHERE a.vouchdt <= '$mtodate' $godowncond $ncond $brcond $subcond $itcond $gcond

                                            GROUP BY a.itemcode, a.size, a.godown
                                            ORDER BY a.size, a.godown ") or die(mysqli_error($conn));
}

$getno = mysqli_num_rows($getitem);

$mfdt = date("d-m-Y", strtotime($mfrmdate));
$mtdt = date("d-m-Y", strtotime($mtodate));
if ($getno == 0) {
    browse("Record Not Found");
    echo "<script>
            window.close();
            </script>";
}

if (isset($_POST["view"])) {
    include("includes/linkshead.php");
    ?>
    <style type="text/css">
        #tabital {
            font-style: italic;
        }

        #font1 {
            font-style: italic;
        }

        #boldfont {
            font-weight: bold;
        }

        .table-condensed>thead>tr>th,
        .table-condensed>tbody>tr>th,
        .table-condensed>tfoot>tr>th,
        .table-condensed>thead>tr>td,
        .table-condensed>tbody>tr>td,
        .table-condensed>tfoot>tr>td {
            padding: 2px;
        }
    </style>

    </head>

    <body>
        <div class="container">
            <?php
            include("includes/head_rep.php");
            ?>

            <div class="row">
                <div class="col-lg-12 ">
                    <table style="background: white;width: 100%" class="table table-condensed table-hover">
                        <thead class="mySearchTr">
                            <tr>
                                <th width='3%' style="font-family: arial;">Sr.</th>
                                <th width='12%'>Barcode</th>
                                <th width='25%'>Item Name</th>
                                <th width='7%'>Size</th>
                                <th width='7%'>Godown</th>
                                <th width='7%' style="text-align: right;">Opening</th>
                                <th width='7%' style="text-align: right;">Add</th>
                                <th width='7%' style="text-align: right;">Less</th>
                                <th width='9%' style="text-align: right;">Balance</th>

                                <?php if ($prnval == 2) { ?>
                                    <?php if ($stockval == "R") { ?>
                                        <th width='9%' style="text-align: right;">Rate</th>
                                        <th width='9%' style="text-align: right;">Value</th>

                                    <?php } else { ?>
                                        <th width='9%' style="text-align: right;">Cost</th>
                                        <th width='9%' style="text-align: right;">Value</th>
                                    <?php } ?>
                                <?php } ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $gropen = 0;
                            $grsale = 0;
                            $grpur = 0;
                            $grbal = 0;
                            $grval = 0;
                            $mopen = 0;

                            $ctr = 0;
                            mysqli_select_db($conn, $zdb);
                            while ($row = mysqli_fetch_object($getitem)) {

                                $iitemcode = $row->itemcode;
                                $ibarcode = $row->barcode;
                                $itemname = $row->name ?? 'Unknown Item';
                                $igodown = $row->godown;
                                $size = $row->size;
                                $cost = $row->cost;
                                $rate = $row->rate;


                                if ($cost > 0) {
                                    $actcost = $cost;
                                } else {
                                    $getcost = mysqli_query($conn, "SELECT `rate` FROM `purtran` WHERE `itemcode`='$iitemcode' and rate > 0 and `vouchdt` >= '$mfrmdate'
                                                                           AND `vouchdt` <= '$mtodate' order by vouchdt desc limit 0,1") or die(mysqli_error($conn));
                                    $chkpurrate = mysqli_fetch_array($getcost);
                                    $actcost = $chkpurrate['rate'];
                                }
                                $newcost = $actcost;

                                if ($rate > 0) {
                                    $actrate = $rate;
                                } else {
                                    $actrate = $chkpurrate['rate'];
                                }
                                $newrate = $actrate;

                                // $getopen = mysqli_query($conn, "SELECT sum(oqty) as oqty FROM `stkopen` WHERE barcode = '$ibarcode' AND size = '$size'  
                                //                                       and godown = '$igodown'  ") or die(mysqli_error($conn));
                                // $iopen = mysqli_fetch_array($getopen);
                                // $openqty = $iopen['oqty'];
                        
                                // $getpur = mysqli_query($conn, "SELECT sum(sqty) as aqty FROM `stkdbf` WHERE barcode = '$ibarcode' AND size = '$size' 
                                //                                       and godown = '$igodown' ") or die(mysqli_error($conn));
                                // $ipur = mysqli_fetch_array($getpur);
                                // $purqty = $ipur['aqty'];
                        

                                // $getsale = mysqli_query($conn, "SELECT sum(sqty) as lqty FROM `stkdbfles` WHERE barcode = '$ibarcode' AND size = '$size' 
                                //                                        and godown = '$igodown' ") or die(mysqli_error($conn));
                                // $isale = mysqli_fetch_array($getsale);
                                // $saleqty1 = $isale['lqty'];
                        
                                // $saleqty = $saleqty1 * -1;
                        
                                $openqty = $row->openqty;
                                $purqty  = $row->purqty;
                                $saleqty = $row->saleqty;

                                $balqty = $openqty + $purqty - $saleqty;

                                if ($stockval == 'R') {
                                    $itemvalue = $newrate * $balqty;
                                } else {
                                    $itemvalue = $newcost * $balqty;
                                }

                                $prnflag = 'N';
                                if ($balqty != 0) {
                                    $prnflag = 'Y';
                                } else {
                                    if ($prnzero == 'Y') {
                                        $prnflag = 'Y';
                                    } else {
                                        $prnflag = 'N';
                                    }
                                }


                                if ($prnflag == 'Y') {
                                    $getg = mysqli_query($conn, "SELECT gcode FROM `godown` WHERE code = '$igodown' ") or die(mysqli_error($conn));
                                    $fetg = mysqli_fetch_array($getg);
                                    $godwname = $fetg['gcode'];


                                    $ctr++;

                                    echo "<tr> ";
                                    echo "<td align='left'>$ctr</td>";
                                    echo "<td align='left'>$ibarcode</td>";
                                    echo "<td align='left'>$itemname</td>";
                                    echo "<td align='left'>$size</td>";
                                    echo "<td align='left'>$godwname</td>";
                                    echo "<td align='right'>$openqty</td>";
                                    echo "<td align='right'>$purqty</td>";
                                    echo "<td align='right'>$saleqty</td>";
                                    echo "<td align='right'>$balqty</td>";
                                    if ($prnval == 2) {
                                        if ($stockval == 'R') {
                                            echo "<td style='text-align:right;'>";
                                            echo "<font><b> " . number_format("$newrate", 0, ".", ",") . "</b>";
                                            echo "</td>";

                                            echo "<td style='text-align:right;'>";
                                            echo "<font><b> " . number_format("$itemvalue", 0, ".", ",") . "</b>";
                                            echo "</td>";
                                        } else {
                                            echo "<td style='text-align:right;'>";
                                            echo "<font><b> " . number_format("$newcost", 0, ".", ",") . "</b>";
                                            echo "</td>";

                                            echo "<td style='text-align:right;'>";
                                            echo "<font><b> " . number_format("$itemvalue", 0, ".", ",") . "</b>";
                                            echo "</td>";
                                        }
                                    }
                                    echo "</tr>";
                                    //                                }
                                    $gropen = $gropen + $openqty;
                                    $grsale = $grsale + $saleqty;
                                    $grpur = $grpur + $purqty;
                                    $grbal = $grbal + $balqty;
                                    $grval = $grval + $itemvalue;
                                }
                            }

                            echo "<tr style ='background-color:white;font-weight:bolder;font-size:18px'> ";
                            echo "<td align='left'></td>";
                            echo "<td align='left'></td>";
                            echo "<td align='left'></td>";
                            echo "<td align='left'></td>";
                            echo "<td align='left'><font size='4px'> Total</font></td>";
                            echo "<td align='right'>$gropen</td>";
                            echo "<td align='right'>$grpur</td>";
                            echo "<td align='right'>$grsale</font></td>";
                            //                            echo "<td align='right'>" . number_format("$grbal", 2, ".", ",") . "</td>";
                            echo "<td align='right'>$grbal</td>";
                            if ($prnval == 2) {
                                echo "<td align='right'>";
                                echo "<font><b></b>";
                                echo "</td>";
                                echo "<td align='right'>";
                                echo "<font><b> " . $grval . "</b>";
                                echo "</td>";
                                mysqli_query($conn, "update accmast set currbal = '$grval', currdc = 'D' WHERE accode = 23 ") or die(mysqli_error($conn));
                            }
                            echo "</tr>";
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>


    </body>

    </html>
    <?php
}


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

    if ($prnval == 2) {
        $contents .= "Sr.,Barcode,Item Name,Color,Opening,Add,Less,Balance,";
        if ($stockval == "R") {
            $contents .= "Rate,Value\n";
        } else {
            $contents .= "Cost,Value\n";
        }
    } else {
        $contents .= "Sr., Barcode, Itemname, Godown, Opening, Add, Less, Balance\n";
    }

    $gropen = 0;
    $grsale = 0;
    $grpur = 0;
    $grbal = 0;
    $grval = 0;
    $mopen = 0;

    $ctr = 0;
    mysqli_select_db($conn, $zdb);
    while ($row = mysqli_fetch_object($getitem)) {

        $ibarcode = $row->barcode;
        $itemname = $row->name;
        $igodown = $row->godown;
        $cost = $row->cost;

        $rate = $row->rate;

        $getcost = mysqli_query($conn, "SELECT `rate` FROM `purtran` WHERE `barcode`='$ibarcode' and rate > 0 
                               and `vouchdt` >= '$mfrmdate' AND `vouchdt` <= '$mtodate' order by vouchdt desc limit 0,1") or die(mysqli_error($conn));
        $chkpurrate = mysqli_fetch_array($getcost);

        if ($cost > 0) {
            $actcost = $cost;
        } else {
            $actcost = $chkpurrate['rate'];
        }
        $newcost = $actcost;

        if ($rate > 0) {
            $actrate = $rate;
        } else {
            $actrate = $chkpurrate['rate'];
        }
        $newrate = $actrate;

        $getopen = mysqli_query($conn, "SELECT sum(oqty) as oqty FROM `stkopen` WHERE barcode = '$ibarcode'  
                                                                      and godown = '$igodown'  ") or die(mysqli_error($conn));
        $iopen = mysqli_fetch_array($getopen);
        $openqty = $iopen['oqty'];

        $getpur = mysqli_query($conn, "SELECT sum(sqty) as aqty FROM `stkdbf` WHERE  barcode = '$ibarcode' 
                                                                      and godown = '$igodown' ") or die(mysqli_error($conn));
        $ipur = mysqli_fetch_array($getpur);
        $purqty = $ipur['aqty'];


        $getsale = mysqli_query($conn, "SELECT sum(sqty) as lqty FROM `stkdbfles` WHERE barcode = '$ibarcode' 
                                                                       and godown = '$igodown' ") or die(mysqli_error($conn));
        $isale = mysqli_fetch_array($getsale);
        $saleqty1 = $isale['lqty'];

        $saleqty = $saleqty1 * -1;

        $balqty = $openqty + $purqty - $saleqty;
        if ($stockval == 'R') {
            $itemvalue = $newrate * $balqty;
        } else {
            $itemvalue = $newcost * $balqty;
        }
        $prnflag = 'N';
        if ($balqty != 0) {
            $prnflag = 'Y';
        } else {
            if ($prnzero == 'Y') {
                $prnflag = 'Y';
            } else {
                $prnflag = 'N';
            }
        }

        if ($prnflag == 'Y') {
            $getg = mysqli_query($conn, "SELECT gcode FROM `godown` WHERE code = '$igodown' ") or die(mysqli_error($conn));
            $fetg = mysqli_fetch_array($getg);
            $godwname = $fetg['gcode'];

            //                                if ($balqty != 0) {
            $ctr++;
            $contents .= "$ctr" . ",";
            $contents .= "$ibarcode" . ",";
            $contents .= "$itemname" . ",";
            $contents .= "$godwname" . ",";
            $contents .= "$openqty" . ",";
            $contents .= "$purqty" . ",";
            $contents .= "$saleqty" . ",";
            if ($prnval == 2) {
                $contents .= "$balqty" . ",";
                if ($stockval == 'R') {
                    $contents .= "$newrate" . ",";
                    $contents .= "$itemvalue" . "\n";
                } else {
                    $contents .= "$newcost" . ",";
                    $contents .= "$itemvalue" . "\n";
                }
            } else {
                $contents .= "$balqty" . "\n";
            }


            $gropen = $gropen + $openqty;
            $grsale = $grsale + $saleqty;
            $grpur = $grpur + $purqty;
            $grbal = $grbal + $balqty;
            $grval = $grval + $itemvalue;
        }
    }
    $contents .= "" . ",";
    $contents .= "" . ",";
    $contents .= "" . ",";
    $contents .= "Total" . ",";
    $contents .= "$gropen" . ",";
    $contents .= "$grpur" . ",";
    $contents .= "$grsale" . ",";
    // $contents .= "$grbal" . ","; 
    if ($prnval == 2) {
        $contents .= "$grbal" . ",";
        $contents .= "" . ",";
        $contents .= "$grval" . "\n";
    } else {
        $contents .= "$grbal" . "\n";
    }
    $contents = strip_tags($contents);

    if ($_POST["dtype"] == 1) {
        header("Content-Disposition: attachment; filename=$formname" . "_Summary" . date('d-m-Y') . ".csv");
        print $contents;
    } else {
        header("Content-Disposition: attachment; filename=$formname" . "_Detail" . date('d-m-Y') . ".csv");
        print $contents;
    }
}

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

    $gbrcd = trim($_POST["itemcode"]);
    $gnm = $_POST["name"];
    $gname = trim($_POST["itemgrp"]);
    $gprodtype = trim($_POST["prodtype"]);
    $gsubgrp = trim($_POST["subgrp"]);
    $prnval = trim($_POST["prnval"]);
    $gperc = trim($_POST["gperc"]);


    $brcond = "";
    $ncond = "";
    $gcond = "";
    $subcond = "";
    $gperccond = "";
    $gprodcond = "";


    if (!empty($_POST["itemcode"])) {
        $brcond = " and `code` = '$gbrcd' ";
    }

    if (!empty($_POST["name"])) {
        $ncond = " and `code` = '$gnm' ";
    }

    if (!empty($_POST["itemgrp"])) {
        $gcond = " and `itemgrp` = '$gname' ";
    }

    if (!empty($_POST["prodtype"])) {
        $gprodcond = " and `prodtype` = '$gprodtype' ";
    }

    if (!empty($_POST["subgrp"])) {
        $subcond = " and `itemsubgrp` = '$gsubgrp' ";
    }

    if (!empty($_POST["gsttype"])) {
        $gperccond = " and `gstperc` = '$gperc' ";
    }

    if (empty($_POST["frmdt"])) {
        browse("FROM DATE CANNOT BE EMPTY");
        header("refresh:1; $grid");
    }
    if (empty($_POST["todt"])) {
        browse("TO DATE CANNOT BE EMPTY");
        header("refresh:1; $grid");
    }


    $mfrmdate = trim($_POST["frmdt"]);
    $mtodate = trim($_POST["todt"]);

    $getitem = mysqli_query($conn, "SELECT * FROM `$maindb` WHERE code != '' $ncond $brcond $subcond $gcond $gprodcond $gperccond group by code") or die(mysqli_error($conn));
    $getno = mysqli_num_rows($getitem);
    //print table($getitem);
    $mfdt = date("d-m-Y", strtotime($mfrmdate));
    $mtdt = date("d-m-Y", strtotime($mtodate));
    if ($getno == 0) {

        browse("Record Not Found");
        echo "<script>
            window.close();
            </script>";
    }

    require("library/fpdf/fpdf.php");

    class pdf extends fpdf
    {

        function Footer()
        {



            //Position at 1.5 cm from bottom

            $this->SetY(-15);

            //Arial italic 8

            $this->SetFont('Arial', 'I', 8);

            //Page number

            $this->Cell(0, 10, 'Page ' . $this->PageNo() . '/{nb}', 0, 0, 'C');
        }

    }

    $pdf = new pdf('P', 'mm', 'A4');

    $pdf->AliasNbPages();

    $pdf->AddPage();
    $pdf->SetFont('Arial', 'I', 10);
    $pdf->SetTextColor(255, 255, 255);
    $pdf->SetFillColor(96, 130, 191);
    $pdf->Cell(8, 7, "Sr.", 1, 0, '', 1);
    $pdf->Cell(20, 7, "Barcode", 1, 0, '', 1);
    $pdf->Cell(50, 7, "Item Name", 1, 0, '', 1);
    $pdf->Cell(20, 7, "Opening", 1, 0, '', 1, 0, 'R');
    $pdf->Cell(20, 7, "Add", 1, 0, '', 1, 0, 'R');
    $pdf->Cell(20, 7, "Less", 1, 0, '', 1, 0, 'R');
    $pdf->Cell(20, 7, "Balance", 1, 0, '', 1, 0, 'R');
    if ($prnval == 2) {

        $pdf->Cell(20, 7, "Cost", 1, 0, '', 1, 0, 'R');
        $pdf->Cell(20, 7, "Value", 1, 0, '', 1, 0, 'R');
    }
    $pdf->SetFont('Arial', '', 1, 0);

    $pdf->SetTextColor(0, 0, 0);
    $pdf->Ln();

    $gropen = 0;
    $grsale = 0;
    $grpur = 0;
    $grbal = 0;
    $grval = 0;
    $mopen = 0;

    $ctr = 0;
    mysqli_select_db($conn, $zdb);
    while ($row = mysqli_fetch_object($getitem)) {


        $icode = $row->code;
        $ibarcode = $row->code;

        $mopen = $row->opening;
        $itemname = $row->name;
        $cost = $row->cost;
        if ($cost > 0) {
            $actcost = $cost;
        } else {
            $getpur = mysqli_query($conn, "SELECT `rate` FROM `purtran` WHERE `itemcode`='$icode' and rate > 0 
                                                           and `vouchdt` >= '$mfrmdate' AND `vouchdt` <= '$mtodate'") or die(mysqli_error($conn));
            $chkpurrate = mysqli_fetch_array($getpur);
            $actcost = $chkpurrate[rate];
        }
        $newcost = $actcost;

        $getopen = mysqli_query($conn, "SELECT sum(qty) as sqty FROM `$trandb` WHERE itemcode = '$icode'  
                                                             and `vouchdt` < '$mfrmdate' ") or die(mysqli_error($conn));
        $iopen = mysqli_fetch_array($getopen);
        $openqty = $iopen['sqty'] + $mopen;

        $getpur = mysqli_query($conn, "SELECT sum(qty) as sqty FROM `$trandb` WHERE  itemcode = '$icode' and
                                                          `vouchdt` >= '$mfrmdate' AND `vouchdt` <= '$mtodate' and qty > 0") or die(mysqli_error($conn));
        $ipur = mysqli_fetch_array($getpur);
        $purqty = $ipur['sqty'];



        $getsale = mysqli_query($conn, "SELECT sum(qty) as sqty FROM `$trandb` WHERE itemcode = '$icode' and
                                                          `vouchdt` >= '$mfrmdate' AND `vouchdt` <= '$mtodate' and qty < 0") or die(mysqli_error($conn));
        $isale = mysqli_fetch_array($getsale);
        $saleqty1 = $isale['sqty'];


        $saleqty = $saleqty1 * -1;

        $balqty = $openqty + $purqty - $saleqty;
        $itemvalue = $newcost * $balqty;

        if ($balqty != 0) {
            $ctr++;
            $pdf->SetFont('Arial', '', 8);
            $pdf->Cell(8, 7, "$ctr", 1);
            $pdf->Cell(20, 7, "$ibarcode", 1);
            $pdf->Cell(50, 7, "$itemname", 1);
            $pdf->Cell(20, 7, "$openqty", 1, 0, 'R');
            $pdf->Cell(20, 7, "$purqty", 1, 0, 'R');
            $pdf->Cell(20, 7, "$saleqty", 1, 0, 'R');
            $pdf->Cell(20, 7, "$balqty", 1, 0, 'R');
            if ($prnval == 2) {
                $pdf->Cell(20, 7, number_format("$newcost", 0, ".", ","), 1, 0, 'R');
                $pdf->Cell(20, 7, number_format("$itemvalue", 0, ".", ","), 1, 0, 'R');
            }
            $pdf->Ln();
        }

        $gropen = $gropen + $openqty;
        $grsale = $grsale + $saleqty;
        $grpur = $grpur + $purqty;
        $grbal = $grbal + $balqty;
        $grval = $grval + $itemvalue;
    }
    $pdf->SetFont('Arial', 'I', 10);
    $pdf->SetTextColor(255, 255, 255);
    $pdf->SetFillColor(255, 0, 0);

    $pdf->Cell(8, 7, " ", 1, 0, '', 1);
    $pdf->Cell(20, 7, " ", 1, 0, '', 1);
    $pdf->Cell(50, 7, "Total", 1, 0, '', 1);
    $pdf->Cell(20, 7, "$gropen", 1, 0, '', 1, 0, 'R');
    $pdf->Cell(20, 7, "$grpur", 1, 0, '', 1, 0, 'R');
    $pdf->Cell(20, 7, "$grsale", 1, 0, '', 1, 0, 'R');
    $pdf->Cell(20, 7, "$grbal", 1, 0, '', 1, 0, 'R');
    if ($prnval == 2) {
        $pdf->Cell(20, 7, " ", 1, 0, '', 1, 0, 'R');
        $pdf->Cell(20, 7, "$grval", 1, 0, '', 1, 0, 'R');
    }
    $pdf->SetFont('Arial', '', 1, 0);

    $pdf->SetTextColor(0, 0, 0);
    $pdf->Ln();

    $pdf->Output("Stock.pdf", "D");
}
?>