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

$maindb = 'credmain';
$trandb = 'credtran';
$formname = "Credit Note Register";
$file = "crdntreg_fr.php";
$keycond = "";

$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"];
$broker = $_POST["broker"];
$item = $_POST["item"];
$prodtype = $_POST["prodtype"];
$dtype = $_POST["dtype"];
$scope = $_POST["scope"];
$printnar = $_POST["prna"];
$gstperc = $_POST["gstperc"];

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

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

if (!empty($broker)) {
    $brokercond = " AND `broker`='$broker' ";
}

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' $brokercond $partycond ") or die(mysqli_error($conn));

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

        @media print {

            .table-bordered>thead>tr>th {
                border: 1px solid black !important;
            }

            .table-bordered>tbody>tr>td {
                border: 1px solid black !important;
            }

            .table-bordered>tbody>tr>th {
                border: 1px solid black !important;
            }

            .table-condensed>tbody>tr>td {
                padding: 3px !important;
            }

            .container {
                margin-left: 30px !important;
                margin-top: 10px !important;
            }
        }
    </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-condensed table-bordered ">
                        <thead class="mySearchTr">
                            <tr>
                                <th style='width:5%'>Sr</th>
                                <th style='width:5%'>Invoice</th>
                                <th style='width:8%'>Date</th>
                                <th style='width:23%'>Broker</th>
                                <th style='width:10%'>Party</th>
                                <th style='width:10%'>GST No.</th>
                                <th style='width:5%' class="text-right">Amount</th>
                                <th style='width:5%' class="text-right">Item Dis.</th>
                                <th width='5%' class="text-right">Packing</th>
                                <th width='5%' class="text-right">Packing GST</th>
                                <th style='width:5%' class="text-right">Taxable Value</th>
                                <th style='width:6%' class="text-right">GST 5%</th>
                                <th style='width:6%' class="text-right">GST 12%</th>
                                <th style='width:6%' class="text-right">GST 18%</th>
                                <th style='width:5%' class="text-right">GST 28%</th>
                                <th style='width:11%' class="text-right">Bill.Amt</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $ctr = 0;
                            $ttotamt = 0;
                            $totpack = 0;
                            $totpackgst = 0;
                            $totbill = 0;
                            $totitmpr = 0;
                            $totdisc = 0;
                            $tottaxamt = 0;
                            $totcgst = 0;
                            $totsgst = 0;
                            $totigst = 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);
                                $getsale = mysqli_query($conn, "SELECT `accode`,`name` FROM `accmast` WHERE `accode`='$pmain[broker]'") or die(mysqli_error($conn));
                                $broker = mysqli_fetch_array($getsale);

                                $ctr++;
                                echo "<tr id='boldfont'>";
                                echo "<td>$ctr</td>";
                                if ($pmain['canc_flag'] != 'C') {
                                    echo "<td>$pmain[invno]</td>";
                                    echo "<td>$pmain[mydt]</td>";
                                    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[packchgs]</td>";
                                    echo "<td class='text-right'>$pmain[packgtamt]</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>";

                                    $ttotamt = $ttotamt + $pmain['subtotal'];
                                    $totitmpr = $totitmpr + $pmain['litemdisc'];
                                    $totdisc = $totdisc + $pmain['discount'];
                                    $totpack = $totpack + $pmain['packchgs'];
                                    $totpackgst = $totpackgst + $pmain['packgtamt'];
                                    $tottaxamt = $tottaxamt + $pmain['tottaxamt'];
                                    $totgst1 = $totcgst1 + $pmain['totgst1'];
                                    $totgst5 = $totgst5 + $pmain['totgst5'];
                                    $totgst12 = $totgst12 + $pmain['totgst12'];
                                    $totgst18 = $totgst18 + $pmain['totgst18'];
                                    $totgst28 = $totgst28 + $pmain['totgst28'];
                                    $totbill = $totbill + $pmain['netamt'];
                                } else {
                                    echo "<td style='color:red'>$pmain[invno]</td>";
                                    echo "<td style='color:red'>$pmain[mydt]</td>";
                                    echo "<td style='color:red'>$broker[name]</td>";
                                    echo "<td style='color:red'>$supp[name]</td>";
                                    echo "<td colspan='9' class='text-center' style='color:red'>********* cancellled bill *********</td>";
                                }
                                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 "<th width='5%;'class='dtype'>Sr</th>";
                                    echo "<th width='8%' class='dtype''>Barcode</th>";
                                    echo "<th width='8%' class='dtype'>Itemname</th>";
                                    echo "<th width='8%' class='dtype'>Size</th>";
                                    echo "<th width='6%' class='dtype'>HSN Code</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='6%' class='numeric dtype'>Total</th>";
                                    echo "<tr>";

                                    $ctr2 = 0;

                                    $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 `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`='$pmain[color]'") or die(mysqli_error($conn));
                                        $color = mysqli_fetch_array($getcolor);

                                        $ctr2++;
                                        echo "<tr>";
                                        echo "<td>$ctr2</td>";
                                        echo "<td>$tran[barcode]</td>";
                                        echo "<td>$item[name]</td>";
                                        echo "<td>$tran[size]</td>";
                                        echo "<td>$tran[hsncode]</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>";
                                }
                            }

                            $colr = "green";
                            echo "<tr> ";
                            echo "<td></td>";
                            echo "<td></td>";
                            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>$totpack</b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b>$totpackgst</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>$totgst5</b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b>$totgst12</b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b>$totgst18</b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b>$totgst28</b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b>$totbill</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");

    $contents .= "Sr, Invoice, Date, Broker, Party,GST No., Amount, Item Dis.,Packing, Packing GST, Taxable Value, GST 5%, GST 12%, GST 18%, GST 28%, Bill.Amt \n";

    $ctr = 0;
    $ttotamt = 0;
    $totpack = 0;
    $totpackgst = 0;
    $totbill = 0;
    $totitmpr = 0;
    $totdisc = 0;
    $tottaxamt = 0;
    $totcgst = 0;
    $totsgst = 0;
    $totigst = 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);
        $getsale = mysqli_query($conn, "SELECT `accode`,`name` FROM `accmast` WHERE `accode`='$pmain[broker]'") or die(mysqli_error($conn));
        $broker = mysqli_fetch_array($getsale);

        $ctr++;

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

            $ttotamt = $ttotamt + $pmain['subtotal'];
            $totitmpr = $totitmpr + $pmain['litemdisc'];
            $totdisc = $totdisc + $pmain['discount'];
            $totpack = $totpack + $pmain['packchgs'];
            $totpackgst = $totpackgst + $pmain['packgtamt'];
            $tottaxamt = $tottaxamt + $pmain['tottaxamt'];
            $totgst1 = $totcgst1 + $pmain['totgst1'];
            $totgst5 = $totgst5 + $pmain['totgst5'];
            $totgst12 = $totgst12 + $pmain['totgst12'];
            $totgst18 = $totgst18 + $pmain['totgst18'];
            $totgst28 = $totgst28 + $pmain['totgst28'];
            $totbill = $totbill + $pmain['netamt'];
        } else {
            $contents .= "$pmain[invno]" . ",";
            $contents .= "$pmain[mydt]" . ",";
            $contents .= "$broker[name]" . ",";
            $contents .= "$supp[name]" . ",";
            $contents .= "********* cancelled bill *********" . ",,,,,,,,,";
        }
        $contents .= "\n";

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

            $contents .= "Sr, Barcode, Itemname, Size, HSN Code, Qty, Rate, Amount, Disc%, Disc. Amt., Taxable Amt., CGST %, CGST Amt., SGST %, SGST Amt., IGST %, IGST Amt., Total \n";

            $ctr2 = 0;

            $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 `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`='$pmain[color]'") or die(mysqli_error($conn));
                $color = mysqli_fetch_array($getcolor);

                $ctr2++;
                echo "<tr>";
                $contents .= "$ctr2" . ",";
                $contents .= "$tran[barcode]" . ",";
                $contents .= "$item[name]" . ",";
                $contents .= "$tran[size]" . ",";
                $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]" . "\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 .= "" . ",";
    $contents .= "" . ",";
    $contents .= "" . ",";
    $contents .= "" . ",";
    $contents .= "Grand Total" . ",";
    $contents .= "$ttotamt" . ",";
    $contents .= "$totitmpr" . ",";
    $contents .= "$totpack" . ",";
    $contents .= "$totpackgst" . ",";
    $contents .= "$tottaxamt" . ",";
    $contents .= "$totgst5" . ",";
    $contents .= "$totgst12" . ",";
    $contents .= "$totgst18" . ",";
    $contents .= "$totgst28" . ",";
    $contents .= "$totbill" . "\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,Group,  Buyer Supplier - Address,State, Pincode, Country,GST No.,Barcode,Itemname,Size,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`,`add1`,`add2`,`add3`,`state`,`pin`,`gstno`,`country` FROM `accmast` WHERE `accode`='{$pmain['party']}'") or die(mysqli_error($conn));
        $supp = mysqli_fetch_array($getsupp);

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

        $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 = '';  // Empty for duplicate voucher numbers
                $invno = '';
                $litemdisc = '';
                $mydt = '';
                $suppname = '';
                $suppstate = '';
                $supppin = '';
                $suppcountry = '';
                $agencyname = '';
                $suppgstno = '';
                $discount = '';
                $packing = '';
                $tottaxamt = '';
                $totgst5 = '';
                $totgst12 = '';
                $totgst18 = '';
                $totgst28 = '';
                $netamt = '';
                $roundoff = '';
                $roundoffdrcr = '';
                $suppadd = '';
            } else {
                $vouchno = $newvouch;  // Show the voucher number for new vouchers
                $prevvouch = $newvouch;  // Update the previous voucher number
                $invno = $pmain['invno'];
                $mydt = $pmain['mydt'];
                $suppname = str_replace(",", " ", $supp['name']);
                $suppadd = str_replace(",", " ", $supp['add1']) . str_replace(",", " ", $supp['add2']) . str_replace(",", " ", $supp['add3']);
                $suppgstno = $supp['gstno'];
                $suppstate = $supp['state'];
                $supppin = $supp['pin'];
                $suppcountry = $supp['country'];
                $agencyname = $agency['name'];
                $litemdisc = $pmain['litemdisc'];
                $discount = $pmain['discount'];
                $packing = $pmain['packing'];
                $tottaxamt = $pmain['tottaxamt'];
                $totgst5 = $pmain['totgst5'];
                $totgst12 = $pmain['totgst12'];
                $totgst18 = $pmain['totgst18'];
                $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 `item` WHERE `code`='{$tran['barcode']}'") 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 .= "{$suppname},";
            $contents .= "{$agencyname},";
            $contents .= "{$suppadd},";
            $contents .= "{$suppstate},";
            $contents .= "{$supppin},";
            $contents .= "{$suppcountry},";
            $contents .= "{$suppgstno},";
            $contents .= "{$tran['barcode']},";
            $contents .= "{$item['name']},";
            $contents .= "{$tran['size']},";
            $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_tally.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.,Invoice,Date,Party,GROUP,Bill Address,Ship Address,State,Pincode,Country,GST No.,Barcode,Itemname,Size,Finished Goods,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,Transporter,Other References,Destination,E-way Bill No,E-way Date,Irn No,Irn Upload Date\n";


    $sr = 1;
    $prevvouch = 0;
    while ($pmain = mysqli_fetch_array($getexcel)) {

        $geteway = mysqli_query($conn, "SELECT *, DATE_FORMAT(`vouchdt`, '%d-%m-%Y')as vouchdt, DATE_FORMAT(`ewaydt`, '%d-%m-%Y %h:%i:%p')as ewaydt, 
        ewaydt as newaydt, DATE_FORMAT(`uploaddate`, '%d-%m-%Y')as uploaddate FROM `gstmain` WHERE vouchno='$pmain[invno]'") or die(mysqli_error($conn));
        $feteway = mysqli_fetch_array($geteway);

        $geteinv = mysqli_query($conn, "SELECT * FROM `gsteinvoice` where invno='$pmain[invno]' and frm=''") or die(mysqli_error($conn));
        $feteinv = mysqli_fetch_array($geteinv);

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

        $getagency = mysqli_query($conn, "SELECT * FROM `accmast` WHERE `accode`='{$pmain['agency']}'") or die(mysqli_error($conn));
        $agency = mysqli_fetch_array($getagency);

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

        $gettrans = mysqli_query($conn, "SELECT * FROM `transport` WHERE `code` = '{$pmain['transporter']}'") or die(mysqli_error($conn));
        $ltrans = mysqli_fetch_array($gettrans);

        $suppadd1 = str_replace(",", " ", $supp['add1']);
        $suppadd2 = str_replace(",", " ", $supp['add2']);
        $suppadd3 = str_replace(",", " ", $supp['add3']);

        $transarray = [
            '1' => "Road",
            '2' => "Rail",
            '3' => "Air",
            '4' => "Ship",
        ];
        $transmodeval = $transarray[$pmain['transmode']];
        $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 = '';  // Empty for duplicate voucher numbers
                $invno = '';
                $litemdisc = '';
                $mydt = '';
                $invoice = '';
                $suppaddress = '';
                $suppcountry = '';
                $suppstate = '';
                $supppin = '';
                $suppgsttype = '';
                $suppgstno = '';
                $suppplsupply = '';
                $ledgername = '';
                $agencyname = '';
                $netamt = '';
                $changemode = " ";
                $fromadd1 = "";
                $fromadd2 = "";
                $fromaddtype = "";
                $frompin = "";
                $fromstate = "";
                $fromactstate = "";
                $toadd1 = "";
                $toadd2 = "";
                $toaddtype = "";
                $tostate = "";
                $toactstate = "";
                $topin = "";
                $ewaydtls = "";
                $transportergst = "";
                $transmode = "";
                $transportlrno = "";
                $transportlrdt = "";
                $transportvehicle = "";
                $transportvehicletype = "";
                $transportplace = "";
                $transportstate = "";
                $ackno = "";
                $ackdt = "";
                $compname = "";
                $roundoff = "";
                $roundoffdrcr = "";
                $litemdisc = "";
                $addpacking = "";
                $taxamt = "";
                $totgst1 = "";
                $totgst5 = "";
                $totgst12 = "";
                $totgst18 = "";
                $totgst28 = "";
                $totalamount = "";
                $roundoff = "";
                $ledgerdrcr = "Cr";
                $transportername = "";
                $otherref = "";
                $destination = "";
                $ewaybillno = "";
                $ewaybilldt = "";
                $ewaysubtype = "";
                $ewaydoctype = "";
                $irnno = "";
                $irndate = "";
            } else {
                $vouchno = $newvouch;
                $prevvouch = $newvouch;
                $mydt = $pmain['mydt'];
                $invno = $pmain['invno'];
                $invoice = "$pmain[invno]";
                $suppaddress = $suppadd1 . $suppadd2 . $suppadd3;
                $suppcountry = "$supp[country]";
                $suppstate = $supp['state'];
                $supppin = $supp['pin'];
                $suppgsttype = "Regular";
                $suppgstno = $supp['gstno'];
                $suppplsupply = $supp['state'];
                $ledgername = $supp['name'];
                $agencyname = $agency['name'];
                $netamt = $pmain['netamt'];
                $ledgerdrcr = "Dr";
                $changemode = "Item Invoice";
                $ewaybillno = "$feteway[ewaybillno]";
                $ewaybilldt = "$feteway[ewaydt]";
                $ewaysubtype = "Supply";
                $ewaydoctype = "Invoice";
                $fromadd1 = "$add1";
                $fromadd2 = $add2 . " " . $add3;
                $fromaddtype = "";
                $frompin = "$pin";
                $fromstate = "$state";
                $fromactstate = "$state";
                $toadd1 = $suppadd1;
                $toadd2 = $suppadd2 . $suppadd3;
                $toaddtype = "";
                $tostate = "$supp[state]";
                $toactstate = "$supp[state]";
                $topin = "$supp[pin]";
                $ewaydtls = "";
                $irnno = "$feteway[irn]";
                $transportergst = "$ltrans[gstno]";
                $transmode = "$transmodeval";
                $transportlrno = "$ltrans[lrno]";
                $transportlrdt = "$ltrans[lrdate]";
                $transportvehicle = "";
                $transportvehicletype = "R- Regular";
                $transportplace = "$pmain[delcity]";
                $transportstate = "$pmain[delstate]";
                $ackno = $feteinv['ackno'];
                $ackdt = $feteway['uploaddate'];
                $compname = "$fromname";
                $roundoff = "$pmain[roundoff]";
                $litemdisc = "$pmain[litemdisc]";
                $addpacking = "$pmain[packchgs]";
                $taxamt = "$pmain[tottaxamt]";
                $totgst1 = "$pmain[totgst1]";
                $totgst5 = "$pmain[totgst5]";
                $totgst12 = "$pmain[totgst12]";
                $totgst18 = "$pmain[totgst18]";
                $totgst28 = "$pmain[totgst28]";
                $totalamount = "$pmain[netamt]";
                $transportername = "$ltrans[name]";
                $otherref = "3";
                $destination = "$pmain[destination]";
                $ewaybillno = "$pmain[ewaybillno]";
                $ewaybilldt = "$pmain[ewaydt]";
                $irnno = "$pmain[irn]";
                $irndate = "$pmain[uploaddate]";

                if ($roundoff > 0) {
                    $roundoffdrcr = "DR";
                } else {
                    $roundoffdrcr = "CR";
                }

                $newline = $contents .= "\n";
            }
            $getitem = mysqli_query($conn, "SELECT `code`,`name` FROM `item` WHERE `code`='{$tran['barcode']}'") 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 .= "{$ledgername},";
            $contents .= "{$agencyname},";
            $contents .= "{$suppaddress},";
            $contents .= "{$suppaddress},";
            $contents .= "{$suppstate},";
            $contents .= "{$supppin},";
            $contents .= "{$suppcountry},";
            $contents .= "{$suppgstno},";
            $contents .= "{$item['code']},";
            $contents .= "{$item['name']},";
            $contents .= "{$tran['size']},";
            $contents .= "FINISHED GOODS,";
            $contents .= "{$tran['hsncode']},";
            $contents .= "{$tran['qty']},";
            $contents .= "{$tran['rate']},";
            $contents .= "{$tran['amount']},";
            $contents .= "{$tran['discperc']},";
            $contents .= "{$tran['discamt']},";
            $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 .= "0,";
            $contents .= "{$addpacking},";
            $contents .= "{$taxamt},";
            $contents .= "{$totgst5},";
            $contents .= "{$totgst12},";
            $contents .= "{$totgst18},";
            $contents .= "{$totgst28},";
            $contents .= "{$totalamount},";
            $contents .= "{$roundoff},";
            $contents .= "{$roundoffdrcr},";
            $contents .= "{$transportername},";
            $contents .= "{$otherref},";
            $contents .= "{$destination},";
            $contents .= "{$ewaybillno},";
            $contents .= "{$ewaybilldt},";
            $contents .= "{$irnno},";
            $contents .= "{$irndate},\n";
            $newline;
            $sr++;
        }
    }

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