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

$admin = $_SESSION["admin_" . $dbname];
$zdb = $_SESSION["zdbyear_" . $dbname];
$myyear = $_SESSION[$myyear];
mysqli_select_db($conn, $zdb);

$maindb = 'salemain';
$trandb = 'saletran';
$zroot = $_SESSION["zdbroot"];

$file = 'prodwisesale_fr.php';

$prodgrp = $_POST["prodgrp"];
$product = $_POST["product"];
$prodlike = $_POST["prodlike"];
$ol = $_POST["ol"];
$dtype = $_POST["dtype"];
$repby = $_POST["repby"];

if ($repby == 2) {
    $report_type = "Amt.";
} else {
    $report_type = "Qty.";
}

$formname = "Product Sale Register (" . $report_type . ")";
$pgrpcond = '';
$prodcond = '';
$prodlikecond = '';
$prodcond2s = '';
if (!empty($prodgrp)) {
    $pgrpcond = " AND `prodgrp` = '$prodgrp' ";
}

if (!empty($product)) {
    $prodcond = " AND `itemcode` = '$product' ";
    $prodcond2 = " AND `code` = '$product' ";
}
if (!empty($prodlike)) {
    $prodlikecond = " AND `name` LIKE '%$prodlike%' ";
}
if (empty($_POST["frmdt"])) {
    browse("From Date Cannot Be Empty");
    header("refresh:1; prodwisesale.php");
}
if (empty($_POST["todt"])) {
    browse("To Date Cannot Be Empty");
    header("refresh:1; prodwisesale.php");
}

$mfrmdate = trim($_POST["frmdt"]);
$mtodate = trim($_POST["todt"]);

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

//if($repby == 2) {
//    $mainqry = mysqli_query($conn, "SELECT itemcode, gram, unit, barcode, vouchdt, vouchno, source, netamt,
//                            DATE_FORMAT(`vouchdt`, '%d-%m-%Y') as mydt FROM `transacn` WHERE `vouchdt` >= '$mfrmdate' 
//                            AND `vouchdt` <= '$mtodate' $prodcond and (`source` = 'SL' or source = 'SR' or source = 'SLDE' or source = 'SLEX') 
//                            and itemcode in (SELECT prodcode from product where prodcode != '' $pgrpcond $prodcond2 $olcond $prodlikecond) group by barcode")or die(mysqli_error($conn));
//}else{

