<?php
require_once("../include/config.php");
require_once("../include/startup.php");
	
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['clientcompanyid']     	= sanitize($_POST['txtcompanyid'],SQL);
	
		$whereclient = "clientcompanyid = ".$companyid;
		$editData	 = $obj_client -> EditClient($Product,$whereclient);
		
 	   $query="select c.head_Email,c.Email1,c.panno,a.duedate,a.billing_membercompanyid,a.invoiceno,a.InvoiceTotalAmount,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,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";
				//die();
		//echo $query;
		$querylist = $obj_proforma ->getInvoice('',$query);
		$rowtoproforma 		=count($querylist);
		$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'];
			$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									= $querylist[$i]['igst_amount'];
			$cgst_percentage								= $querylist[$i]['cgst_percentage'];
			$cgst_amount									= $querylist[$i]['cgst_amount'];
			$sgst_percentage								= $querylist[$i]['sgst_percentage'];
			$sgst_amount									= $querylist[$i]['sgst_amount'];
			$ugst_percentage								= $querylist[$i]['ugst_percentage'];
			$ugst_amount									= $querylist[$i]['ugst_amount'];
			$discount_percentage							= $querylist[$i]['discount_percentage'];
			$discount_amount								= number_format($querylist[$i]['discount_amount']);
			$InvoiceBaseAmountBeforeDiscount			= $querylist[$i]['InvoiceBaseAmountBeforeDiscount'];
			$InvoiceBaseAmount							= number_format($querylist[$i]['InvoiceBaseAmount']);
			$InvoiceTotalAmount							= number_format($querylist[$i]['InvoiceTotalAmount']);
			$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);
				//die();
				
				
				if($rowtoproforma > 1)
				{
					$productarray .='<tr>';
					$productarray	.='<td style="padding-top:20px;">'.$counter.'</td>';
					$productarray	.='<td><div style="height:auto"><b>'.$productname.'</b>';
					$productarray	.='<br><br><b>'.$product_description.'</b></div><br>';
					$productarray	.='</td>';
					$productarray	.='<td valign="top"><br>'.$ProductBaseAmount.'</td>';
					$productarray	.=	'<td valign="top"><br>'.$quantity.'</td>';
					$productarray	.='<td valign="top"><br>'.$ProductBaseAmount.'</td>';
					$productarray	.=	'</tr>	';	
				}
				else 
				{
					$productarray .='<tr>';
					$productarray	.='<td style="padding-top:20px;">'.$counter.'</td>';
					$productarray	.='<td><div style="height:250px"><b>'.$productname.'</b>';
					$productarray	.='<br><br><b>'.$product_description.'</b></div><br>';
					$productarray	.='</td>';
					$productarray	.='<td valign="top"><br>'.$ProductBaseAmount.'</td>';
					$productarray	.=	'<td valign="top"><br>'.$quantity.'</td>';
					$productarray	.='<td valign="top"><br>'.$ProductBaseAmount.'</td>';
					$productarray	.=	'</tr>	';	
				}
			}
			if($igst_amount == '' || $igst_amount == 0)
			{

				$row_gst .='<tr>';
				$row_gst .='<td valign="top" colspan="2" rowspan="4">
							<b>In words
							Rs.'.$InvoiceTotalAmountinword.'
							<br>GST ID : '.$gstno.'
							<br>PAN No : '.$panno.'</b></td>';
			 	$row_gst .='<td colspan="2">';
				$row_gst .='<b>CGST 9%</b>';
				$row_gst .='</td>';
				$row_gst .='<td>';
				$row_gst .='<b>'.$cgst_amount.'</b>';
				$row_gst .='</td>';
				$row_gst .='</tr>';
				$row_gst .='<tr>';
				$row_gst .='<td colspan="2">';
				$row_gst .='<b>SGST 9%</b>';
				$row_gst .='</td>';
				$row_gst .='<td><b>'.$sgst_amount.'</b></td>';
				$row_gst .='</tr>';
				$row_gst .='<tr>';
				$row_gst .='<td colspan="2">';
				$row_gst .='<b>Total</b>';
				$row_gst .='</td>';
				$row_gst .='<td><b>'.$InvoiceTotalAmount.'</b></td>';
				$row_gst .='</tr>';
				$row_gst .='<tr>';
				$row_gst .='<td colspan="3">
							<b>For Evergrow Solutions Pvt. Ltd.</b><br><br>
							<b>Director </b><br><b>(Electronic Invoice do not need signature)</b>';
				$row_gst .='</td>';
				$row_gst .='</tr>';
			}
			else 
			{
				$row_gst .='<tr>';
				$row_gst .='<td valign="top" colspan="2" rowspan="3">
							<b>In words	Rs.'.$InvoiceTotalAmountinword.'
							<br>GST ID : '.$gstno.'
							<br>PAN No : '.$panno.'</b>
							</td>';
				$row_gst .='<td colspan="2">';
				$row_gst .='<b>IGST 18%</b>';
				$row_gst .='</td>';
				$row_gst .='<td>';
				$row_gst .='<b>'.$igst_amount.'</b>';
				$row_gst .='</td>';
				$row_gst .='</tr>';
				$row_gst .='<tr>';
				$row_gst .='<td colspan="2">';
				$row_gst .='<b>Total</b>';
				$row_gst .='</td>';
				$row_gst .='<td><b>'.$InvoiceTotalAmount.'</b></td>';
				$row_gst .='</tr>';
				$row_gst .='<tr>';
				$row_gst .='<td colspan="3">';
				$row_gst .='<b>For Evergrow Solutions Pvt. Ltd.<br><br>
									<b>Director </b><br>
									(Electronic Invoice do not need signature)</b>';
				$row_gst .='</td>';
				$row_gst .='</tr>';
										
			}
									
			if($discount_amount != '') 
			{
				$row_discount .='<tr>';
				$row_discount .='<td colspan="2"><b>Less 36000/- discount (1 yr. Membership Free)</b></td>';
				$row_discount .='<td colspan="2"><b>DISCOUNT </b></td>';
				$row_discount .='<td><b>'.$discount_amount.'</b></td>';
				$row_discount .='</tr>';
			}
			else 
			{
				$row_discount .='';
			}
		
			$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,
					"[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,
					"[company_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			
					);
		 	
		  			//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("This is Invoice ");
										
			 	 $fromEmail = array('nagma.m@evergrowsolutions.com' =>'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') // 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';</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 
	{
			// All members 
			 	  $sql = "select 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
			 			    from mstmember x
					  		 inner join trninvoicetomember a on x.memberid = a.memberid 
					  		 inner join trninvoicetomemberdetails b on a.memberinvoicesid = b.memberinvoicesid
					  		 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 and  a.isdeleted= 0 and quotes_proforma_invoice = 2 
					  		 group by a.memberinvoicesid";
					//echo $sql;
					$sqllist = $obj->getCompany('','',$sql);
					if(is_array($sqllist))
					{
						$rowcount = count($sqllist);
					}
					
					// 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 a.TotalAmount,b.InvoiceTotalAmount FROM user_company_payment_header a  
										//inner join trninvoicetomember b on a.memberinvoicesid=b.memberinvoicesid";
				  $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;
}   



	
	
?>
