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

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

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

$namecond = '';

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

if (!empty($name)) {
    $itemcond = " AND b.itemname = '$name' ";
    $itemcond1 = " AND a.itemname = '$name' ";
    $itemcond2 = " AND `itemname` ='$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'];


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

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.itemcode 
                                    FROM $maindb a, $trandb b  WHERE  a.`vouchdt`>= '$mfrmdate'  AND  a.`vouchdt` <='$mtodate' 
                                    AND a.`vouchno` = b.`vouchno` $itemcond 
                             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
                                    FROM `credmain` a, `credtran` b  WHERE a.`vouchdt`>= '$mfrmdate' AND  a.`vouchdt` <='$mtodate' 
                                    AND a.`vouchno` = b.`vouchno` $itemcond ") or die(mysqli_error($conn));

$getpmain = mysqli_query($conn, "SELECT * FROM `itdata` order by vouchdt, type, vouchno ") or die(mysqli_error($conn));

mysqli_query($conn, "drop temporary table if exists costdata") or die(mysqli_error($conn));
mysqli_query($conn, "create temporary table costdata 
                            SELECT salevouch, itemname, size, purcost, sum(recdqty) as recdqty 
                                   FROM salepurch WHERE `billdate` >= '$mfrmdate'  $itemcond2  group by salevouch, itemname, size ") or die(mysqli_error($conn));

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"); ?>
            <table class="table table-bordered">
                <thead class="mySearchTr">
                    <tr style=" background-color: #78909C;">
                        <th style="width:3%;">Sr.</th>
                        <th style="width:8%;">Date</th>
                        <th style="width:8%;">Voucher</th>
                        <th style="width:20%;">Customer</th>
                        <th style="width:10%;">Item</th>
                        <th style="width:9%;">Size</th>
                        <th style="width:7%;" class='text-right'>Rate</th>
                        <th style="width:7%;" class='text-right'>Cost</th>
                        <th style="width:9%;" class='text-right'>P/L (Each)</th>
                        <th style="width:8%;" class='text-right'>Qty.</th>
                        <th style="width:9%;" class='text-right'>P/L Amount</th>
                    </tr>
                </thead>

                <?php
                $ctr = 0;
                $tqty = 0;
                $tpl = 0;

                while ($rowm = mysqli_fetch_array($getpmain)) {
                    $type = $rowm['type'];
                    $vouchno = $rowm['vouchno'];
                    $qty = $rowm['qty'];
                    $rate = $rowm['rate'];
                    $cost = $rowm['cost'];
                    $itemname = $rowm['itemname'];
                    $size = $rowm['size'];

                    $partyname = '';
                    $getparty = mysqli_query($conn, "SELECT `name` FROM `accmast` WHERE  `accode`='$rowm[customer]' ") or die(mysqli_error($conn));
                    $fetparty = mysqli_fetch_array($getparty);
                    $partyname = $fetparty['name'];

                    if ($type == 'S') {
                        $purcost = '';
                        $getcost = mysqli_query($conn, "SELECT `recdqty`, (`recdqty` * `purcost`) as costamt  FROM `costdata` 
                                                                WHERE `itemname`='$itemname' and size = '$size' and salevouch = '$vouchno' ") or die(mysqli_error($conn));
                        $fetcost = mysqli_fetch_array($getcost);
                        $puramt = $fetcost['costamt'];
                        $purqty = $fetcost['recdqty'];

                        $purcost1 = $puramt / $purqty;
                        $purcost = abs($purcost1, 0);
                    } else {
                        $purcost = $cost;
                    }

                    $pleach = $rate - $purcost;
                    $saleamt = $qty * $rate;
                    $puramt = $qty * $purcost;

                    $plamt = $saleamt - $puramt;


                    $ctr++;
                    echo "<tr>";
                    echo "<td>$ctr</td>";
                    echo "<td>$rowm[mydt]</td>";
                    echo "<td>$rowm[vouchno]</td>";
                    echo "<td>$partyname</td>";
                    echo "<td>$itemname</td>";
                    echo "<td>$size</td>";
                    echo "<td class='text-right'>" . number_format($rate, 2) . "</td>";
                    echo "<td class='text-right'>" . number_format($purcost, 2) . "</td>";
                    echo "<td class='text-right'>" . number_format($pleach, 2) . "</td>";
                    echo "<td class='text-right'>" . number_format($qty, 2) . "</td>";
                    echo "<td class='text-right'>" . number_format($plamt, 2) . "</td>";
                    echo "</tr>";

                    $tqty = $tqty + $qty;
                    $tpl = $tpl + $plamt;
                }
                echo "<tr> ";
                echo "<td  ></td>";
                echo "<td  ></td>";
                echo "<td  ></td>";
                echo "<td  ></td>";
                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 class='text-right' style=' color: #1ABC9C;' ><b>" . number_format($tpl, 2) . "</b></td>";
                echo "</tr>";
                ?> 
            </table>
        </div>
        <?php
        include("includes/linksfoot.php");
        ?>
    </body>
    </html>
    <?php
}


if (isset($_POST["excel"])) {
    $contents .= "Sr.,Date,Customer,Bill No.,Qty.,Rate,Avg. Cost,P/L (Each),P/L Amount\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;
    }
}
?>