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

$maindb = "rawmain";
$trandb = "rawtran";
$formname = "GSTR2_1";
$file = "gstr2_b2b.php";

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

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

    include('includes/head_excel_rep.php');

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

    $para = $_REQUEST["para"];
    if ($para == "P") {     // && finished product
        $maindb = "pgstmain";
        $trandb = "pgsttran";
        $maindb2 = 'debmain';
        $trandb2 = 'debtran';
        $mattype = "Finished Products";
    } else {                  //  && raw material
        $maindb = "purrawmain";
        $trandb = "purrawtran";
        $maindb2 = 'debrawmain';
        $trandb2 = 'debrawtran';
        $trandb_oth = 'debothraw';

        $mattype = "Raw Material";
    }
    
    if (empty($_POST["fdate"])) {
        browse("From Date Cannot Be Empty");
    }
    if (empty($_POST["tdate"])) {
        browse("To Date Cannot Be Empty");
    }

//    $getpmain = mysqli_query($conn, "SELECT 'P' as mode, a.vouchno, a.invno, a.vouchdt, DATE_FORMAT(a.`vouchdt`, '%d-%m-%Y') as mydt, sum(b.cgstamt) as cgst, sum(b.igstamt) as igst, 
//                                           (b.cgstrate + b.sgstrate + b.igstrate) as gstperc, sum(b.subtot) as tamt, a.netamt 
//                                            FROM `$maindb` a, `$trandb` b 
//                                            WHERE a.`vouchdt` >= '$mfrmdate' AND a.`vouchdt` <= '$mtodate' and
//                                            a.party in (select accode from accmast where gstno != '') and a.vouchno = b.vouchno 
//                                            group by mode, vouchno, gstperc order by vouchdt, invno ") or die(mysqli_error($conn));
    
    $getpmain = mysqli_query($conn, "SELECT * from 
                                        (select 'P' as mode, a.vouchno, a.invno, a.vouchdt, a.party, DATE_FORMAT(a.`vouchdt`, '%d-%m-%Y') as mydt, sum(b.cgstamt) as cgst, sum(b.igstamt) as igst, 
                                           (b.cgstrate + b.sgstrate + b.igstrate) as gstperc, sum(b.subtot) as tamt, a.netamt 
                                            FROM `$maindb` a, `$trandb` b 
                                            WHERE a.`vouchdt` >= '$mfrmdate' AND a.`vouchdt` <= '$mtodate' and
                                            a.party in (select accode from accmast where gstno != '') and a.vouchno = b.vouchno 
                                            group by vouchno, gstperc
                                        union all
                                        select 'E' as mode, a.vouchno, a.invno, a.vouchdt, a.party, DATE_FORMAT(a.`vouchdt`, '%d-%m-%Y') as mydt, sum(b.cgstamt) as cgst, sum(b.igstamt) as igst, 
                                           (b.cgstrate + b.sgstrate + b.igstrate) as gstperc, sum(b.subtot) as tamt, a.billamt as netamt
                                            FROM `purexpmain` a, `purexptran` b 
                                            WHERE a.`vouchdt` >= '$mfrmdate' AND a.`vouchdt` <= '$mtodate' and
                                            a.party in (select accode from accmast where gstno != '') and a.vouchno = b.vouchno 
                                            group by vouchno, gstperc) a
                                        order by vouchdt, invno ") or die(mysqli_error($conn));
    
    
    $get = mysqli_num_rows($getpmain);
//    browse($get);
//    print table($getpmain);
//    die();

    $contents .= "GST No., Receiver Name, Inv. No, Inv. Date, Type, Inv. Value, Place of Supply,Reverse Charge, Applicable % of Tax Rate, Inv. Type, E-Comm GST, Rate, Taxable Value, Integrated Tax Paid, Central Tax Paid, State/UT Tax Paid, Cess Paid, Eligible For ITC, Availed ITC Integrated Tax, Availed ITC Central Tax, Availed ITC State/UT Tax, Availed ITC Cess\n";

    $ctr = 0;
    $totamt = 0;
    $totdisc = 0;
    $totbill = 0;

    while ($pmain = mysqli_fetch_array($getpmain)) {
        $qrecpgst = mysqli_query($conn, "SELECT `gstno`, `state`, `statecode`,`accode`, `name` from `accmast` where `accode`= '$pmain[party]' ")or die(mysqli_error($conn));
        $frecpgst = mysqli_fetch_array($qrecpgst);

        $ctr++;
        $gstno = $frecpgst['gstno'];
        $invno = $pmain['invno'];
        $invdt = $pmain['mydt'];

        $state = $frecpgst['state'];
        $stcode = $frecpgst['statecode'];
        $revchrg = "N";
        $invtype = "Regular";
        $ecommgst = '';

//        if ($pmain[oms] == '') {
//          $gstrate = $pmain[cgstperc] * 2;
//        } else {
//          $gstrate = $pmain[igstperc];
//        }
        $invval = $pmain['netamt'];
        $rate = $pmain['gstperc'];
        $taxval = $pmain['tamt'];
        $cess = '';


//        $contents.= $ctr . ",";
        $contents .= $gstno . ",";
        $contents .= $frecpgst['name'] . ",";
        $contents .= $invno . ",";
        $contents .= $invdt . ",";
        $contents .= $mattype . ",";
        $contents .= $invval . ",";
        $contents .= $stcode . '-' . $state . ",";
        $contents .= $revchrg . ",";
        $contents .= "" . ",";
        $contents .= $invtype . ",";
        $contents .= $ecommgst . ",";
        $contents .= $rate . ",";
        $contents .= $taxval . ",";
        $contents .= $pmain['igst'] . ",";
        $contents .= $pmain['cgst'] . ",";
        $contents .= $pmain['cgst'] . ",";
        $contents .= $cess . ",";
        $contents .= "" . ",";
        $contents .= "" . ",";
        $contents .= "" . ",";
        $contents .= "" . "\n";

        $totinvval = $totinvval + $invval;
        $tottaxval = $tottaxval + $taxval;
        $totcgst = $totcgst + $pmain['cgst'];
        $totigst = $totigst + $pmain['igst'];
    }

    if ($tottaxval > 0) {

        $contents .= " " . ",";
        $contents .= " " . ",";
        $contents .= " " . ",";
        $contents .= "Total" . ",";
        $contents .= "" . ",";
        $contents .= $totinvval . ",";
        $contents .= " " . ",";
        $contents .= " " . ",";
        $contents .= " " . ",";
        $contents .= " " . ",";
        $contents .= " " . ",";
        $contents .= " " . ",";
        $contents .= $tottaxval . ",";
        $contents .= $totigst . ",";
        $contents .= $totcgst . ",";
        $contents .= $totcgst . ",";
        $contents .= " " . ",";
        $contents .= "" . ",";
        $contents .= "" . ",";
        $contents .= "" . ",";
        $contents .= "" . ",";
//    $contents.= " " . ",";
        $contents .= "" . "\n";
        $contents .= "\n";
    }

    if ($para == "P") {     // && finished product
        $getpmain2 = mysqli_query($conn, "SELECT a.*, DATE_FORMAT(a.`vouchdt`, '%d-%m-%Y') as mydt, sum(b.cgstamt) as cgst,sum(b.igstamt) as igst, 
                             (b.cgstrate + b.sgstrate + b.igstrate) as gstperc, sum(b.subtot) as tamt  FROM `$maindb2` a, `$trandb2` b 
                             WHERE a.`vouchdt` >= '$mfrmdate' AND a.`vouchdt` <= '$mtodate' and a.party in (select accode from accmast where gstno != '') 
                             and a.vouchno = b.vouchno group by b.vouchno,b.gstperc order by a.vouchdt, a.invno ")or die(mysqli_error($conn));
        $get2 = mysqli_num_rows($getpmain2);
        
        $contents .= "\n\n Debit Note \n";
    } else {
        $getpmain2 = mysqli_query($conn, "select * from 
                             (SELECT a.invno, a.netamt, a.vouchdt, a.party, DATE_FORMAT(a.`vouchdt`, '%d-%m-%Y') as mydt, 
                                     sum(b.cgstamt) as cgst,sum(b.igstamt) as igst, (b.cgstrate + b.sgstrate + b.igstrate) as gstperc, 
                                     sum(b.subtot) as tamt  FROM `$maindb2` a, `$trandb2` b 
                                     WHERE a.`vouchdt` >= '$mfrmdate' AND a.`vouchdt` <= '$mtodate' and a.credtype != 'O' 
                                     and a.party in (select accode from accmast where gstno != '') 
                                     and a.vouchno = b.vouchno group by b.vouchno,b.gstperc
                             union all        
                             SELECT a.invno, a.netamt, a.vouchdt, a.party, DATE_FORMAT(a.`vouchdt`, '%d-%m-%Y') as mydt, 
                                     (a.totcgst) as cgst, (a.totigst) as igst, (a.cgstperc + a.sgstperc + a.igstperc) as gstperc, 
                                     a.subtotal as tamt  FROM `$maindb2` a, `$trandb_oth` b 
                                     WHERE a.`vouchdt` >= '$mfrmdate' AND a.`vouchdt` <= '$mtodate' and a.credtype = 'O' 
                                     and a.party in (select accode from accmast where gstno != '') 
                                     and a.vouchno = b.vouchno group by a.vouchno ) a 
                             order by vouchdt, invno ") or die(mysqli_error($conn));

        $get2 = mysqli_num_rows($getpmain2);
        
    }

    $contents .= "GST No., Receiver Name, Inv. No, Inv. Date, Type, Inv. Value, Place of Supply,Reverse Charge, Applicable % of Tax Rate, Inv. Type, E-Comm GST, Rate, Taxable Value, Integrated Tax Paid, Central Tax Paid, State/UT Tax Paid, Cess Paid, Eligible For ITC, Availed ITC Integrated Tax, Availed ITC Central Tax, Availed ITC State/UT Tax, Availed ITC Cess\n";

    $ctr = 0;
    $totamt = 0;
    $totdisc = 0;
    $totbill = 0;
    $totinvval = 0;
    $tottaxval = 0;
    $totcgst = 0;
    $totigst = 0;

    while ($pmain = mysqli_fetch_array($getpmain2)) {
        $qrecpgst = mysqli_query($conn, "SELECT `gstno`, `state`, `statecode`,`accode`, `name` from `accmast` where `accode`= '$pmain[party]' ")or die(mysqli_error($conn));
        $frecpgst = mysqli_fetch_array($qrecpgst);

        $ctr++;
        $gstno = $frecpgst['gstno'];
        $invno = $pmain['invno'];
        $invdt = $pmain['mydt'];


        $state = $frecpgst['state'];
        $stcode = $frecpgst['statecode'];
        $revchrg = "N";
        $invtype = "Regular";
        $ecommgst = '';

//        if ($pmain[oms] == '') {
//          $gstrate = $pmain[cgstperc] * 2;
//        } else {
//          $gstrate = $pmain[igstperc];
//        }
        $invval = $pmain['netamt'];
        $rate = $pmain['gstperc'];
        $taxval = $pmain['tamt'];
        $cess = '';


//        $contents.= $ctr . ",";
        $contents .= $gstno . ",";
        $contents .= $frecpgst['name'] . ",";
        $contents .= $invno . ",";
        $contents .= $invdt . ",";
        $contents .= $mattype . ",";
        $contents .= $invval . ",";
        $contents .= $stcode . '-' . $state . ",";
        $contents .= $revchrg . ",";
        $contents .= "" . ",";
        $contents .= $invtype . ",";
        $contents .= $ecommgst . ",";
        $contents .= $rate . ",";
        $contents .= $taxval . ",";
        $contents .= $pmain['igst'] . ",";
        $contents .= $pmain['cgst'] . ",";
        $contents .= $pmain['cgst'] . ",";
        $contents .= $cess . ",";
        $contents .= "" . ",";
        $contents .= "" . ",";
        $contents .= "" . ",";
        $contents .= "" . "\n";

        $totinvval = $totinvval + $invval;
        $tottaxval = $tottaxval + $taxval;
        $totcgst = $totcgst + $pmain['cgst'];
        $totigst = $totigst + $pmain['igst'];
    }

    if ($tottaxval > 0) {

        $contents .= " " . ",";
        $contents .= " " . ",";
        $contents .= " " . ",";
        $contents .= "Total" . ",";
        $contents .= "" . ",";
        $contents .= $totinvval . ",";
        $contents .= " " . ",";
        $contents .= " " . ",";
        $contents .= " " . ",";
        $contents .= " " . ",";
        $contents .= " " . ",";
        $contents .= " " . ",";
        $contents .= $tottaxval . ",";
        $contents .= $totigst . ",";
        $contents .= $totcgst . ",";
        $contents .= $totcgst . ",";
        $contents .= " " . ",";
        $contents .= "" . ",";
        $contents .= "" . ",";
        $contents .= "" . ",";
        $contents .= "" . ",";
//    $contents.= " " . ",";
        $contents .= "" . "\n";
        $contents .= "\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;
    }
}
?>