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

$maindb = 'salemain';
$trandb = 'saletran';

// $maindb2 = 'vatmain';
// $trandb2 = 'vattran';

$formname = "Item Wise P/L";
$file = "itemwisepl.php";

ini_set('display_errors', 1);
error_reporting(E_ERROR);

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

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

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

$a = 1;

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


if (empty($_POST["frmdt"])) {
    browse("From Date Cannot Be Empty");
    header("refresh:1; itemwisepl.php");
    $a = 0;
}

if (empty($_POST["todt"])) {
    browse("To Date Cannot Be Empty");
    header("refresh:1; itemwisepl.php");
    $a = 0;
}

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


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

// mysqli_query($conn, "drop temporary table if exists itempl ") or die(mysqli_error($conn));
// mysqli_query($conn, "create temporary table itempl 
//                             SELECT a.`itemcode`, b.name as itemname, a.qty, a.rate, a.cost, (a.qty * (a.rate - a.cost)) as pl 
//                                    FROM $trandb a, product b WHERE a.`itemcode` = b.`code` and  
//                                    a.`vouchdt` >= '$mfrmdate'  AND  a.`vouchdt` <= '$mtodate' $itemcond1 $itemgrpcond1 and 
//                                    a.vouchno in (Select vouchno from $maindb where canc_flag != 'C' and `vouchdt` >= '$mfrmdate'  
//                                                   AND  `vouchdt` <= '$mtodate')
//                             union all                          
//                             SELECT a.`itemcode`, b.name as itemname, a.qty, a.rate, a.cost, (a.qty * (a.rate - a.cost)) as pl 
//                                    FROM $trandb2 a, product b WHERE a.`itemcode` = b.`code` and  
//                                    a.`vouchdt` >= '$mfrmdate'  AND  a.`vouchdt` <= '$mtodate' $itemcond1 $itemgrpcond1 and 
//                                    a.vouchno in (Select vouchno from $maindb2 where canc_flag != 'C' and `vouchdt` >= '$mfrmdate'  
//                                                   AND  `vouchdt` <= '$mtodate')" ) or die(mysqli_error($conn));
mysqli_query($conn, "drop temporary table if exists itempl ") or die(mysqli_error($conn));
mysqli_query($conn, "create temporary table itempl 
                            SELECT a.`itemcode`, b.name as itemname, a.qty, a.rate, a.cost, (a.qty * (a.rate - a.cost)) as pl 
                                   FROM $trandb a, product b WHERE a.`itemcode` = b.`code` and  
                                   a.`vouchdt` >= '$mfrmdate'  AND  a.`vouchdt` <= '$mtodate' $itemcond1 and 
                                   a.vouchno in (Select vouchno from $maindb where `vouchdt` >= '$mfrmdate'  
                                                  AND  `vouchdt` <= '$mtodate')") or die(mysqli_error($conn));

$getpmain = mysqli_query($conn, "SELECT itemcode, itemname, sum(qty) as tqty, sum(pl) as tpl from itempl group by itemcode order by itemname") or die(mysqli_error($conn));
//print table($getpmain);
//die();

if (isset($_POST["view"])) {
    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");
            ?>

            <?php
            if ($dtype == 1) {
                ?>
                <table style="width:70%" class="table table-bordered  table-hover table-striped ">

                    <thead class="mySearchTr">
                        <tr style=" background-color: #78909C;">
                            <th style="width:10%;">Sr.</th>
                            <th style="width:30%;">Item</th>
                            <th style="width:11%;" class='text-right'>Qty.</th>
                            <th style="width:15%;" class='text-right'>P/L Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $ctr = 0;
                        $plamt = 0;
                        $seltot = 0;
                        $purtot = 0;
                        $tqty = 0;
                        while ($rowm = mysqli_fetch_array($getpmain)) {
                            $itemcode = $rowm['itemcode'];
                            $itemname = $rowm['itemname'];

                            $tqty = $rowm['tqty'];
                            $plamt = $rowm['tpl'];

                            $ctr++;

                            echo "<tr>";
                            echo "<td>$ctr</td>";
                            echo "<td>$itemname</td>";
                            echo "<td class='text-right'>$tqty</td>";
                            echo "<td class='text-right'>$plamt</td>";
                            echo "</tr>";

                            $ttqty = $ttqty + $tqty;
                            $tplamt = $tplamt + $plamt;
                        }
                        echo "<tr>";
                        echo "<td></td>";
                        echo "<td class='text-right'><b  style='font-size:18px;color:green;text-align:right'>Total</b></td>";
                        echo "<td class='text-right'><b style='font-size:18px;color:green'>$ttqty</b></td>";
                        echo "<td class='text-right'><b style='font-size:18px;color:green'>$tplamt</b></td>";
                        echo "</tr>";
                        ?>
                    </tbody>
                </table>

                <?php
            } else {
                while ($rowm = mysqli_fetch_array($getpmain)) {
                    $itemcode = $rowm['itemcode'];
                    //                    $itrate = $rowm['cost'];
        
                    //  union all
                    //                 SELECT 'SLVT' as source, a.vouchdt, DATE_FORMAT(a.`vouchdt`,'%d-%m-%Y') as  mydt , a.`party`, a.`vouchno`,
                    //                 b.qty, b.rate, b.cost,b.rate,  b.`amount`, b.`itemcode`, 
                    //                 a.`grossamt`, a.`totdisc` FROM $maindb2 a, $trandb2 b  
                    //                 WHERE  b.itemcode = '$itemcode' and a.`vouchdt`>= '$mfrmdate'  
                    //                 AND  a.`vouchdt` <='$mtodate' AND a.`vouchno` = b.`vouchno` and a.canc_flag != 'C' 
        
                    $get = mysqli_query($conn, "SELECT 'SL' as source, 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.`grossamt`, a.`totdisc` FROM $maindb a, $trandb b  
                                    WHERE  b.itemcode = '$itemcode' and a.`vouchdt`>= '$mfrmdate'  
                                    AND  a.`vouchdt` <='$mtodate' AND a.`vouchno` = b.`vouchno`  ") or die(mysqli_error($conn));
                    $getno = mysqli_num_rows($get);
                    //                    print table($get);
                    //                    die();
        
                    if ($getno > 0) {
                        ?>

                        <table class="table table-bordered">
                            <tr class="mySearchTr">
                                <td style="color: white;width:70%"><b>Product : <?php echo $rowm['itemname']; ?></b></td>
                                <td style="color: white;width:30%" class="text-right"><b>Stock Unit : </b></td>
                            </tr>
                        </table>

                        <table style="" class="table table-bordered  table-hover table-striped ">

                            <thead class="mySearchTr">
                                <tr style=" background-color: #7E827E;">
                                    <th style="width:5%;">Sr.</th>
                                    <th style="width:10%;">Date</th>
                                    <th style="width:21%;">Customer</th>
                                    <th style="width:5%;">Source</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;

                                $dperc = 0;
                                while ($row = mysqli_fetch_array($get)) {
                                    $dis = $row['totdisc'];
                                    $dperc = ($dis * 100) / $row['grossamt'];
                                    
                                    $sldate = $row['vouchdt'];
                                    
                                    $srate = $row['rate'];
                                    // browse($row['cost']);
                                    $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 `cost` FROM `purtran` WHERE `itemcode`='$row[itemcode]' and cost > 0 and vouchdt <= '$sldate'") or die(mysqli_error($conn));
                                    $chkpurrate = mysqli_num_rows($getpur);
                                    $itrate = $getpur['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 `itemcode`='$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 = $row['qty'] * $diff;
                                    } else {
                                        $actpurrate = 0;
                                        $diff = 0;
                                        $pl = 0;
                                    }


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

                                    echo "<tr> ";
                                    echo "<td>$ctr</td>";
                                    echo "<td>$row[mydt]</td>";
                                    echo "<td>$sparty[name]</td>";
                                    echo "<td>$row[source]</td>";
                                    echo "<td>$row[vouchno]</td>";
                                    echo "<td class='text-right'>$row[qty]</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 + $row['qty'];
                                    $tpl = $tpl + $pl;
                                }
                                echo "<tr> ";
                                echo "<td  ></td>";
                                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  ></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;
                    }
                }
                echo "<tr style='background-color:#98f9f0'> ";
                echo "<td  ></td>";
                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>
                <?php
            }
            ?>

        </div>

        <?php
        include("includes/linksfoot.php");
        ?>
    </body>

    </html>
    <?php
}


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

    if ($dtype == 1) {

        $contents .= "Sr., Item, Qty., P/L Amount \n";

        $ctr = 0;
        $plamt = 0;
        $seltot = 0;
        $purtot = 0;
        $tqty = 0;
        while ($rowm = mysqli_fetch_array($getpmain)) {
            $itemcode = $rowm['itemcode'];
            $itemname = $rowm['itemname'];

            $tqty = $rowm['tqty'];
            $plamt = $rowm['tpl'];

            $ctr++;

            $contents .= "$ctr" . ",";
            $contents .= "$itemname" . ",";
            $contents .= "$tqty" . ",";
            $contents .= "$plamt" . "\n";

            $ttqty = $ttqty + $tqty;
            $tplamt = $tplamt + $plamt;
        }
        $contents .= "" . ",";
        $contents .= "Total" . ",";
        $contents .= "$ttqty" . ",";
        $contents .= "$tplamt" . ",";
        ?>

        <?php
    } else {
        while ($rowm = mysqli_fetch_array($getpmain)) {
            $itemcode = $rowm['itemcode'];

            $get = mysqli_query($conn, "SELECT 'SL  ' as source, a.vouchdt, DATE_FORMAT(a.`vouchdt`,'%d-%m-%Y') as  mydt , a.`party`, a.`vouchno`,
                                    b.qty, b.rate, b.cost,b.rate,  b.`amount`, b.`itemcode`, 
                                    a.`grossamt`, a.`totdisc` FROM $maindb a, $trandb b  
                                    WHERE  b.itemcode = '$itemcode' and a.`vouchdt`>= '$mfrmdate'  
                                    AND  a.`vouchdt` <='$mtodate' AND a.`vouchno` = b.`vouchno` and a.canc_flag != 'C' 
                                    union all
                                    SELECT 'SLVT' as source, a.vouchdt, DATE_FORMAT(a.`vouchdt`,'%d-%m-%Y') as  mydt , a.`party`, a.`vouchno`,
                                    b.qty, b.rate, b.cost,b.rate,  b.`amount`, b.`itemcode`, 
                                    a.`grossamt`, a.`totdisc` FROM $maindb2 a, $trandb2 b  
                                    WHERE  b.itemcode = '$itemcode' and a.`vouchdt`>= '$mfrmdate'  
                                    AND  a.`vouchdt` <='$mtodate' AND a.`vouchno` = b.`vouchno` and a.canc_flag != 'C' ") or die(mysqli_error($conn));
            $getno = mysqli_num_rows($get);

            if ($getno > 0) {

                $contents .= "Item - $rowm[itemname] \n";

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

                $ctr = 0;
                $tqty = 0;
                $tpl = 0;
                $totamt = 0;

                $dperc = 0;
                while ($row = mysqli_fetch_array($get)) {
                    $dis = $row['totdisc'];
                    $dperc = ($dis * 100) / $row['grossamt'];

                    $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 `cost` FROM `purtran` WHERE `itemcode`='$row[itemcode]' and cost > 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 `itemcode`='$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 = $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[source]" . ",";
                    $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 .= "" . ",";
                $contents .= "Total" . ",";
                $contents .= "$tqty" . ",";
                $contents .= "" . ",";
                $contents .= "" . ",";
                $contents .= "" . ",";
                $contents .= "$tpl" . "\n";

                $gtqty = $gtqty + $tqty;
                $gtrate = $gtrate + $tpl;
                $gtott = $gtott + $totamt;
            }
        }

        $contents .= "" . ",";
        $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;
    }
}
?>