<?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);
$zroot = $_SESSION["zdbroot"];

$maindb = "purexpmain";
$trandb = "purexptran";
$file = 'purexpreg_fr.php';
ini_set('display_errors', 1);
error_reporting(E_ERROR);

$supplier = $_POST["supplier"];
$p = $_GET["p"];
$ptype = $_POST["ptype"];
$pchtype = $_POST["pchtype"];
$dtype = $_POST["dtype"];
$gsttype = $_POST["gsttype"];

if (!empty($supplier)) {
    $suppcond = " AND `party` = '$supplier' ";
    $suppcond2 = " AND `accode` = '$supplier' ";
}

if (!empty($ptype)) {
    $ptypecond = " AND `paidby`= '$ptype'";
}

if ($ptype == "C") {
    $paytype = "CASH";
} else {
    $paytype = "CREDIT";
}

$formname = 'Purchase Expense Register';

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



if (($_GET["fdt"]) != '') {
    $mfdt = $_GET["fdt"];
    $mtdt = $_GET["tdt"];
    $mfrmdate = date("y-m-d", strtotime($mfdt));
    $mtodate = date("y-m-d", strtotime($mtdt));
    $dtype = $_GET["rpt"];
} else {

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

    if (empty($_POST["frmdt"])) {
        browse("From Date Cannot Be Empty");
        header("refresh:1; saleitemgrp.php");
    }
    if (empty($_POST["todt"])) {
        browse("To Date Cannot Be Empty");
        header("refresh:1; saleitemgrp.php");
    }
    $mfdt = date("d-m-Y", strtotime($mfrmdate));
    $mtdt = date("d-m-Y", strtotime($mtodate));
}



