<?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 = 'Negative Stock';

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

$grid = 'negstock.php';


$prodcode = $_POST["prodcode"];
$product = $_POST["product"];
$prodgrp = $_POST["prodgrp"];
$type = $_POST["type"];
$godown = $_POST["godown"];
$prinval = $_POST["prinval"];

$brcond = "";
$ncond = "";
$gcond = "";
$subcond = "";
$gperccond = "";
$gprodcond = "";
$seriescond = "";
$itemsubcond = "";
$suppcond = "";

if (!empty($prodcode)) {
    $pcodecond = " AND a.`itemcode` = '$prodcode' ";
}

if (!empty($prodgrp)) {
    $grpcond = " AND b.`prodgrp` = '$prodgrp' ";
}


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

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


mysqli_query($conn, "drop temporary table if exists tempdb") or die(mysqli_error($conn));
mysqli_query($conn, "create temporary table tempdb 
                            SELECT sum(a.qty) as sqty, a.itemcode as code, 
                                   b.name, b.cost, b.rate FROM `$trandb` a, `$maindb` b 
                                   WHERE a.itemcode = b.code and a.`vouchdt` <= '$mtodate' 
                                   $pcodecond $grpcond group by a.itemcode") or die(mysqli_error($conn));

$gettran = mysqli_query($conn, "SELECT code, name, cost, rate, sqty FROM `tempdb` where sqty < 0 order by code ") or die(mysqli_error($conn));


//$mfdt = date("d-m-Y", strtotime($mfrmdate));
$mtdt = date("d-m-Y", strtotime($mtodate));

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

        #font1 {
            font-style: italic;
        }

        #boldfont {
            font-weight: bold;
        }

        th {
            background: #7E827E;
            position: sticky;
            top: 0;
        }
    </style>

    </head>

    <body>
        <div class="container" style="width:100%">

            <div class="row">
                <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 ">
                    <?php
                    include("includes/head_rep.php");
                    ?>
                    <table style="background: white;width: 65%" class="table table-condensed table-bordered">
                        <thead class="mySearchTr">
                            <tr>
                                <th align="left" width='5%' style="font-family: arial;">Sr.</th>
                                <th align="left" width='10%'>Code</th>
                                <th align="left" width='35%'>Name</th>
                                <th width='15%' style="text-align: right;"> Balance </th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $gropen = 0;
                            $grsale = 0;
                            $grpur = 0;
                            $grbal = 0;
                            $grval = 0;
                            $mopen = 0;
                            $ctr = 0;

                            $totqty = $totval = 0;

                            while ($row = mysqli_fetch_object($gettran)) {
                                $ctr++;
                                $icode = $row->code;
                                $itemname = $row->name;
                                $cost = $row->cost;
                                $rate = $row->rate;
                                $qty = $row->sqty;

                                if ($prnval == 2) {
                                    if ($cost > 0) {
                                        $actcost = $cost;
                                    } else {
                                        $getpur = mysqli_query($conn, "SELECT `rate` FROM `purtran` WHERE `itemcode`='$icode' and rate > 0 
                                                                           and `vouchdt` <= '$mtodate'") or die(mysqli_error($conn));
                                        $getnum = mysqli_num_rows($getpur);
                                        if ($getnum > 0) {
                                            $chkpurrate = mysqli_fetch_array($getpur);
                                            $actcost = $chkpurrate['rate'];
                                        } else {
                                            $actcost = $rate;
                                        }
                                    }
                                    $newcost = $actcost;
                                }

                                echo "<tr>";
                                echo "<td align='left'><font size='3px'>$ctr</td>";
                                echo "<td align='left'><font size='3px'>$icode</td>";
                                echo "<td align='left'><font size='3px'>$itemname</td>";
                                echo "<td align='right' style='background-color:#B8F4F7'><font size='3px'><b>$qty</b></td>";
                                echo "</tr>";
                                $gr1 = $gr1 + $qty;
                            }

                            echo "<tr style='background-color:#97f9f0'>";
                            echo "<td></td>";
                            echo "<td></td>";
                            echo "<td style= 'text-align: right; font-size:15px'><b>Total</b></td>";
                            echo "<td style= 'text-align: right; font-size:15px'><b>$gr1</b></td>";
                            echo "<td></td>";

                            echo "</tr>";
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </body>

    </html>
    <?php
}


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

    $contents .= "Sr., Code, Name, Balance \n";

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

    $totqty = $totval = 0;

    while ($row = mysqli_fetch_object($gettran)) {
        $ctr++;
        $icode = $row->code;
        $itemname = $row->name;
        $cost = $row->cost;
        $rate = $row->rate;
        $qty = $row->sqty;

        if ($prnval == 2) {
            if ($cost > 0) {
                $actcost = $cost;
            } else {
                $getpur = mysqli_query($conn, "SELECT `rate` FROM `purtran` WHERE `itemcode`='$icode' and rate > 0 
                                                                           and `vouchdt` <= '$mtodate'") or die(mysqli_error($conn));
                $getnum = mysqli_num_rows($getpur);
                if ($getnum > 0) {
                    $chkpurrate = mysqli_fetch_array($getpur);
                    $actcost = $chkpurrate['rate'];
                } else {
                    $actcost = $rate;
                }
            }
            $newcost = $actcost;
        }

        $contents .= "$ctr" . ",";
        $contents .= "$icode" . ",";
        $contents .= "$itemname" . ",";
        $contents .= "$qty" . "\n";

        $gr1 = $gr1 + $qty;
    }

    $contents .= "" . ",";
    $contents .= "" . ",";
    $contents .= "Total" . ",";
    $contents .= "$gr1" . "\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 a.*,b.code, b.name, b.itemgrp, b.cost, b.opening FROM `$trandb` a, `$maindb` b WHERE a.itemcode = b.code 
    //                          $ncond $brcond $gcond $subcond group by a.itemcode") or die(mysqli_error($conn));
    $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('L', 'mm', 'A4');

    $pdf->AliasNbPages();

    $pdf->AddPage();
    include("includes/head_rep_pdf.php");
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->SetFillColor(64, 37, 91);
    $pdf->SetTextColor(255, 255, 255);
    if ($prnval == 2) {
        $pdf->Cell(10, 7, "Sr.", 1, 0, '', 1);
        $pdf->Cell(39, 7, "Barcode", 1, 0, '', 1);
        $pdf->Cell(49, 7, "Item Name", 1, 0, '', 1);
        $pdf->Cell(30, 7, "Opening", 1, 0, 'R', 1);
        $pdf->Cell(30, 7, "Add", 1, 0, 'R', 1);
        $pdf->Cell(30, 7, "Less", 1, 0, 'R', 1);
        $pdf->Cell(30, 7, "Balance", 1, 0, 'R', 1);
        $pdf->Cell(30, 7, "Cost", 1, 0, 'R', 1);
        $pdf->Cell(30, 7, "Value", 1, 0, 'R', 1);
    } else {
        $pdf->Cell(10, 7, "Sr.", 1, 0, '', 1);
        $pdf->Cell(48, 7, "Barcode", 1, 0, '', 1);
        $pdf->Cell(60, 7, "Item Name", 1, 0, '', 1);
        $pdf->Cell(40, 7, "Opening", 1, 0, 'R', 1);
        $pdf->Cell(40, 7, "Add", 1, 0, 'R', 1);
        $pdf->Cell(40, 7, "Less", 1, 0, 'R', 1);
        $pdf->Cell(40, 7, "Balance", 1, 0, 'R', 1);
    }
    $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;

        $ctr++;
        $pdf->SetFont('Arial', '', 8);
        if ($prnval == 2) {
            $pdf->Cell(10, 7, "$ctr", 1);
            $pdf->Cell(39, 7, "$ibarcode", 1);
            $pdf->Cell(49, 7, "$itemname", 1);
            $pdf->Cell(30, 7, "$openqty", 1, 0, 'R');
            $pdf->Cell(30, 7, "$purqty", 1, 0, 'R');
            $pdf->Cell(30, 7, "$saleqty", 1, 0, 'R');
            $pdf->Cell(30, 7, "$balqty", 1, 0, 'R');
            $pdf->Cell(30, 7, number_format("$newcost", 0, ".", ","), 1, 0, 'R');
            $pdf->Cell(30, 7, number_format("$itemvalue", 0, ".", ","), 1, 0, 'R');
        } else {
            $pdf->Cell(10, 7, "$ctr", 1);
            $pdf->Cell(48, 7, "$ibarcode", 1);
            $pdf->Cell(60, 7, "$itemname", 1);
            $pdf->Cell(40, 7, "$openqty", 1, 0, 'R');
            $pdf->Cell(40, 7, "$purqty", 1, 0, 'R');
            $pdf->Cell(40, 7, "$saleqty", 1, 0, 'R');
            $pdf->Cell(40, 7, "$balqty", 1, 0, 'R');
        }
        $pdf->Ln();
        $gropen = $gropen + $openqty;
        $grsale = $grsale + $saleqty;
        $grpur = $grpur + $purqty;
        $grbal = $grbal + $balqty;
        $grval = $grval + $itemvalue;
    }
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->SetFillColor(255, 255, 255);
    $pdf->SetTextColor(239, 007, 030);
    if ($prnval == 2) {
        $pdf->Cell(10, 7, " ", 1, 0, '', 1);
        $pdf->Cell(39, 7, " ", 1, 0, '', 1);
        $pdf->Cell(49, 7, "Total", 1, 0, '', 1);
        $pdf->Cell(30, 7, "$gropen", 1, 0, 'R', 1);
        $pdf->Cell(30, 7, "$grpur", 1, 0, 'R', 1);
        $pdf->Cell(30, 7, "$grsale", 1, 0, 'R', 1);
        $pdf->Cell(30, 7, "$grbal", 1, 0, 'R', 1);
        $pdf->Cell(30, 7, " ", 1, 0, '', 1);
        $pdf->Cell(30, 7, "$grval", 1, 0, 'R', 1);
    } else {
        $pdf->Cell(10, 7, " ", 1, 0, '', 1);
        $pdf->Cell(48, 7, " ", 1, 0, '', 1);
        $pdf->Cell(60, 7, "Total", 1, 0, '', 1);
        $pdf->Cell(40, 7, "$gropen", 1, 0, 'R', 1);
        $pdf->Cell(40, 7, "$grpur", 1, 0, 'R', 1);
        $pdf->Cell(40, 7, "$grsale", 1, 0, 'R', 1);
        $pdf->Cell(40, 7, "$grbal", 1, 0, 'R', 1);
    }
    $pdf->Ln();

    $pdf->SetFont('Arial', '', 1, 0);

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