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

$maindb = 'debmain';
$trandb = 'deboth';
$formname = "Debit Note (Others) Register";
$file = "debothreg_fr.php";
$keycond = " and `credtype` = 'O'";

$zroot = 'cepheisy_msp_root';

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

$party = $_POST["party"];
$dtype = $_POST["dtype"];
$scope = $_POST["scope"];
$gstperc = $_POST["gstperc"];

$mscopecond = "";
$gstcond = "";
$partycond = "";

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

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


//    if (!empty($frmdt)) {
//        $frmdtcond = " AND `vouchdt`='$frmdt' ";
//    }
//
//    if (!empty($todt)) {
//        $todtcond = " AND `todt`='$todt' ";
//    }

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

if (!empty($gstperc)) {
    $gstcond = " AND a.`gstperc`='$gstperc' ";
}

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

$getpmain = mysqli_query($conn, "SELECT *, DATE_FORMAT(`vouchdt`, '%d-%m-%Y') as mydt FROM `$maindb` WHERE `vouchdt` >= '$mfrmdate' 
                            AND `vouchdt` <= '$mtodate' $keycond $gstcond $partycond $mscopecond ") or die(mysqli_error($conn));
$get = mysqli_num_rows($getpmain);
//    browse($get);
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;
        }
    </style>
    <!--<script src="MyScript/item.js" type="text/javascript"></script>-->
    </head>
    <body>
        <div class="container" style="width:1300px">
            <?php include("includes/head_rep.php"); ?>
            <div class="row">
                <div class="col-lg-12 pad">
                    <table style="background: white;width: 100%" class="table table-bordered table-condensed table-hover">
                        <thead class="mySearchTr">
                            <tr>
                                <th style="width:5%">Sr</th>
                                <th style="width:5%">Inv.No</th>
                                <th style="width:10%">Date</th>
                                <th style="width:10%">Party</th>
                                <th width='5%'>GST No.</th>
                                <th style="width:5%" class="text-right">Amount</th>
                                <th style="width:5%" class="text-right">Item Disc</th>
                                <th style="width:4%" class="text-right">Cash Disc%</th>
                                <th style="width:5%" class="text-right">Cash Disc Amt</th>
                                <th style="width:5%" class="text-right">Less Disc</th>
                                <th style="width:5%" class="text-right">Add Pack</th>
                                <th style="width:5%" class="text-right">Taxable Value</th>
                                <th width='6%' class="text-right">GST 5%</th>
                                <th width='6%' class="text-right">GST 12%</th>
                                <th width='6%' class="text-right">GST 18%</th>
                                <th width='5%' class="text-right">GST 28%</th>
                                <th style="width:9%" class="text-right">Bill.Amt</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $ctr = 0;
                            $tottaxamt = 0;
                            $totgst5 = 0;
                            $totgst12 = 0;
                            $totgst18 = 0;
                            $totgst28 = 0;
                            $totbill = 0;
                            $totamt = 0;
                            $totdisc = 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";
                                }

                                $mtotgst5 = 0;
                                $mtotgst12 = 0;
                                $mtotgst18 = 0;
                                $mtotgst28 = 0;

                                if ($pmain['credtype'] == "O") {

                                    // OMS condition
                                    if ($pmain['oms'] == 1) {
                                        $gstAmount = $pmain['totigst'];
                                    } else {
                                        $gstAmount = $pmain['totcgst'] + $pmain['totsgst'];
                                    }

                                    switch ($pmain['gstperc']) {
                                        case 1: $mtotgst5 = $gstAmount;
                                            break;
                                        case 2: $mtotgst12 = $gstAmount;
                                            break;
                                        case 3: $mtotgst18 = $gstAmount;
                                            break;
                                        case 4: $mtotgst28 = $gstAmount;
                                            break;
                                    }
                                } else {
                                    $mtotgst5 = $pmain['totgst5'];
                                    $mtotgst12 = $pmain['totgst12'];
                                    $mtotgst18 = $pmain['totgst18'];
                                    $mtotgst28 = $pmain['totgst28'];
                                }

                                $ctr++;
                                Echo "<tr id='boldfont'>";
                                Echo "<td>$ctr</td>";
                                Echo "<td>$pmain[vouchno]</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[litemdisc]</td>";
                                Echo "<td class='text-right'>$pmain[cdiscperc]</td>";
                                Echo "<td class='text-right'>$pmain[cdiscamt]</td>";
                                Echo "<td class='text-right'>$pmain[lesother]</td>";
                                Echo "<td class='text-right'>$pmain[packing]</td>";
                                Echo "<td class='text-right'>$pmain[tottaxamt]</td>";
                                Echo "<td class='text-right'>$mtotgst5</td>";
                                Echo "<td class='text-right'>$mtotgst12</td>";
                                Echo "<td class='text-right'>$mtotgst18</td>";
                                Echo "<td class='text-right'>$mtotgst28</td>";
                                Echo "<td class='text-right'>$pmain[netamt]</td>";
                                Echo "</tr>";

                                $tottaxamt = $tottaxamt + $pmain['tottaxamt'];
                                $totgst5 = $totgst5 + $mtotgst5;
                                $totgst12 = $totgst12 + $mtotgst12;
                                $totgst18 = $totgst18 + $mtotgst18;
                                $totgst28 = $totgst28 + $mtotgst28;
                                $totbill = $totbill + $pmain['netamt'];
                                $totamt = $totamt + $pmain['subtotal'];
                                $totdisc = $totdisc + $pmain['discount'];

                                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 style='background-color: #cccccc;width:5%;'>Sr</th>";
                                    Echo "<th style='background-color: #cccccc;width:80%; class='numeric''>Description</th>";
                                    Echo "<th style='background-color: #cccccc;width:10%;' class='numeric'>Amount</th>";
                                    Echo "</tr>";

                                    $ctr2 = 0;
                                    $tot = 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 * FROM `item` WHERE `code`='$tran[item]'") or die(mysqli_error($conn));
                                        $item = mysqli_fetch_array($getitem);

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

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

                                    Echo "<tr style=' '>";
                                    Echo "<td style=' 'class='numeric'></td>";
                                    Echo "<th style='text-align:right;color:blue; '>Total</th>";
                                    Echo "<th style='text-align:right;color:blue; '>$tot</td>";
                                    Echo "</tr>";
                                    Echo "</table>";
                                    Echo "</td>";
                                }
                            }
                            $colr = "red";
                            echo "<tr> ";
                            echo "<td></td>";
                            echo "<td></td>";
                            echo "<td></td>";
                            echo "<td></td>";
                            echo "<td></td>";
                            echo "<td></td>";
                            echo "<td></td>";
                            echo "<td></td>";
                            echo "<td></td>";
                            echo "<td align='right' colspan='2' style='color:$colr;'><h4><b>Grand Total</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"])) {

    $contents .= "Sr, Inv.No, Date, Party, GST NO., Amount, Item Disc, Cash Disc%, Cash Disc Amt, Less Disc, Add Pack, Taxable Value, GST 5%,GST 12%,GST 18%,GST 28%, Bill.Amt \n";

    $ctr = 0;
    $tottaxamt = 0;
    $totgst5 = 0;
    $totgst12 = 0;
    $totgst18 = 0;
    $totgst28 = 0;
    $totbill = 0;
    $totamt = 0;
    $totdisc = 0;

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

        $mtotgst5 = 0;
        $mtotgst12 = 0;
        $mtotgst18 = 0;
        $mtotgst28 = 0;

        if ($pmain['credtype'] == "O") {

            // OMS condition
            if ($pmain['oms'] == 1) {
                $gstAmount = $pmain['totigst'];
            } else {
                $gstAmount = $pmain['totcgst'] + $pmain['totsgst'];
            }

            switch ($pmain['gstperc']) {
                case 1: $mtotgst5 = $gstAmount;
                    break;
                case 2: $mtotgst12 = $gstAmount;
                    break;
                case 3: $mtotgst18 = $gstAmount;
                    break;
                case 4: $mtotgst28 = $gstAmount;
                    break;
            }
        } else {
            $mtotgst5 = $pmain['totgst5'];
            $mtotgst12 = $pmain['totgst12'];
            $mtotgst18 = $pmain['totgst18'];
            $mtotgst28 = $pmain['totgst28'];
        }

        $ctr++;

        $contents .= $ctr . ",";
        $contents .= $pmain['vouchno'] . ",";
        $contents .= $pmain['mydt'] . ",";
        $contents .= $supp['name'] . ",";
        $contents .= $pmain['subtotal'] . ",";
        $contents .= $pmain['litemdisc'] . ",";
        $contents .= $pmain['cdiscperc'] . ",";
        $contents .= $pmain['cdiscamt'] . ",";
        $contents .= $pmain['lesother'] . ",";
        $contents .= $pmain['packing'] . ",";
        $contents .= $pmain['tottaxamt'] . ",";
        $contents .= $mtotgst5 . ",";
        $contents .= $mtotgst12 . ",";
        $contents .= $mtotgst18 . ",";
        $contents .= $mtotgst28 . ",";
        $contents .= $pmain['netamt'] . "\n";

        $tottaxamt = $tottaxamt + $pmain['tottaxamt'];
        $totgst5 = $totgst5 + $mtotgst5;
        $totgst12 = $totgst12 + $mtotgst12;
        $totgst18 = $totgst18 + $mtotgst18;
        $totgst28 = $totgst28 + $mtotgst28;
        $totbill = $totbill + $pmain['netamt'];
        $totamt = $totamt + $pmain['subtotal'];
        $totdisc = $totdisc + $pmain['discount'];

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

            $contents .= "Sr, Description, Amount \n";

            $ctr2 = 0;
            $tot = 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 * FROM `item` WHERE `code`='$tran[item]'") or die(mysqli_error($conn));
                $item = mysqli_fetch_array($getitem);

                $ctr2++;

                $contents .= $ctr . ",";
                $contents .= $tran['descrip'] . ",";
                $contents .= $tran['amount'] . "\n";

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

            $contents .= "" . ",";
            $contents .= "Total" . ",";
            $contents .= $tot . "\n";
        }
    }
    $colr = "red";

    $contents .= "" . ",";
    $contents .= "" . ",";
    $contents .= "" . ",";
    $contents .= "" . ",";
    $contents .= "" . ",";
    $contents .= "" . ",";
    $contents .= "" . ",";
    $contents .= "" . ",";
    $contents .= "" . ",";
    $contents .= "" . ",";
    $contents .= "Grand Total" . ",";
    $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));

    $contents  .= "Sr.,	Invoice, Date, Party, Address, State, Pin,Country, GST No., 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, 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
                $mydt = '';
                $suppname = '';
                $suppadd = '';
                $suppstate = '';
                $supppin = '';
                $suppgstno = '';
                $suppcountry = '';
                $litemdisc = '';
                $discount = '';
                $packing = '';
                $tottaxamt = '';
                $cgstperc = '';
                $totcgst = '';
                $sgstperc = '';
                $totsgst = '';
                $igstperc = '';
                $totigst = '';
                $totgst5 = '';
                $totgst12 = '';
                $totgst18 = '';
                $totgst28 = '';
                $roundoff = '';
                $roundoffdrcr = '';
                $netamt = '';
            } else {
                $vouchno = $newvouch;  // Show the voucher number for new vouchers
                $invno = $pmain['invno'];
                $prevvouch = $newvouch;  // Update the previous voucher number
                $mydt = $pmain['mydt'];
                $suppname = str_replace(",", " ", $supp['name']);
                $suppadd = str_replace(",", " ", $supp['add1']) . str_replace(",", " ", $supp['add2']) . str_replace(",", " ", $supp['add3']);
                $suppstate = $supp['state'];
                $suppcountry = $supp['country'];
                $supppin = $supp['pin'];
                $suppgstno = $supp['gstno'];
                $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'];
                $roundoff = $pmain['roundoff'];
                
                if ($roundoff > 0) {
                    $roundoffdrcr = "CR";
                    } else {
                    $roundoffdrcr = "DR";
                }
                $newline = $contents .= "\n";
            }
            $getitem = mysqli_query($conn, "SELECT `code`,`name` FROM `item` WHERE `code`='{$tran['itemcode']}'") 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 .= "{$suppadd},";
            $contents .= "{$suppstate},";
            $contents .= "{$supppin},";
            $contents .= "{$suppcountry},";
            $contents .= "{$suppgstno},";
            $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['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;
}
?>   