$getpmain2 = mysqli_query($conn, "SELECT *,DATE_FORMAT(`vouchdt`, '%d-%m-%Y') as mydt FROM `$maindb` 
                                                WHERE `vouchdt` >= '$mfrmdate' AND `vouchdt` <= '$mtodate'
                                                $suppcond $ptypecond  $pcond order by `vouchdt`,`vouchno`") or die(mysqli_error($conn));


$getno2 = mysqli_num_rows($getpmain2);


if (isset($_POST["view"]) || ($_GET["view"])) {


    include("includes/linkshead.php");
?>
    <style type="text/css">
        #tabital {
            font-style: italic;
        }

        #font1 {
            font-style: italic;
        }

        #boldfont {
            font-weight: bold;
        }
    </style>
    </head>

    <body>


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

            if ($getno2 > 0) {
            ?>
                <div class="row">
                    <div class="col-lg-12 pad">
                        <table class="table table-condesed table-bordered">
                            <tr class="mySearchTr">
                                <!--9221292520-->
                                <th width="100%" class="h4" style="color:white"><b>Purchase Expense Register</b></th>
                            </tr>
                            <tr>
                                <td style="font-size: 15px;padding:5px" class="HDFont" colspan="2">
                                    Total No. of Record :&nbsp;&nbsp;<b><?php echo $getno2; ?></b>
                                </td>
                            </tr>
                        </table>
                        <?php if ($ptype != "") { ?>
                            <table width="100%" class="table" style="background-color: #98F9F0">
                                <tr>
                                    <td width="7%" style="font-size:14px">Pay Type : </td>
                                    <td width="93%" style="font-size:14px"><b><?php echo $paytype; ?></b></td>
                                </tr>
                            </table>
                        <?php } ?>
                        <table style="background: white;width: 100%"
                            class="table table-condensed table-striped table-hover table-bordered">
                            <thead class="mySearchTr">
                                <tr>
                                    <th width="3%;">Sr</th>
                                    <th width="4%;">Voucher</th>
                                    <th width="6%;">Invoice No.</th>
                                    <th width="6%;">Date</th>
                                    <th width="19%;">Party Name</th>
                                    <th width="8%;">GST NO.</th>
                                    <?php if ($ptype != "") { ?>
                                        <th width="7%;">Pay type</th>
                                    <?php } ?>
                                    <th width="6%;" class="text-right">Sub Total</th>
                                    <th width="5%;" class="text-right">Disc Amt.</th>
                                    <th width="5%;" class="text-right">Taxable</th>
                                    <th width="5%;" class="text-right">GST 3%</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="7%;" class="text-right">Net Amount</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $pctr = 0;
                                $ptotamt = 0;
                                $ptotdiscamt = 0;
                                $ptottaxable = 0;
                                $ptotgst3 = 0;
                                $ptotgst5 = 0;
                                $ptotgst12 = 0;
                                $ptotgst18 = 0;
                                $ptotgst28 = 0;
                                $ptotpackamt = $ptotstamt = $ptotothamt = $ptotbillamt = 0;
                                $pchtypecond = "";



                                while ($pmain = mysqli_fetch_array($getpmain2)) {
                                    if ($pmain['paidby'] == "C") {
                                        $ptyped = "CASH";
                                    } else {
                                        $ptyped = "CREDIT";
                                    }


                                    $gparty = mysqli_query($conn, "SELECT `accode`,`name`, gstno,csttin FROM `accmast` where `accode` = '$pmain[party]'") or die(mysqli_error($conn));
                                    $sparty = mysqli_fetch_array($gparty);

                                    // $ggodw = mysqli_query($conn, "SELECT `code`,`gcode` FROM `godown` where `code` = '$pmain[godown]'") or die(mysqli_error($conn));
                                    // $sgodw = mysqli_fetch_array($ggodw);

                                    $mown = mysqli_query($conn, "SELECT `accode`, `name` FROM `accmast` WHERE accode = '$pmain[debitac]' ORDER BY name") or die(mysqli_error($conn));
                                    $trow = mysqli_fetch_array($mown);

                                    $voucher = $pmain['vouchno'];
                                    $invno = $pmain['invno'];
                                    $mydt = $pmain['mydt'];
                                    $gcode = $sgodw['gcode'];
                                    $party = $sparty['name'];
                                    $gstno = $sparty['csttin'];
                                    $gst3 = $pmain['totgst3'];
                                    $gst5 = $pmain['totgst5'];
                                    $gst12 = $pmain['totgst12'];
                                    $gst18 = $pmain['totgst18'];
                                    $gst28 = $pmain['totgst28'];
                                    $billamt = $pmain['billamt'];
                                    $subtot = $pmain['grossamt'];
                                    $totdisc = $pmain['discamt'];
                                    $taxable = $pmain['taxableamt'];

                                    $pctr++;
                                    echo "<tr data-href='purchase_exp.php?mode=edit&vouchno=$voucher' class='clickable-row2' [target]='_blank'>";
                                    echo "<td>$pctr</td>";
                                    echo "<td>$voucher</td>";
                                    echo "<td>$invno</td>";
                                    echo "<td>$mydt</td>";
                                    //                                    Echo"<td>$gcode</td>";
                                    echo "<td>$party</td>";
                                    echo "<td>$gstno</td>";
                                    if ($ptype != "") {
                                        echo "<td>$ptyped</td>";
                                    }
                                    echo "<td class='text-right'>$subtot</td>";
                                    echo "<td class='text-right'>$totdisc</td>";
                                    echo "<td class='text-right'>$taxable</td>";
                                    echo "<td class='text-right'>$gst3</td>";
                                    echo "<td class='text-right'>$gst5</td>";
                                    echo "<td class='text-right'>$gst12</td>";
                                    echo "<td class='text-right'>$gst18</td>";
                                    echo "<td class='text-right'>$gst28</td>";
                                    echo "<td class='text-right'>$billamt</td>";
                                    echo "</tr>";



                                    $pgrsubtot = $pgrsubtot + $subtot;
                                    $pgrtotdis = $pgrtotdis + $totdisc;
                                    $pgrtottaxable = $pgrtottaxable + $taxable;
                                    $pgrtotgst3 = $pgrtotgst3 + $gst3;
                                    $pgrtotgst5 = $pgrtotgst5 + $gst5;
                                    $pgrtotgst12 = $pgrtotgst12 + $gst12;
                                    $pgrtotgst18 = $pgrtotgst18 + $gst18;
                                    $pgrtotgst28 = $pgrtotgst28 + $gst28;
                                    $pgrtotbillamt = $pgrtotbillamt + $billamt;

                                    $ptotpackamt = $ptotpackamt + $pmain['packamt'];
                                    $ptotstamt = $ptotstamt + $pmain['stamt'];
                                    $ptotothamt = $ptotothamt + $pmain['otheramt'];
                                    $ptotbillamt = $ptotbillamt + $pmain['billamt'];


                                    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='' style='background-color:#BABFC2'>";
                                        echo "<th style='width:5%;'>Sr</th>";
                                        echo "<th style='width:15%;' class=''>Expense</th>";
                                        echo "<th style='width:7%;' class=''>HSN Code</th>";
                                        echo "<th style='width:5%;' class='text-right'>Amount</th>";
                                        echo "<th style='width:4%;' class='text-right'>Disc%</th>";
                                        echo "<th style='width:8%;' class='text-right'>Disc. Amt.</th>";
                                        echo "<th style='width:8%;' class='text-right'>Taxable Amount</th>";
                                        if ($gsttype == 1) {
                                            echo "<th style='width:5%;' class='text-right'>IGST Rate</th>";
                                            echo "<th style='width:5%;' class='text-right'>IGST Amount</th>";
                                        } elseif ($gsttype == 2) {
                                            echo "<th style='width:5%;' class='text-right'>CGST Rate</th>";
                                            echo "<th style='width:5%;' class='text-right'>CGST Amount</th>";
                                            echo "<th style='width:5%;' class='text-right'>SGST Rate</th>";
                                            echo "<th style='width:5%;' class='text-right'>SGST Amount</th>";
                                        } elseif ($gsttype == '') {

                                            echo "<th style='width:5%;' class='text-right'>CGST Rate</th>";
                                            echo "<th style='width:5%;' class='text-right'>CGST Amount</th>";
                                            echo "<th style='width:5%;' class='text-right'>SGST Rate</th>";
                                            echo "<th style='width:5%;' class='text-right'>SGST Amount</th>";
                                            echo "<th style='width:5%;' class='text-right'>IGST Rate</th>";
                                            echo "<th style='width:5%;' class='text-right'>IGST Amount</th>";
                                        }
                                        echo "<th style='width:5%;' class='text-right'>Total</th>";
                                        echo "</tr>";
                                        echo "<thead>";
                                        echo "<tr>";

                                        $pctr2 = 0;
                                        $ptotqty = 0;
                                        $ptotrate = 0;
                                        $ptotamount = $ptotdiscount = $ptotsubtot = $ptotcgstamt = $ptotsgstamt = $ptotigstamt = 0;

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

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

                                            $ctr2++;
                                            echo "<tr>";
                                            echo "<td>$ctr2</td>";
                                            echo "<td>$showitem[name]</td>";
                                            echo "<td>$tran[hsncode]</td>";
                                            echo "<td class='text-right'>$tran[amount]</td>";
                                            echo "<td class='text-right'>$tran[discperc]</td>";
                                            echo "<td class='text-right'>$tran[discamt]</td>";
                                            echo "<td class='text-right'>$tran[subtot]</td>";
                                            if ($gsttype == 1) {
                                                echo "<td class='text-right'>$tran[igstrate]</td>";
                                                echo "<td class='text-right'>$tran[igstamt]</td>";
                                            } elseif ($gsttype == 2) {
                                                echo "<td class='text-right'>$tran[cgstrate]</td>";
                                                echo "<td class='text-right'>$tran[cgstamt]</td>";
                                                echo "<td class='text-right'>$tran[sgstrate]</td>";
                                                echo "<td class='text-right'>$tran[sgstamt]</td>";
                                            } elseif ($gsttype == '') {

                                                echo "<td class='text-right'>$tran[cgstrate]</td>";
                                                echo "<td class='text-right'>$tran[cgstamt]</td>";
                                                echo "<td class='text-right'>$tran[sgstrate]</td>";
                                                echo "<td class='text-right'>$tran[sgstamt]</td>";
                                                echo "<td class='text-right'>$tran[igstrate]</td>";
                                                echo "<td class='text-right'>$tran[igstamt]</td>";
                                            }
                                            echo "<td class='text-right'>$tran[amount]</td>";
                                            echo "</tr>";

                                            $ptotqty = $ptotqty + $tran['qty'];
                                            $ptotamount = $ptotamount + $tran['amount'];
                                            $ptotdiscount = $ptotdiscount + $tran['discamt'];
                                            $ptotsubtot = $ptotsubtot + $tran['subtot'];
                                            $ptotcgstamt = $ptotcgstamt + $tran['cgstamt'];
                                            $ptotsgstamt = $ptotsgstamt + $tran['sgstamt'];
                                            $ptotigstamt = $ptotigstamt + $tran['igstamt'];
                                        }

                                        echo "<tr style='background-color:#d8e0e6'>";
                                        echo "<td></td>";
                                        echo "<td></td>";
                                        echo "<td>Total</td>";
                                        echo "<td class='text-right'>$ptotamount</td>";
                                        echo "<td></td>";
                                        echo "<td class='text-right'>$ptotdiscount</td>";
                                        echo "<td class='text-right'>$ptotsubtot</td>";
                                        if ($gsttype == 1) {
                                            echo "<td></td>";
                                            echo "<td class='text-right'>$ptotigstamt</td>";
                                        } elseif ($gsttype == 2) {
                                            echo "<td></td>";
                                            echo "<td class='text-right'>$ptotcgstamt</td>";
                                            echo "<td></td>";
                                            echo "<td class='text-right'>$ptotsgstamt</td>";
                                        } elseif ($gsttype == '') {

                                            echo "<td></td>";
                                            echo "<td class='text-right'>$ptotcgstamt</td>";
                                            echo "<td></td>";
                                            echo "<td class='text-right'>$ptotsgstamt</td>";
                                            echo "<td></td>";
                                            echo "<td class='text-right'>$ptotigstamt</td>";
                                        }
                                        echo "<td class='text-right'>$ptotamount</td>";
                                        echo "</tr>";
                                        echo "</table>";
                                    }
                                }
                                echo "<tr style='background-color: #98F9F0'>";
                                echo "<td></td>";
                                echo "<td></td>";
                                echo "<td></td>";
                                echo "<td></td>";
                                echo "<td></td>";
                                if ($ptype != "") {
                                    echo "<td></td>";
                                }
                                echo "<td class='text-right'><b>Total</b></td>";
                                echo "<td class='numeric text-right'><b>$pgrsubtot</b></td>";
                                echo "<td class='numeric text-right'><b>$pgrtotdis</b></td>";
                                echo "<td class='numeric text-right'><b>$pgrtottaxable</b></td>";
                                echo "<td class='numeric text-right'><b>$pgrtotgst3</b></td>";
                                echo "<td class='numeric text-right'><b>$pgrtotgst5</b></td>";
                                echo "<td class='numeric text-right'><b>$pgrtotgst12</b></td>";
                                echo "<td class='numeric text-right'><b>$pgrtotgst18</b></td>";
                                echo "<td class='numeric text-right'><b>$pgrtotgst28</b></td>";
                                echo "<td class='numeric text-right'><b>$pgrtotbillamt</b></td>";
                                echo "</tr>";
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>

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

    </html>
