<?php
require_once("../include/config.php");
require_once("../include/startup.php");

$csv = (isset($_POST['csv_output'])?'1':'0');
		
$csv1 = (isset($_POST['csv_outputs'])?'1':'0');
	if ($csv=='1')
		{
			header("Content-type: application/octet-stream");
			header("Content-Disposition: attachment; filename=\"GSTR1.csv\"");
			
			$paymentlist = str_replace('\\"','"',$_POST['csv_output']);
			echo $paymentlist;
			exit();
		}
	else if ($csv1=='1')
		{
			header("Content-type: application/octet-stream");
			header("Content-Disposition: attachment; filename=\"GST-3B.csv\"");
			
			$paymentlist1 = str_replace('\\"','"',$_POST['csv_outputs']);
			echo $paymentlist1;
			exit();
		}
		else
		{
			require_once("header1.html");
		}

if($G_memberid > 0)
{
	
	$companyid = intval($_REQUEST['txtcompanyid']);
	$memberinvoicesid = intval($_REQUEST['txtmemberinvoicesid']);
	$memberid = $G_memberid;
	$obj_client  = new Client();
	$obj  = new Company();
	$obj_proforma  = new Invoice_frproforma();
	$obj_Invoice  = new Invoice();
		
	if(isset($_POST['SUBMIT']))
	{
		
		$Product['Email1'] 	      			= sanitize($_POST['Email1'],SQL);
		$Product['coverletter'] 	      			= sanitize($_POST['coverletter'],SQL);
	 	//$Product['clientcompanyid']     	= sanitize($_POST['txtcompanyid'],SQL);
	
		$whereclient = "clientcompanyid = ".$companyid;
		$editData	 = $obj_client -> EditClient($Product,$whereclient);
	 
   $query="select c.head_Email ,c.Email1,c.coverletter,c.panno,a.duedate,a.billing_membercompanyid,a.invoiceno,a.InvoiceTotalAmount,a.InvoiceSubTotalAmount,a.invoicedate
					,a.duedate,a.billed_membername,a.discount_amount,a.inv_Add1,a.inv_Pin,a.inv_CityName,a.inv_Add2,a.inv_StateName,a.invoiceno,a.InvoiceTotalAmount,a.InvoiceBaseAmount,d.gstno,a.inv_GST_no,
					a.InvoiceBaseAmountBeforeDiscount,a.cgst_amount,a.sgst_amount,a.igst_amount,d.upload_logo,d.upload_header,d.Addline1,d.Addline2,d.head_CityName,d.head_StateidName,d.companyname,d.head_Pin,d.head_TelNo,d.panno,c.PersonName1,d.head_Email as companyEmail,b.* from mstmember x
				  	inner join trninvoicetomember a on x.memberid = a.memberid 
				  	inner join trninvoicetomemberdetails b on a.memberinvoicesid = b.memberinvoicesid
              	inner join mstclients c on b.billed_membercompanyid = c.clientcompanyid
              	inner join user_company d on a.billing_membercompanyid=d.membercompanyid
             	where x.memberid =$memberid and  a.isdeleted= 0 and quotes_proforma_invoice = 2 and a.memberinvoicesid = $memberinvoicesid";

          
/*

             	$query="select c.head_Email,a.billed_membername,a.duedate,a.billing_membercompanyid,a.invoiceno,a.InvoiceTotalAmount,a.InvoiceSubTotalAmount,a.invoicedate
					,a.duedate,a.billed_membername,a.discount_amount,a.inv_Add1,a.inv_Pin,a.inv_CityName,a.inv_Add2,a.inv_StateName,a.invoiceno,a.InvoiceBaseAmount,d.gstno,a.inv_GST_no,
					a.InvoiceBaseAmountBeforeDiscount,a.cgst_amount,a.sgst_amount,a.igst_amount,
					b.ProductTotalAmount,
					d.upload_logo,d.upload_header,d.companyname,d.gstno,d.panno,
					d.Addline1,d.Addline2,d.head_CityName,d.head_StateidName,d.Country,d.head_Pin,d.head_TelNo,d.head_Email,a.cgst_percentage,a.sgst_percentage,a.igst_percentage,b.* 
					from mstmember x
				  	inner join trninvoicetomember a on x.memberid = a.memberid 
				  	inner join trninvoicetomemberdetails b on a.memberinvoicesid = b.memberinvoicesid
              	inner join mstclients c on b.billed_membercompanyid = c.clientcompanyid
              	inner join user_company d on a.billing_membercompanyid=d.membercompanyid
             	where x.memberid =$memberid and  a.isdeleted= 0 and quotes_proforma_invoice = 2 and a.memberinvoicesid = $memberinvoicesid";
             */	echo $query;
				//die();
		
		$querylist = $obj_proforma ->getInvoice('',$query);
		$rowtoproforma 		=count($querylist);



			//echo $csvcolumnsname;
			
		


		$counter = 0;
		$igst_amount = 0;
		for($i=0;$i<$rowtoproforma;$i++)
		{		
			$counter++;
			$memberid										= $memberid;
			$memberinvoicesid								= $memberinvoicesid;	
			$billed_membercompanyid						= $querylist[$i]['billed_membercompanyid'];
			$billing_membercompanyid					= $billing_membercompanyid_proforma;
			$billed_membername 							= $querylist[$i]['billed_membername'];
			$billed_PersonName 							= $querylist[$i]['PersonName1'];

			$InvoiceBaseAmountBeforeDiscount       = $querylist[$i]['InvoiceBaseAmountBeforeDiscount'];
			$inv_Add1										= $querylist[$i]['inv_Add1'];
			$inv_Add2										= $querylist[$i]['inv_Add2'];
			$inv_Add3										= $querylist[$i]['inv_Add3'];
			$inv_Add4										= $querylist[$i]['inv_Add4'];
			$address                        			= $querylist[$i]['inv_Add1'].'</br>'.$querylist[$i]['inv_Add2'].'</br>'.$querylist[$i]['inv_CityName'].' '.$querylist[$i]['inv_Pin'];
			$panno											= $querylist[$i]['panno'];
			$gstno											= $querylist[$i]['gstno'];
			$quotes_proforma_invoice					=	0;
			$inv_CityName 									= $querylist[$i]['inv_CityName'];
			$inv_Pin 										= $querylist[$i]['inv_Pin'];
			$inv_StateName 								= $querylist[$i]['inv_StateName'];
			$inv_head_Stateid								= $querylist[$i]['inv_head_Stateid'];
			$invoiceno 										= $querylist[$i]['invoiceno'];
			$invoicedate									= date('d-m-Y',strtotime($querylist[$i]['invoicedate']));
			$duedate											= $querylist[$i]['duedate'];
			$status 											= $querylist[$i]['status'];
			$igst_percentage								= $querylist[$i]['igst_percentage'];
			$igst_amount									= format_number($querylist[$i]['igst_amount']);
			$cgst_percentage								= $querylist[$i]['cgst_percentage'];
			$cgst_amount									= format_number($querylist[$i]['cgst_amount']);
			$sgst_percentage								= $querylist[$i]['sgst_percentage'];
			$sgst_amount									= format_number($querylist[$i]['sgst_amount']);
			$ugst_percentage								= $querylist[$i]['ugst_percentage'];
			$ugst_amount									= format_number($querylist[$i]['ugst_amount']);
			$discount_percentage							= $querylist[$i]['discount_percentage'];
			$discount_amount								= format_number($querylist[$i]['discount_amount']);
			$InvoiceBaseAmountBeforeDiscount			= $querylist[$i]['InvoiceBaseAmountBeforeDiscount'];
			$InvoiceBaseAmount							= format_number($querylist[$i]['InvoiceBaseAmount']);
			$InvoiceTotalAmount							= format_number($querylist[$i]['InvoiceTotalAmount']);
				$InvoiceSubTotalAmount						= format_number($querylist[$i]['InvoiceSubTotalAmount']);
			$InvoiceTotalAmount1							= $querylist[$i]['InvoiceTotalAmount'];
			$quantity										= $querylist[$i]['quantity'];
			//$discount_amount							= $querylist[$i]['discount_amount'];
			//$price											= $querylist[$i]['InvoiceTotalAmount'];
			$ProductBaseAmount							= number_format($querylist[$i]['ProductBaseAmount']);
			$ProductTotalAmount							= number_format($querylist[$i]['ProductTotalAmount']);
			$productname									= $querylist[$i]['productname'];
			//$product_description						= str_replace(' ', "\n", $querylist[$i]['product_description']);
			$product_description							= $querylist[$i]['product_description'];
			$product_unit									= $querylist[$i]['product_unit'];
			$inv_GST_no										= $querylist[$i]['inv_GST_no'];
			$toEmails									= $querylist[$i]['head_Email'].','.$querylist[$i]['Email1'];
			
		
			$InvoiceTotalAmountinword					= number_to_words($InvoiceTotalAmount1);
						
				
				
				if($rowtoproforma >=3)
			{
				
				$data_design = 'style="height:auto;"';
				//$data_design = 'style="height:150px;"';
			}
			else
			{
				$data_design = 'style="height:180px;"';
				
			}

				$productarray .='<tr>';
				$productarray	.='<td style="padding-top:20px;border-top:none;border-bottom:none;">'.$counter.'</td>';
				$productarray	.='<td style="border-top:none;border-bottom:none;"><div '.$data_design.'><b>'.$productname.'</b>';
				$productarray	.='<br><br><b>'.$product_description.'</b></div><br>';
				$productarray	.='</td>';
				$productarray	.='<td  style="border-top:none;border-bottom:none;" valign="top" align="right"><br><b>'.$ProductBaseAmount.'</b></td>';
				$productarray	.=	'<td  style="border-top:none;border-bottom:none;" valign="top" align="right"><br><b>'.$quantity.'</b></td>';
				$productarray	.='<td  style="border-top:none;border-bottom:none;" valign="top" align="right"><br><b>'.$ProductTotalAmount.'</b></td>';
			}
			
$companyname 		= $querylist[0]['companyname'];
		$gstno 				= $querylist[0]['gstno'];
		$panno 				= $querylist[0]['panno'];
		$Addline1 			= $querylist[0]['Addline1'];
		$Addline2 			= $querylist[0]['Addline2'];
		$head_CityName 	= $querylist[0]['head_CityName'];
		$head_StateidName = $querylist[0]['head_StateidName'];
		$Country 			= $querylist[0]['Country'];
		$head_Pin 			= $querylist[0]['head_Pin'];
		$head_TelNo 		= $querylist[0]['head_TelNo'];
		$head_Email 		= $querylist[0]['head_Email'];
		$upload_logo_display 	= $querylist[0]['upload_logo'];
		$upload_header_display  = $querylist[0]['upload_header'];
		$formEmails										= $querylist[0]['companyEmail'];
		$coverletters										= $querylist[0]['coverletter'];
			if($igst_amount == '' || $igst_amount == 0)
		{

				$row_gst .='<tr>';
				$row_gst .='<td valign="top" colspan="2" rowspan="5">
							<b>In words
							Rs. '.$InvoiceTotalAmountinword.' Only
							<br>GST ID : '.$gstno.'
							<br>PAN No : '.$panno.'</b></td>';
				$row_gst .='<td colspan="2">';
				$row_gst .='<b>SubTotal</b>';
				$row_gst .='</td>';
				$row_gst .='<td align="right"><b>'.$InvoiceSubTotalAmount.'</b>';
				$row_gst .='</td>';
				$row_gst .='</tr>';
				$row_gst .='<tr>';
			 	$row_gst .='<td colspan="2">';
				$row_gst .='<b>CGST '.$cgst_percentage.'%</b>';
				$row_gst .='</td>';
				$row_gst .='<td align="right">';
				$row_gst .='<b>'.$cgst_amount.'</b>';
				$row_gst .='</td>';
				$row_gst .='</tr>';
				$row_gst .='<tr>';
				$row_gst .='<td colspan="2">';
				$row_gst .='<b>SGST '.$sgst_percentage.'%</b>';
				$row_gst .='</td>';
				$row_gst .='<td align="right"><b>'.$sgst_amount.'</b></td>';
				$row_gst .='</tr>';
				$row_gst .='<tr>';
				$row_gst .='<td colspan="2">';
				$row_gst .='<b>Grand Total</b>';
				$row_gst .='</td>';
				$row_gst .='<td align="right"><b>'.$InvoiceTotalAmount.'</b></td>';
				$row_gst .='</tr>';
				$row_gst .='<tr>';
				$row_gst .='<td colspan="3">
							<b>For '.$companyname.'</b><br><br>
							<b>Director </b><br><br>(Electronic Invoice do not need signature)';
				$row_gst .='</td>';
				$row_gst .='</tr>';
		}
		else 
		{
				$row_gst .='<tr>';
				$row_gst .='<td valign="top" colspan="2" rowspan="5">
							<b>In words	Rs. '.$InvoiceTotalAmountinword.' Only
							<br>GST ID : '.$gstno.'
							<br>PAN No : '.$panno.'</b>
							</td>';
				$row_gst .='<td colspan="2">';
				$row_gst .='<b>SubTotal</b>';
				$row_gst .='</td>';
				$row_gst .='<td align="right"><b>'.$InvoiceSubTotalAmount.'</b>';
				$row_gst .='</td>';
				$row_gst .='</tr>';
				$row_gst .='<tr>';
				$row_gst .='<td colspan="2">';
				$row_gst .='<b>IGST '.$igst_percentage.'%</b>';
				$row_gst .='</td>';
				$row_gst .='<td align="right">';
				$row_gst .='<b>'.$igst_amount.'</b>';
				$row_gst .='</td>';
				$row_gst .='</tr>';

				$row_gst .='<tr>';
				$row_gst .='<td colspan="2">';
				$row_gst .='<b>Grand Total</b>';
				$row_gst .='</td>';
				$row_gst .='<td align="right"><b>'.$InvoiceTotalAmount.'</b></td>';
				$row_gst .='</tr>';
				$row_gst .='<tr>';
				$row_gst .='<td colspan="3">';
				$row_gst .='<b>For '.$companyname.'<br><br>
									<b>Director </b><br><br>
									(Electronic Invoice do not need signature)';
				$row_gst .='</td>';
				$row_gst .='</tr>';
				
		}
		
									
			if($discount_amount != '') {
			$row_discount .='<tr>';
			$row_discount .='<td colspan="2"><b>Less Rs.'.$discount_amount.'  discount</b></td>';
			$row_discount .='<td colspan="2"><b>Discount </b></td>';
			$row_discount .='<td align="right"><b>'.$discount_amount.'</b></td>';
			$row_discount .='</tr>';
		}
		else {
			$row_discount .='';
			}
									
		$upload_header = GALLERY_PHOTO_PATH.$querylist[0]['upload_header'];
		$upload_logo = GALLERY_PHOTO_PATH.$querylist[0]['upload_logo'];
		if($upload_header_display != '')
		{
			$header_display = '<td valign="top" style="border-bottom:none;">
												<img src="'.$upload_header.'" width="280px" height="150px">
									 </td>';
		}
		else 
		{
					if($upload_logo_display != '')
					{
						$header_display = '<td valign="top" width="30%"  style="border-bottom:none;">
												<img src="'.$upload_logo.'" width="150px">
												</td>
												<td  width="70%">
												<h2 style="margin:0;">'.$companyname.'</h2>
													
													<p>Admn Off: '.$Addline1.'<br>
													'.$Addline2.' '.$head_CityName.' - '.$head_Pin.' '.$head_StateidName.' <br>
													Phone : '.$head_TelNo.'<br>
													Email : '.$head_Email.'
													</p>
												</td>';
					}
					else 
					{
						$header_display = '<td colspan="5"  style="border-bottom:none;">
													<h2 style="margin:0;">'.$companyname.'</h2>
													
													<p>Admn Off: '.$Addline1.'<br>
													'.$Addline2.' '.$head_CityName.' - '.$head_Pin.' '.$head_StateidName.' <br>
													Phone : '.$head_TelNo.'<br>
													Email : '.$head_Email.'
													</p>
												</td>';
					}

					
				}
		
			$swiftdir = GLOBAL_INCLUDE_PATH."htmltopdf";
			//echo $dir; 
			//$MerTemplateFile = $dir."/final_invoice-manu_new.php";
			$MerTemplateFile = "invoice_template_new.php";
	
			ob_start();
			require_once($MerTemplateFile);
			$pdf_html_mer = ob_get_contents();
			ob_end_clean();
	
			require_once($swiftdir.'/dompdf/dompdf_config.inc.php');
			require_once($swiftdir.'/swift/swift_required.php');
				
			$replace = array(
			      "[productname]"								=> $productname,
					"[billed_membername]"						=> $billed_membername,
					"[ProductBaseAmount]"						=> $ProductBaseAmount,
					"[InvoiceTotalAmount]"						=> $InvoiceTotalAmount,
					"[InvoiceSubTotalAmount]"						=> $InvoiceSubTotalAmount,
					"[InvoiceBaseAmount]"						=> $InvoiceBaseAmount,
					"[InvoiceTotalAmountinword]"				=> $InvoiceTotalAmountinword,
					"[address]"										=>	$address,
					"[InvoiceBaseAmountBeforeDiscount]"		=> $InvoiceBaseAmountBeforeDiscount,
					"[productname]"								=> $productname,
					"[product_description]"						=> $product_description,
					"[ProductTotalAmount]"						=> $ProductTotalAmount,
					"[ProductTotalAmount1]"						=> $ProductTotalAmount1,
					"[inv_GST_no]"                         =>	$inv_GST_no,
					"[inv_Add1]"                         	=>	$inv_Add1,
					"[panno]" 										=>	$panno,
					"[gstno]" 										=>	$gstno,
					"[quantity]"									=> $quantity,
					"[product_unit]" 								=> $product_unit,
					"[cgst_amount_product]"						=> $cgst_amount_product,
					"[sgst_amount_product]"						=> $sgst_amount_product,
					"[igst_amount_product]"						=> $igst_amount_product,
					"[invoiceno]"			     				   => $invoiceno,
					"[invoicedate]"								=> $invoicedate,
					"[discount_amount]"							=> $discount_amount,
					"[productarray]"								=>	$productarray,
					"[cgst_amount]"								=> $cgst_amount,
					"[sgst_amount]"								=> $sgst_amount,
					"[igst_amount]"								=> $igst_amount,
					"[row_gst]"										=>	$row_gst,
					"[row_discount]"								=>	$row_discount,
 		         "[rowspan]"             					=> $rowspan,
 		         "[header_display]"							=> $header_display	
					);
		 	
		  			//require_once("proforma_template_new.php");
		  			
		  				

	
	          $resultstr	  = strtr($TEMPLATE["PAGES"]["PAGE"],$replace);
	          $result_template = strtr($pdf_html_mer,$replace);
		
				 $dompdf = new DOMPDF(); // Create new instance of dompdf
				 $dompdf->load_html($result_template); // Load the html
				 $dompdf->render(); // Parse the html, convert to PDF
				 $pdf_content = $dompdf->output(); // Put contents of pdf into variable for later
								
				// $html_message = nl2br("Dear ".$billed_membername.",");
								$html_message = nl2br("<tr><b>Dear $billed_PersonName,</b></tr><tr><br></tr><tr>$coverletters</tr><tr><br><br></tr><tr>Regards,</tr><tr><b>$companyname</b></tr><tr><b>$head_TelNo</b></tr>");
					
					//$html_message3 = nl2br("Regards,");
					//$html_message4 = nl2br("");
					//$html_message5 = nl2br($billed_membername);		formEmails
			 	// $fromEmail = array('nagma.m@evergrowsolutions.com' =>'Invoice');
				$fromEmail = array($formEmails =>'Invoice');
										
					// Load the SwiftMailer files
					//print_r($toEmails);
				$mailer = new Swift_Mailer(new Swift_MailTransport()); // Create new instance of SwiftMailer	
				$fileName = str_replace(' ','-',$billed_membername).'.pdf'; 
					//$message = Swift_Message::newInstance('/usr/sbin/exim -bs')
				$message = Swift_Message::newInstance()
								       ->setSubject('Invoice') // Message subject
									   ->setTo($toEmails) // Array of people to send to
									   ->setBcc($BCCEmails) // Array of people to send to
									   ->setFrom($fromEmail) // From:
									   ->setBody($html_message,'text/html')
									   // ->setBody($html_message2,'text/html')
									    // ->addPart('Please find attached invoice', 'text/html')
									    // Attach that HTML message from earlier
				

								


									   ->attach(Swift_Attachment::newInstance($pdf_content,$fileName, 'application/pdf')); // Attach the generated PDF from earlier
						
				// Send the email, and show user message
				if ($mailer->send($message))
				{
					//$success = true;
					$mail_array['is_mail_send']=1;
					$mail_array['mail_send_by']=$G_memberid;
					$mail_array['mail_send_date']=date('Y-m-d');
					$wheremail="memberinvoicesid = $memberinvoicesid";
				
					$editemail =$obj_Invoice->EditInvoice($mail_array,$wheremail);
				echo "<script type='text/javascript'>alert('Email Send Successfully.');
													window.location.href='".DOC_ROOT."admin/viewInvoice.php';
													window.location.reload();
													</script>";	
			
					 
				}	
				else
				{
					$error = true;
					$strmessageHeader = "There was Error while Sending Emails. Please try again";
					echo $strmessageHeader;		
				}
				$dompdf -> __destruct();
				unset($dompdf);
				unset($pdf_content);
				//unset($mailer);
				unset($message);			
    		
	}
	else 
	{

		//echo"<pre>";
		//print_r($_POST);

		$montharray = $_POST['cmbmonth'];
				$montharray_count =  count($_POST['cmbmonth']);
				if($montharray_count > 0) 
				{
					$month_id = '(';
					for($i=0;$i<$montharray_count;$i++) 
					{
							$month =  explode('-',$montharray[$i]);
						if($i == 0) 
						{
								$month_id .= $month[0];
							$monthvar .= $month[1];
						}
						else 
						{
							$month_id .=",".$month[0];
							$monthvar .= ",".$month[1];
						}
								 
					}
					$month_id .= ')';
					
					$where_cond_month = "MONTH(a.invoicedate) in $month_id and";
				}		

	$display1 = $_POST['txtfromdate'];
	$display2 = $_POST['txttodate'];
	
	$fromdate	= date("Y-m-d", strtotime($_POST['txtfromdate']));
	$todate		= date("Y-m-d", strtotime($_POST['txttodate']));
		if ($fromdate=='1970-01-01')
	{
		$where_date ="";
	}
	else
	{
		$where_date ="date(a.invoicedate) BETWEEN '$fromdate' and '$todate'and";
	}
$day = $_POST['opt'];
$todayedate = $_POST['todayedate'];
$yesterdaydate = $_POST['yesterdaydate'];
$this_month = $_POST['this_month'];
$last_month = $_POST['last_month'];

$this_quarter = $_POST['this_quarter'];
	$this_quarter_months =  explode('-',$this_quarter);
		$this_quarter_month1 .= $this_quarter_months[0];
		$this_quarter_month2 .= $this_quarter_months[1];
		$this_quarter_month3 .= $this_quarter_months[2];
$last_quarter = $_POST['last_quarter'];
	$last_quarter_months =  explode('-',$last_quarter);
		$last_quarter_month1 .= $last_quarter_months[0];
		$last_quarter_month2 .= $last_quarter_months[1];
		$last_quarter_month3 .= $last_quarter_months[2];		
$today=date('Y-m-d', strtotime($todayedate));
$yesterday=date('Y-m-d', strtotime($yesterdaydate));


switch ($day) {
    case "today":
    
        $where_day .= "and invoicedate = '$today'";
        break;
    case "yesterday":
        $where_day .= "and invoicedate = '$yesterday'";
        break;
    case "Last_7_days":
     	$where_day .= "and invoicedate >= CURRENT_DATE()-7";
        break;
    case "last_30_days":
   		//$where_day .= "and invoicedate >= CURRENT_DATE()-30";
   		$where_day .= "and MONTH(invoicedate) in ('$this_month')";
        break;
    case "This_month":
       // $where_day .= "and invoicedate >= CURRENT_DATE()-30";
        $where_day .= "and MONTH(invoicedate) in ('$this_month')";
        
        break;
    case "Last_month":
       // $where_day .= "and invoicedate >= CURRENT_DATE()-60";
         $where_day .= "and MONTH(invoicedate) in ('$last_month')";
        break;
    case "This_quarter":
		$where_day = "and MONTH(invoicedate) in ('$this_quarter_month1,$this_quarter_month2,$this_quarter_month3')";
		//$where_day .= "";
        break;
    case "Last_quarter":
		$where_day = "and MONTH(invoicedate) in ('$last_quarter_month1,$last_quarter_month2,$last_quarter_month3')";
		//$where_day .= "";
        break;
    case "All_time":
    	$where_day .= "";
       // $where_day .= "and invoicedate >= CURRENT_DATE()-30";
        break;
    default:
        $where_day .= "";
}

	
//echo $this_quarterg;

			// All members 
			 	  $sql = "select *,e.head_Email,a.memberinvoicesid,a.billed_membercompanyid,a.paid_total_amount,a.billing_membercompanyid,a.invoiceno,a.is_mail_send,
			 				 a.InvoiceTotalAmount,a.invoicedate,a.duedate,a.billed_membername,c.TotalAmount,a.approved,MONTH(CURRENT_DATE()) as today_date,CURRENT_DATE() -1 as Yesterday_date 
			 			    from mstmember x
					  		 inner join trninvoicetomember a on x.memberid = a.memberid 
					  		 inner join trninvoicetomemberdetails b on a.memberinvoicesid = b.memberinvoicesid
					  		 inner join mstclients e on b.billed_membercompanyid = e.clientcompanyid
					  		 left join user_company_payment_header  c on a.memberinvoicesid = c.memberinvoicesid
					  		 left join user_company_payment_detail  d on a.memberinvoicesid = d.memberinvoicesid
					  		 where x.memberid = $memberid  $where_day and $where_date a.isdeleted= 0 and quotes_proforma_invoice = 2 
					  		 group by a.memberinvoicesid  DESC";
					// $sql;
					//die();
					$sqllist = $obj->getCompany('','',$sql);
					if(is_array($sqllist))
					{
						$rowcount = count($sqllist);
					}

					 $sql2 = "select *,e.head_Email,a.memberinvoicesid,a.billed_membercompanyid,a.paid_total_amount,a.billing_membercompanyid,a.invoiceno,a.is_mail_send,
			 				 a.InvoiceTotalAmount,a.invoicedate,a.duedate,a.billed_membername,c.TotalAmount,a.approved,MONTH(CURRENT_DATE()) as today_date,CURRENT_DATE() -1 as Yesterday_date 
			 			    from mstmember x
					  		 inner join trninvoicetomember a on x.memberid = a.memberid 
					  		 inner join trninvoicetomemberdetails b on a.memberinvoicesid = b.memberinvoicesid
					  		 inner join mstclients e on b.billed_membercompanyid = e.clientcompanyid
					  		 left join user_company_payment_header  c on a.memberinvoicesid = c.memberinvoicesid
					  		 left join user_company_payment_detail  d on a.memberinvoicesid = d.memberinvoicesid
					  		 where x.memberid = $memberid  $where_day and $where_date a.isdeleted= 0 and quotes_proforma_invoice = 2 
					  		 group by a.memberinvoicesid  order by a.invoicedate ASC";
					//echo $sql;
					//die();
					$heading = "Invoice  Report ";
					$sqllist2 = $obj->getCompany('','',$sql2);
					$rowcount = count($sqllist2);
					if ($sqllist2)
					{
						$rowcount_adv = $rowcount;
					}
					else
					{
						$rowcount_adv=0;
					}
					$sql_invoice2 = "select SUM(InvoiceTotalAmount) as InvoiceTotalAmounts  from trninvoicetomember where memberid = $memberid  and isdeleted=0 $where_day and $where_date  quotes_proforma_invoice = 2";


	//echo $sql_invoice1;
					$sql_invoice_list2 = $obj_Invoice->getInvoice('',$sql_invoice2);
	
		
			
						$InvoiceTotalAmount1  				= $sql_invoice_list2[0]['InvoiceTotalAmounts'];

					$maxrows = $rowcount_adv;
					$csvcolumnsname ='"","<b>Company Name</b>","Invoice No","Invoice Date","GST NO","Amount","IGST","CGST","SGST","Total"'."\n";
				
			 for($i=0;$i<$maxrows;$i++) 
         	{ 
         		$memberinvoicesid					= $sqllist2[$i]['memberinvoicesid'];
         		$companyid							= $sqllist2[$i]['billed_membercompanyid'];
         		$billing_membercompanyid		= $sqllist2[$i]['billing_membercompanyid'];
         		$statusdata							= $sqllist2[$i]['status'];
         		$invoiceno							= $sqllist2[$i]['invoiceno'];
         		//$InvoiceTotalAmount				= $sqllist[$i]['InvoiceTotalAmount'];
         		$invoicedate						= date("j M Y",strtotime($sqllist2[$i]['invoicedate']));
         		$invoicedatemonth						= date("M Y",strtotime($sqllist2[$i]['invoicedate']));
         		//date("M jS, Y", strtotime("2011-01-05"));
         		$duedate								= date("j M Y",strtotime($sqllist2[$i]['duedate']));
         		$billed_membername				= $sqllist2[$i]['billed_membername'];   
         		$TotalAmount 						= $sqllist2[$i]['TotalAmount']; //total payment by that invoice id
         		$approved							= $sqllist2[$i]['approved'];  //Invoice approve status
         			$InvoiceBaseAmount			= $sqllist2[$i]['InvoiceBaseAmount'];
					$InvoiceTotalAmount			= $sqllist2[$i]['InvoiceTotalAmount'];
					$inv_GST_no						=	$sqllist2[$i]['inv_GST_no'];
         	
					$is_mail_send						= $sqllist2[$i]['is_mail_send'];
     			  $balance1 							= $InvoiceTotalAmount - $TotalAmount;
         			$paid_total_amount				= $sqllist2[$i]['paid_total_amount'];
         			if($paid_total_amount == '0')
         			{
         		
         			 $balance1 							= $InvoiceTotalAmount - $TotalAmount;
         			}
         			else
         			{
         	
						$balance1 =  $InvoiceTotalAmount - $paid_total_amount;
         			}

         			$cgst_amount					= $sqllist2[$i]['cgst_amount'];
			
					$sgst_amount					= $sqllist2[$i]['sgst_amount'];
					$igst_amount					= $sqllist2[$i]['igst_amount'];
					$sgst_percentage 				= $sqllist2[$i]['sgst_percentage'];
					$cgst_percentage 				= $sqllist2[$i]['cgst_percentage'];
					$igst_percentage 				= $sqllist2[$i]['igst_percentage'];


         				$reportname = '"'.$heading.'"'."\n";
						$csvtotalincome = "\n".'"","","","","","","","","Total Amount","'.$InvoiceTotalAmount1.'",""'."\n";
						$csvdata .= '"'.$invoicedatemonth.'","'.$billed_membername.'","'.$invoiceno.'","'.$invoicedate.'","'.$inv_GST_no.'","'.$InvoiceBaseAmount.'","'.$igst_amount.'","'.$cgst_amount.'","'.$sgst_amount.'","'.$InvoiceTotalAmount.'"'."\n";
						$paymentresultCSV = $reportname.$csvcolumnsname.$csvdata.$csvtotalincome;

       			 }

        	$sql_invoice1 = "select *,CONCAT(MONTHNAME(invoicedate),'-',YEAR(invoicedate)) as invoicedate_ym ,COUNT(*),SUM(cgst_amount) as cgst_amount,SUM(sgst_amount) as sgst_amount,SUM(igst_amount) as igst_amount,SUM(InvoiceBaseAmount) as InvoiceBaseAmount,SUM(InvoiceTotalAmount) as InvoiceTotalAmount 
					from trninvoicetomember

					 where memberid = $memberid  and isdeleted=0 $where_day and $where_date  quotes_proforma_invoice = 2 GROUP by MONTH(invoicedate)";
					 $heading1 = "GSTR 3 B";
				//echo $sql_invoice1;
				$sql_invoice_list1 = $obj_Invoice->getInvoice('',$sql_invoice1);
	
				//$sqllist2 = $obj->getCompany('','',$sql2);
					$rowcount1 = count($sql_invoice_list1);
					if ($sql_invoice_list1)
					{
						$rowcount_adv1 = $rowcount1;
					}
					else
					{
						$rowcount_adv1=0;
					}
			
			$maxrows1 = $rowcount_adv1;
			$csvcolumnsname1 ='"","Amount","IGST","CGST","SGST","Total"'."\n";

			 for($i=0;$i<$maxrows1;$i++) 
         	{ 
         		$memberinvoicesid					= $sql_invoice_list1[$i]['memberinvoicesid'];
         		$companyid							= $sql_invoice_list1[$i]['billed_membercompanyid'];
         		$billing_membercompanyid		= $sql_invoice_list1[$i]['billing_membercompanyid'];
         		
         		$invoiceno							= $sql_invoice_list1[$i]['invoiceno'];
         		
         		$invoicedatemonth1						= date("M Y",strtotime($sql_invoice_list1[$i]['invoicedate_ym']));
         		//date("M jS, Y", strtotime("2011-01-05"));
         			$duedate								= date("j M Y",strtotime($sql_invoice_list1[$i]['duedate']));
         		
         			$InvoiceBaseAmount			= $sql_invoice_list1[$i]['InvoiceBaseAmount'];
					$InvoiceTotalAmount			= $sql_invoice_list1[$i]['InvoiceTotalAmount'];
					
         	
				
         			$cgst_amount					= $sql_invoice_list1[$i]['cgst_amount'];
			
					$sgst_amount					= $sql_invoice_list1[$i]['sgst_amount'];
					$igst_amount					= $sql_invoice_list1[$i]['igst_amount'];
					$sgst_percentage 				= $sql_invoice_list1[$i]['sgst_percentage'];
					$cgst_percentage 				= $sql_invoice_list1[$i]['cgst_percentage'];
					$igst_percentage 				= $sql_invoice_list1[$i]['igst_percentage'];
					//$InvoiceTotalAmount1  				= $sql_invoice_list1[$i]['InvoiceTotalAmounts'];

         				$reportname1 = '"'.$heading1.'"'."\n";
						$csvtotalincome1 = "\n".'"","","","","Total Amount","'.$InvoiceTotalAmount1.'",""'."\n";
						$csvdata1 .= '"'.$invoicedatemonth1.'","'.$InvoiceBaseAmount.'","'.$igst_amount.'","'.$cgst_amount.'","'.$sgst_amount.'","'.$InvoiceTotalAmount.'"'."\n";
						$paymentresultCSV1 = $reportname1.$csvcolumnsname1.$csvdata1.$csvtotalincome1;

      			  }


					  $sql1 = "select MONTHNAME(CURRENT_DATE()) as This_monthname,MONTHNAME(CURRENT_DATE())-1 as Last_monthname,MONTH(CURRENT_DATE()) as This_month,MONTH(CURRENT_DATE())-1 as Last_month,CURRENT_DATE() as today_date,CURRENT_DATE() -1 as Yesterday_date,MONTH(CURRENT_DATE())+1 as This_month_quter2,MONTH(CURRENT_DATE())+2 as This_month_quter3,MONTH(CURRENT_DATE())-2 as Last_month_quter2,MONTH(CURRENT_DATE())-3 as Last_month_quter3
			 			    from mstmember x
					  		 inner join trninvoicetomember a on x.memberid = a.memberid 
					  		 where x.memberid = $memberid and a.isdeleted= 0 and quotes_proforma_invoice = 2 
					  		 group by a.memberinvoicesid";
					//echo $sql;
					//die();
					$sqllist1 = $obj->getCompany('','',$sql1);


					$today_date						= date("d-M",strtotime($sqllist1[0]['today_date']));
					$Yesterday_date						= date("d-M",strtotime($sqllist1[0]['Yesterday_date']));
					$This_month						= $sqllist1[0]['This_month'];
					 $This_monthname = date("M", mktime(0, 0, 0, $This_month, 10));
					$Last_month						= $sqllist1[0]['Last_month'];
					$Last_month						= $sqllist1[0]['Last_month'];
					 $Last_monthname = date("M", mktime(0, 0, 0, $Last_month, 10));
					//$This_monthname						= $sqllist1[0]['This_monthname'];
					
					$This_month_quter2						= $sqllist1[0]['This_month_quter2'];
					$This_quter_monthname2 = date("M", mktime(0, 0, 0, $This_month_quter2, 10));
					$This_month_quter3						= $sqllist1[0]['This_month_quter3'];
					$This_quter_monthname3 = date("M", mktime(0, 0, 0, $This_month_quter3, 10));
					$Last_month_quter2						= $sqllist1[0]['Last_month_quter2'];
					$Last_quter_monthname2 = date("M", mktime(0, 0, 0, $Last_month_quter2, 10));
					$Last_month_quter3						= $sqllist1[0]['Last_month_quter3'];
					$Last_quter_monthname3 = date("M", mktime(0, 0, 0, $Last_month_quter3, 10));

					//echo $This_month;
					//echo $Last_month;
					//echo $This_monthname;
					//echo $Last_monthname;
					// Active members 
					$sql1 = "select * from user_company where memberid = $memberid and memberapprovalstatus = 1";
					$Activesqllist = $obj->getCompany('','',$sql1);
					if(is_array($Activesqllist))
					{
						$Activerowcount = count($Activesqllist);
					}
				
					// Inactive members 
					$sql2 = "select * from user_company where memberid = $memberid and memberapprovalstatus = 0";
					$Inactivesqllist = $obj->getCompany('','',$sql2);
					if(is_array($Inactivesqllist))
					{
						$Inactiverowcount = count($Inactivesqllist);
					}
					
					
	
				  $sql_payment = "SELECT memberinvoicesid,SUM(TotalAmount) as paid_total_amount
									FROM user_company_payment_header GROUP BY  memberinvoicesid";
									
               $sql_paymentlist = $obj->getCompany('','',$sql_payment);
					if(is_array($sql_paymentlist))
					{
						$payment_rowcount = count($sql_paymentlist);
					}
					//$TotalAmount1 = 0;
					 for($i=0;$i<$payment_rowcount;$i++) 
         		 { 
         	 		 $memberinvoicesid				= $sql_paymentlist[$i]['memberinvoicesid'];
         		 	 $invoicearry['paid_total_amount']				=             $sql_paymentlist[$i]['paid_total_amount'];
         			 $where ="memberinvoicesid =$memberinvoicesid";
						 $update_invoice = $obj_Invoice ->EditInvoice($invoicearry,$where);
      			}
		}
 	
		require_once("header1.html");
		require_once("leftnav.html");
		require_once("viewInvoice1.html");
		require_once("footer1.html");
}
else if (!headers_sent($filename, $linenum)) 
{
				$redirect_url = DOC_ROOT."login.php";
				header("Location: $redirect_url");
    				exit;
					// You would most likely trigger an error here.
}
else 
{
				echo "Headers already sent in $filename on line $linenum\n" .
          			"Cannot redirect, for now please click this <a ";
    				exit;
}   



	
	
?>
