<?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_fr.php";

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

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


$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'];
// if (!empty($prevyear)) {
//     $olddb = $zroot1 . $compcd . '_' . $prevyear;
// } else {
// $olddb = "";
// }

$name = $_POST['name'];
$dtype = $_POST['rtype'];
$itemgrp = $_POST['itemgrp'];

$namecond = '';
$itemgrpcond = '';

$a = 1;

//if (empty($name) && empty($itemgrp)) {
//    browse('Item Name / Group Cannot Be Empty');
//    $a = 0;
//    header("refresh:1; itemwise.php");
//}

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

if (!empty($itemgrp)) {
    $itemgrpcond = " where `itemgrp`= '$itemgrp' ";
    $itemgrpcond3 = " and `itemgrp`= '$itemgrp' ";
    $itemgrpcond1 = " and b.`itemgrp`='$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'];

$dtype = 2;

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

    if ($a == 1) {
        $mfdt = date("d-m-Y", strtotime($mfrmdate));
        $mtdt = date("d-m-Y", strtotime($mtodate));
        $select_purchase_rate = "(SELECT AVG(`rate`) as rate FROM `purtran` WHERE `itemcode`= b.item AND vouchdt <= a.vouchdt) as purchase_rate";
        $select_old_purchase_rate = "(SELECT AVG(`rate`) as rate FROM `purtran` WHERE `itemcode`= b.item and `rate` > 0) as old_purchase_rate";
//        $select_transfer_rate =  "(SELECT GROUP_CONCAT(`rate`) FROM `transacn` WHERE `itemcode`= item and `source`='TR' and `vouchdt` <=  vouchdt ) as transfer_rate ";


        mysqli_query($conn, "drop temporary table if exists trandata") or die(mysqli_error($conn));
        mysqli_query($conn, "create temporary table trandata 
                                    SELECT vouchdt, `rate`, itemcode FROM `transacn` WHERE `source`='TR' and qty > 0 
                                           and `rate` > 0 group by itemcode, vouchdt, rate ")or die(mysqli_error($conn));

        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`,  a.`subtotal`,
                                                a.lesother, a.`cdiscamt` , 
                                                c.name as itemname, c.cost as item_cost, c.itemgrp, c.itemsubgrp, c.unit, 
                                                $select_purchase_rate, $select_old_purchase_rate
                                                FROM $maindb a INNER JOIN $trandb b ON a.`vouchno` = b.`vouchno` INNER JOIN item c ON b.item = c.code  
                                                WHERE a.`vouchdt`>= '$mfrmdate'  AND  a.`vouchdt` <='$mtodate'                                                    
                                                union all
                                                SELECT 'R' as type, a.vouchdt, DATE_FORMAT(a.`vouchdt`,'%d-%m-%Y') as  mydt, 
                                                a.`party`, a.`vouchno`, (b.qty * - 1) as qty, b.rate, 00000 as cost,  b.`amount`, b.`item`, a.`subtotal`, 
                                                a.`lessoth` as lesother, a.`cdisamt` as cdiscamt, 
                                                c.name as itemname, c.cost as item_cost, c.itemgrp, c.itemsubgrp, c.unit, 
                                                $select_purchase_rate, $select_old_purchase_rate
                                                FROM credmain a INNER JOIN credtran b ON a.`vouchno` = b.`vouchno` INNER JOIN item c ON b.item = c.code 
                                                WHERE a.`vouchdt`>= '$mfrmdate'  AND  a.`vouchdt` <='$mtodate' 
                                                 ") or die(mysqli_error($conn));

        $getpmain = mysqli_query($conn, "SELECT * FROM `itdata` group by item order by itemname") or die(mysqli_error($conn));

//$getpmain = mysqli_query($conn, "SELECT *  FROM $maindb   where `vouchno` >= '$mfrmdate' and `vouchno`<= '$todate'  order by `vouchdt` ")or die(mysqli_error($conn));
//        print table($getpmain);
//        die();

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

                $a1 = 0;
                $sctr = 0;

                mysqli_query($conn, "delete from `pl_data` WHERE `vouchdt` >= '$mfrmdate'  AND  `vouchdt` <= '$mtodate' $itemcond3 $itemgrpcond3 ") or die(mysqli_error($conn));

                $a = $b = $c = $d = 0;

                while ($rowm = mysqli_fetch_array($getpmain)) {
                    $itemcode = $rowm['item'];
                    $itemname = $rowm['itemname'];
                    $pur_rate = $rowm['purchase_rate'];
                    $old_pur_rate = $rowm['old_purchase_rate'];
                    $itemgrp = $rowm['itemgrp'];
                    $itemsubgrp = $rowm['itemsubgrp'];
                    $unit = $rowm['unit'];

                    $get = mysqli_query($conn, "select a.*, b.name as partyname from itdata a, accmast b where a.item = '$itemcode' 
                                                       and a.party = b.accode order by a.vouchdt ") or die(mysqli_error($conn));

                    $getno = mysqli_num_rows($get);

                    if ($getno > 0) {
                        if ($dtype == 1) {
                            if ($a1 == 0) {
                                $a1 = 1;
                                ?>
                                <table  style="" class="table table-bordered  table-hover table-striped ">
                                    <thead class="mySearchTr">
                                        <tr style=" background-color: #78909C;">
                                            <th style="width:5%;">Sr.</th>
                                            <th style="width:40%;">Item</th>
                                            <th style="width:15%;"  class='text-right'>Qty.</th>
                                            <th style="width:15%;" class='text-right'>P/L Amount</th>
                                        </tr>
                                    </thead>
                                    <?php
                                }
                            } else {
                                ?>
                                <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: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>
                                    <?php
                                }
                                ?>
                                <tbody>
                                    <?php
                                    $ctr = 0;
                                    $tqty = 0;
                                    $tpl = 0;
                                    $totamt = 0;
                                    $month = 0;

                                    while ($row = mysqli_fetch_array($get)) {
                                        $costfrom = "";
                                        $dperc = 0;
                                        $dis = $row['lesother'] + $row['cdiscamt'];
                                        $dperc = ($dis * 100) / $row['subtotal'];

                                        $sldate = $row['vouchdt'];
                                        $vouchno = $row['vouchno'];
                                        $qty = $row['qty'];
                                        $partyname = $row['partyname'];
                                        $party = $row['party'];

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

                                        $itrate = $row['item_cost'];

                                        $tpurrate = 0;

                                        if ($itrate > 0) {
                                            $avgpurrate = $itrate;
                                            $costfrom = "1";
                                            $a++;
//                                            browse($costfrom);
//                                            browse($avgpurrate);
                                        } else {
                                            if ($pur_rate > 0) {
                                                $avgpurrate = $pur_rate;
                                                $b++;
                                            } else {
                                                if ($old_pur_rate > 0) {
                                                    $avgpurrate = $old_pur_rate;
                                                    $c++;
                                                } else {
//                                                    $getfromtrnf = mysqli_query($conn, "SELECT avg(`rate`) as rate FROM trandata WHERE `itemcode`='$row[item]' 
//                                                                                                and  `vouchdt` <= '$sldate' ") or die(mysqli_error($conn));
//                                                    $tnum = mysqli_num_rows($getfromtrnf);
//                                                    if ($tnum > 0) {
//                                                        $costfrom = "T";
//                                                        while ($showpurtrn = mysqli_fetch_array($getfromtrnf)) {
//                                                            $tpurrate = $tpurrate + $showpurtrn['rate'];
//                                                        }
//                                                        $avgpurrate = round($tpurrate / $tnum, 2);
//                                                        $d++;
//                                                    } else {
//                                                        $avgpurrate = round($itrate, 2);
//                                                    }

                                                    $getfromtrnf = mysqli_query($conn, "SELECT avg(`rate`) as rate FROM trandata WHERE `itemcode`='$row[item]' 
                                                                                                and  `vouchdt` <= '$sldate' ") or die(mysqli_error($conn));
                                                    $costfrom = "T";
                                                    $showpurtrn = mysqli_fetch_array($getfromtrnf);
                                                    $avgpurrate = round($showpurtrn['$tpurrate'], 2);
                                                    $d++;
                                                    if ($avgpurrate > 0) {
                                                        
                                                    } 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,2);
                                        $mnrateround = number_format($sactrate, 2);
                                        $diffround = round($diff);
                                        $plround = round($pl);

                                        if ($dtype == 2) {
                                            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>$partyname</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;

                                        mysqli_query($conn, "INSERT INTO `pl_data` (`vouchno`, `vouchdt`, `itemcode`, `itemgrp`, `itemsubgrp`, `partyname`,   
                                                                          `accode`, `qty`, `unit`, `rate`, `avgcost`, `pl_each`, `pl_amt`, `costfrom`) 
                                                                    VALUES ('$vouchno', '$sldate', '$itemcode', '$itemgrp', '$itemsubgrp', '$partyname',
                                                                         '$party', '$qty', '$unit', '$mnrateround', '$actpurrate', '$diffround', '$plround', '$costfrom' )") or die(mysqli_error($conn));
                                    }

                                    echo "<tr> ";
                                    if ($dtype == 1) {
                                        $sctr++;
                                        echo "<td class='text-right' >$sctr</td>";
                                        echo "<td class='text-left' >$itemname</td>";
                                        echo "<td class='text-right' ><b>$tqty</b></td>";
                                        echo "<td class='text-right' ><b>" . number_format($tpl, 2) . "</b></td>";
                                    } else {
                                        echo "<td  ></td>";
                                        echo "<td  ></td>";
                                        echo "<td  ></td>";
                                        echo "<td class='text-right' style=' color: #1ABC9C;'><b>Total</b></td>";
                                        echo "<td class='text-right' style=' color: #1ABC9C;'><b>$tqty</b></td>";
                                        echo "<td  ></td>";
                                        echo "<td  ></td>";
                                        echo "<td  ></td>";
                                        echo "<td class='text-right' style=' color: #1ABC9C;' ><b>" . number_format($tpl, 2) . "</b></td>";
                                    }
                                    echo "</tr>";
                                    $gtqty = $gtqty + $tqty;
                                    $gtrate = $gtrate + $tpl;
                                    $gtott = $gtott + $totamt;
                                }
                            }
//                                    browse($a);
//                                    browse($b);
//                                    browse($c);
//                                    browse($d);


                            if ($dtype == 1) {
                                echo "<tr> ";
                                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 class='text-right' style=' color: red;' ><b>" . number_format($gtrate, 2) . "</b></td>";
                                echo "</tr>";
                            } else {
                                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'];
    $itemgrp = $_POST['itemgrp'];

    $namecond = '';
    $itemgrpcond = '';

    $a = 1;

    if (empty($name) && empty($itemgrp)) {
        browse('Item Name / Group Cannot Be Empty');
        $a = 0;
        header("refresh:1; itemwise.php");
    }

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

    if (!empty($itemgrp)) {
        $itemgrpcond = " where `itemgrp`='$itemgrp' ";
        $itemgrpcond1 = " and b.`itemgrp`='$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 = trim($_POST["frmdt"]);
    $mtodate = trim($_POST["todt"]);

    if ($a == 1) {

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


        $getpmain = mysqli_query($conn, "SELECT a.`item`, b.name as itemname, b.cost FROM $trandb a, item b WHERE a.`item` = b.`code` and 
                            a.`vouchdt` >= '$mfrmdate'  AND  a.`vouchdt` <= '$mtodate'  $itemcond1 $itemgrpcond1 group by a.item order by b.name") or die(mysqli_error($conn));

        while ($rowm = mysqli_fetch_array($getpmain)) {
            $itemcode = $rowm[item];
            $itrate = $rowm[cost];

            $get = mysqli_query($conn, "SELECT a.vouchdt, DATE_FORMAT(a.`vouchdt`,'%d-%m-%Y') as  mydt , a.`party`, a.`vouchno`, b.qty, b.rate,  b.`amount`, b.`item`, 
                                    a.`subtotal`, a.`lesother`, a.`cdiscamt`   
                                    FROM $maindb a, $trandb b  WHERE  b.item = '$itemcode' and a.`vouchdt`>= '$mfrmdate'  
                                    AND  a.`vouchdt` <='$mtodate' AND a.`vouchno` = b.`vouchno` order by b.item") or die(mysqli_error($conn));
            $getno = mysqli_num_rows($get);
            if ($getno > 0) {
                $contents .= "Item" . "-" . $rowm[itemname] . "\n";

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

                while ($row = mysqli_fetch_array($get)) {
                    $dperc = 0;
                    $dis = $row[lesother] + $row[cdiscamt];
                    $dperc = ($dis * 100) / $row[subtotal];

                    $sldate = $row[vouchdt];

                    $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 `itemcode`='$row[item]' and rate > 0 and vouchdt <= '$sldate'")or die(mysqli_error($conn));
                    $chkpurrate = mysqli_num_rows($getpur);

                    $tpurrate = 0;
                    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 `itemcode`='$row[item]' and `rate` > 0 ")or die(mysqli_error($conn));
                            $tnum = mysqli_num_rows($getpurold);

                            if ($numshowrate > 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 = $row[qty] * $diff;
                    } else {
                        $actpurrate = 0;
                        $diff = 0;
                        $pl = 0;
                    }


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

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

                    $tqty = $tqty + $row[qty];
                    $tpl = $tpl + $pl;
                }
                $contents .= " " . ",";
                $contents .= " " . ",";
                $contents .= " " . ",";
                $contents .= "Total" . ",";
                $contents .= " " . ",";
                $contents .= " " . ",";
                $contents .= " " . ",";
                $contents .= number_format($tpl, 2, '.', ' ') . "\n";

                $gtqty = $gtqty + $tqty;
                $gtrate = $gtrate + $tpl;
                $gtott = $gtott + $totamt;
            }
        }
        $contents .= " " . ",";
        $contents .= " " . ",";
        $contents .= " " . ",";
        $contents .= "Grand Total" . ",";
        $contents .= $gtqty . ",";
        $contents .= " " . ",";
        $contents .= " " . ",";
        $contents .= " " . ",";
        $contents .= number_format($gtrate, 2, '.', ' ') . ",";
    }
    $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"])) {

 if ($a == 1) {
       $mfdt = date("d-m-Y", strtotime($mfrmdate));
        $mtdt = date("d-m-Y", strtotime($mtodate));
        $select_purchase_rate = "(SELECT AVG(`rate`) as rate FROM `purtran` WHERE `itemcode`= b.item AND vouchdt <= a.vouchdt) as purchase_rate";
        $select_old_purchase_rate = "(SELECT AVG(`rate`) as rate FROM `purtran` WHERE `itemcode`= b.item and `rate` > 0) as old_purchase_rate";
//        $select_transfer_rate =  "(SELECT GROUP_CONCAT(`rate`) FROM `transacn` WHERE `itemcode`= item and `source`='TR' and `vouchdt` <=  vouchdt ) as transfer_rate ";


        mysqli_query($conn, "drop temporary table if exists trandata") or die(mysqli_error($conn));
        mysqli_query($conn, "create temporary table trandata 
                                    SELECT vouchdt, `rate`, itemcode FROM `transacn` WHERE `source`='TR' and qty > 0 
                                           and `rate` > 0 group by itemcode, vouchdt, rate ")or die(mysqli_error($conn));

        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`,  a.`subtotal`,
                                                a.lesother, a.`cdiscamt` , 
                                                c.name as itemname, c.cost as item_cost, c.itemgrp, c.itemsubgrp, c.unit, 
                                                $select_purchase_rate, $select_old_purchase_rate
                                                FROM $maindb a INNER JOIN $trandb b ON a.`vouchno` = b.`vouchno` INNER JOIN item c ON b.item = c.code  
                                                WHERE a.`vouchdt`>= '$mfrmdate'  AND  a.`vouchdt` <='$mtodate'                                                    
                                                union all
                                                SELECT 'R' as type, a.vouchdt, DATE_FORMAT(a.`vouchdt`,'%d-%m-%Y') as  mydt, 
                                                a.`party`, a.`vouchno`, (b.qty * - 1) as qty, b.rate, 00000 as cost,  b.`amount`, b.`item`, a.`subtotal`, 
                                                a.`lessoth` as lesother, a.`cdisamt` as cdiscamt, 
                                                c.name as itemname, c.cost as item_cost, c.itemgrp, c.itemsubgrp, c.unit, 
                                                $select_purchase_rate, $select_old_purchase_rate
                                                FROM credmain a INNER JOIN credtran b ON a.`vouchno` = b.`vouchno` INNER JOIN item c ON b.item = c.code 
                                                WHERE a.`vouchdt`>= '$mfrmdate'  AND  a.`vouchdt` <='$mtodate'   ") or die(mysqli_error($conn));

       
    $getpmain = mysqli_query($conn, "SELECT * FROM `itdata` group by item order by itemname") or die(mysqli_error($conn));

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

    class pdf extends fpdf {

        function Footer() {

            $this->SetY(-15);
            $this->SetFont('Arial', 'I', 8);
            $this->Cell(0, 10, 'Page ' . $this->PageNo() . '/{nb}', 0, 0, 'C');
        }

    }

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

    $pdf->AliasNbPages();
    $pdf->AddPage();

//    $pdf->ln(-7);
   
//$getpmain = mysqli_query($conn, "SELECT *  FROM $maindb   where `vouchno` >= '$mfrmdate' and `vouchno`<= '$todate'  order by `vouchdt` ")or die(mysqli_error($conn));
//        print table($getpmain);
//        die();
        $a1 = 0;
        $sctr = 0;
               
        
        mysqli_query($conn, "delete from `pl_data` WHERE `vouchdt` >= '$mfrmdate'  AND  `vouchdt` <= '$mtodate' $itemcond3 $itemgrpcond3 ") or die(mysqli_error($conn));

        
        $a = $b = $c = $d = 0;

        while ($rowm = mysqli_fetch_array($getpmain)) {
            $itemcode = $rowm['item'];
            $itemname = $rowm['itemname'];
            $pur_rate = $rowm['purchase_rate'];
            $old_pur_rate = $rowm['old_purchase_rate'];
            $itemgrp = $rowm['itemgrp'];
            $itemsubgrp = $rowm['itemsubgrp'];
            $unit = $rowm['unit'];

            $get = mysqli_query($conn, "select a.*, b.name as partyname from itdata a, accmast b where a.item = '$itemcode' 
                                                       and a.party = b.accode order by a.vouchdt ") or die(mysqli_error($conn));

            $getno = mysqli_num_rows($get);

            if ($getno > 0) {
                if ($dtype == 1) {
                    if ($a1 == 0) {
                        $a1 = 1;
//                        $pdf->Cell(18, 7, "Sr.", 1, 0, '', 1);
//                        $pdf->Cell(35, 7, "Item", 1, 0, '', 1);
//                        $pdf->Cell(70, 7, "Qty", 1, 0, '', 1);
//                        $pdf->Cell(25, 7, "P/L Amount", 1, 0, '', 1);
//                        $pdf->ln();
                    }
                } else {
                    
//                    browse($rowm['itemname']);
//                    $pdf->SetFillColor(255, 255, 255);
//                    $pdf->SetTextColor(0, 0, 0);
                    $pdf->Cell(190, 10, "Item - $rowm[itemname]", 0, 0, 'L');
                    $pdf->ln();


                    $pdf->SetFont('Arial', 'B', 11);
                    $pdf->SetTextColor(255, 255, 255);
                    $pdf->SetFillColor(120, 144, 156);
                    $pdf->Cell(18, 7, "Sr.", 1, 0, '', 1);
                    $pdf->Cell(35, 7, "Date", 1, 0, '', 1);
                    $pdf->Cell(70, 7, "Customer", 1, 0, '', 1);
                    $pdf->Cell(25, 7, "Bill No.", 1, 0, '', 1);
                    $pdf->Cell(23, 7, "Qty.", 1, 0, 'R', 1);
                    $pdf->Cell(26, 7, "Rate", 1, 0, 'R', 1);
                    $pdf->Cell(26, 7, "Avg. Cost", 1, 0, 'R', 1);
                    $pdf->Cell(26, 7, "P/L (Each)", 1, 0, 'R', 1);
                    $pdf->Cell(30, 7, "P/L Amount", 1, 0, 'R', 1);
                    $pdf->ln();
                }
                
                
                $ctr = 0;
                $tqty = 0;
                $tpl = 0;
                $totamt = 0;
                $month = 0;

                while ($row = mysqli_fetch_array($get)) {
                    $costfrom = "";
                    $dperc = 0;
                    $dis = $row['lesother'] + $row['cdiscamt'];
                    $dperc = ($dis * 100) / $row['subtotal'];

                    $sldate = $row['vouchdt'];
                    $vouchno = $row['vouchno'];
                    $qty = $row['qty'];
                    $partyname = $row['partyname'];
                    $party = $row['party'];

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


                    $itrate = $row['item_cost'];

                    $tpurrate = 0;

                    if ($itrate > 0) {
                        $avgpurrate = $itrate;
                        $costfrom = "1";
                        $a++;
                    } else {
                        if ($pur_rate > 0) {
                            $avgpurrate = $pur_rate;
                            $b++;
                        } else {
                            if ($old_pur_rate > 0) {
                                $avgpurrate = $old_pur_rate;
                                $c++;
                            } else {
//                                                    
                                $getfromtrnf = mysqli_query($conn, "SELECT avg(`rate`) as rate FROM trandata WHERE `itemcode`='$row[item]' 
                                                                                                and  `vouchdt` <= '$sldate' ") or die(mysqli_error($conn));
                                $costfrom = "T";
                                $showpurtrn = mysqli_fetch_array($getfromtrnf);
                                $avgpurrate = round($showpurtrn['$tpurrate'], 2);
                                $d++;
                                if ($avgpurrate > 0) {
                                    
                                } else {
                                    $avgpurrate = round($itrate, 2);
                                }
                            }
                        }
                    }

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

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

                    $pdf->SetFillColor(255, 255, 255);
                    $pdf->SetTextColor(0, 0, 0);

                    if ($dtype == 2) {
                        if ($row['type'] == 'S') {
                            $ctr++;
                            $pdf->Cell(18, 7, "$ctr", 1, 0, '', 1);
                        } else {
                            $pdf->Cell(20, 7, "GR", 1, 0, '', 1);
                        }

                        $pdf->Cell(35, 7, "$row[mydt]", 1, 0, '', 1);
                        $pdf->Cell(70, 7, "$partyname", 1, 0, '', 1);
                        $pdf->Cell(25, 7, "$row[vouchno]", 1, 0, '', 1);
                        $pdf->Cell(23, 7, "$qty", 1, 0, 'R', 1);
                        $pdf->Cell(26, 7, "$mnrateround", 1, 0, 'R', 1);
                        $pdf->Cell(26, 7, "$actpurrate", 1, 0, 'R', 1);
                        $pdf->Cell(26, 7, "$diffround", 1, 0, 'R', 1);
                        $pdf->Cell(30, 7, "$plround", 1, 0, 'R', 1);
                        $pdf->ln();
                    }

                    $tqty = $tqty + $qty;
                    $tpl = $tpl + $pl;
                    
                    mysqli_query($conn, "INSERT INTO `pl_data` (`vouchno`, `vouchdt`, `itemcode`, `itemgrp`, `itemsubgrp`, `partyname`,   
                                                                `accode`, `qty`, `unit`, `rate`, `avgcost`, `pl_each`, `pl_amt`, `costfrom`) 
                                                           VALUES ('$vouchno', '$sldate', '$itemcode', '$itemgrp', '$itemsubgrp', '$partyname',
                                                                  '$party', '$qty', '$unit', '$mnrateround', '$actpurrate', '$diffround', '$plround', '$costfrom' )") or die(mysqli_error($conn));
                }    
                    $pdf->SetFillColor(255, 255, 255);
                    $pdf->SetTextColor(26, 188, 156);
                    if ($dtype == 1) {
                        $sctr++;
                        $pdf->Cell(20, 7, "$ctr", 1, 0, '', 1);
                        $pdf->Cell(20, 7, "$itemname", 1, 0, '', 1);
                        $pdf->Cell(20, 7, "$tqty", 1, 0, '', 1);
                        $pdf->Cell(20, 7, "$tpl", 1, 0, '', 1);
                    } else {
                        $pdf->Cell(18, 7, "", 1, 0, '', 1);
                        $pdf->Cell(35, 7, "", 1, 0, '', 1);
                        $pdf->Cell(70, 7, "", 1, 0, '', 1);
                        $pdf->Cell(25, 7, "Total", 1, 0, 'R', 1);
                        $pdf->Cell(23, 7, "$tqty", 1, 0, 'R', 1);
                        $pdf->Cell(26, 7, "", 1, 0, '', 1);
                        $pdf->Cell(26, 7, "", 1, 0, '', 1);
                        $pdf->Cell(26, 7, "", 1, 0, '', 1);
                        $pdf->Cell(30, 7, "$tpl", 1, 0, 'R', 1);
                        $pdf->ln();
                    }
                    $gtqty = $gtqty + $tqty;
                    $gtrate = $gtrate + $tpl;
                    $gtott = $gtott + $totamt;
            
                    }
            
        }
        $pdf->Output("itemwise2_fr.pdf", "I");
    }
}
?>