package com.reallinkbilling.download;

import static java.awt.Color.WHITE;
import static org.apache.pdfbox.pdmodel.font.PDType1Font.HELVETICA;
import static org.vandeseer.easytable.settings.HorizontalAlignment.CENTER;
import static org.vandeseer.easytable.settings.HorizontalAlignment.RIGHT;
import static org.vandeseer.easytable.settings.VerticalAlignment.BOTTOM;
import static org.vandeseer.easytable.settings.HorizontalAlignment.LEFT;

import java.awt.Color;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDPageContentStream.AppendMode;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;
import org.vandeseer.easytable.TableDrawer;
import org.vandeseer.easytable.structure.Row;
import org.vandeseer.easytable.structure.Table;
import org.vandeseer.easytable.structure.Table.TableBuilder;
import org.vandeseer.easytable.structure.cell.TextCell;

import com.reallinkbilling.cipher.EncryptionDecryption;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.resource.NumberToWordsConverter;
import com.opensymphony.xwork2.ActionSupport;

public class DownloadCustomerPaymentSlip extends ActionSupport implements SessionAware{



	    

	/**
	 * 
	 */
	private static final long serialVersionUID = -488761454485401478L;

	private HttpSession session;
	
	public HttpServletRequest request;
	public HttpServletResponse response;
	private SessionMap<String,Object> sessionMap;
	
	
	private String key;
	private String paymentId;
	private String size;
	private String lang;
	private String paymentDate;
	private String custName;
	private String amount;
	private String paymentDetails;
   
	
	private final static Color BLUE_DARK = new Color(76, 129, 190);
	private final static Color BLUE_LIGHT_1 = new Color(186, 206, 230);
	private final static Color BLUE_LIGHT_2 = new Color(218, 230, 242);

	private final static Color GRAY_LIGHT_1 = new Color(245, 245, 245);
	private final static Color GRAY_LIGHT_2 = new Color(240, 240, 240);
	private final static Color GRAY_LIGHT_3 = new Color(216, 216, 216);
	private static final float PADDING10 = 10f;
	private static final float PADDING20 = 20f;
	private static final float PADDING30 = 30f;
	private static final float PADDING40 = 40f;
	private static final float PADDING50 = 50f;
	
