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

$maindb = 'salemain';
$trandb = 'saletran';
$formname = "Item Wise P/L";
$file = "itemwise_gst.php";

//browse('work in progress....');

$admin = $_SESSION["admin_" . $dbname];
$zdb = $_SESSION["zdbyear_" . $dbname];
$compcd = $_SESSION["comp_" . $dbname];

$myyear = $_SESSION[$myyear];
mysqli_select_db($conn, $zdb);
$zroot = $_SESSION["zdir"];
//browse($zroot);

$zroot1 = substr($zroot, 0, -4);

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

//browse($prevyear);

if (!empty($prevyear)) {
$olddb = $zroot1 . $compcd . '_' . $prevyear;
} else {
$olddb = "";
}
//browse($olddb);

if (isset($_POST["view"])) {
$name = $_POST['name'];
$dtype = $_POST['rtype'];
//    $itemgrp = $_POST['itemgrp'];
//    $godown = trim($_POST["godown"]);
//    $dtype - 1 for summary and 2 or detail

$namecond = '';
$itemgrpcond = '';
$godowncond = "";

$a = 1;

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

if (!empty($name)) {
$itemcond = " AND b.itemcode='$name' ";
$itemcond1 = " AND a.itemcode='$name' ";
$itemcond2 = " AND `item`='$name' ";
}

//    if (!empty($itemgrp)) {
//        $itemgrpcond = " where `prodgrp`='$itemgrp' ";
//        $itemgrpcond1 = " and b.`prodgrp`='$itemgrp' ";
//    }

if (empty($_POST["frmdt"])) {
browse("From Date Cannot Be Empty");
header("refresh:1; itemwise.php");
}
if (empty($_POST["todt"])) {
browse("To Date Cannot Be Empty");
header("refresh:1; itemwise.php");
}

$mfrmdate = $_POST['frmdt'];
$mtodate = $_POST['todt'];

if ($a == 1) {
$mfdt = date("d-m-Y", strtotime($mfrmdate));
$mtdt = date("d-m-Y", strtotime($mtodate));


mysqli_query($conn, "drop temporary table if exists idata") or die(mysqli_error($conn));

if ($dtype == 1) {
mysqli_query($conn, "create temporary table idata 
                                    SELECT a.itemcode, b.barcode, b.name as itemname, a.cost, a.rate, a.qty, a.amount, (a.qty * a.cost) as costamt
                                           FROM $trandb a, product b WHERE a.itemcode = b.`code` and a.`vouchdt` >= '$mfrmdate'  
                                           AND  a.`vouchdt` <= '$mtodate' $itemcond1 $itemgrpcond1 ") or die(mysqli_error($conn));

$getpmain = mysqli_query($conn, "SELECT itemcode, barcode, itemname, sum(qty) as qty, sum(amount) as amount, sum(costamt) as costamt 
                                                    FROM `idata` group by itemcode order by itemname") or die(mysqli_error($conn));
//            print table($getpmain);
//            die();
} else {
mysqli_query($conn, "create temporary table idata 
                                    SELECT a.itemcode, b.barcode, b.name as itemname, a.cost, a.rate, a.qty, a.amount, (a.qty * a.cost) as costamt
                                           FROM $trandb a, product b WHERE a.itemcode = b.`code` and a.`vouchdt` >= '$mfrmdate'  
                                           AND  a.`vouchdt` <= '$mtodate' $itemcond1 $itemgrpcond1
                                    UNION ALL           
                                    SELECT a.itemcode, b.barcode, b.name as itemname, a.cost, a.rate, (a.qty * -1) as qty, (a.amount * - 1) as amount, (a.qty * a.cost) as costamt 
                                           FROM `credtran` a, product b WHERE a.itemcode = b.`code` and a.`vouchdt` >= '$mfrmdate'  
                                           AND  a.`vouchdt` <= '$mtodate' $itemcond1 $itemgrpcond1 ") or die(mysqli_error($conn));
$getpmain = mysqli_query($conn, "SELECT * FROM `idata` group by itemcode order by itemname") or die(mysqli_error($conn));
}
include("includes/linkshead.php");
?>
<style>
    @media print
    {    
        .no-print, .no-print *
        {
            display: none !important;
        }
    }
</style>
</head>
<body>
    <div class="container">
        <?php
        include("includes/head_rep.php");
        if ($dtype == 1) {
        ?>
        <table  style="" class="table table-bordered  table-hover table-striped ">
            <!--                        <div class = "row">
                                        <div class = "col-lg-6 col-sm-6">
                                            <label class = "label-control">Item - </label>
                                            <label class = "label-control"><?Php echo $rowm['itemname']; ?>
                                            </label>
                                        </div>
                                    </div>-->

            <thead class="mySearchTr">
                <tr style=" background-color: #78909C;">
                    <th style="width:5%;">Sr.</th>
                    <th style="width:15%;">Barcode</th>
                    <th style="width:25%;">Item Name</th>
                    <th style="width:15%;" class='text-right'>Qty.</th>
                    <th style="width:15%;" class='text-right'>Sale Amount</th>
                    <th style="width:15%;" class='text-right'>Cost Amount</th>
                    <th style="width:15%;" class='text-right'>P/L Amount</th>
                </tr>
            </thead>

            <?php
            $ctr = 0;
            $tqty = 0;
            $tpl = 0;
            $tamount = 0;
            $tcostamt = 0;
            $month = 0;
            while ($rowm = mysqli_fetch_array($getpmain)) {
            $barcode = $rowm['barcode'];
            $itemname = $rowm['itemname'];
            $qty = $rowm['qty'];
            $amount = $rowm['amount'];
            $costamt = $rowm['costamt'];
            $plamt = $amount - $costamt;
            $ctr++;

            echo "<tr>";
            echo "<td>$ctr</td>";
            echo "<td>$barcode</td>";
            echo "<td>$itemname</td>";
            echo "<td class='text-right'>" . number_format($qty, 2) . "</td>";
            echo "<td class='text-right'>" . number_format($amount, 2) . "</td>";
            echo "<td class='text-right'>" . number_format($costamt, 2) . "</td>";
            echo "<td class='text-right'>" . number_format($plamt, 2) . "</td>";
            echo "</tr>";

            $tqty = $tqty + $qty;
            $tamount = $tamount + $amount;
            $tcostamt = $tcostamt + $costamt;
            $tpl = $tpl + $plamt;

            ///////////// credit note = goods return


            $getcred = mysqli_query($conn, "SELECT  cost, rate, sum(qty) as qty, sum(amount) as amount, sum(qty * cost) as costamt 
                                           FROM `credtran` WHERE barcode = '$barcode' and `vouchdt` >= '$mfrmdate'  
                                           AND  `vouchdt` <= '$mtodate' group by itemcode ") or die(mysqli_error($conn));
            $credno = mysqli_num_rows($getcred);
            if ($credno > 0) {
            $cred = mysqli_fetch_array($getcred);
            $cqty = $cred['qty'] * - 1;
            $camount = $cred['amount'];
            $ccostamt = $cred['costamt'];
            $cplamt = ($camount - $ccostamt) * -1;

            echo "<tr style='color:red'>";
            echo "<td>Return</td>";
            echo "<td>$barcode</td>";
            echo "<td>$itemname</td>";
            echo "<td class='text-right'>" . number_format($cqty, 2) . "</td>";
            echo "<td class='text-right'>" . number_format($camount, 2) . "</td>";
            echo "<td class='text-right'>" . number_format($ccostamt, 2) . "</td>";
            echo "<td class='text-right'>" . number_format($cplamt, 2) . "</td>";
            echo "</tr>";

            $tqty = $tqty + $cqty;
            $tamount = $tamount + $camount;
            $tcostamt = $tcostamt + $ccostamt;
            $tpl = $tpl + $cplamt;
            }
            }
            echo "<tr> ";
            echo "<td ></td>";
            echo "<td ></td>";
            echo "<td class='text-right' style=' color: #11823B;'><b>Total</b></td>";
            echo "<td class='text-right' style=' color: #11823B;' ><b>" . number_format($tqty, 2) . "</b></td>";
            echo "<td class='text-right' style=' color: #11823B;' ><b>" . number_format($tamount, 2) . "</b></td>";
            echo "<td class='text-right' style=' color: #11823B;' ><b>" . number_format($tcostamt, 2) . "</b></td>";
            echo "<td class='text-right' style=' color: #11823B;' ><b>" . number_format($tpl, 2) . "</b></td>";
            echo "</tr>";
            ?> 
            </tbody>
        </table>
        <?php
        } else {
        while ($rowm = mysqli_fetch_array($getpmain)) {
        $itemcode = $rowm['itemcode'];
//                    $itrate = $rowm['cost'];

        mysqli_query($conn, "drop temporary table if exists itdata") or die(mysqli_error($conn));
        mysqli_query($conn, "create temporary table itdata 
                                                SELECT 'S' as type, a.vouchdt, DATE_FORMAT(a.`vouchdt`,'%d-%m-%Y') as  mydt, 
                                                a.`party`, a.`vouchno`, b.qty, b.rate, b.cost,  b.`amount`, b.item as itemcode, a.`subtotal`, a.litemdisc 
                                                FROM $maindb a, $trandb b  WHERE  b.item = '$itemcode'  and a.`vouchdt`>= '$mfrmdate'  
                                                AND  a.`vouchdt` <='$mtodate' AND a.`vouchno` = b.`vouchno` $godowncond
                                                union all
                                                SELECT 'R' as type, a.vouchdt, DATE_FORMAT(a.`vouchdt`,'%d-%m-%Y') as  mydt, 
                                                a.`party`, a.`vouchno`, b.qty, b.rate, b.cost,  b.`amount`, b.itemcode, a.`subtotal`, a.`litemdisc` 
                                                FROM `credmain` a, `credtran` b  WHERE  b.itemcode = '$itemcode' and a.`vouchdt`>= '$mfrmdate'  
                                                AND  a.`vouchdt` <='$mtodate' AND a.`vouchno` = b.`vouchno` $godowncond ") or die(mysqli_error($conn));

        $get = mysqli_query($conn, "select * from itdata order by vouchdt ") or die(mysqli_error($conn));
        $getno = mysqli_num_rows($get);
        if ($getno > 0) {
        ?>
        <table  style="" class="table table-bordered  table-hover table-striped ">

            <div class = "row">
                <div class = "col-lg-6 col-sm-6">
                    <label class = "label-control">Item - </label>
                    <label class = "label-control"><?Php echo $rowm['itemname']; ?>
                        <?php // browse($rowm[itemname]);           ?>
                    </label>
                </div>
            </div>

            <thead class="mySearchTr">
                <tr style=" background-color: #78909C;">
                    <th style="width:10%;">Sr.</th>
                    <th style="width:10%;">Date</th>
                    <th style="width:21%;">Customer</th>
                    <th style="width:10%;">Bill No.</th>
                    <th style="width:8%;"  class='text-right'>Qty.</th>
                    <th style="width:8%;"  class='text-right'>Rate</th>
                    <th style="width:8%;"  class='text-right'>Avg. Cost</th>
                    <th style="width:10%;" class='text-right'>P/L (Each)</th>
                    <th style="width:15%;" class='text-right'>P/L Amount</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $ctr = 0;
                $tqty = 0;
                $tpl = 0;
                $totamt = 0;
                $month = 0;
                while ($row = mysqli_fetch_array($get)) {
                $dperc = 0;
                $dis = $row['lesother'];

                if ($row['subtotal'] > 0) {
                $subtotal = $row['subtotal'];
                } else {
                $subtotal = 1;
                }
                $dperc = ($dis * 100) / $subtotal;

                $sldate = $row['vouchdt'];

                if ($row['type'] == 'S') {
                $qty = $row['qty'];
                } else {
                $qty = $row['qty'] * -1;
                }

                $srate = $row['rate'];
                $sactrate = $srate - (($row['rate'] * $dperc) / 100);

                $getparty = mysqli_query($conn, "SELECT `accode`, `name` FROM `accmast` WHERE  `accode`='$row[party]' ORDER BY `name`") or die(mysqli_error($conn));
                $sparty = mysqli_fetch_array($getparty);

                $getpur = mysqli_query($conn, "SELECT `rate` FROM `purtran` WHERE `item`='$row[item]' and rate > 0 
                                                                           and vouchdt <= '$sldate'")or die(mysqli_error($conn));
                $chkpurrate = mysqli_num_rows($getpur);
                $itrate = $row['cost'];

                $tpurrate = 0;
                if ($itrate > 0) {
                $avgpurrate = $itrate;
                } else {
                if ($chkpurrate > 0) {
                $tnum = $chkpurrate;
                while ($showpur = mysqli_fetch_array($getpur)) {
                $tpurrate = $tpurrate + $showpur['rate'];
                }
                $avgpurrate = round($tpurrate / $tnum, 2);
                } else {
                if (!empty($prevyear) && $olddb != "") {
                $getpurold = mysqli_query($conn, "SELECT `rate` FROM $olddb.`purtran` WHERE `item`='$row[item]' and `rate` > 0 ")or die(mysqli_error($conn));
                $tnum = mysqli_num_rows($getpurold);

                if ($tnum > 0) {
                while ($showpurold = mysqli_fetch_array($getpurold)) {
                $tpurrate = $tpurrate + $showpurold['rate'];
                }
                $avgpurrate = round($tpurrate / $tnum, 2);
                } else {
                $getfromtrnf = mysqli_query($conn, "SELECT `rate` FROM `transacn` WHERE `itemcode`='$row[item]' and `source`='TR' and qty > 0 
                                                                            and `rate` > 0 and `vouchdt` <= '$sldate' ")or die(mysqli_error($conn));
                $tnum = mysqli_num_rows($getfromtrnf);
                if ($tnum > 0) {
                while ($showpurtrn = mysqli_fetch_array($getfromtrnf)) {
                $tpurrate = $tpurrate + $showpurtrn['rate'];
                }
                $avgpurrate = round($tpurrate / $tnum, 2);
                } else {
                $avgpurrate = round($itrate, 2);
                }
                }
                }
                }
                }


                if ($avgpurrate > 0) {
                $actpurrate = $avgpurrate;
                $diff = $sactrate - $actpurrate;
                $pl = $qty * $diff;
                } else {
                $actpurrate = 0;
                $diff = 0;
                $pl = 0;
                }

                $mnrateround = round($sactrate);
                $diffround = round($diff);
                $plround = round($pl);

                if ($row['type'] == 'S') {
                $ctr++;
                echo "<tr> ";
                echo "<td>$ctr</td>";
                } else {
                echo "<tr style='color:red'> ";
                echo "<td>GR</td>";
                }


                echo "<td>$row[mydt]</td>";
                echo "<td>$sparty[name]</td>";
                echo "<td>$row[vouchno]</td>";
                echo "<td class='text-right'>" . number_format($qty, 2) . "</td>";
                echo "<td class='text-right'>$mnrateround</td>";
                echo "<td class='text-right'>$actpurrate</td>";
                echo "<td class='text-right'>$diffround</td>";
                echo "<td class='text-right'>$plround</td>";
                echo "</tr>";

                $tqty = $tqty + $qty;
                $tpl = $tpl + $pl;
                }
                echo "<tr> ";
                echo "<td  ></td>";
                echo "<td  ></td>";
                echo "<td  ></td>";
                echo "<td class='text-right' style=' color: #11823B;'><b>Total</b></td>";
                echo "<td class='text-right' style=' color: #11823B;'><b>$tqty</b></td>";
                echo "<td  ></td>";
                echo "<td  ></td>";
                echo "<td  ></td>";
                echo "<td class='text-right' style=' color: #11823B;' ><b>" . number_format($tpl, 2) . "</b></td>";
                echo "</tr>";

                $gtqty = $gtqty + $tqty;
                $gtrate = $gtrate + $tpl;
                $gtott = $gtott + $totamt;
                }
                }
                echo "<tr> ";
                echo "<td  ></td>";
                echo "<td  ></td>";
                echo "<td  ></td>";
                echo "<td class='text-right' style=' color: red;'><b>Grand Total</b></td>";
                echo "<td class='text-right' style=' color: red;'><b>$gtqty</b></td>";
                echo "<td  ></td>";
                echo "<td  ></td>";
                echo "<td  ></td>";
                echo "<td class='text-right' style=' color: red;' ><b>" . number_format($gtrate, 2) . "</b></td>";
                echo "</tr>";
                }
                }
                ?> 
            </tbody>
        </table>
    </div>
    <?php
    include("includes/linksfoot.php");
    ?>
</body>
</html>
<?php
}



if (isset($_POST["excel"])) {
$name = $_POST['name'];
$dtype = $_POST['rtype'];

$namecond = '';
$itemgrpcond = '';
$godowncond = "";

$a = 1;

if (!empty($name)) {
$itemcond = " AND b.itemcode='$name' ";
$itemcond1 = " AND a.itemcode='$name' ";
$itemcond2 = " AND `item`='$name' ";
}

if (empty($_POST["frmdt"])) {
browse("From Date Cannot Be Empty");
header("refresh:1; itemwise.php");
}
if (empty($_POST["todt"])) {
browse("To Date Cannot Be Empty");
header("refresh:1; itemwise.php");
}

$mfrmdate = $_POST['frmdt'];
$mtodate = $_POST['todt'];

if ($a == 1) {
$mfdt = date("d-m-Y", strtotime($mfrmdate));
$mtdt = date("d-m-Y", strtotime($mtodate));

mysqli_query($conn, "drop temporary table if exists idata") or die(mysqli_error($conn));

if ($dtype == 1) {
mysqli_query($conn, "create temporary table idata 
                                    SELECT a.itemcode, b.barcode, b.name as itemname, a.cost, a.rate, a.qty, a.amount, (a.qty * a.cost) as costamt
                                           FROM $trandb a, product b WHERE a.itemcode = b.`code` and a.`vouchdt` >= '$mfrmdate'  
                                           AND  a.`vouchdt` <= '$mtodate' $itemcond1 $itemgrpcond1 ") or die(mysqli_error($conn));

$getpmain = mysqli_query($conn, "SELECT itemcode, barcode, itemname, sum(qty) as qty, sum(amount) as amount, sum(costamt) as costamt 
                                                    FROM `idata` group by itemcode order by itemname") or die(mysqli_error($conn));
//            print table($getpmain);
//            die();
} else {
mysqli_query($conn, "create temporary table idata 
                                    SELECT a.itemcode, b.barcode, b.name as itemname, a.cost, a.rate, a.qty, a.amount, (a.qty * a.cost) as costamt
                                           FROM $trandb a, product b WHERE a.itemcode = b.`code` and a.`vouchdt` >= '$mfrmdate'  
                                           AND  a.`vouchdt` <= '$mtodate' $itemcond1 $itemgrpcond1
                                    UNION ALL           
                                    SELECT a.itemcode, b.barcode, b.name as itemname, a.cost, a.rate, (a.qty * -1) as qty, (a.amount * - 1) as amount, (a.qty * a.cost) as costamt 
                                           FROM `credtran` a, product b WHERE a.itemcode = b.`code` and a.`vouchdt` >= '$mfrmdate'  
                                           AND  a.`vouchdt` <= '$mtodate' $itemcond1 $itemgrpcond1 ") or die(mysqli_error($conn));
$getpmain = mysqli_query($conn, "SELECT * FROM `idata` group by itemcode order by itemname") or die(mysqli_error($conn));
}
if ($dtype == 1) {

$contents .= "Barcode, Item Name, Qty., Sale Amount, Cost Amount, P/L Amount\n";

$ctr = 0;
$tqty = 0;
$tpl = 0;
$tamount = 0;
$tcostamt = 0;
$month = 0;
while ($rowm = mysqli_fetch_array($getpmain)) {
$barcode = $rowm['barcode'];
$itemname = $rowm['itemname'];
$qty = $rowm['qty'];
$amount = $rowm['amount'];
$costamt = $rowm['costamt'];
$plamt = $amount - $costamt;
$ctr++;


$contents .= "$ctr" . ",";
$contents .= "$barcode" . ",";
$contents .= "$itemname" . ",";
$contents .= "$qty" . ",";
$contents .= "$amount" . ",";
$contents .= "$costamt" . ",";
$contents .= "$plamt" . "\n";

$tqty = $tqty + $qty;
$tamount = $tamount + $amount;
$tcostamt = $tcostamt + $costamt;
$tpl = $tpl + $plamt;

///////////// credit note = goods return


$getcred = mysqli_query($conn, "SELECT  cost, rate, sum(qty) as qty, sum(amount) as amount, sum(qty * cost) as costamt 
                                           FROM `credtran` WHERE barcode = '$barcode' and `vouchdt` >= '$mfrmdate'  
                                           AND  `vouchdt` <= '$mtodate' group by itemcode ") or die(mysqli_error($conn));
$credno = mysqli_num_rows($getcred);
if ($credno > 0) {
$cred = mysqli_fetch_array($getcred);
$cqty = $cred['qty'] * - 1;
$camount = $cred['amount'];
$ccostamt = $cred['costamt'];
$cplamt = ($camount - $ccostamt) * -1;



$contents .= "Return" . ",";
$contents .= "$barcode" . ",";
$contents .= "$itemname" . ",";
$contents .= "$cqty" . ",";
$contents .= "$camount" . ",";
$contents .= "$ccostamt" . ",";
$contents .= "$cplamt" . "\n";

$tqty = $tqty + $cqty;
$tamount = $tamount + $camount;
$tcostamt = $tcostamt + $ccostamt;
$tpl = $tpl + $cplamt;
}
}
$contents .= "" . ",";
$contents .= "" . ",";
$contents .= "Total" . ",";
$contents .= "$tqty" . ",";
$contents .= "$tamount" . ",";
$contents .= "$tcostamt" . ",";
$contents .= "$tpl" . "\n";
} else {
while ($rowm = mysqli_fetch_array($getpmain)) {
$itemcode = $rowm['itemcode'];
//                    $itrate = $rowm['cost'];

mysqli_query($conn, "drop temporary table if exists itdata") or die(mysqli_error($conn));
mysqli_query($conn, "create temporary table itdata 
                                                SELECT 'S' as type, a.vouchdt, DATE_FORMAT(a.`vouchdt`,'%d-%m-%Y') as  mydt, 
                                                a.`party`, a.`vouchno`, b.qty, b.rate, b.cost,  b.`amount`, b.item as itemcode, a.`subtotal`, a.litemdisc 
                                                FROM $maindb a, $trandb b  WHERE  b.item = '$itemcode'  and a.`vouchdt`>= '$mfrmdate'  
                                                AND  a.`vouchdt` <='$mtodate' AND a.`vouchno` = b.`vouchno` $godowncond
                                                union all
                                                SELECT 'R' as type, a.vouchdt, DATE_FORMAT(a.`vouchdt`,'%d-%m-%Y') as  mydt, 
                                                a.`party`, a.`vouchno`, b.qty, b.rate, b.cost,  b.`amount`, b.itemcode, a.`subtotal`, a.`litemdisc` 
                                                FROM `credmain` a, `credtran` b  WHERE  b.itemcode = '$itemcode' and a.`vouchdt`>= '$mfrmdate'  
                                                AND  a.`vouchdt` <='$mtodate' AND a.`vouchno` = b.`vouchno` $godowncond ") or die(mysqli_error($conn));

$get = mysqli_query($conn, "select * from itdata order by vouchdt ") or die(mysqli_error($conn));
$getno = mysqli_num_rows($get);
if ($getno > 0) {

    $contents .= "Sr, Date, Customer, Bill No., Qty., Rate, Avg. Cost, P/L (Each), P/L Amount\n";

        $ctr = 0;
        $tqty = 0;
        $tpl = 0;
        $totamt = 0;
        $month = 0;
        while ($row = mysqli_fetch_array($get)) {
        $dperc = 0;
        $dis = $row['lesother'];

        if ($row['subtotal'] > 0) {
        $subtotal = $row['subtotal'];
        } else {
        $subtotal = 1;
        }
        $dperc = ($dis * 100) / $subtotal;

        $sldate = $row['vouchdt'];

        if ($row['type'] == 'S') {
        $qty = $row['qty'];
        } else {
        $qty = $row['qty'] * -1;
        }

        $srate = $row['rate'];
        $sactrate = $srate - (($row['rate'] * $dperc) / 100);

        $getparty = mysqli_query($conn, "SELECT `accode`, `name` FROM `accmast` WHERE  `accode`='$row[party]' ORDER BY `name`") or die(mysqli_error($conn));
        $sparty = mysqli_fetch_array($getparty);

        $getpur = mysqli_query($conn, "SELECT `rate` FROM `purtran` WHERE `item`='$row[item]' and rate > 0 
                                                                           and vouchdt <= '$sldate'")or die(mysqli_error($conn));
        $chkpurrate = mysqli_num_rows($getpur);
        $itrate = $row['cost'];

        $tpurrate = 0;
        if ($itrate > 0) {
        $avgpurrate = $itrate;
        } else {
        if ($chkpurrate > 0) {
        $tnum = $chkpurrate;
        while ($showpur = mysqli_fetch_array($getpur)) {
        $tpurrate = $tpurrate + $showpur['rate'];
        }
        $avgpurrate = round($tpurrate / $tnum, 2);
        } else {
        if (!empty($prevyear) && $olddb != "") {
        $getpurold = mysqli_query($conn, "SELECT `rate` FROM $olddb.`purtran` WHERE `item`='$row[item]' and `rate` > 0 ")or die(mysqli_error($conn));
        $tnum = mysqli_num_rows($getpurold);

        if ($tnum > 0) {
        while ($showpurold = mysqli_fetch_array($getpurold)) {
        $tpurrate = $tpurrate + $showpurold['rate'];
        }
        $avgpurrate = round($tpurrate / $tnum, 2);
        } else {
        $getfromtrnf = mysqli_query($conn, "SELECT `rate` FROM `transacn` WHERE `itemcode`='$row[item]' and `source`='TR' and qty > 0 
                                                                            and `rate` > 0 and `vouchdt` <= '$sldate' ")or die(mysqli_error($conn));
        $tnum = mysqli_num_rows($getfromtrnf);
        if ($tnum > 0) {
        while ($showpurtrn = mysqli_fetch_array($getfromtrnf)) {
        $tpurrate = $tpurrate + $showpurtrn['rate'];
        }
        $avgpurrate = round($tpurrate / $tnum, 2);
        } else {
        $avgpurrate = round($itrate, 2);
        }
        }
        }
        }
        }


        if ($avgpurrate > 0) {
        $actpurrate = $avgpurrate;
        $diff = $sactrate - $actpurrate;
        $pl = $qty * $diff;
        } else {
        $actpurrate = 0;
        $diff = 0;
        $pl = 0;
        }

        $mnrateround = round($sactrate);
        $diffround = round($diff);
        $plround = round($pl);

        if ($row['type'] == 'S') {
        $ctr++;

        $contents .= "$ctr" . ",";
        } else {
        $contents .= "GR" . ",";
        }


        $contents .= "$row[mydt]" . ",";
        $contents .= "$sparty[name]" . ",";
        $contents .= "$row[vouchno]" . ",";
        $contents .= "$qty" . ",";
        $contents .= "$mnrateround" . ",";
        $contents .= "$actpurrate" . ",";
        $contents .= "$diffround" . ",";
        $contents .= "$plround" . "\n";

        $tqty = $tqty + $qty;
        $tpl = $tpl + $pl;
        }
        $contents .= "" . ",";
        $contents .= "" . ",";
        $contents .= "" . ",";
        $contents .= "Total" . ",";
        $contents .= "$tqty" . ",";
        $contents .= "" . ",";
        $contents .= "" . ",";
        $contents .= "" . ",";
        $contents .= "$tpl" . "\n";

        $gtqty = $gtqty + $tqty;
        $gtrate = $gtrate + $tpl;
        $gtott = $gtott + $totamt;
        }
        }
        $contents .= "" . ",";
        $contents .= "" . ",";
        $contents .= "" . ",";
        $contents .= "Grand Total" . ",";
        $contents .= "$gtqty" . ",";
        $contents .= "" . ",";
        $contents .= "" . ",";
        $contents .= "" . ",";
        $contents .= "$gtrate" . "\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;
}
}
?>