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

$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"]);
$gperc = trim($_POST["gperc"]);

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

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

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

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


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

$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.totqty) as sqty, a.godown, a.itemcode, b.name, 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") 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();
} 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.totqty) as sqty, a.godown, a.itemcode, b.name, b.cost, b.rate FROM transacn a, proddbf b 
                                   WHERE a.vouchdt >= '$mfrmdate' AND a.vouchdt <= '$mtodate' 
                                   and a.itemcode = b.code $godowncond group by a.itemcode ") 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.totqty) as oqty, a.godown, a.itemcode, b.name, b.cost, b.rate FROM transacn a, proddbf b 
                                   WHERE a.vouchdt < '$mfrmdate' and a.itemcode = b.code $godowncond  group by a.itemcode ") or die(mysqli_error($conn));

//$getitem = mysqli_query($conn, "SELECT * FROM `stkdbf` group by name, godown ") or die(mysqli_error($conn));
    $getitem = mysqli_query($conn, "SELECT a.* from (SELECT * FROM `stkdbf` 
                                                     union  
                                                     SELECT * from stkopen )  a group by name ") 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='6%'>Cost</th>
                                <th width='6%'>Rate</th>
                                <th width='20%'>Item Name</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) { ?>
                                    <th width='9%' style="text-align: right;">Cost</th>
                                    <th width='9%' style="text-align: right;">Value</th>
                                    <?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)) {

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

                                if ($cost > 0) {
                                    $actcost = $cost;
                                } else {
                                    $getcost = mysqli_query($conn, "SELECT `rate` FROM `purtran` WHERE `itemcode`='$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);
                                    $actcost = $chkpurrate['rate'];
                                }
                                $newcost = $actcost;

                                $getopen = mysqli_query($conn, "SELECT sum(oqty) as oqty FROM `stkopen` WHERE itemcode = '$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  itemcode = '$ibarcode' 
                                                                      and godown = '$igodown' and sqty > 0 ") or die(mysqli_error($conn));
                                $ipur = mysqli_fetch_array($getpur);
                                $purqty = $ipur['aqty'];

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

                                $saleqty = $saleqty1 * -1;

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


                                if ($prnflag == 'Y') {



//                                if ($balqty != 0) {
                                    $ctr++;

                                    echo "<tr class='clickable-row2' data-href='inwoutrep_fr.php?itcode=$ibarcode&fdt=$mfrmdate&tdt=$mtodate&view=view' data-target='_blank'>";
                                    echo "<td align='left'>$ctr</td>";
                                    echo "<td align='left'>$cost</td>";
                                    echo "<td align='left'>$rate</td>";
                                    echo "<td align='left'>$itemname</td>";
                                    echo "<td align='right'>$openqty</td>";
                                    echo "<td align='right'>$purqty</td>";
                                    echo "<td align='right'>$saleqty</td>";
                                    echo "<td align='right'>" . number_format($balqty, 2, ".", ",") . "</td>";
                                    if ($prnval == 2) {

                                        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' colspan='3'></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>";
                            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"])) {

    $contents .= "Sr., Itemname, Opening, Add, Less, Balance, Cost, Value\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->itemcode;
        $itemname = $row->name;
        $igodown = $row->godown;
        $cost = $row->cost;

        if ($cost > 0) {
            $actcost = $cost;
        } else {
            $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);
            $actcost = $chkpurrate['rate'];
        }
        $newcost = $actcost;

        $getopen = mysqli_query($conn, "SELECT sum(oqty) as oqty FROM `stkopen` WHERE itemcode = '$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  itemcode = '$ibarcode' 
                                                                      and godown = '$igodown' and sqty > 0 ") or die(mysqli_error($conn));
        $ipur = mysqli_fetch_array($getpur);
        $purqty = $ipur['aqty'];

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

        $saleqty = $saleqty1 * -1;

        $balqty = $openqty + $purqty - $saleqty;
        $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" . ",";
            $contents .= "$balqty" . "\n";

//            if ($prnval == 2) {
//            $contents .= "$newcost" . ",";
//            $contents .= "$itemvalue" . "\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 .= "" . ",";
        $contents .= "$grval" . "\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");
}
?>