	public void download(){
	
			this.setSession(ServletActionContext.getRequest().getSession(false)); 
		
	        if(this.getSession()==null || this.getSession().getAttribute("login")==null){ 
	        	addActionMessage("Please Login First !!!");
	         }  
	        else{
	        	
	        	
				Date d = new Date();
	        	SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
	        	
	        	String today = dateFormat.format(d);
				
	        	  java.util.Date date = new java.util.Date();
        	      long t = date.getTime();	        	     
        	      java.sql.Time time = new java.sql.Time(t);
        	      
	        	String shopId = (String) this.getSessionMap().get("shopId");
	    		String shopCode = (String) this.getSessionMap().get("shopCode");
	    		  

	        	Connection connection = null;
				PreparedStatement preparedStatement= null;
				ResultSet resultSet = null;
			
				String keyDetails [] = EncryptionDecryption.decrypt(this.getKey()).split("#");
    			String customerId = keyDetails[0];
    				
				String sql = "";
				String db = (String)  this.getSessionMap().get("db");
				
				try
				{
					connection = GetDBConnection.getDBConnection(db);
					  
					sql = "SELECT "
	       					+ "customer_id,"
	       					+ "customer_name,"
	       					+ "DATE_FORMAT(entry_date,'%d-%m-%Y'),"
	       					+ "payment_amount," 
	       					+ "payment_details "
	       					+ "FROM "
	       					+ "shop_customer_payment_master "
	       					+ "WHERE "
	       					+ "entry_id = ? "
	       					+ "AND "
    						+ "shop_id = ? "
							+ "AND "
							+ "shop_code = ?";
					
					preparedStatement = connection.prepareStatement(sql);
					preparedStatement.setString(1, this.getPaymentId());
	       			preparedStatement.setString(2, shopId);
    				preparedStatement.setString(3, shopCode);
    				   
    				resultSet = preparedStatement.executeQuery();
    				
    				if(resultSet.next())
    				{
    					this.setCustName(resultSet.getString(2));
       					this.setPaymentDate(resultSet.getString(3));
       					this.setAmount(resultSet.getString(4));
       					this.setPaymentDetails(resultSet.getString(5));	 
       					
    					
    				}else {
    					addActionError(this.getText("message.error.urlTemperedInformationNotFound"));
    				}
    				
    				
    				
    				if (this.getLang().equalsIgnoreCase("eng") && this.getSize().equals("A4"))
    						{

    					

    						// System.out.println("Bill Type:"+billInfoDAO.getBillType());
    						PDDocument document = new PDDocument();
    						PDPage page = null;
    						page = new PDPage(PDRectangle.A4);

    						document.addPage(page);
    						
    						response = ServletActionContext.getResponse();

    						request = ServletActionContext.getRequest();

    						String path = request.getSession().getServletContext().getRealPath("/images/");

    						
    						String shopnameenglish = (String) this.getSessionMap().get("shopnameenglish");
    						String address = (String) this.getSessionMap().get("shopaddresseng");
    						String shopCustCareNumber = (String) this.getSessionMap().get("shopcustcarenumber");

    						 
    						PDPageContentStream contentStream = new PDPageContentStream(document, page, AppendMode.APPEND, true);

    						
    						
    						
    						
    						
    						
    						
    						Table printedOn;
    						Table header;
    						Table paymentTable;
    						Table paymentTable2;
    						Table signature;
    						
    						
    						
    						TableBuilder tableprintedOnBuilder = Table.builder().addColumnsOfWidth(550).font(HELVETICA)
    								.borderColor(Color.BLACK).horizontalAlignment(CENTER);

    						
    						Row printedOnDetailsRow = Row.builder()
    								.add(TextCell.builder().text("Printed On : "+today+" "+time)
    										.borderWidthBottom(0F).horizontalAlignment(RIGHT).build())
    								.backgroundColor(WHITE).textColor(Color.BLACK).font(HELVETICA)
    								.fontSize(8).horizontalAlignment(CENTER).build();

    						tableprintedOnBuilder.addRow(printedOnDetailsRow);
    						
    						printedOn = tableprintedOnBuilder.build();

    						

    						TableBuilder tableHeaderBuilder = Table.builder().addColumnsOfWidth(550).font(HELVETICA)
    								.borderColor(Color.BLACK).horizontalAlignment(CENTER);

    						
    						Row paymentDetailsRow = Row.builder()
    								.add(TextCell.builder().text("Payment Receipt")
    										.paddingTop(5F)    
    							            .paddingBottom(5F)
    							            .borderWidthBottom(0.5F).horizontalAlignment(CENTER).build())
    								.backgroundColor(WHITE).textColor(Color.BLACK).font(PDType1Font.HELVETICA_BOLD)
    								.fontSize(10).horizontalAlignment(CENTER).build();

    						Row headerName = Row.builder()
    								.add(TextCell.builder().text(shopnameenglish).horizontalAlignment(CENTER)
    										.paddingTop(5F)    
    							            .borderWidth(0).lineSpacing(10F).build())
    								.backgroundColor(WHITE).textColor(Color.BLACK).font(PDType1Font.HELVETICA_BOLD)
    								.fontSize(20).horizontalAlignment(CENTER).build();

    						Row addressRow = Row.builder()
    								.add(TextCell.builder().text(address).borderWidthBottom(0F)
    										.horizontalAlignment(CENTER).build())
    								.backgroundColor(WHITE).textColor(Color.BLACK).font(PDType1Font.HELVETICA_BOLD)
    								.fontSize(9).horizontalAlignment(CENTER).build();
    						
    						Row mobileNoRow = Row.builder()
    								.add(TextCell.builder().text("Contact : "+shopCustCareNumber).borderWidthBottom(0.5F)
    										.paddingBottom(5F)
    							            .horizontalAlignment(CENTER).build())
    								.backgroundColor(WHITE).textColor(Color.BLACK).font(PDType1Font.HELVETICA_BOLD)
    								.fontSize(9).horizontalAlignment(CENTER).build();

    						
    						
    						tableHeaderBuilder.addRow(paymentDetailsRow);
    						tableHeaderBuilder.addRow(headerName);
    						tableHeaderBuilder.addRow(addressRow);
    						tableHeaderBuilder.addRow(mobileNoRow);
    						
    						header = tableHeaderBuilder.build();

    						TableBuilder paymentDetails = Table.builder().addColumnsOfWidth(270, 280)
    								.font(HELVETICA).borderWidth(0.5F).borderColor(Color.BLACK);

    						Row receiptNoDateRow1 = Row.builder()
    							    .add(TextCell.builder()
    							            .text("Receipt No : " + this.getPaymentId())
    							            .horizontalAlignment(LEFT)
    							            .fontSize(11)
    							            .lineSpacing(12F)
    							            .borderWidthTop(0.5F)
    							            .borderWidthBottom(1.5F)  
    							            .borderWidthLeft(0.5F)
    							            .borderWidthRight(0.0F)  
    							            .paddingTop(5F)    
    							            .paddingBottom(5F)
    							            .font(PDType1Font.HELVETICA_BOLD)
    							            .textColor(Color.BLACK)
    							            .backgroundColor(WHITE)
    							            .build())
    							    .add(TextCell.builder()
    							            .text("Receipt Date : " + this.getPaymentDate())
    							            .horizontalAlignment(RIGHT)
    							            .fontSize(11)
    							            .lineSpacing(12F)
    							            .borderWidthTop(0.5F)
    							            .borderWidthBottom(1.5F)  
    							            .borderWidthLeft(0.0F)    
    							            .borderWidthRight(0.5F)
    							            .paddingTop(5F)    
    							            .paddingBottom(5F)
    							            .font(PDType1Font.HELVETICA_BOLD)
    							            .textColor(Color.BLACK)
    							            .backgroundColor(WHITE)
    							            .build())
    							    .build();


    						paymentDetails.addRow(receiptNoDateRow1);
    						paymentTable = paymentDetails.build();

    						
    						
    						Float totalAmounttoConvert = Float.parseFloat(this.getAmount());

    						DecimalFormat dfConvert = new DecimalFormat("##.##");
    						String convertedAmount = NumberToWordsConverter
    								.getConverted(dfConvert.format(totalAmounttoConvert));

    						
    						TableBuilder paymentDetails2 = Table.builder().addColumnsOfWidth(200, 350)
    								.font(HELVETICA).borderWidth(1).borderColor(Color.BLACK);

    						
    						Row customerDetailsRow3 = Row.builder()
    							    .add(TextCell.builder()
    							            .text("Received With, Thanks From, ")
    							            .horizontalAlignment(LEFT)
    							            .fontSize(11)
    							            .borderWidth(0.5F)
    							            .lineSpacing(5F)
    							            .paddingTop(8F)    
    							            .paddingBottom(8F)
    							            .font(PDType1Font.HELVETICA) 
    							            .textColor(Color.BLACK)
    							            .backgroundColor(WHITE)
    							            .build())
    							    .add(TextCell.builder()
    							            .text(this.getCustName())
    							            .horizontalAlignment(LEFT)
    							            .fontSize(11)
    							            .borderWidth(0.5F)
    							            .lineSpacing(5F)
    							            .paddingTop(8F)    
    							            .paddingBottom(8F)
    							            .font(PDType1Font.HELVETICA_BOLD) 
    							            .textColor(Color.BLACK)
    							            .backgroundColor(WHITE)
    							            .build())
    							    .horizontalAlignment(CENTER)
    							    .build();

    						Row amountRow4 = Row.builder()
    								 .add(TextCell.builder()
     							            .text("Sum Of Rupees, ")
     							            .horizontalAlignment(LEFT)
     							            .fontSize(11)
     							            .borderWidth(0.5F)
     							            .lineSpacing(5F)
     							            .paddingTop(8F)    
   							                .paddingBottom(8F)
   							                .font(PDType1Font.HELVETICA) 
     							            .textColor(Color.BLACK)
     							            .backgroundColor(WHITE)
     							            .build())
    								 .add(TextCell.builder()
     							            .text(convertedAmount)
     							            .horizontalAlignment(LEFT)
     							            .fontSize(11)
     							            .borderWidth(0.5F)
     							            .lineSpacing(5F)
     							            .paddingTop(8F)    
   							                .paddingBottom(8F)
   							                .font(PDType1Font.HELVETICA_BOLD) 
     							            .textColor(Color.BLACK)
     							            .backgroundColor(WHITE)
     							            .build())
     							    .horizontalAlignment(CENTER)
     							    .build();
    								
    						Row byCashRow5 = Row.builder()
    								
    								.add(TextCell.builder()
     							            .text("By Cash, ")
     							            .horizontalAlignment(LEFT)
     							            .fontSize(11)
     							            .borderWidth(0.5F)
     							            .lineSpacing(5F)
     							            .paddingTop(8F)    
   							                .paddingBottom(8F)
   							                .font(PDType1Font.HELVETICA) 
     							            .textColor(Color.BLACK)
     							            .backgroundColor(WHITE)
     							            .build())
    								 .add(TextCell.builder()
     							            .text(this.getAmount()+"/-")
     							            .horizontalAlignment(LEFT)
     							            .fontSize(11)
     							            .borderWidth(0.5F)
     							            .lineSpacing(5F)
     							            .paddingTop(8F)    
  							                .paddingBottom(8F)
  							                .font(PDType1Font.HELVETICA_BOLD) 
     							            .textColor(Color.BLACK)
     							            .backgroundColor(WHITE)
     							            .build())
     							    .horizontalAlignment(CENTER)
     							    .build();
    						
    								
    							
    						 Row byCashRow6 = Row.builder()
     								
     								.add(TextCell.builder()
      							            .text("Details : " + this.getPaymentDetails())
      							            .colSpan(2)
      							            .horizontalAlignment(LEFT)
      							            .fontSize(11)
      							            .borderWidth(0.5F)
      							            .lineSpacing(5F)
      							            .paddingTop(8F)    
    							                .paddingBottom(8F)
    							                .font(PDType1Font.HELVETICA) 
      							            .textColor(Color.BLACK)
      							            .backgroundColor(WHITE)
      							            .build())
     								 
      							    .horizontalAlignment(CENTER)
      							    .build();
     						
     						paymentDetails2.addRow(customerDetailsRow3);
     						paymentDetails2.addRow(amountRow4);
     						paymentDetails2.addRow(byCashRow5);
     						paymentDetails2.addRow(byCashRow6);
     						paymentTable2 = paymentDetails2.build();

     						TableBuilder signatureBuilder = Table.builder()
    							    .addColumnsOfWidth(200, 100, 200) 
    							    .font(HELVETICA)
    							    .borderColor(Color.BLACK)
    							    .horizontalAlignment(CENTER);

    							
    							Row shopNameRow = Row.builder()
    							    .add(TextCell.builder().text("").borderWidth(0).build()) 
    							    .add(TextCell.builder().text("").borderWidth(0).build()) 
    							    .add(TextCell.builder().text(shopnameenglish).verticalAlignment(BOTTOM)
    							        .horizontalAlignment(RIGHT).borderWidth(0).lineSpacing(0.5F).build()) 
    							    .backgroundColor(Color.WHITE).textColor(Color.BLACK).font(PDType1Font.HELVETICA_BOLD)
    							    .fontSize(8).horizontalAlignment(CENTER).height(20F).build();

    						   	
    							Row signRow = Row.builder()
    							    .add(TextCell.builder().text("Customer Signature").verticalAlignment(BOTTOM)
    							        .horizontalAlignment(LEFT).borderWidth(0).lineSpacing(0.5F).build()) 
    							    .add(TextCell.builder().text("").borderWidth(0).build())                
    							    .add(TextCell.builder().text("Authorised Signature").verticalAlignment(BOTTOM)
    							        .horizontalAlignment(RIGHT).borderWidth(0).lineSpacing(0.5F).build()) 
    							    .backgroundColor(Color.WHITE).textColor(Color.BLACK).font(PDType1Font.HELVETICA_BOLD)
    							    .fontSize(10).horizontalAlignment(CENTER).height(20F).build();

    							
    							signatureBuilder.addRow(shopNameRow);
    							signatureBuilder.addRow(signRow);

    							signature = signatureBuilder.build();
    						

    						float startY = page.getMediaBox().getHeight() - PADDING20;

    						TableDrawer.builder().contentStream(contentStream).table(printedOn).startX(PADDING20)
							.startY(startY + 12).build().draw();

    						TableDrawer.builder().contentStream(contentStream).table(header).startX(PADDING20)
    								.startY(startY- 5).build().draw();

    						TableDrawer.builder().contentStream(contentStream).table(paymentTable).startX(PADDING20)
    								.startY(startY - 95).build().draw();

    						TableDrawer.builder().contentStream(contentStream).table(paymentTable2).startX(PADDING20)
							.startY(startY - 135).build().draw();

    						TableDrawer.builder().contentStream(contentStream).table(signature).startX(PADDING20)
							.startY(startY - 290).build().draw();

    						float tableX = 20f;      // left position
    						float tableY = 820f;     // top position of the table
    						float tableWidth = 550f; // total width of the table
    						float tableHeight = 340f; // fixed height for visual block (adjust as needed)

    						
    						contentStream.setStrokingColor(Color.BLACK);   // border color
    						contentStream.setLineWidth(0.5f);              // border thickness

    						contentStream.addRect(tableX, tableY - tableHeight, tableWidth, tableHeight);  // draw table border
    						contentStream.stroke();


      						 float currectY = startY - 450;
      					        
      						
      						
      						TableDrawer.builder().contentStream(contentStream).table(printedOn).startX(PADDING20)
   							.startY(currectY + 12).build().draw();

      						TableDrawer.builder().contentStream(contentStream).table(header).startX(PADDING20)
      								.startY(currectY- 5).build().draw();

      						TableDrawer.builder().contentStream(contentStream).table(paymentTable).startX(PADDING20)
      								.startY(currectY - 95).build().draw();

      						TableDrawer.builder().contentStream(contentStream).table(paymentTable2).startX(PADDING20)
   							.startY(currectY - 135).build().draw();

      						TableDrawer.builder().contentStream(contentStream).table(signature).startX(PADDING20)
   							.startY(currectY - 290).build().draw();

      						 tableX = 20f;      // left position
      						 tableY = 370f;     // top position of the table
      						 tableWidth = 550f; // total width of the table
      						 tableHeight = 340f; // fixed height for visual block (adjust as needed)

      						
      						contentStream.setStrokingColor(Color.BLACK);   // border color
      						contentStream.setLineWidth(0.5f);              // border thickness

      						contentStream.addRect(tableX, tableY - tableHeight, tableWidth, tableHeight);  // draw table border
      						contentStream.stroke();
      						
    						contentStream.close();

    						
    						// System.out.println(path);

    						document.save(path + "/customer_salary_slip_PaymentDate-"+this.getPaymentDate()+".pdf");
    						document.close();

    						response.setHeader("Content-disposition", "inline; filename = "+"customer_salary_slip_PaymentDate-"+this.getPaymentDate()+".pdf");
    						response.setContentType("application/pdf");
    						@SuppressWarnings("resource")
    						FileInputStream fileInputStream = new FileInputStream(path + "/customer_salary_slip_PaymentDate-"+this.getPaymentDate()+".pdf");
    						PrintWriter out = response.getWriter();
    						int bytes;
    						while ((bytes = fileInputStream.read()) != -1) {
    							out.write(bytes);
    						}
    						fileInputStream.close();
    						out.flush();
    						out.close();

    					

    				}

    				
					
				}
				catch (SQLException e) 
				{

					e.printStackTrace();
					addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Collection details could not be found !");


				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}catch(Exception e)
				{
					e.printStackTrace();
				}
				finally {
					
					
					if(resultSet !=null)
					{
						try {resultSet.close(); resultSet = null;} catch (SQLException e) {}
					}
					if(preparedStatement != null)
					{
						try {preparedStatement.close(); preparedStatement = null;} catch (SQLException e) {}
					}
					if(connection != null)
					{
						
						try {connection.close();
						 connection = null;
						}catch (SQLException e) {}
					}
				
			}
        }
}



