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

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

$olddb = $zroot1 . $compcd . '_' . $prevyear;

//browse($olddb);

if (isset($_POST["view"])) {
    $name = $_POST[name];
    $dtype = $_POST[rtype];
    $itemgrp = $_POST[itemgrp];



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


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


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


//    if ($dtype == 1) {
//        $getpmain = mysqli_query($conn, "SELECT a.item,sum(qty) as sqty, a.rate 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));
////        $getpmain = mysqli_query($conn, "SELECT a.*, b.*, (b.qty * b.rate) as pl  FROM $maindb a, $trandb b  where a.vouchno = b.vouchno and
////        $getpmain = mysqli_query($conn, "SELECT a.*, b.*  FROM $maindb a, $trandb b  where a.vouchno = b.vouchno and
////            a.vouchdt >= '$mfrmdate' and a.vouchdt<= '$mtodate' and b.item in (select code from item $itemgrpcond ) $itemcond group by b.item  order by b.item")or die(mysqli_error($conn));
//    }
//    else {
    $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.code") 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);
    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
            while ($rowm = mysqli_fetch_array($getpmain)) {
                $itemcode = $rowm[item];

                $itrate = $rowm[cost];

                $get = mysqli_query($conn, "SELECT 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) {
                    ?>
                    <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;

                            while ($row = mysqli_fetch_array($get)) {
                                $dperc =0;
                                $dis = $row[lesother] + $row[cdiscamt];
                                $dperc = ($dis * 100) / $row[subtotal]; 
                                
                                $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'")or die(mysqli_error($conn));
                                $chkpurrate = mysqli_num_rows($getpur);

//                                    browse($chkpurrate);

                                if ($chkpurrate > 0) {
//                                        browse('idhar');
                                    $purrate = 0;

                                    $numshowrate = mysqli_num_rows($getpur);
                                    while ($showpur = mysqli_fetch_array($getpur)) {
                                        $purrate = $purrate + $showpur[rate];
                                    }
                                    $tpurrate = $purrate;
                                } else {
                                    $purrate = 0;
//browse('yaha');
                                    $getpurold = mysqli_query($conn, "SELECT `rate` FROM $olddb.`purtran` WHERE `itemcode`='$row[item]'")or die(mysqli_error($conn));
                                    $numshowrate = mysqli_num_rows($getpurold);
//                                        browse($numshowrate);
                                    while ($showpurold = mysqli_fetch_array($getpurold)) {
                                        $purrate = $purrate + $showpurold[rate];
                                    }
                                    $tpurrate = $purrate;
                                }
                                $avgpurrate = round($tpurrate / $numshowrate, 2);


                                if ($avgpurrate != "") {
                                    $actpurrate = $avgpurrate;
                                    
                                    $mnrate = $row[rate] - (($row[rate] * $dperc)/100);
                                  
                                } else {
                                    $actpurrate = 0;
                                    $mnrate = 0;
                                }

                                if ($purrate > 0) {
                                    $actrate = $mnrate - $actpurrate;
                                    $pl = $row[qty] * $actrate;
                                } else {
                                    $actrate = $mnrate - $actpurrate;
                                    $pl = $row[qty] * $actrate;
                                }


                                $ctr++;
                                $mnrateround  = round($mnrate);
                                $actrateround = round($actrate);
                                $plround = round($pl);
                                
                                echo "<tr> ";
                                echo "<td>$ctr</td>";
                                echo "<td>$row[mydt]</td>";
                                echo "<td>$sparty[name]</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'>$avgpurrate</td>";
                                echo "<td class='text-right'>$actrateround</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 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>$tpl</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>$gtrate</b></td>";
                    echo "</tr>";
                    ?> 
                </tbody>

            </table>

        </div>

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