$mainqry = mysqli_query($conn, "SELECT itemcode, barcode, vouchdt, vouchno, source, 
                            DATE_FORMAT(`vouchdt`, '%d-%m-%Y') as mydt FROM `transacn` WHERE `vouchdt` >= '$mfrmdate' 
                            AND `vouchdt` <= '$mtodate' $prodcond and (`source` = 'SL' or source = 'SR' or source = 'SLVT')
                            and itemcode in (SELECT code from product where code != '' $pgrpcond $prodcond2 $prodlikecond) group by itemcode") or die(mysqli_error($conn));
//}
$getno = mysqli_num_rows($mainqry);

if (isset($_POST["view"])) {
    include("includes/linkshead.php");
?>
    <style type="text/css">
        #tabital {
            font-style: italic;
        }

        #font1 {
            font-style: italic;
        }

        #boldfont {
            font-weight: bold;
        }

        th {
            background: #26A69A;
        }

        .dth {
            background: #BABFC2;
        }

        .colr {
            background: #26A69A;
            font-size: 17px;
        }

        table tr td {
            font-size: 14px;
        }

        total {
            font-size: 16px;

        }
    </style>
    </head>

    <body>


        <div class="container" style="width:90%">
            <?php include("includes/head_rep.php"); ?>
            <div class="row">
                <div class="col-lg-12">

                    <table style="background: white;width: 100%" class="table table-condensed table-striped table-bordered">
                        <thead class="mySearchTr">
                            <tr>
                                <th width='5%'>Sr</th>
                                <th width='40%'>Product Name</th>
                                <? if ($repby == 2) { ?>
                                    <th width='7%' class="text-right">Total Sale Amt.</th>
                                    <th width='7%' class="text-right">Total Return Amt.</th>
                                    <th width='7%' class="text-right">Net Amt.</th>
                                <? } else {
                                ?>
                                    <th width='7%' class="text-right">Total Sale Qty.</th>
                                    <th width='7%' class="text-right">Return</th>
                                    <th width='7%' class="text-right">Net Qty.</th>
                                <? } ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $ctr = 0;
                            $grtotsalqty = $grtotretqty = $grtotqty = 0;
                            $grtotlocamt = $grtotdeeamt = $grtotexpamt = $grtotalamt = $grtotretamt = $grtotnetamt = 0;

                            while ($fmain = mysqli_fetch_array($mainqry)) {

                                // mysqli_query($conn, "drop temporary table if exists itempl ") or die(mysqli_error($conn));
                                // mysqli_query($conn, "create temporary table itempl 
                                //                                SELECT `barcode`,SUM(qty) AS qty, rate, SUM(amount) AS totalamt FROM `saletran` where 
                                //                         `itemcode` = '$fmain[itemcode]'  and `vouchdt` >= '$mfrmdate' 
                                //                          AND `vouchdt` <= '$mtodate' and 
                                //                          vouchno in (select vouchno from salemain where `vouchdt` >= '$mfrmdate' 
                                //                          AND `vouchdt` <= '$mtodate' and canc_flag != 'C')
                                //                          UNION ALL    
                                //                          SELECT `barcode`,SUM(qty) AS qty, rate, SUM(amount) AS totalamt FROM `vattran` where 
                                //                         `itemcode` = '$fmain[itemcode]'  and `vouchdt` >= '$mfrmdate' 
                                //                          AND `vouchdt` <= '$mtodate' and 
                                //                          vouchno in (select vouchno from vatmain where `vouchdt` >= '$mfrmdate' 
                                //                          AND `vouchdt` <= '$mtodate' and canc_flag != 'C')") or die(mysqli_error($conn));

                                // $gsalqty = mysqli_query($conn, "SELECT `barcode`,SUM(qty) AS qty, rate, SUM(totalamt) AS totalamt FROM `itempl` group by barcode order by barcode ") or die(mysqli_error($conn));
                                $gsalqty = mysqli_query($conn, "SELECT `barcode`,SUM(qty) AS qty, SUM(amount) AS totalamt  FROM `saletran` where 
                                                                        `itemcode` = '$fmain[itemcode]' and `vouchdt` >= '$mfrmdate' AND `vouchdt` <= '$mtodate'") or die(mysqli_error($conn));

                                $fsalqty = mysqli_fetch_array($gsalqty);
                                $locqty = abs($fsalqty['qty']);

                                $locamt = $fsalqty['totalamt'];

                                //                                $gonlsalqty = mysqli_query($conn, "SELECT `barcode`,SUM(qty) AS qty, SUM(subtot) AS totalamt FROM `slonltran` where 
                                //                                                        `barcode` = '$fmain[barcode]'  and `vouchdt` >= '$mfrmdate' 
                                //                                                         AND `vouchdt` <= '$mtodate' and 
                                //                                                         vouchno in (select vouchno from slonlmain where `vouchdt` >= '$mfrmdate' 
                                //                                                         AND `vouchdt` <= '$mtodate' and canc_flag != 'C')") or die(mysqli_error($conn));
                                //                                $fonlsalqty = mysqli_fetch_array($gonlsalqty);
                                //                                $onlqty = abs($fonlsalqty['qty']);
                                //                                $onlamt = $fonlsalqty['totalamt'];


                                $gretnqty = mysqli_query($conn, "SELECT `barcode`,SUM(qty) AS qty, SUM(subtot) AS totalamt  FROM `credtran` where 
                                                         `itemcode` = '$fmain[itemcode]' and `vouchdt` >= '$mfrmdate' AND `vouchdt` <= '$mtodate'") or die(mysqli_error($conn));
                                $retnqty = mysqli_fetch_array($gretnqty);
                                $retqty = $retnqty['qty'];
                                $retamt = $retnqty['totalamt'];

                                $getitemname = mysqli_query($conn, "SELECT name from product where code = '$fmain[itemcode]' ") or die(mysqli_error($conn));
                                $fitem = mysqli_fetch_array($getitemname);
                                $itemname = $fitem['name'];

                                if ($retnqty['qty'] != '') {
                                    $retqty = $retnqty['qty'];
                                } else {
                                    $retqty = 0;
                                }
                                $salqty = $locqty + $deemqty + $expqty + $onlqty;
                                $totqty = $salqty - $retqty;
                                $totalamt = $locamt + $deemamt + $expamt + $onlamt;
                                $netamt = $totalamt - $retamt;
                                $ctr++;

                                echo "<tr>";
                                echo "<td>$ctr</td>";
                                echo "<td>$itemname</td>";
                                if ($repby == 2) {
                                    echo "<td class='text-right'>$totalamt</td>";
                                    echo "<td class='text-right'>$retamt</td>";
                                    echo "<td class='text-right'>$netamt</td>";

                                    $grtotlocamt = $grtotlocamt + $locamt;
                                    $grtotalamt = $grtotalamt + $totalamt;
                                    $grtotretamt = $grtotretamt + $retamt;
                                    $grtotnetamt = $grtotnetamt + $netamt;
                                } else {

                                    echo "<td class='text-right'>$salqty</td>";
                                    echo "<td class='text-right'>$retqty</td>";
                                    echo "<td class='text-right'>$totqty</td>";

                                    $grtotsalqty = $grtotsalqty + $salqty;
                                    $grtotretqty = $grtotretqty + $retqty;
                                    $grtotloc = $grtotloc + $locqty;
                                    $grtotonl = $grtotonl + $onlqty;
                                    $grtotqty = $grtotqty + $totqty;
                                }
                                echo "</tr>";


                                if ($_POST["dtype"] == 2) {

                                    echo "<tr style='height:10px;'>";
                                    echo "<td colspan='25'>";
                                    echo "<table style='width:100%;' id='tabital' class='table table-condensed table-hover table-bordered'>";
                                    echo "<thead>";
                                    echo "<tr class='mySearchTr2'>";
                                    echo "<th width='7%'  class='dth'>Sr</th>";
                                    echo "<th width='10%'  class='dth'>Date</th>";
                                    echo "<th width='10%'  class='dth'>Source</th>";
                                    echo "<th width='10%'  class='dth'>Voucher</th>";
                                    echo "<th width='33%'  class='dth'>Party Name</th>";
                                    echo "<th width='10%'  class='text-right dth'>Qty.</th>";
                                    echo "<th width='10%'  class='text-right dth'>Rate</th>";
                                    echo "<th width='10%'  class='text-right dth'>Amt.</th>";
                                    echo "</tr>";

                                    $ctr2 = 0;
                                    $totqty = 0;
                                    $slqty = 0;
                                    $totamt = 0;

                                    $gettran = mysqli_query($conn, "SELECT `vouchno`, `source`, DATE_FORMAT(`vouchdt`, '%d-%m-%Y') as `mydt`, `accode`, qty, 
                                                            `rate` FROM `transacn` WHERE `vouchdt` >= '$mfrmdate' AND `vouchdt` <= '$mtodate'
                                                             AND `itemcode`='$fmain[itemcode]' and (`source` = 'SL' or `source` = 'SLVT' ) ") or die(mysqli_error($conn));
                                    while ($tran = mysqli_fetch_array($gettran)) {
                                        $qty = abs($tran['qty']);

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

                                        $amt = $qty * $tran['rate'];

                                        $ctr2++;
                                        echo "<tr>";
                                        echo "<td>$ctr2</td>";
                                        echo "<td>$tran[mydt]</td>";
                                        echo "<td>$tran[source]</td>";
                                        echo "<td>$tran[vouchno]</td>";
                                        echo "<td>$customer[name]</td>";
                                        echo "<td class='text-right'>$qty</td>";
                                        echo "<td class='text-right'>$tran[rate]</td>";
                                        echo "<td class='text-right'>$amt</td>";
                                        echo "</tr>";

                                        $slqty = $slqty + $qty;
                                        $totqty = $totqty + $qty;
                                        $totamt = $totamt + $amt;
                                    }

                                    $getcred = mysqli_query($conn, "SELECT `vouchno`, `source`, DATE_FORMAT(`vouchdt`, '%d-%m-%Y') as `mydt`, `accode`, qty, 
                                                                           `rate`  FROM `transacn` WHERE `itemcode`='$fmain[itemcode]' and `source`='SR' ") or die(mysqli_error($conn));
                                    $credtranno = mysqli_num_rows($getcred);

                                    if ($credtranno > 0) {
                                        $ctr3 = 0;
                                        $credqty = 0;
                                        while ($cred = mysqli_fetch_array($getcred)) {

                                            $cdqty = abs($cred['qty']);

                                            $gcust = mysqli_query($conn, "SELECT `accode`,`name` FROM `accmast` WHERE `accode`='$cred[accode]'") or die(mysqli_error($conn));
                                            $custm = mysqli_fetch_array($gcust);

                                            $amount = $qty * $cred['rate'];

                                            $ctr3++;
                                            echo "<tr style='background-color:black'>";
                                            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 "</tr>";

                                            echo "<tr>";
                                            echo "<td>$ctr3</td>";
                                            echo "<td>$cred[mydt]</td>";
                                            echo "<td>$cred[source]</td>";
                                            echo "<td>$cred[vouchno]</td>";
                                            echo "<td>$custm[name]</td>";
                                            echo "<td class='text-right'>$cdqty</td>";
                                            echo "<td class='text-right'>$cred[rate]</td>";
                                            echo "<td class='text-right'>$amount</td>";
                                            echo "</tr>";

                                            $credqty = $credqty + $cdqty;
                                        }
                                        $totqty = $slqty - $credqty;
                                    }

                                    echo "<tr>";
                                    echo "<td class='dth'></td>";
                                    echo "<td class='dth'></td>";
                                    echo "<td class='dth'></td>";
                                    echo "<td class='dth'></td>";
                                    echo "<td class='text-right dth'>Total</td>";
                                    echo "<td class='text-right dth'>$totqty</td>";
                                    echo "<td class='text-right dth'></td>";
                                    echo "<td class='text-right dth'>$totamt</td>";
                                    echo "</tr>";
                                    echo "</table>";
                                }
                            }
                            if ($repby == 2) {
                                echo "<tr style='color: blue; font-size: 14px;'>";
                                echo "<td ></td>";
                                echo "<td class='text-right '><b>Total</b></td>";
                                echo "<td class='numeric text-right'><b>$grtotlocamt</b></td>";
                                echo "<td class='numeric text-right'><b>$grtotalamt</b></td>";
                                echo "<td class='numeric text-right'><b>$grtotretamt</b></td>";
                                echo "<td class='numeric text-right'><b>$grtotnetamt</b></td>";
                                echo "</tr>";

                                $mtotlocamt = $grtotlocamt;
                                $mtotonlamt = $grtotonlamt;
                                $mtotalamt = $grtotalamt;
                                $mtotretamt = $grtotretamt;
                                $mtotnetamt = $grtotnetamt;

                                echo "<tr style='background-color: #98F9F0; color: red'>";
                                echo "<td class='text-right' colspan='2'><b>Grand Total</b></td>";
                                echo "<td class='numeric text-right'><b>$mtotalamt</b></td>";
                                echo "<td class='numeric text-right'><b>$mtotretamt</b></td>";
                                echo "<td class='numeric text-right'><b>$mtotnetamt</b></td>";
                                echo "</tr>";
                            } else {
                                echo "<tr>";
                                echo "<td class='colr'></td>";
                                echo "<td class='text-right colr'><b>Total</b></td>";
                                echo "<td class='numeric text-right colr'><b>$grtotsalqty</b></td>";
                                echo "<td class='numeric text-right colr'><b>$grtotretqty</b></td>";
                                echo "<td class='numeric text-right colr'><b>$grtotqty</b></td>";
                                echo "</tr>";
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php include("includes/linksfoot.php");
        ?>
    </body>

    </html>
<?php
}

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

    $contents .= "Sr, Product Name,";
    if ($repby == 2) {
        $contents .= "Total Sale Amt., Total Retuen Amt., Net Amt \n";
    } else {
        $contents .= "Total Sale Qty., Return, Net Qty. \n";
    }

    $ctr = 0;
    $grtotsalqty = $grtotretqty = $grtotqty = 0;
    $grtotlocamt = $grtotdeeamt = $grtotexpamt = $grtotalamt = $grtotretamt = $grtotnetamt = 0;

    while ($fmain = mysqli_fetch_array($mainqry)) {

        $gsalqty = mysqli_query($conn, "SELECT `barcode`,SUM(qty) AS qty, SUM(amount) AS totalamt  FROM `saletran` where 
                                                                        `itemcode` = '$fmain[itemcode]' and `vouchdt` >= '$mfrmdate' AND `vouchdt` <= '$mtodate'") or die(mysqli_error($conn));

        $fsalqty = mysqli_fetch_array($gsalqty);
        $locqty = abs($fsalqty['qty']);

        $locamt = $fsalqty['totalamt'];

        $gretnqty = mysqli_query($conn, "SELECT `barcode`,SUM(qty) AS qty, SUM(subtot) AS totalamt  FROM `credtran` where 
                                                         `itemcode` = '$fmain[itemcode]' and `vouchdt` >= '$mfrmdate' AND `vouchdt` <= '$mtodate'") or die(mysqli_error($conn));
        $retnqty = mysqli_fetch_array($gretnqty);
        $retqty = $retnqty['qty'];
        $retamt = $retnqty['totalamt'];

        $getitemname = mysqli_query($conn, "SELECT name from product where code = '$fmain[itemcode]' ") or die(mysqli_error($conn));
        $fitem = mysqli_fetch_array($getitemname);
        $itemname = $fitem['name'];

        if ($retnqty['qty'] != '') {
            $retqty = $retnqty['qty'];
        } else {
            $retqty = 0;
        }
        $salqty = $locqty + $deemqty + $expqty + $onlqty;
        $totqty = $salqty - $retqty;
        $totalamt = $locamt + $deemamt + $expamt + $onlamt;
        $netamt = $totalamt - $retamt;
        $ctr++;

        $contents .= "$ctr" . ",";
        $contents .= "$itemname" . ",";
        if ($repby == 2) {
            $contents .= "$totalamt" . ",";
            $contents .= "$retamt" . ",";
            $contents .= "$netamt" . "\n";

            $grtotlocamt = $grtotlocamt + $locamt;
            $grtotalamt = $grtotalamt + $totalamt;
            $grtotretamt = $grtotretamt + $retamt;
            $grtotnetamt = $grtotnetamt + $netamt;
        } else {

            $contents .= "$salqty" . ",";
            $contents .= "$retqty" . ",";
            $contents .= "$totqty" . "\n";

            $grtotsalqty = $grtotsalqty + $salqty;
            $grtotretqty = $grtotretqty + $retqty;
            $grtotloc = $grtotloc + $locqty;
            $grtotonl = $grtotonl + $onlqty;
            $grtotqty = $grtotqty + $totqty;
        }

        if ($_POST["dtype"] == 2) {

            $contents .= "Sr, Date, Source, Voucher, Party Name, Qty., Rate, Amt. \n";

            $ctr2 = 0;
            $totqty = 0;
            $slqty = 0;
            $totamt = 0;

            $gettran = mysqli_query($conn, "SELECT `vouchno`, `source`, DATE_FORMAT(`vouchdt`, '%d-%m-%Y') as `mydt`, `accode`, qty, 
                                                            `rate` FROM `transacn` WHERE `vouchdt` >= '$mfrmdate' AND `vouchdt` <= '$mtodate'
                                                             AND `itemcode`='$fmain[itemcode]' and (`source` = 'SL' or `source` = 'SLVT' ) ") or die(mysqli_error($conn));
            while ($tran = mysqli_fetch_array($gettran)) {
                $qty = abs($tran['qty']);

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

                $amt = $qty * $tran['rate'];

                $ctr2++;
                $contents .= "$ctr2" . ",";
                $contents .= "$tran[mydt]" . ",";
                $contents .= "$tran[source]" . ",";
                $contents .= "$tran[vouchno]" . ",";
                $contents .= "$customer[name]" . ",";
                $contents .= "$qty" . ",";
                $contents .= "$tran[rate]" . ",";
                $contents .= "$amt" . "\n";

                $slqty = $slqty + $qty;
                $totqty = $totqty + $qty;
                $totamt = $totamt + $amt;
            }

            $getcred = mysqli_query($conn, "SELECT `vouchno`, `source`, DATE_FORMAT(`vouchdt`, '%d-%m-%Y') as `mydt`, `accode`, qty, 
                                                                           `rate`  FROM `transacn` WHERE `itemcode`='$fmain[itemcode]' and `source`='SR' ") or die(mysqli_error($conn));
            $credtranno = mysqli_num_rows($getcred);

            if ($credtranno > 0) {
                $ctr3 = 0;
                $credqty = 0;
                while ($cred = mysqli_fetch_array($getcred)) {

                    $cdqty = abs($cred['qty']);

                    $gcust = mysqli_query($conn, "SELECT `accode`,`name` FROM `accmast` WHERE `accode`='$cred[accode]'") or die(mysqli_error($conn));
                    $custm = mysqli_fetch_array($gcust);

                    $amount = $qty * $cred['rate'];

                    $ctr3++;
                    $contents .= "" . ",";
                    $contents .= "" . ",";
                    $contents .= "" . ",";
                    $contents .= "" . ",";
                    $contents .= "" . ",";
                    $contents .= "" . ",";
                    $contents .= "" . ",";
                    $contents .= "" . "\n";

                    $contents .= "$ctr3" . ",";
                    $contents .= "$cred[mydt]" . ",";
                    $contents .= "$cred[source]" . ",";
                    $contents .= "$cred[vouchno]" . ",";
                    $contents .= "$custm[name]" . ",";
                    $contents .= "$cdqty" . ",";
                    $contents .= "$cred[rate]" . ",";
                    $contents .= "$amount" . "\n";

                    $credqty = $credqty + $cdqty;
                }
                $totqty = $slqty - $credqty;
            }

            $contents .= "" . ",";
            $contents .= "" . ",";
            $contents .= "" . ",";
            $contents .= "" . ",";
            $contents .= "Total" . ",";
            $contents .= "$totqty" . ",";
            $contents .= "" . ",";
            $contents .= "$totamt" . "\n";
        }
    }
    if ($repby == 2) {
        $contents .= "" . ",";
        $contents .= "Total" . ",";
        $contents .= "$grtotlocamt" . ",";
        $contents .= "$grtotalamt" . ",";
        $contents .= "$grtotretamt" . ",";
        $contents .= "$grtotnetamt" . "\n";

        $mtotlocamt = $grtotlocamt;
        $mtotonlamt = $grtotonlamt;
        $mtotalamt = $grtotalamt;
        $mtotretamt = $grtotretamt;
        $mtotnetamt = $grtotnetamt;

        $contents .= "Grand Total" . ",";
        $contents .= "$mtotalamt" . ",";
        $contents .= "$mtotretamt" . ",";
        $contents .= "$mtotnetamt" . "\n";
    } else {
        $contents .= "" . ",";
        $contents .= "Total" . ",";
        $contents .= "$grtotsalqty" . ",";
        $contents .= "$grtotretqty" . ",";
        $contents .= "$grtotqty" . "\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;
    }
}
?>