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

$maindb = "rawmain";
$trandb = "rawtran";
// $formname = "Material Given to Karigar Register";
$formname = "Sale Register";
$file = "slmultigstreg.php";

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

$invno = $_POST["invno"];
$party = $_POST["party"];
$dtype = $_POST["dtype"];
$scope = $_POST["scope"];
$printnar = $_POST["prna"];

$dtypecond = "";
$mscopecond = "";
$itemcond = "";
$gstcond = "";
$prodtypecond = "";
$partycond = "";

$mfrmdate = trim($_POST["fdate"]);
$mtodate = trim($_POST["tdate"]);

if (!empty($party)) {
    $partycond = " AND `party`='$party' ";
}

if (!empty($dtype)) {
    $dtypecond = " AND `dtype`='$dtype' ";
}

if (!empty($scope)) {
    $mscopecond = " AND `type`='$scope' ";
}

if (empty($_POST["fdate"])) {
    browse("From Date Cannot Be Empty");
    header("refresh:1; slgstreg.php");
}
if (empty($_POST["tdate"])) {
    browse("To Date Cannot Be Empty");
    header("refresh:1; slgstreg.php");
}

$getpmain = mysqli_query($conn, "SELECT *,DATE_FORMAT(`vouchdt`, '%d-%m-%Y') as mydt FROM `$maindb` where
                           `vouchdt` >= '$mfrmdate' AND `vouchdt` <= '$mtodate' $partycond  ORDER BY vouchdt") or die(mysqli_error($conn));

$compno = $_SESSION["comp_" . $dbname];

$mfdt = date("d-m-Y", strtotime($mfrmdate));
$mtdt = date("d-m-Y", strtotime($mtodate));
if (isset($_POST["view"])) {
    include("includes/linkshead.php");
    ?>
    <style type="text/css">
        #tabital {
            font-style: italic;
        }

        #font1 {
            font-style: italic;
        }

        #boldfont {
            font-weight: bold;
        }

        .dtype {
            background-color: #cccccc;
        }
    </style>
    </head>

    <body>
        <div class="container">
            <?php include("includes/head_rep.php"); ?>

            <div class="row">
                <div class="col-lg-12 pad">
                    <table style="background: white;width: 100%" class="table table-striped table-condensed table-bordered table-hover">
                        <thead class="mySearchTr">
                            <tr>
                                <th width='5%'>Sr</th>
                                <th width='5%'>Invoice</th>
                                <th width='12%'>Date</th>
                                <?php if ($compno != '103') { ?>
                                    <th width='19%'>Broker</th>
                                <?php } ?>

                                <th width='19%'>Supplier</th>
                                <th width='8%'>GST No.</th>
                                <th width='5%' class="text-right">Amount</th>
                                <th width='5%' class="text-right">Discount</th>
                                <th width='5%' class="text-right">Taxable Value</th>
                                <th width='5%' class="text-right">GST 5%</th>
                                <th width='5%' class="text-right">GST 12%</th>
                                <th width='5%' class="text-right">GST 18%</th>
                                <th width='5%' class="text-right">GST 28%</th>
                                <th width='11%' class="text-right">Bill.Amt</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $ctr = 0;
                            $ttotamt = 0;
                            $totpack = 0;
                            $totbill = 0;
                            $totitmpr = 0;
                            $totdisc = 0;
                            $tottaxamt = 0;
                            $totcgst = 0;
                            $totsgst = 0;
                            $totigst = 0;
                            $ttotamount = 0;

                            $totbill = $tottaxamt = $ttotgst5 = $ttotgst12 = $ttotgst18 = $ttotgst28 = $ttotalamount = 0;

                            while ($pmain = mysqli_fetch_array($getpmain)) {

                                $getsupp = mysqli_query($conn, "SELECT `accode`,`name`,`gstno` FROM `accmast` WHERE `accode`='$pmain[party]'") or die(mysqli_error($conn));
                                $supp = mysqli_fetch_array($getsupp);

                                $getbroker = mysqli_query($conn, "SELECT `accode`,`name` FROM `accmast` WHERE `accode`='$pmain[broker]'") or die(mysqli_error($conn));
                                $broker = mysqli_fetch_array($getbroker);

                                $ctr++;
                                if ($pmain['canc_flag'] != 'C') {
                                    echo "<tr id='boldfont'>";
                                    echo "<td>$ctr</td>";
                                    echo "<td>$pmain[invno]</td>";
                                    echo "<td>$pmain[mydt]</td>";
                                    if ($compno != '103') {
                                        echo "<td>$broker[name]</td>";
                                    }
                                    echo "<td>$supp[name]</td>";
                                    echo "<td>$supp[gstno]</td>";
                                    echo "<td class='text-right'>$pmain[subtotal]</td>";
                                    echo "<td class='text-right'>$pmain[litemdisc]</td>";
                                    echo "<td class='text-right'>$pmain[tottaxamt]</td>";
                                    echo "<td class='text-right'>$pmain[totgst5]</td>";
                                    echo "<td class='text-right'>$pmain[totgst12]</td>";
                                    echo "<td class='text-right'>$pmain[totgst18]</td>";
                                    echo "<td class='text-right'>$pmain[totgst28]</td>";
                                    echo "<td class='text-right'>$pmain[netamt]</td>";
                                    echo "</tr>";
                                    $ttotamt += $pmain['subtotal'];
                                    $totitmpr += $pmain['litemdisc'];
                                    $totdisc += $pmain['discount'];
                                    $totpack += $pmain['couamt'];
                                    $tottaxamt += $pmain['tottaxamt'];
                                    $ttotgst5 += $pmain['totgst5'];
                                    $ttotgst12 += $pmain['totgst12'];
                                    $ttotgst18 += $pmain['totgst18'];
                                    $ttotgst28 += $pmain['totgst28'];
                                    $ttotamount += $pmain['netamt'];
                                } else {
                                    echo "<tr id='boldfont'>";
                                    echo "<td style='color:red'>$ctr</td>";
                                    echo "<td style='color:red'>$pmain[invno]</td>";
                                    echo "<td style='color:red'>$pmain[mydt]</td>";
                                    if ($compno != '103') {
                                        echo "<td>$broker[name]</td>";
                                    }
                                    echo "<td style='color:red;'>$supp[name]</td>";
                                    echo "<td colspan='3' class='text-center' style='color:red'>********* cancellled bill *********</td>";
                                    echo "</tr>";
                                }


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

                                    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 "<th width='3%;'class='dtype'>Sr</th>";
                                    Echo "<th width='8%' class='dtype'>Material</th>";
                                    Echo "<th width='6%' class='dtype'>Color</th>";
                                    Echo "<th width='6%' class='dtype'>HSN Code</th>";
                                    Echo "<th width='4%' class='numeric dtype'>Lot</th>";
                                    Echo "<th width='6%' class='numeric dtype'>Qty</th>";
                                    Echo "<th width='6%' class='numeric dtype'>Rate</th>";
                                    Echo "<th width='6%' class='numeric dtype'>Amount</th>";
                                    Echo "<th width='6%' class='numeric dtype'>Disc%</th>";
                                    Echo "<th width='6%' class='numeric dtype'>Disc. Amt.</th>";
                                    Echo "<th width='6%' class='numeric dtype'>Taxable Amt.</th>";
                                    Echo "<th width='6%' class='numeric dtype'>CGST %</th>";
                                    Echo "<th width='6%' class='numeric dtype'>CGST Amt.</th>";
                                    Echo "<th width='6%' class='numeric dtype'>SGST %</th>";
                                    Echo "<th width='6%' class='numeric dtype'>SGST Amt.</th>";
                                    Echo "<th width='6%' class='numeric dtype'>IGST %</th>";
                                    Echo "<th width='6%' class='numeric dtype'>IGST Amt.</th>";
                                    Echo "<th width='8%' class='numeric dtype'>Total</th>";
                                    echo "<tr>";

                                    $ctr2 = 0;
                                    $totyard = $totmtrs = $totqty = $totdisc = $totdiscamt = $totcgst = $totsgst = $totigst = $totamt = $tottaxable = $total = 0;

                                    $gettran = mysqli_query($conn, "SELECT * FROM `$trandb` WHERE `vouchno`='$pmain[vouchno]'") or die(mysqli_error($conn));
                                    while ($tran = mysqli_fetch_array($gettran)) {

                                        $getitem = mysqli_query($conn, "SELECT `code`,`name` FROM `rawmat` WHERE `code`='$tran[item]'") or die(mysqli_error($conn));
                                        $item = mysqli_fetch_array($getitem);

                                        $getcolor = mysqli_query($conn, "SELECT `code`,`name` FROM `color` WHERE `code`='$tran[color]'") or die(mysqli_error($conn));
                                        $color = mysqli_fetch_array($getcolor);

                                        $ctr2++;
                                        echo "<tr>";
                                        echo "<td>$ctr2</td>";
                                        echo "<td>$item[name]</td>";
                                        echo "<td>$color[name]</td>";
                                        Echo "<td>$tran[hsncode]</td>";
                                        echo "<td class='numeric'>$tran[lot]</td>";
                                        Echo "<td class='numeric'>$tran[qty]</td>";
                                        Echo "<td class='numeric'>$tran[rate]</td>";
                                        Echo "<td class='numeric'>$tran[amount]</td>";
                                        Echo "<td class='numeric'>$tran[discperc]</td>";
                                        Echo "<td class='numeric'>$tran[discount]</td>";
                                        Echo "<td class='numeric'>$tran[subtot]</td>";
                                        Echo "<td class='numeric'>$tran[cgstrate]</td>";
                                        Echo "<td class='numeric'>$tran[cgstamt]</td>";
                                        Echo "<td class='numeric'>$tran[sgstrate]</td>";
                                        Echo "<td class='numeric'>$tran[sgstamt]</td>";
                                        Echo "<td class='numeric'>$tran[igstrate]</td>";
                                        Echo "<td class='numeric'>$tran[igstamt]</td>";
                                        Echo "<td class='numeric'>$tran[total]</td>";
                                        Echo "</tr>";

                                        $totamt = $totamt + $tran['amount'];
                                        $tottaxable = $tottaxable + $tran['subtot'];
                                        $totqty = $totqty + $tran['qty'];
                                        $totdisc = $totdisc + $tran['discperc'];
                                        $totdiscamt = $totdiscamt + $tran['discount'];
                                        $totcgst = $totcgst + $tran['cgstamt'];
                                        $totsgst = $totsgst + $tran['sgstamt'];
                                        $totigst = $totigst + $tran['igstamt'];
                                        $total = $total + $tran['total'];
                                    }
                                    echo "<tr> ";
                                    $colr1 = "blue";

                                    echo "<td style='color:$colr1'</td>";
                                    echo "<td style='color:$colr1'</td>";
                                    echo "<td style='color:$colr1'</td>";
                                    echo "<td style='color:$colr1'</td>";
                                    echo "<td style='color:$colr1' id='font1'><h5><b>Total</b></h5></td>";
                                    echo "<td style='color:$colr1' id='font1' class='text-right'><h5><b>$totqty</b></h5></td>";
                                    echo "<td style='color:$colr1' id='font1'></td>";
                                    echo "<td style='color:$colr1' id='font1' class='numeric'><h5><b>$totamt</b></h5></td>";
                                    echo "<td style='color:$colr1' id='font1' class='numeric'><h5><b>$totdisc</b></h5></td>";
                                    echo "<td style='color:$colr1' id='font1' class='numeric'><h5><b>$totdiscamt</b></h5></td>";
                                    echo "<td style='color:$colr1' id='font1' class='numeric'><h5><b>$tottaxable</b></h5></td>";
                                    echo "<td style='color:$colr1' id='font1' class='numeric'><h5><b></b></h5></td>";
                                    echo "<td style='color:$colr1' id='font1' class='numeric'><h5><b>$totcgst</b></h5></td>";
                                    echo "<td style='color:$colr1' id='font1' class='numeric'><h5><b></b></h5></td>";
                                    echo "<td style='color:$colr1' id='font1' class='numeric'><h5><b>$totsgst</b></h5></td>";
                                    echo "<td style='color:$colr1' id='font1' class='numeric'><h5><b></b></h5></td>";
                                    echo "<td style='color:$colr1' id='font1' class='numeric'><h5><b>$totigst</b></h5></td>";
                                    echo "<td style='color:$colr1' id='font1' class='numeric'><h5><b>$total</b></h5></td>";
                                    echo "</tr>";

                                    echo "</table>";
                                    echo "</td>";
                                }
                                // if ($_POST["dtype"] == 3) {
                                //     $gettran = mysqli_query($conn, "SELECT * FROM `prodmake` WHERE `vouchno`='$pmain[vouchno]'") or die(mysqli_error($conn));
                                //     if (mysqli_num_rows($gettran) > 0) {
                                //         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 "<h4>Product Making</h4>";
                                //         echo "<th width='5%;' style='background-color:#0a8bfa' class='dtype'>Sr</th>";
                                //         echo "<th width='8%'  style='background-color:#0a8bfa' class='dtype'>Item</th>";
                                //         echo "<th width='8%'  style='background-color:#0a8bfa' class='dtype'>Color</th>";
                                //         echo "<th width='6%'  style='background-color:#0a8bfa' class='numeric dtype'>Qty</th>";
                                //         echo "<th width='6%'  style='background-color:#0a8bfa' class='numeric dtype'>Rate</th>";
                                //         echo "<tr>";
                                //         $ctr2 = 0;
                                //         $totqty = $totdisc = $totdiscamt = $totcgst = $totsgst = $totigst = $totamt = 0;
                                //         while ($tran = mysqli_fetch_array($gettran)) {
                                //             $getitem = mysqli_query($conn, "SELECT `code`,`name` FROM `item` WHERE `code`='$tran[item]'") or die(mysqli_error($conn));
                                //             $item = mysqli_fetch_array($getitem);
                                //             $getcolor = mysqli_query($conn, "SELECT `code`,`name` FROM `color` WHERE `code`='$tran[color]'") or die(mysqli_error($conn));
                                //             $color = mysqli_fetch_array($getcolor);
                                //             $ctr2++;
                                //             echo "<tr>";
                                //             echo "<td>$ctr2</td>";
                                //             echo "<td>$item[name]</td>";
                                //             echo "<td>$color[name]</td>";
                                //             echo "<td class='numeric'>$tran[qty]</td>";
                                //             echo "<td class='numeric'>$tran[rate]</td>";
                                //             echo "</tr>";
                                //         }
                                //         echo "</table>";
                                //         echo "</td>";
                                //     }
                                // }
                            }

                            $colr = "green";
                            echo "<tr> ";
                            echo "<td></td>";
                            echo "<td></td>";
                            if ($compno != '103') {
                                echo "<td></td>";
                            }
                            echo "<td></td>";
                            echo "<td></td>";
                            echo "<td align='right' style='color:$colr;'><h4><b>Grand Total</b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b>$ttotamt</b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b>$totitmpr</b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b>$tottaxamt</b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b>$ttotgst5</b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b>$ttotgst12</b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b>$ttotgst18</b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b>$ttotgst28</b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b>$ttotamount</b></h4></td>";
                            echo "</tr>";
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

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

    </html>
    <?php
}


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

    include("includes/head_excel_rep.php");

    if ($compno != '103') {
        $contents .= "Sr, Invoice, Date, Broker, Supplier, GST No., Amount ,Discount ,Taxable Value ,GST 5% ,GST 12% ,GST 18% ,GST 28%, Bill.Amt \n";
    } else {
        $contents .= "Sr, Invoice, Date, Supplier, GST No., Amount ,Discount ,Taxable Value ,GST 5% ,GST 12% ,GST 18% ,GST 28%, Bill.Amt \n";
    }

    $ctr = 0;
    $ttotamt = 0;
    $totpack = 0;
    $totbill = 0;
    $totitmpr = 0;
    $totdisc = 0;
    $tottaxamt = 0;
    $totcgst = 0;
    $totsgst = 0;
    $totigst = 0;
    $ttotamount = 0;

    $totbill = $tottaxamt = $ttotgst5 = $ttotgst12 = $ttotgst18 = $ttotgst28 = $ttotalamount = 0;

    while ($pmain = mysqli_fetch_array($getpmain)) {
        $getsupp = mysqli_query($conn, "SELECT `accode`,`name`,`gstno` FROM `accmast` WHERE `accode`='$pmain[party]'") or die(mysqli_error($conn));
        $supp = mysqli_fetch_array($getsupp);
        $getbroker = mysqli_query($conn, "SELECT `accode`,`name` FROM `accmast` WHERE `accode`='$pmain[broker]'") or die(mysqli_error($conn));
        $broker = mysqli_fetch_array($getbroker);

        $ctr++;
        if ($pmain['canc_flag'] != 'C') {
            $contents .= $ctr . ",";
            $contents .= "$pmain[invno]" . ",";
            $contents .= "$pmain[mydt]" . ",";
            if ($compno != '103') {
                $contents .= "$broker[name]" . ",";
            }
            $contents .= "$supp[name]" . ",";
            $contents .= "$supp[gstno]" . ",";
            $contents .= "$pmain[subtotal]" . ",";
            $contents .= "$pmain[litemdisc]" . ",";
            $contents .= "$pmain[tottaxamt]" . ",";
            $contents .= "$pmain[totgst5]" . ",";
            $contents .= "$pmain[totgst12]" . ",";
            $contents .= "$pmain[totgst18]" . ",";
            $contents .= "$pmain[totgst28]" . ",";
            $contents .= "$pmain[netamt]" . "\n";

            $ttotamt = $ttotamt + $pmain['subtotal'];
            $totitmpr = $totitmpr + $pmain['lesother'];

            $tottaxamt += $pmain['tottaxamt'];
            $ttotgst5 += $pmain['totgst5'];
            $ttotgst12 += $pmain['totgst12'];
            $ttotgst18 += $pmain['totgst18'];
            $ttotgst28 += $pmain['totgst28'];
            $ttotamount += $pmain['netamt'];
        } else {
            $contents .= $ctr . ",";
            $contents .= "$pmain[invno]" . ",";
            $contents .= "$pmain[mydt]" . ",";
            if ($compno != '103') {
                $contents .= "$broker[name]" . ",";
            }
            $contents .= "$supp[name]" . "\n";
        }

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

            $contents .= "Sr, Material, Color, HSN Code, Lot, Qty, Rate, Amount, Disc%, Disc. Amt., Taxable Amt., CGST %, CGST Amt., SGST %, SGST Amt., IGST %, IGST Amt., Total\n";

            $ctr2 = 0;
            $totyard = $totmtrs = $totqty = $totdisc = $totdiscamt = $totcgst = $totsgst = $totigst = $totamt = $tottaxable = $total = 0;

            $gettran = mysqli_query($conn, "SELECT * FROM `$trandb` WHERE `vouchno`='$pmain[vouchno]' order by srno") or die(mysqli_error($conn));
            while ($tran = mysqli_fetch_array($gettran)) {

                $getitem = mysqli_query($conn, "SELECT `code`,`name` FROM `rawmat` WHERE `code`='$tran[item]'") or die(mysqli_error($conn));
                $item = mysqli_fetch_array($getitem);

                $getcolor = mysqli_query($conn, "SELECT `code`,`name` FROM `color` WHERE `code`='$tran[color]'") or die(mysqli_error($conn));
                $color = mysqli_fetch_array($getcolor);

                $ctr2++;
                $contents .= "$ctr2" . ",";
                $contents .= "$item[name]" . ",";
                $contents .= "$color[name]" . ",";
                $contents .= "$tran[hsncode]" . ",";
                $contents .= "$tran[lot]" . ",";
                $contents .= "$tran[qty]" . ",";
                $contents .= "$tran[rate]" . ",";
                $contents .= "$tran[amount]" . ",";
                $contents .= "$tran[discperc]" . ",";
                $contents .= "$tran[discount]" . ",";
                $contents .= "$tran[subtot]" . ",";
                $contents .= "$tran[cgstrate]" . ",";
                $contents .= "$tran[cgstamt]" . ",";
                $contents .= "$tran[sgstrate]" . ",";
                $contents .= "$tran[sgstamt]" . ",";
                $contents .= "$tran[igstrate]" . ",";
                $contents .= "$tran[igstamt]" . ",";
                $contents .= "$tran[total]" . "\n";

                $totamt = $totamt + $tran['amount'];
                $tottaxable = $tottaxable + $tran['subtot'];
                $totqty = $totqty + $tran['qty'];
                $totdisc = $totdisc + $tran['discperc'];
                $totdiscamt = $totdiscamt + $tran['discount'];
                $totcgst = $totcgst + $tran['cgstamt'];
                $totsgst = $totsgst + $tran['sgstamt'];
                $totigst = $totigst + $tran['igstamt'];
                $total = $total + $tran['total'];
            }

            $contents .= "" . ",";
            $contents .= "" . ",";
            $contents .= "" . ",";
            $contents .= "" . ",";
            $contents .= "Total" . ",";
            $contents .= "$totqty" . ",";
            $contents .= "" . ",";
            $contents .= "$totamt" . ",";
            $contents .= "$totdisc" . ",";
            $contents .= "$totdiscamt" . ",";
            $contents .= "$tottaxable" . ",";
            $contents .= "" . ",";
            $contents .= "$totcgst" . ",";
            $contents .= "" . ",";
            $contents .= "$totsgst" . ",";
            $contents .= "" . ",";
            $contents .= "$totigst" . ",";
            $contents .= "$total" . "\n";
        }
    }

    $contents .= "" . ",";
    $contents .= "" . ",";
    if ($compno != '103') {
        $contents .= "" . ",";
    }
    $contents .= "" . ",";
    $contents .= "" . ",";
    $contents .= "Grand Total" . ",";
    $contents .= "$ttotamt" . ",";
    $contents .= "$totitmpr" . ",";
    $contents .= "$tottaxamt" . ",";
    $contents .= "$ttotgst5" . ",";
    $contents .= "$ttotgst12" . ",";
    $contents .= "$ttotgst18" . ",";
    $contents .= "$ttotgst28" . ",";
    $contents .= "$ttotamount" . "\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;
    }
}

