<?php

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

$maindb = "salemain";
$trandb = "saletran";
$formname = "GSTR1_7";
$file = "gstr1_7.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"])) {

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

    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 *, DATE_FORMAT(`vouchdt`, '%d-%m-%Y') as mydt FROM `$maindb` WHERE `vouchdt` >= '$mfrmdate' 
                            AND `vouchdt` <= '$mtodate' ")or die(mysqli_error($conn));
    $get = mysqli_num_rows($getpmain);
//    browse($get);

    $contents.="Sr No., Place of Supply, Rate, Gross Advance Received, Cess Amt\n";


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

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

        $ctr++;
        $state = $pmain[state];
        $stcode = $pmain[statecode];
        $rate = $trate;
        $ladv = $pmain[ladvance];
        $taxval = $pmain[tottaxamt];
        $cess = '';


        $contents.= $ctr . ",";
        $contents.= $stcode . '-' . $state . ",";
        $contents.= $rate . ",";
        $contents.= $ladv . ",";
        $contents.= $cess . "\n";

        $totladv = $totladv + $ladv;
    }
    $contents.= " " . ",";
    $contents.= "Total" . ",";
    $contents.= " " . ",";
    $contents.= $totladv . ",";
    $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;
    }
}
?>