<?php

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


if($G_memberid > 0)
{
$company_obj  					= new Company();		
$obj  							=  new Product();
$invoice_obj	=	new Invoice_frquotation();
$client_obj  					=	new Client();


 	$memberid = $G_memberid;
 	$billed_membercompanyid 	= (int)($_GET['companyid']);
	$billing_membercompanyid 	= (int)($_GET['billing_membercompanyid']);
	$memberinvoicesid 			= (int)($_GET['memberinvoicesid']);


		if($_POST['SUBMIT'])
		{
			$invoicearray['memberid'] 							= $memberid;
		   $invoicearray['memberinvoicesid'] 				= $memberinvoicesid;
			$invoicearray['billed_membername'] 				= sanitize($_POST['txtcompany_name'],SQL);
			$invoicearray['inv_Add1'] 							= sanitize($_POST['inv_Add1'],SQL);
			$invoicearray['inv_Add2'] 							= sanitize($_POST['inv_Add2'],SQL);
			$invoicearray['inv_Add3'] 							= sanitize($_POST['inv_Add3'],SQL);
			$invoicearray['inv_CityName'] 					= sanitize($_POST['inv_CityName'],SQL);
			$invoicearray['inv_Pin'] 							= sanitize($_POST['inv_Pin'],SQL);
			$invoicearray['inv_StateName'] 					= sanitize($_POST['inv_StateName'],SQL);
			$invoicearray['inv_head_Stateid'] 				= sanitize($_POST['inv_head_Stateid'],SQL);
			$invoicearray['inv_GST_no'] 						= sanitize($_POST['gstno'],SQL);
			$invoicearray['inv_Country'] 						= sanitize($_POST['txtcountry'],SQL);
			$invoicearray['inv_CityName'] 					= sanitize($_POST['txtcompany_city'],SQL);
			$gstno_available 	= sanitize($_POST['gstno'],SQL);
			$gstno_notavailable       = 'GST Not available';
			$gstno_notapplicable         = 'GST Not applicable';
			if($_POST['txtgstapplicable'] == '1')
			{
				if($gstno_available == '')
				{
					$invoicearray['inv_GST_no'] 			= $gstno_notavailable;
				}
				else if($gstno_available != '')
				{
					$invoicearray['inv_GST_no'] 			= $gstno_available;
				}

			}

			if($_POST['txtgstapplicable'] == '2')
			{
				if($gstno_available == '')
				{
					$invoicearray['inv_GST_no'] 			= $gstno_notapplicable;
				}
				else if($gstno_available != '')
				{
					$invoicearray['inv_GST_no'] 			= $gstno_available;
				}

			}
			if($_POST['txtgstapplicable'] == '3')
			{
				if($gstno_available == '')
				{
					$invoicearray['inv_GST_no'] 			= $gstno_notavailable;
				}
				/*else if($gstno_available != '')
				{
					$invoicearray['inv_GST_no'] 			= $gstno_available;
				}*/

			}
			
			
			$invoicearray['quotes_proforma_invoice']	=	0;
			$invoicearray['invoiceno'] 					= $_POST['txtinv_no'];
			$invoicearray['invoicedate'] 					= date("Y-m-d",strtotime($_POST['txtinv_date']));
			$invoicearray['duedate'] 						= date("Y-m-d",strtotime($_POST['txtinv_duedate']));
			$invoicearray['status_invoice'] 						= $_POST['txtgstapplicable'];
			$invoicearray['last_edited_by']			  = $G_memberid;
			$invoicearray['last_edit_date']          = date('Y-m-d h:m:s');
			
			
			
		
			
			
			
 		if( $_POST['txtgstapplicable'] == '1' || $_POST['txtgstapplicable'] == '2' || $_POST['txtgstapplicable'] == '3')
		{
			// If Product Not Available Start Of product addition
			$itemname_display_array	= $_POST['txtitemname_asperinvoice_display1'];
			if(is_array($itemname_display_array))
			{
				$rowcountitemname = count($itemname_display_array);
			}
			
			for($j=0;$j<$rowcountitemname;$j++)
			{
				$itemname	= $itemname_display_array[$j];	
				$product_available_query = "Select * from mstproducts where productname = '$itemname' and membercompanyid = $billing_membercompanyid ";	
				$productrow = $obj-> getProduct('',$product_available_query);
				$productname = $productrow[0]['productname'];
				if($itemname != $productname)
				{
					$addproduct['itemno'] 			 = $_POST['txtitemno_asperinvoice_display1'][$j];
					$addproduct['productname'] 	 = $_POST['txtitemname_asperinvoice_display1'][$j];
					$addproduct['hsn_code'] 		 = $_POST['txthsncode_asperinvoice_display1'][$j];
					$addproduct['price'] 			 = $_POST['txtitemprice_asperinvoice_display1'][$j];
					$addproduct['membercompanyid'] = $billing_membercompanyid;
					$addproduct['memberid'] 		 = $memberid;
					$addproductrow = $obj-> AddProduct($addproduct);
					
				}				
			}	
			// End of product addition
				
			$cgstper 				= 0;
			$cgstamt 				= 0;
			$sgstper 				= 0;
			$sgstamt 				= 0;	

			if($billed_membercompanyid > 0)
			{
				$taxtype   = CheckTypeOfGST($billed_membercompanyid,$statecode);
			}
			else 
			{
				$taxtype   = CheckTypeOfGSTWithoutCustomerId($stateid,$statecode);
			}
				
				
			if($taxtype == 'IGST') 
			{		
				$tax_percent  = $_POST['tax'];
			 	$invoicearray['igst_percentage'] = $tax_percent	;
				$invoicearray['igst_amount'] 		= $_POST['gst_amt'];
					
			}
			//else if($taxtype == 'SGST' || $taxtype == 'CGST'){
			 else if($taxtype == 'SC_GST'){
					$tax_percent  = $_POST['tax'];
						$invoicearray['cgst_percentage'] = $tax_percent / 2;
						$cgst_amount 							= $_POST['gst_amt']/2;
						$invoicearray['cgst_amount'] 		= $cgst_amount;
						$invoicearray['sgst_percentage'] = $tax_percent / 2;
						$invoicearray['sgst_amount'] 		= $cgst_amount;
			}
			if($_POST['discounts'] > 0)
			{
				if($_POST['select_discounts_mode'] == '%') 
				{
					$invoicearray['discount_percentage'] 	= $_POST['discounts'];
				}
				else if($_POST['select_discounts_mode'] == '1')
				{
					$invoicearray['discount_flat'] 			= $_POST['discounts'];
				}
				$discount_amount 									= $_POST['storefinaldiscountamt'];
				$invoicearray['discount_amount'] 			= $discount_amount;			
					
				$invoicearray['InvoiceBaseAmount'] 			= $_POST['invoicebaseamount'];
				$invoicearray['InvoiceTotalAmount'] 		= $_POST['final_amt'];
				$invoicearray['InvoiceSubTotalAmount'] 		= $_POST['subtotal_amt'];
				$invoicearray['SEZ_remark'] 	= "";
			}
			else 
			{
			    $invoicearray['discount_percentage'] 	= '';
			    $invoicearray['discount_flat'] 			= '';
			    $invoicearray['discount_amount'] 			= '';
				$invoicearray['InvoiceBaseAmount'] 			= $_POST['invoicebaseamount'];
				$invoicearray['InvoiceTotalAmount'] 		= $_POST['final_amt'];
				$invoicearray['InvoiceSubTotalAmount'] 		= $_POST['subtotal_amt'];
			
				$invoicearray['SEZ_remark'] 	= "";
			}
		
				$wherecondition ="memberinvoicesid =".$memberinvoicesid."";
				 $edit_invoice = $invoice_obj -> EditInvoice($invoicearray,$wherecondition);
				//print_r($invoicearray);	
					
			
					 
					/* if($invoice_fromcompanyname != '') {
						$data['companyname'] = $_POST['txturcompany_name'];
					 	//print_r($data);
					 	$wherecompany = " membercompanyid = $billing_membercompanyid ";
				 		$company_details_data = $company_obj->EditCompany($data,$wherecompany);	
				 }	*/
				 
		$itemno   = $_POST['txtitemno_asperinvoice_display1'];
		
		if(is_array($itemno))
		{
			$rowcountitemno = count($itemno);
		}
		
		
		if($edit_invoice == true) 
		{
				 		
		 	$delete_invoice_details = $invoice_obj -> DeleteInvoiceDetails("memberinvoicesid =".$memberinvoicesid);
	
			if($delete_invoice_details == true) 
			{
				if($memberinvoicesid > '')
				{
					for($j=0;$j<$rowcountitemno;$j++)
					{
						 $itemno1	= $itemno[$j];
						 $itemname	= $itemname_display_array[$j];
						 $sqltext = "Select * from mstproducts  where isdeleted = 0 and  ( itemno = '".($itemno1)."' or productname  = '".($itemname)."') and membercompanyid = $billing_membercompanyid order by Product_ID desc";
				
						 $row = $obj-> getProduct('',$sqltext);
						 $total = 0;
						 $quantity  = $_POST['txtitemquantity_asperinvoice_display1'][$j];
						 $productid = $row[0]['Product_ID'];
						 if($quantity > 0)
						 {
								$memberinvoicedetail['memberinvoicesid'] 		= $memberinvoicesid;
								$memberinvoicedetail['itemno'] 					= $row[0]['itemno'];
								$memberinvoicedetail['productname'] 			= $row[0]['productname'];
								//$memberinvoicedetail['product_description'] 	= $row[0]['product_description'];	
								$memberinvoicedetail['quantity '] 				= $quantity;	
								
								/*$memberinvoicedetail['product_description'] 		= $_POST['txtitemdescription_asperinvoice_display2'][$j];
								//}	
								$memberinvoicedetail['ProductBaseAmount'] 		= $_POST['txtitemprice_asperinvoice_display1'][$j];
								$memberinvoicedetail['ProductTotalAmount'] 		= $_POST['txtitemprice_asperinvoice_display1'][$j]*$quantity;*/

								$memberinvoicedetail['product_description'] 		= sanitize($_POST['txtitemdescription_asperinvoice_display2'][$j],SQL);
								//}
								//}
									
								$memberinvoicedetail['ProductBaseAmount'] 		= sanitize($_POST['txtitemprice_asperinvoice_display1'][$j],SQL);
								$memberinvoicedetail['ProductTotalAmount'] 		= sanitize($_POST['txtitemprice_asperinvoice_display1'][$j]*$quantity,SQL);
							
				
								$memberinvoicedetail['billed_membercompanyid'] 				= $billed_membercompanyid;
								$add_memberinvoicedetail = $invoice_obj -> AddInvoiceDetails($memberinvoicedetail);
						 }
					}	
				 }	
				}
		}	
	}//if gst as per invoice complete
	
				if($edit_invoice)
				{
					$redirect_url = DOC_ROOT."admin/viewQuotes.php";
					header("Location: $redirect_url");
	    			exit;
				}	
		}
		else 
		{
				
			
					
			$sql = "select * from trninvoicetomember_frquotation where memberinvoicesid = $memberinvoicesid ";
			
				$inv_add_list 	= $invoice_obj-> getInvoice('',$sql);	
				//print_r($inv_add_list);	
		
				$inv_add_data1 = count($inv_add_list);
		
				for($i=0;$i<$inv_add_data1;$i++)
				{
					$billed_membername 			= $inv_add_list[$i]['billed_membername'];
					$invoiceno						= $inv_add_list[$i]['invoiceno'];
					$invoicedate					= date("d-m-Y",strtotime($inv_add_list[$i]['invoicedate']));
					$duedate							= date("d-m-Y",strtotime($inv_add_list[$i]['duedate']));
					
					$discount_percentage			= $inv_add_list[$i]['discount_percentage'];
					$discount_flat					= $inv_add_list[$i]['discount_flat'];
					$discount_amount				= $inv_add_list[$i]['discount_amount'];
					$InvoiceBaseAmount			= $inv_add_list[$i]['InvoiceBaseAmount'];
					$InvoiceTotalAmount			= $inv_add_list[$i]['InvoiceTotalAmount'];
					$InvoiceSubTotalAmount			= $inv_add_list[$i]['InvoiceSubTotalAmount'];
					$cgst_amount					= $inv_add_list[$i]['cgst_amount'];
			
					$sgst_amount					= $inv_add_list[$i]['sgst_amount'];
					$igst_amount					= $inv_add_list[$i]['igst_amount'];
					$sgst_percentage 				= $inv_add_list[$i]['sgst_percentage'];
					$cgst_percentage 				= $inv_add_list[$i]['cgst_percentage'];
					$igst_percentage 				= $inv_add_list[$i]['igst_percentage'];
					$inv_Add1						= $inv_add_list[$i]['inv_Add1'];
					$inv_Add2						= $inv_add_list[$i]['inv_Add2'];
					$inv_Add3						= $inv_add_list[$i]['inv_Add3'];
					$inv_Pin							= $inv_add_list[$i]['inv_Pin'];
					//$inv_State						= $invoicelist[0]['inv_State'];
					$inv_head_Stateid				= $inv_add_list[$i]['inv_head_Stateid'];
					$inv_StateName					= $inv_add_list[$i]['inv_StateName'];
					$inv_GST_no						=	$inv_add_list[$i]['inv_GST_no'];
					$CityName						= $inv_add_list[$i]['inv_CityName'];
					$Country							= $inv_add_list[$i]['inv_Country'];
				$status_invoice					= $inv_add_list[$i]['status_invoice'];
				$Total_cspercentage           = $cgst_percentage + $sgst_percentage;
				$Total_Final_amount				= $cgst_amount + $sgst_amount; //tax total amount
				if($status_invoice == '0')
		      {
					$valselect0      = "selected";
		      }
		      elseif($status_invoice  == '1')
		      {
					$valselect1      = "selected";
		      }
		       elseif($status_invoice  == '2')
		      {
					$valselect2      = "selected";
		      }
		      elseif($status_invoice  == '3')
		      {
					$valselect3      = "selected";
		      }
			
				if($discount_percentage != '')
		      {
					$dalselect0      = "selected";
					$discount_value_display = $discount_percentage;
		      }
		      elseif($discount_flat != '')
		      {
		      	
					$dalselect1      = "selected";
					$discount_value_display = $discount_flat;
		      }
		      
		      if($cgst_percentage > 0 && $sgst_percentage > 0)
		      {
		      
		      
					$tax_value_display = $Total_cspercentage;
					 $Total_Final_percentage = $Total_cspercentage;
 					//$Total_Final_amount = $Total_csamount;
 					$Total_Final_amount				= $cgst_amount + $sgst_amount; 
					//$talselect0      = "selected";
		      }
		      else
		      {
		      	$tax_value_display = $igst_percentage;
		      $Total_Final_percentage = $igst_percentage;
				$Total_Final_amount = $igst_amount;
					//$talselect1      = "selected";
		      }
		      
		 
		 
				}
				 $getsql = "select * from trninvoicetomemberdetails_frquotation where memberinvoicesid = $memberinvoicesid order by invoicedetailid asc";
				
				 $detaillist	=	$invoice_obj->getInvoiceDetails('',$getsql);
				 if(is_array($detaillist))
				 {
				  	$invoicecount = count($detaillist);
				 }
				 $j = 0;
							
				for($i=0;$i<$invoicecount;$i++)
				{
				
					$itemno			 = $detaillist[$i]['itemno'];	
					$productname 				=	$detaillist[$i]['productname'];	
					$ProductBaseAmount	 	=	$detaillist[$i]['ProductBaseAmount'];
					$quantity					=	$detaillist[$i]['quantity'];
					$hsn_code		 = $detaillist[$i]['hsn_code'];	
					$product_description 		=	$detaillist[$i]['product_description'];
						$ProductTotalAmount		=	$detaillist[$i]['ProductTotalAmount'];
					$j = $i+1;
				
					$trndetails .='<tr id="txtdisplay_'.$j.'">
							<td width="1%"><input type="checkbox" class="case"/></td>
							
							<td style="text-align: center;"><span id="snum'.$j.'" >'.($j).'</span></td>
							
							<td><input type="text"  name="txtitemno_asperinvoice_display1[]" value="'.$itemno.'" data-type="itemno" id="txtitemno_asperinvoice_display_'.$j.'" class="form-control autocomplete_txt data_display" autocomplete="off"><ul id="searchResult_" style="margin-bottom:0px;"></ul></td>
							
							<td><input type="text" name="txtitemname_asperinvoice_display1[]" value="'.$productname.'" data-type="productname" id="txtitemname_asperinvoice_display_'.$j.'" class="form-control autocomplete_txt" autocomplete="off">
								<center><label><b> Item Description </b></label></center>
								<textarea type="text" name="txtitemdescription_asperinvoice_display2[]" value="'.$product_description.'"   data-type="productdescription" id="txtitemdescription_asperinvoice_display_'.$j.'"     class="form-control" rows="7" autocomplete="off">'.$product_description.'</textarea>
							</td>
							
							<td><input type="text" name="txthsncode_asperinvoice_display1[]" value="'.$hsn_code.'" id="txthsncode_asperinvoice_display_'.$j.'" class="form-control" autocomplete="off"></td>
							
							<td><input type="text" name="txtitemprice_asperinvoice_display1[]" value="'.$ProductBaseAmount.'" id="txtitemprice_asperinvoice_display_'.$j.'" class="form-control autooriginalprice_display " autocomplete="off"></td>
						 	<td><input type="text" name="txtitemquantity_asperinvoice_display1[]" value="'.$quantity.'"  data-type="itemno" id="txtitemquantity_asperinvoice_display_'.$j.'" class="form-control  autocomplete_quantity"  autocomplete="off"></td>
							<td><input type="text" name="txtitemsubtotal_asperinvoice_display1[]" value="'.$ProductTotalAmount.'" id="txtitemsubtotal_asperinvoice_display_'.$j.'" class="form-control  autototal_display" autocomplete="off" style="text-align: right;"></td>
						</tr>	';
				}	
					$sqltext_company = "Select * from user_company  where membercompanyid = $billing_membercompanyid ";
				
					$company_data = $company_obj->getCompany('','',$sqltext_company);
					$invoice_fromcompanyname = $company_data[0]['companyname'];
						
					$fromcompany_inv_Add1						= $company_data[0]['Addline1'];
					$fromcompany_inv_Add2						= $company_data[0]['Addline2'];
					$fromcompany_inv_Add3						= $company_data[0]['Add3'];
					$fromcompany_inv_Pin							= $company_data[0]['head_Pin'];
			
					$fromcompany_inv_head_Stateid				= $company_data[0]['head_Stateid1'];
					$fromcompany_inv_StateName					= $company_data[0]['StateName'];
					$fromcompany_inv_GST_no						= $company_data[0]['gstno'];
					$fromcompany_CityName						= $company_data[0]['head_CityName'];
					$fromcompany_Country							= $company_data[0]['Country'];	
					
					require_once("edit_quotes1.html");
		 			
		}
		require_once("header1.html");
		require_once("leftnav.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;
}   

					
	
	

?>