if (isset($_POST["tally"])) {
    include("includes/head_excel_rep.php");

    $getexcel = mysqli_query($conn, "SELECT *, DATE_FORMAT(`vouchdt`, '%d-%m-%Y') as mydt FROM `$maindb` 
                WHERE `vouchdt` >= '$mfrmdate' AND `vouchdt` <= '$mtodate' $partycond $salemcond $mscopecond 
                ORDER BY vouchdt ASC") or die(mysqli_error($conn));

// Initialize CSV content with headers
    $contents = "Sr.,Invoice,Date,Party,Address, State, Country, Pincode, GST No.,Raw Material,Itemname,Colour,HSN,Qty,Rate,Amount,Disc%,Disc. Amt.,Taxable Amt.,CGST%,CGST Amt.,SGST %,SGST Amt,IGST %,IGST Amt.,Total Amount,Item Discount,Bill Discount,Packing,Taxable Value,GST 5%,GST 12%,GST 18%,GST 28%,Bill. Amt, Roundoff, DR/CR Roundoff \n";

    $sr = 1;
    $prevvouch = 0;
    while ($pmain = mysqli_fetch_array($getexcel)) {
        // Get party/supplier details
        $getsupp = mysqli_query($conn, "SELECT `accode`,`name`,`gstno`,`add1`,`add2`,`add3`,`state`,`country`,`pin` FROM `accmast` WHERE `accode`='{$pmain['party']}'") or die(mysqli_error($conn));
        $supp = mysqli_fetch_array($getsupp);

        // Get salesman details
        $getsale = mysqli_query($conn, "SELECT `accode`,`name` FROM `accmast` WHERE `accode`='{$pmain['salesman']}'") or die(mysqli_error($conn));
        $sale = mysqli_fetch_array($getsale);

        $unclaimgst = $pmain["unclaimgst"];

        $gettran = mysqli_query($conn, "SELECT * FROM `$trandb` WHERE `vouchno`='{$pmain['vouchno']}'") or die(mysqli_error($conn));

        while ($tran = mysqli_fetch_array($gettran)) {
            $newvouch = $pmain['vouchno'];
            if ($prevvouch == $newvouch) {
                $vouchno = '';
                $invno = '';
                $litemdisc = '';
                $discount = '';
                $packing = '';
                $tottaxamt = '';
                $totgst5 = '';
                $totgst12 = '';
                $totgst18 = '';
                $totgst28 = '';
                $roundoff = '';
                $roundoffdrcr = '';
                $netamt = '';
                $mydt = '';
                $party = '';
                $address = '';
                $state = '';
                $country = '';
                $pincode = '';
                $rawmaterial = '';
            } else {
                $vouchno = $newvouch;
                $prevvouch = $newvouch;
                $invno = $pmain['invno'];
                $mydt = $pmain['mydt'];
                $party = $supp['name'];
                $add = $supp['add1'] . " " . $supp['add2'] . " " . $supp['add3'];
                $address = str_replace(",", " ", $add);
                $state = $supp['state'];
                $country = $supp['country'];
                $pincode = $supp['pin'];
                $rawmaterial = "Raw Material";
                $litemdisc = $pmain['litemdisc'];
                $discount = $pmain['discount'];
                $packing = $pmain['packchgs'];
                $packgtperc = $pmain['packgtperc'];
                $tottaxamt = $pmain['tottaxamt'];

                if ($packgtperc == '5.00') {
                    $totgst5 = $pmain['totgst5'] + $pmain['packgtamt'];
                } else {
                    $totgst5 = $pmain['totgst5'];
                }
                if ($packgtperc == '12.00') {
                    $totgst12 = $pmain['totgst12'] + $pmain['packgtamt'];
                } else {
                    $totgst12 = $pmain['totgst12'];
                }
                if ($packgtperc == '18.00') {
                    $totgst18 = $pmain['totgst18'] + $pmain['packgtamt'];
                } else {
                    $totgst18 = $pmain['totgst18'];
                }
                if ($packgtperc == '28.00') {
                    $totgst28 = $pmain['totgst28'] + $pmain['packgtamt'];
                } else {
                    $totgst28 = $pmain['totgst28'];
                }
                // $totgst12 = $pmain['totgst12'];
                // $totgst18 = $pmain['totgst18'];
                // $totgst28 = $pmain['totgst28'];
                $netamt = $pmain['netamt'];
                $roundoff = $pmain['roundoff'];
                if ($roundoff > 0) {
                    $roundoffdrcr = "CR";
                    } else {
                    $roundoffdrcr = "DR";
                }
                $newline = $contents .= "\n";
            }
            
            $getitem = mysqli_query($conn, "SELECT `code`,`name` FROM `rawmat` WHERE `code`='{$tran['item']}'") or die(mysqli_error($conn));
            $item = mysqli_fetch_array($getitem);

            $getcolor = mysqli_query($conn, "SELECT `code`,`name` FROM `color` WHERE `code`='{$tran['color']}'") or die(mysqli_error($conn));
            $color = mysqli_fetch_array($getcolor);

            $contents .= "{$sr},";
            $contents .= "{$invno},";
            $contents .= "{$mydt},";
            $contents .= "{$party},";
            $contents .= "{$address},";
            $contents .= "{$state},";
            $contents .= "{$country},";
            $contents .= "{$pincode},";
            $contents .= "{$supp['gstno']},";
            $contents .= "{$rawmaterial},";
            $contents .= "{$item['name']},";
            $contents .= "{$color['name']},";
            $contents .= "{$tran['hsncode']},";
            $contents .= "{$tran['qty']},";
            $contents .= "{$tran['rate']},";
            $contents .= "{$tran['amount']},";
            $contents .= "{$tran['discperc']},";
            $contents .= "{$tran['discount']},";
            $contents .= "{$tran['subtot']},";
            $contents .= "{$tran['cgstrate']},";
            $contents .= "{$tran['cgstamt']},";
            $contents .= "{$tran['sgstrate']},";
            $contents .= "{$tran['sgstamt']},";
            $contents .= "{$tran['igstrate']},";
            $contents .= "{$tran['igstamt']},";
            $contents .= "{$tran['total']},";
            $contents .= "{$litemdisc},";
            $contents .= "{$discount},";
            $contents .= "{$packing},";
            $contents .= "{$tottaxamt},";
            $contents .= "{$totgst5},";
            $contents .= "{$totgst12},";
            $contents .= "{$totgst18},";
            $contents .= "{$totgst28},";
            $contents .= "{$netamt},";
            $contents .= "{$roundoff},";
            $contents .= "{$roundoffdrcr}\n";
            $newline;

            $sr++;
        }
    }

    $contents = strip_tags($contents);
    header("Content-Disposition: attachment; filename = $formname" . "_Tally Formnat" . date('d-m-Y') . " .csv");
    print $contents;
}

if (isset($_POST["tally2"])) {
    include("includes/head_excel_rep.php");

    $getexcel = mysqli_query($conn, "SELECT *, DATE_FORMAT(`vouchdt`, '%d-%m-%Y') as mydt FROM `$maindb` 
                WHERE `vouchdt` >= '$mfrmdate' AND `vouchdt` <= '$mtodate' $partycond $salemcond $mscopecond 
                ORDER BY vouchdt ASC") or die(mysqli_error($conn));

    $contents = "Sr.,Voucher Date, Voucher Type Name, Voucher Number, Reference No., Reference Date, Buyer Supplier - Address,Buyer Supplier - GST IN/ UIN, Buyer/Supplier - State, Buyer/Supplier - Pincode,Buyer/Supplier - Country, Order Nos, Order Date, Mode/Terms of Payment,Other References, Terms Of Delivery, Ledger Name, Ledger Amount, Ledger Rate, Ledger Amount Dr/Cr, Item Name, Item Description,Actual Quantity, Billed Quantity, Item Rate, Disc %, Item Rate Per, Item Amount, Change Mode, Bill Type of Ref, Bill Name,Roundoff, Bill Amount, Bill Amount Dr/Cr, Bill Due Dt / Credit Days, Voucher Narration, e-Invoice - Bill to Place, e-Invoice - Ship to Place,e-Invoice - Dispatch From Name, e-Invoice - Dispatch From Address, e-Invoice - Dispatch From State, e-Invoice - Dispatch From Pincode,e-Invoice - Dispatch From Place\n";

    $sr = 1;
    $prevvouch = 0;
    while ($pmain = mysqli_fetch_array($getexcel)) {
        $getsupp = mysqli_query($conn, "SELECT `accode`,`name`,`gstno`,`add1`,`add2`,`add3`,`state`,`country`,`pin` FROM `accmast` WHERE `accode`='{$pmain['party']}'") or die(mysqli_error($conn));
        $supp = mysqli_fetch_array($getsupp);

        $getsale = mysqli_query($conn, "SELECT `accode`,`name` FROM `accmast` WHERE `accode`='{$pmain['salesman']}'") or die(mysqli_error($conn));
        $sale = mysqli_fetch_array($getsale);

        $unclaimgst = $pmain["unclaimgst"];

        $gettran = mysqli_query($conn, "SELECT * FROM `$trandb` WHERE `vouchno`='{$pmain['vouchno']}'") or die(mysqli_error($conn));

        while ($tran = mysqli_fetch_array($gettran)) {
            $newvouch = $pmain['vouchno'];
            $roundoff = $pmain['roundoff'];
                
                
            if ($prevvouch == $newvouch) {
                $vouchno = '';
                $invno = '';
                $refno = "";
                $refdt = "";
                $ordno = "";
                $orddt = "";
                $termspay = "";
                $othref = "";
                $termsdelv = "";
                $ledgername = "";
                $ledgeramt = "";
                $ledgerrate = "";
                $ledgeramtcrdr = "";
                $itemrateper = "";
                $changemod = "";
                $billtyperef = "";
                $billname = "";
                $billamt = "";
                $billamtdrcr = $roundoffdrcr;
                $billduedt = "";
                $vouchnarr = "";
                $einvbilltoplace = "";
                $einvshiptoplace = "";
                $einvdisname = "";
                $einvdisadd = "";
                $einvdisstate = "";
                $einvdispin = "";
                $einvdisplace = "";
                $litemdisc = '';
                $discount = '';
                $packing = '';
                $packgtamt = '';
                $tottaxamt = '';
                $totgst5 = '';
                $totgst12 = '';
                $totgst18 = '';
                $totgst28 = '';
                $netamt = '';
                $roundoff = '';
                $suppstate = '';
                $suppgstno = '';  
                $suppin = '';
                $suppcountry = '';
            } else {
                $vouchno = $newvouch;
                $invno = $pmain['invno'];
                $refno = "";
                $refdt = "";
                $ordno = "";
                $orddt = "";
                $termspay = "";
                $othref = "";
                $termsdelv = "";
                $ledgername = "";
                $ledgeramt = "";
                $ledgerrate = "";
                $ledgeramtcrdr = "";
                $itemrateper = "";
                $changemod = "";
                $billtyperef = "";
                $billname = "";
                $billamt = "";
                $billamtdrcr = $roundoffdrcr;
                $billduedt = "";
                $vouchnarr = "";
                $einvbilltoplace = "";
                $einvshiptoplace = "";
                $einvdisname = "";
                $einvdisadd = "";
                $einvdisstate = "";
                $einvdispin = "";
                $einvdisplace = "";
                $prevvouch = $newvouch;
                $litemdisc = $pmain['litemdisc'];
                $discount = $pmain['discount'];
                $packing = $pmain['packchgs'];
                $packgtperc = $pmain['packgtperc'];
                $tottaxamt = $pmain['tottaxamt'];
                $suppstate = $supp['state'];
                $suppgstno = $supp['gstno'];
                $suppin = $supp['pin'];
                $suppcountry = $supp['country'];
                
                if ($packgtperc == '5.00') {
                    $totgst5 = $pmain['totgst5'] + $pmain['packgtamt'];
                } else {
                    $totgst5 = $pmain['totgst5'];
                }
                if ($packgtperc == '12.00') {
                    $totgst12 = $pmain['totgst12'] + $pmain['packgtamt'];
                } else {
                    $totgst12 = $pmain['totgst12'];
                }
                if ($packgtperc == '18.00') {
                    $totgst18 = $pmain['totgst18'] + $pmain['packgtamt'];
                } else {
                    $totgst18 = $pmain['totgst18'];
                }
                if ($packgtperc == '28.00') {
                    $totgst28 = $pmain['totgst28'] + $pmain['packgtamt'];
                } else {
                    $totgst28 = $pmain['totgst28'];
                }
                $netamt = $pmain['netamt'];
                $roundoff = $pmain['roundoff'];
                if ($roundoff > 0) {
                    $roundoffdrcr = "DR";
                    } else {
                    $roundoffdrcr = "CR";
                }
                $newline = $contents .= "\n";
            }
            $getitem = mysqli_query($conn, "SELECT `code`,`name` FROM `rawmat` WHERE `code`='{$tran['item']}'") or die(mysqli_error($conn));
            $item = mysqli_fetch_array($getitem);

            $getcolor = mysqli_query($conn, "SELECT `code`,`name` FROM `color` WHERE `code`='{$tran['color']}'") or die(mysqli_error($conn));
            $color = mysqli_fetch_array($getcolor);

            $suppadd = str_replace(",", " ", $supp['add1']) . str_replace(",", " ", $supp['add2']) . str_replace(",", " ", $supp['add3']);

            $contents .= "{$sr},";
            $contents .= "{$pmain['mydt']},";
            $contents .= "Sale Invoice,";
            $contents .= "{$invno},";
            $contents .= "{$refno},";
            $contents .= "{$refdt},";
            $contents .= "{$suppadd},";
            $contents .= "{$suppgstno},";
            $contents .= "{$suppstate},";
            $contents .= "{$supppin},";
            $contents .= "{$suppcountry},";
            $contents .= "{$ordno},";
            $contents .= "{$orddt},";
            $contents .= "{$termspay},";
            $contents .= "{$othref},";
            $contents .= "{$termsdelv},";
            $contents .= "{$ledgername},";
            $contents .= "{$ledgeramt},";
            $contents .= "{$ledgerrate},";
            $contents .= "{$ledgeramtcrdr},";
            $contents .= "{$item['name']},";
            $contents .= "{$item['name']},";
            $contents .= "{$tran['qty']},";
            $contents .= "{$tran['qty']},";
            $contents .= "{$tran['rate']},";
            $contents .= "{$tran['discperc']},";
            $contents .= "{$itemrateper},";
            $contents .= "{$tran['amount']},";
            $contents .= "{$changemod},";
            $contents .= "{$billtyperef},";
            $contents .= "{$billname},";
            $contents .= "{$roundoff},";
            $contents .= "{$billamt},";
            $contents .= "{$billamtdrcr},";
            $contents .= "{$billduedt},";
            $contents .= "{$vouchnarr},";
            $contents .= "{$einvsbilltoplace},";
            $contents .= "{$einvshiptoplace},";
            $contents .= "{$einvdisname},";
            $contents .= "{$einvdisadd},";
            $contents .= "{$einvdisstate},";
            $contents .= "{$einvdispin},";
            $contents .= "{$einvdisplace}\n";
            $sr++;
        }
    }

    $contents = strip_tags($contents);
    header("Content-Disposition: attachment; filename = $formname" . "_Tally Format_New_" . date('d-m-Y') . " .csv");
    print $contents;
}
?>