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

$maindb = 'debrawmain';
$trandb = 'debothraw';
$formname = "Purchase Return / Debit Note Register";

$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)) {
    if ($scope == 1) {
        $mscopecond = " AND `unclaimgst`=''";
    } else {
        $mscopecond = " AND `unclaimgst`='1' ";
    }
}

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' AND credtype = 'O'  $partycond $mscopecond order by vouchno ") or die(mysqli_error($conn));

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

    include("includes/linkshead.php");
    $mfdt = date("d-m-Y", strtotime($mfrmdate));
    $mtdt = date("d-m-Y", strtotime($mtodate));
?>
    <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" style="width:1400px">
            <?php include("includes/head_rep.php"); ?>

            <div class="row">
                <div class="col-lg-12 ">
                    <table style="background: white;width: 100%" class="table table-striped table-condensed table-bordered table-hover">
                        <thead class="mySearchTr">
                            <tr>
                                <th width='5%'>Voucher</th>
                                <th width='5%'>Invoice</th>
                                <th width='7%'>Date</th>
                                <th width='19%'>Supplier</th>
                                <th width='7%' class="">GST No.</th>
                                <th width='7%' class="text-right">Amount</th>
                                <th width='7%' class="text-right">Taxable Value</th>
                                <th width='6%' class="text-right">CGST %</th>
                                <th width='6%' class="text-right">CGST Amt.</th>
                                <th width='6%' class="text-right">SGST %</th>
                                <th width='6%' class="text-right">SGST Amt.</th>
                                <th width='6%' class="text-right">IGST %</th>
                                <th width='6%' class="text-right">IGST Amt.</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;


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

                                $unclaimgst = $pmain["unclaimgst"];

                                $colr = "";
                                $unclaimhead = "";
                                if ($unclaimgst == "1") {
                                    $colr = "style='color:#ff006e'";
                                    $unclaimhead = " - Unclaimed GST";
                                }

                                $ctr++;
                                echo "<tr id='boldfont'>";
                                echo "<td>$pmain[vouchno]</td>";
                                echo "<td>$pmain[invno]</td>";
                                echo "<td>$pmain[mydt]</td>";
                                echo "<td $colr>$supp[name]$unclaimhead</td>";
                                echo "<td $colr>$supp[gstno]</td>";
                                echo "<td class='text-right'>$pmain[subtotal]</td>";
                                echo "<td class='text-right'>$pmain[tottaxamt]</td>";
                                echo "<td class='text-right'>$pmain[cgstperc]</td>";
                                echo "<td class='text-right'>$pmain[totcgst]</td>";
                                echo "<td class='text-right'>$pmain[sgstperc]</td>";
                                echo "<td class='text-right'>$pmain[totsgst]</td>";
                                echo "<td class='text-right'>$pmain[igstperc]</td>";
                                echo "<td class='text-right'>$pmain[totigst]</td>";
                                echo "<td class='text-right'>$pmain[netamt]</td>";
                                echo "</tr>";

                                $ttotamt = $ttotamt + $pmain['subtotal'];
                                $tottottaxamt = $tottottaxamt + $pmain['tottaxamt'];

                                $tottotcgst     += $pmain['totcgst'];
                                $tottotsgst     += $pmain['totsgst'];
                                $tottotigst    += $pmain['totigst'];
                                $ttotalamount += $pmain['netamt'];

                                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='40%' class='dtype'>Description</th>";
                                    echo "<th width='10%' class='numeric dtype'>Amount</th>";
                                    echo "<tr>";

                                    $ctr2 = 0;
                                    $totamt = 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)) {

                       
                                        $ctr2++;
                                        echo "<tr>";
                                        echo "<td>$ctr2</td>";
                                        echo "<td>$tran[descrip]</td>";
                                        echo "<td class='numeric'>$tran[amount]</td>";
                                        echo "</tr>";

                                        $totamt = $totamt + $tran['amount'];
                                    }

                                    $colr1 = "blue";
                                    
                                    echo "<tr>";
                                    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='numeric'><h5><b>$totamt</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 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>$tottottaxamt</b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b></b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b>$tottotcgst</b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b></b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b>$tottotsgst</b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b></b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b>$tottotigst</b></h4></td>";
                            echo "<td align='right' style='color:$colr;' id='font'><h4><b>$ttotalamount</b></h4></td>";
                            echo "</tr>";
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </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));

    $contents .= "Voucher, Invoice, Date, Supplier, GST No., Amount, Taxable Value, CGST %, CGST Amt, SGST %, SGST Amt, IGST %, IGST Amt, Bill Amt. \n";
    
                            $ctr = 0;
                            $ttotamt = 0;
                            $totpack = 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);

                                $ctr++;
                                $contents .= "$pmain[vouchno]" . ",";
                                $contents .= "$pmain[invno]" . ",";
                                $contents .= "$pmain[mydt]" . ",";
                                $contents .= "$supp[name]" . ",";
                                $contents .= "$supp[gstno]" . ",";
                                $contents .= "$pmain[subtotal]" . ",";
                                $contents .= "$pmain[tottaxamt]" . ",";
                                $contents .= "$pmain[cgstperc]" . ",";
                                $contents .= "$pmain[totcgst]" . ",";
                                $contents .= "$pmain[sgstperc]" . ",";
                                $contents .= "$pmain[totsgst]" . ",";
                                $contents .= "$pmain[igstperc]" . ",";
                                $contents .= "$pmain[totigst]" . ",";
                                $contents .= "$pmain[netamt]" . "\n";
                                
                                $ttotamt = $ttotamt + $pmain['subtotal'];
                                $tottottaxamt = $tottottaxamt + $pmain['tottaxamt'];

                                $tottotcgst     += $pmain['totcgst'];
                                $tottotsgst     += $pmain['totsgst'];
                                $tottotigst    += $pmain['totigst'];
                                $ttotalamount += $pmain['netamt'];

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

                                    $contents .= "Sr., Description, Amount \n";
                                    
                                    $ctr2 = 0;
                                    $totamt = 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)) {

                                        $ctr2++;
                                        $contents .= "$ctr2" . ",";
                                        $contents .= "$tran[descrip]" . ",";
                                        $contents .= "$tran[amount]" . "\n";

                                        $totamt = $totamt + $tran['amount'];
                                    }

                                    $colr1 = "blue";
                                    
                                    $contents .= "" . ",";
                                    $contents .= "Total" . ",";
                                    $contents .= "$totamt" . "\n";
                                }
                            }

                            $colr = "green";
                            $contents .= "" . ",,,,";
                            $contents .= "Total" . ",";
                            $contents .= "$ttotamt" . ",";
                            $contents .= "$tottottaxamt" . ",";
                            $contents .= "" . ",";
                            $contents .= "$tottotcgst" . ",";
                            $contents .= "" . ",";
                            $contents .= "$tottotsgst" . ",";
                            $contents .= "" . ",";
                            $contents .= "$tottotigst" . ",";
                            $contents .= "$ttotalamount" . "\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));

    $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, Description\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);
        
        $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 = '';  // Empty for duplicate voucher numbers
                $litemdisc = '';
                $discount = '';
                $packing = '';
                $tottaxamt = '';
                $cgstperc = '';
                $totcgst = '';
                $sgstperc = '';
                $totsgst = '';
                $igstperc = '';
                $totigst = '';
                $totgst5 = '';
                $totgst12 = '';
                $totgst18 = '';
                $totgst28 = '';
                $roundoff = '';
                $roundoffdrcr = '';
                $netamt = '';
                $suppname = '';
                $suppaddress = '';
                $suppstate = '';
                $suppcountry = '';
                $supppin = '';
            } else {
                $vouchno = $newvouch;  // Show the voucher number for new vouchers
                $invno = $pmain['invno'];
                $prevvouch = $newvouch;  // Update the previous voucher number
                $litemdisc = $pmain['litemdisc'];
                $discount = $pmain['discount'];
                $packing = $pmain['packing'];
                $tottaxamt = $pmain['tottaxamt'];
                $totgst5 = $pmain['totgst5'];
                $totgst12 = $pmain['totgst12'];
                $totgst18 = $pmain['totgst18'];
                $totgst28 = $pmain['totgst28'];
                $cgstperc = $pmain['cgstperc'];
                $totcgst = $pmain['totcgst'];
                $sgstperc = $pmain['sgstperc'];
                $totsgst = $pmain['totsgst'];
                $igstperc = $pmain['igstperc'];
                $totigst = $pmain['totigst'];
                $netamt = $pmain['netamt'];
                $add = $supp['add1'] . " " . $supp['add2'] . " " . $supp['add3'];
                $suppaddress = str_replace(",", " ", $add);
                $suppname = $supp['name'];
                $suppstate = $supp['state'];
                $suppcountry = $supp['country'];
                $supppin = $supp['pin'];
                $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 .= "{$pmain['mydt']},";
            $contents .= "{$suppname},";
            $contents .= "{$suppaddress},";
            $contents .= "{$suppstate},";
            $contents .= "{$suppcountry},";
            $contents .= "{$supppin},";
            $contents .= "{$supp['gstno']},";
            $contents .= "{$item['name']},";
            $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['amount']},";
            $contents .= "{$cgstperc},";
            $contents .= "{$totcgst},";
            $contents .= "{$sgstperc},";
            $contents .= "{$totsgst},";
            $contents .= "{$igstperc},";
            $contents .= "{$totigst},";
            $contents .= "{$tran['amount']},";
            $contents .= "{$litemdisc},";
            $contents .= "{$discount},";
            $contents .= "{$packing},";
            $contents .= "{$tottaxamt},";
            $contents .= "{$totgst5},";
            $contents .= "{$totgst12},";
            $contents .= "{$totgst18},";
            $contents .= "{$totgst28},";
            $contents .= "{$netamt},";
            $contents .= "{$roundoff},";
            $contents .= "{$roundoffdrcr},";
            $contents .= "{$tran['descrip']}\n";
            $newline;

            $sr++;
        }
    }

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