<?php
}

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

    $mfdt = date("d-m-Y", strtotime($mfrmdate));
    $mtdt = date("d-m-Y", strtotime($mtodate));
    include('includes/head_excel_rep.php');

    if ($getno2 > 0) {
        $contents .= "Purchase Expense Register\n";
        $contents .= "Total No. of Records : $getno2\n";
        if ($ptype != "") {
            $contents .= "Pay Type : $paytype\n";
            $pt = "Pay Type,";
        } else {
            $pt = "";
        }


        $contents .= "Sr, Voucher, Invoice No., Date, Party Name, GST NO.,";
        if ($ptype != "") {
            $contents .= "Pay type,";
        }
        $contents .= "Total, Disc Amt., Taxable, GST 3%, GST 5%, GST 12%, GST 18%, GST 28%, Net Amount \n";

        $pctr = 0;
        $ptotamt = 0;
        $ptotdiscamt = 0;
        $ptottaxable = 0;
        $ptotgst3 = 0;
        $ptotgst5 = 0;
        $ptotgst12 = 0;
        $ptotgst18 = 0;
        $ptotgst28 = 0;
        $ptotpackamt = $ptotstamt = $ptotothamt = $ptotbillamt = 0;
        $pchtypecond = "";



        while ($pmain = mysqli_fetch_array($getpmain2)) {
            if ($pmain['paidby'] == "C") {
                $ptyped = "CASH";
            } else {
                $ptyped = "CREDIT";
            }


            $gparty = mysqli_query($conn, "SELECT `accode`,`name`, gstno,csttin FROM `accmast` where `accode` = '$pmain[party]'") or die(mysqli_error($conn));
            $sparty = mysqli_fetch_array($gparty);

            $mown = mysqli_query($conn, "SELECT `accode`, `name` FROM `accmast` WHERE accode = '$pmain[debitac]' ORDER BY name") or die(mysqli_error($conn));
            $trow = mysqli_fetch_array($mown);

            $voucher = $pmain['vouchno'];
            $invno = $pmain['invno'];
            $mydt = $pmain['mydt'];
            $gcode = $sgodw['gcode'];
            $party = $sparty['name'];
            $gstno = $sparty['csttin'];
            $gst3 = $pmain['totgst3'];
            $gst5 = $pmain['totgst5'];
            $gst12 = $pmain['totgst12'];
            $gst18 = $pmain['totgst18'];
            $gst28 = $pmain['totgst28'];
            $billamt = $pmain['billamt'];
            $subtot = $pmain['grossamt'];
            $totdisc = $pmain['discamt'];
            $taxable = $pmain['taxableamt'];

            $pctr++;
            $contents .= "$pctr" . ",";
            $contents .= "$voucher" . ",";
            $contents .= "$invno" . ",";
            $contents .= "$mydt" . ",";
            $contents .= "$party" . ",";
            $contents .= "$gstno" . ",";
            if ($ptype != "") {
                $contents .= "$ptyped" . ",";
            }
            $contents .= "$subtot" . ",";
            $contents .= "$totdisc" . ",";
            $contents .= "$taxable" . ",";
            $contents .= "$gst3" . ",";
            $contents .= "$gst5" . ",";
            $contents .= "$gst12" . ",";
            $contents .= "$gst18" . ",";
            $contents .= "$gst28" . ",";
            $contents .= "$billamt" . "\n";



            $pgrsubtot = $pgrsubtot + $subtot;
            $pgrtotdis = $pgrtotdis + $totdisc;
            $pgrtottaxable = $pgrtottaxable + $taxable;
            $pgrtotgst3 = $pgrtotgst3 + $gst3;
            $pgrtotgst5 = $pgrtotgst5 + $gst5;
            $pgrtotgst12 = $pgrtotgst12 + $gst12;
            $pgrtotgst18 = $pgrtotgst18 + $gst18;
            $pgrtotgst28 = $pgrtotgst28 + $gst28;
            $pgrtotbillamt = $pgrtotbillamt + $billamt;

            $ptotpackamt = $ptotpackamt + $pmain['packamt'];
            $ptotstamt = $ptotstamt + $pmain['stamt'];
            $ptotothamt = $ptotothamt + $pmain['otheramt'];
            $ptotbillamt = $ptotbillamt + $pmain['billamt'];


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

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

                $pctr2 = 0;
                $ptotqty = 0;
                $ptotrate = 0;
                $ptotamount = $ptotdiscount = $ptotsubtot = $ptotcgstamt = $ptotsgstamt = $ptotigstamt = 0;

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

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

                    $ctr2++;

                    $contents .= "$ctr2" . ",";
                    $contents .= "$showitem[name]" . ",";
                    $contents .= "$tran[hsncode]" . ",";
                    $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[amount]" . "\n";

                    $ptotqty = $ptotqty + $tran['qty'];
                    $ptotamount = $ptotamount + $tran['amount'];
                    $ptotdiscount = $ptotdiscount + $tran['discamt'];
                    $ptotsubtot = $ptotsubtot + $tran['subtot'];
                    $ptotcgstamt = $ptotcgstamt + $tran['cgstamt'];
                    $ptotsgstamt = $ptotsgstamt + $tran['sgstamt'];
                    $ptotigstamt = $ptotigstamt + $tran['igstamt'];
                }

                $contents .= "" . ",";
                $contents .= "" . ",";
                $contents .= "Total" . ",";
                $contents .= "$ptotamount" . ",";
                $contents .= "" . ",";
                $contents .= "$ptotdiscount" . ",";
                $contents .= "$ptotsubtot" . ",";

                $contents .= "" . ",";
                $contents .= "$ptotcgstamt" . ",";
                $contents .= "" . ",";
                $contents .= "$ptotsgstamt" . ",";
                $contents .= "" . ",";
                $contents .= "$ptotigstamt" . ",";
                $contents .= "$ptotamount" . "\n";
            }
        }

        $contents .= "" . ",";
        $contents .= "" . ",";
        $contents .= "" . ",";
        $contents .= "" . ",";
        $contents .= "" . ",";
        if ($ptype != "") {
            $contents .= "" . ",";
        }
        $contents .= "Total" . ",";
        $contents .=  "$pgrsubtot" . ",";
        $contents .=  "$pgrtotdis" . ",";
        $contents .=  "$pgrtottaxable" . ",";
        $contents .=  "$pgrtotgst3" . ",";
        $contents .=  "$pgrtotgst5" . ",";
        $contents .=  "$pgrtotgst12" . ",";
        $contents .=  "$pgrtotgst18" . ",";
        $contents .=  "$pgrtotgst28" . ",";
        $contents .=  "$pgrtotbillamt" . "\n";
    }

    $contents = strip_tags($contents);

    if ($_POST["dtype"] == 1 || $_POST["dtype"] == 3) {
        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' $suppcond $ptypecond  $pcond
                ORDER BY vouchdt ASC") or die(mysqli_error($conn));

    // Initialize CSV content with headers
    $contents = "Sr.,Invoice,Date,Party,Address, State, Pin, Country, GST No.,Expense,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)) {

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

        
        $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['invno'];
            if ($prevvouch == $newvouch) {
                $vouchno = '';  // Empty for duplicate voucher numbers
                $litemdisc = '';
                $discount = '';
                $billaddress = '';
                $suppstate = '';
                $suppin = '';
                $suppcountry = '';
                $packing = '';
                $tottaxamt = '';
                $totgst5 = '';
                $totgst12 = '';
                $totgst18 = '';
                $totgst28 = '';
                $roundoff = "";
                $roundoffdrcr = "";
                $netamt = '';
                } else {
                    $vouchno = $newvouch;  // Show the voucher number for new vouchers
                    $prevvouch = $newvouch;  // Update the previous voucher number
                    $billaddress = str_replace(",", " ", $supp['add1'] . ' ' . $supp['add2'] . ' ' . $supp['add3']);
                    $suppstate = $supp['state'];
                    $suppin = $supp['pin'];
                    $suppcountry = $supp['country'];
                $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['billamt'];
                $roundoff = "$pmain[roundoff]";
                if ($roundoff > 0) {
                    $roundoffdrcr = "DR";
                } else {
                    $roundoffdrcr = "CR";
                }
                $newline = $contents .= "\n";
            }
            $getitem = mysqli_query($conn, "SELECT `accode`,`name` FROM `accmast` WHERE `accode`='$tran[expense]'") or die(mysqli_error($conn));
            $showitem = mysqli_fetch_array($getitem);


            $contents .= "{$sr},";
            $contents .= "{$vouchno},";
            $contents .= "{$pmain['mydt']},";
            $contents .= "{$supp['name']},";
            $contents .= "{$billaddress},";
            $contents .= "{$suppstate},";
            $contents .= "{$suppin},";
            $contents .= "{$suppcountry},";
            $contents .= "{$supp['gstno']},";
            $contents .= "{$showitem['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' $suppcond $ptypecond  $pcond
                ORDER BY vouchdt ASC") or die(mysqli_error($conn));

    // Initialize CSV content with headers
    $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, 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,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` 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['invno'];
            if ($prevvouch == $newvouch) {
                $vouchno = '';
                $refno = "";
                $refdt = "";
                $ordno = "";
                $orddt = "";
                $termspay = "";
                $othref = "";
                $termsdelv = "";
                $ledgername = "";
                $ledgeramt = "";
                $ledgerrate = "";
                $ledgeramtcrdr = "";
                $itemrateper = "";
                $changemod = "";
                $billtyperef = "";
                $billname = "";
                $billamt = "";
                $billamtdrcr = "Dr";
                $billduedt = "";
                $vouchnarr = "";
                $einvbilltoplace = "";
                $einvshiptoplace = "";
                $einvdisname = "";
                $einvdisadd = "";
                $einvdisstate = "";
                $einvdispin = "";
                $einvdisplace = "";
                $litemdisc = '';
                $discount = '';
                $packing = '';
                $tottaxamt = '';
                $totgst5 = '';
                $totgst12 = '';
                $totgst18 = '';
                $totgst28 = '';
                $netamt = '';
            } else {
                $vouchno = $newvouch;
                $refno = "";
                $refdt = "";
                $ordno = "";
                $orddt = "";
                $termspay = "";
                $othref = "";
                $termsdelv = "";
                $ledgername = "";
                $ledgeramt = "";
                $ledgerrate = "";
                $ledgeramtcrdr = "";
                $itemrateper = "";
                $changemod = "";
                $billtyperef = "";
                $billname = "";
                $billamt = "";
                $billamtdrcr = "Dr";
                $billduedt = "";
                $vouchnarr = "";
                $einvbilltoplace = "";
                $einvshiptoplace = "";
                $einvdisname = "";
                $einvdisadd = "";
                $einvdisstate = "";
                $einvdispin = "";
                $einvdisplace = "";
                $prevvouch = $newvouch;
                $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['billamt'];
                $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);

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

            $contents .= "{$sr},";
            $contents .= "{$pmain['mydt']},";
            $contents .= "Purchase Invoice,";
            $contents .= "{$vouchno},";
            $contents .= "{$refno},";
            $contents .= "{$refdt},";
            $contents .= "{$suppadd},";
            $contents .= "{$supp['gstno']},";
            $contents .= "{$supp['state']},";
            $contents .= "{$supp['pin']},";
            $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 .= "{$billamt},";
            $contents .= "{$billamtdrcr},";
            $contents .= "{$billduedt},";
            $contents .= "{$vouchnarr},";
            $contents .= "{$einvsbilltoplace},";
            $contents .= "{$einvshiptoplace},";
            $contents .= "{$einvdisname},";
            $contents .= "{$einvdisadd},";
            $contents .= "{$einvdisstate},";
            $contents .= "{$einvdispin},";
            $contents .= "{$einvdisplace}\n";


            // $contents .= "{$supp['name']},";
            // $contents .= "{$tran['barcode']},";
            // $contents .= "{$color['name']},";
            // $contents .= "{$tran['hsncode']},";
            // $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}\n";
            // $newline;

            $sr++;
        }
    }

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