	public HttpSession getSession() {
		return session;
	}



	public void setSession(HttpSession session) {
		this.session = session;
	}
      

	public SessionMap<String, Object> getSessionMap() {
		return sessionMap;
	}

	public void setSessionMap(SessionMap<String, Object> sessionMap) {
		this.sessionMap = sessionMap;
	}

	@Override  
	public void setSession(Map<String, Object> map) {  
	    sessionMap=(SessionMap<String, Object>)map;  
	}



	public HttpServletRequest getRequest() {
		return request;
	}



	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}



	public HttpServletResponse getResponse() {
		return response;
	}



	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}



	public String getKey() {
		return key;
	}



	public void setKey(String key) {
		this.key = key;
	}



	public String getPaymentId() {
		return paymentId;
	}



	public void setPaymentId(String paymentId) {
		this.paymentId = paymentId;
	}



	public String getSize() {
		return size;
	}



	public void setSize(String size) {
		this.size = size;
	}



	public String getLang() {
		return lang;
	}



	public void setLang(String lang) {
		this.lang = lang;
	}



	public String getPaymentDate() {
		return paymentDate;
	}



	public void setPaymentDate(String paymentDate) {
		this.paymentDate = paymentDate;
	}



	public String getCustName() {
		return custName;
	}



	public void setCustName(String custName) {
		this.custName = custName;
	}



	public String getAmount() {
		return amount;
	}



	public void setAmount(String amount) {
		this.amount = amount;
	}



	public String getPaymentDetails() {
		return paymentDetails;
	}



	public void setPaymentDetails(String paymentDetails) {
		this.paymentDetails = paymentDetails;
	}



	
    
}

