<?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["product"]);
$gnm = $_POST["name"];
$gname = trim($_POST["itemgrp"]);
$gprodtype = trim($_POST["prodtype"]);
$gsubgrp = trim($_POST["subgrp"]);
$prnval = trim($_POST["prnval"]);
$gperc = trim($_POST["gperc"]);
$prodname = trim($_POST["prodname"]);

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


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

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

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

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

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

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

if (!empty($_POST["itemgrp"])) {
    $gcond = " and `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");
}
//browse($brcond);
$mfrmdate = trim($_POST["frmdt"]);
$mtodate = trim($_POST["todt"]);

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


$getitem = mysqli_query($conn, "SELECT sum(a.qty) as balqty,sum(a.cartqty)as cartqty, a.godown, a.itemcode, b.name, b.cost, b.pkg FROM transacn a, proddbf b 
                                   WHERE a.vouchdt >= '$mfrmdate' AND a.vouchdt <= '$mtodate' 
                                   and a.itemcode = b.code  $godowncond group by a.godown, a.itemcode order by b.name, 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-bordered">
                        <thead class="mySearchTr">
                            <tr>

                                <th width='5%' style="font-family: arial;">Sr.</th>
                                <th width='8%'>Barcode</th>
                                <th width='30%'>Name</th>
                                <th width='10%'>Godown</th>
                                <th width='9%' style="text-align: right;">Cartons</th>
                                <th width='9%' style="text-align: right;">Per/Carton</th>
                                <th width='9%' style="text-align: right;">Qty.</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;
                            $carton = 0;
                            $pkg = 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;
                                $cartqty = $row->cartqty;
                                $balqty = $row->balqty;
                                $pkg = $row->pkg;


                                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;

                                $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 name FROM `godown` WHERE code = '$igodown' ") or die(mysqli_error($conn));
                                    $fetg = mysqli_fetch_array($getg);
                                    $godwname = $fetg['name'];


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

                                    //  $carton = round($balqty / $pkg,2);

                                    // for retailers
                                    // $carton1 = intval($balqty / $pkg);
                                    // $carton2 = fmod($balqty,$pkg);
                                    // $carton = $carton1 . '.' . $carton2 ;
                                    
                                    echo "<tr> ";
                                    echo "<td align='left'>$ctr</td>";
                                    echo "<td align='left'>$ibarcode</td>";
                                    echo "<td align='left'>$itemname</td>";
                                    echo "<td align='left'>$godwname</td>";
                                    echo "<td align='right' style = 'font-size:14px'>$cartqty</td>";
                                    echo "<td align='right' style = 'font-size:14px'>$pkg</td>";
                                    echo "<td align='right' style = 'font-size:14px'>" . 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;
                                    $grcart = $grcart + $cartqty;

                                    $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'><font size='4px'> Total</font></td>";
                            echo "<td align='right' style = 'font-size:14px'>$grcart</font></td>";
                            echo "<td align='right'></font></td>";
                            echo "<td align='right' style = 'font-size:14px'>" . number_format("$grbal", 2, ".", ",") . "</td>";
                            if ($prnval == 2) {
                                echo "<td align='right'>";
                                echo "<font><b></b>";
                                echo "</td>";
                                echo "<td align='right' style = 'font-size:14px'><font><b> " . $grval . "</b></td>";
                            }
                            echo "</tr>";
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>


    </body>
    </html>
    <?php
}


if (isset($_POST["excel"])) {
    $contents .= "Sr., Barcode, Itemname, Godown, Opening Qty., Add Qty., Less Qty., Carton, Per Carton, Balance Qty., Cost, Value\n";

    $gropen = 0;
    $grsale = 0;
    $grpur = 0;
    $grbal = 0;
    $grval = 0;
    $mopen = 0;
    $grcart = 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;
        $pkg = $row->pkg;

        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 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' 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 barcode = '$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'];

            $carton = intval($balqty / $pkg);

//                                if ($balqty != 0) {
            $ctr++;
            $contents .= "$ctr" . ",";
            $contents .= "$ibarcode" . ",";
            $contents .= "$itemname" . ",";
            $contents .= "$godwname" . ",";
            $contents .= "$openqty" . ",";
            $contents .= "$purqty" . ",";
            $contents .= "$saleqty" . ",";
            $contents .= "$carton" . "\n";
            $contents .= "$pkg" . "\n";
            $contents .= "$balqty" . "\n";

//            if ($prnval == 2) {
//            $contents .= "$newcost" . ",";
//            $contents .= "$itemvalue" . "\n";
//            }
            $gropen = $gropen + $openqty;
            $grsale = $grsale + $saleqty;
            $grpur = $grpur + $purqty;
            $grcart = $grcart + $carton;
            $grbal = $grbal + $balqty;
            $grval = $grval + $itemvalue;
        }
    }
    $contents .= "" . ",";
    $contents .= "" . ",";
    $contents .= "" . ",";
    $contents .= "Total" . ",";
    $contents .= "$gropen" . ",";
    $contents .= "$grpur" . ",";
    $contents .= "$grsale" . ",";
    $contents .= "$grcart" . ",";
    $contents .= "" . ",";
    $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");
}
?>