<%@page import="java.util.ArrayList"%>
<%@page import="java.lang.*"%>
<%@page import="com.csc.library.database.StaticProperties"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.Vector"%>
<%@page import="java.util.LinkedHashMap"%>
<%@page import="com.csc.library.report.ReportUDF"%>
<%@page import="javax.servlet.jsp.jstl.sql.Result"%>
<%@page import="java.io.FileOutputStream"%>
<%@page import="com.csc.library.utilities.MyLog"%>
<%@page import="java.io.OutputStream"%>
<%@page import="com.csc.library.database.DataSet"%>

<%@page import="java.io.ByteArrayOutputStream"%>
<%@page import="java.net.URLDecoder"%>
<%@page import="java.text.DecimalFormat"%>
<%@page import="java.net.URLEncoder"%>
<%@page import="java.util.HashMap"%>
<%@page import="com.csc.library.database.DataSet"%>
<%@page import="com.csc.library.session.InitialInquiry"%>
<%@page import="com.csc.library.utilities.UProfile"%>
<%@page import="com.csc.library.utilities.CscCalendar"%>
<%@page import="com.csc.library.session.DbInquiry"%>
<%@page import="com.csc.library.utilities.CheckNull"%>
<%@page import="com.csc.library.entry.HelpEntry"%>
<%@page import="com.itextpdf.text.*"%>
<%@page import="com.itextpdf.text.pdf.*"%>
<%@page import="java.io.ByteArrayOutputStream" %>
<%@page import="com.csc.library.entry.HelpEntry,com.csc.library.system.*,com.csc.library.utilities.*"%>
<%@page import="com.csc.library.entry.*,com.csc.library.database.*,com.csc.library.session.*"  %>
<%@page import="java.util.Iterator,com.csc.library.timeattendance.DayShift,com.csc.library.timeattendance.Shift"  %>
<%@page import="com.csc.library.timeattendance.WorkingShift,com.csc.library.report.ReportUDF"  %>
<%@page import="java.text.DecimalFormat,java.util.*"  %>
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<jsp:useBean id="SALEFORCEO14" class="com.csc.library.system.Task" scope="page"/>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Insert title here</title>
	</head>
	<body>
	<%	
	SALEFORCEO14.setChannel(request,response);
	UIManager screen = (UIManager) SALEFORCEO14.process("SingleEntry","SALEFORCEO14");	
	screen.getRecord().set("dayshift","");
	CscCalendar cs=new CscCalendar();
	ReportUDF rp=new ReportUDF();
		//setHelpEntry(screen);
		DecimalFormat df = new DecimalFormat("#,###,###");
		DecimalFormat two = new DecimalFormat("00");
		String employeeid = request.getParameter("employeeid");
		String date_start = request.getParameter("date_start");
		String date_end = request.getParameter("date_end");
		String Buname = request.getParameter("__mbu");
		String lang = request.getParameter("__language");
		String chkgas = request.getParameter("gas");
		double count = 0.00;
		String setStart = cs.setCscCalendar(date_start).getYYYYMMDD();
		String setEnd = cs.setCscCalendar(date_end).getYYYYMMDD();
		
		
		
		
		screen.referLangOn();
			float[] sizeColumn = new float[] {0.62f,1.1f,0.75f,0.42f,2.3f,0.88f,0.93f,0.78f,0.78f,0.78f,0.78f,0.78f,0.78f,0.78f,0.78f,0.78f,0.78f,0.78f,0.78f,0.67f,0.95f,0.79f};
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		Document document = new Document(PageSize.A4.rotate(),36,36,114,36);
		PdfWriter.getInstance(document, baos);
		document.open();
		document.addTitle("Document Title");
		
	    BaseFont bf = BaseFont.createFont(application.getRealPath("FONTS/Cordia.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
	    BaseFont bfHead = BaseFont.createFont(application.getRealPath("FONTS/Cordia.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
	    Font font = new Font(bf, 13);
	    Font fontHead = new Font(bfHead,20);
		Font fontH = new Font(bfHead, 13);
	    fontH.setStyle(1);
	    //fontHead.setStyle(1); // ตัวหนา
	    
	    // set vlign middle
	    Phrase content = new Phrase("Blah blah blah", font);
		Float fontSize = content.getFont().getSize();
		Float capHeight = content.getFont().getBaseFont().getFontDescriptor(BaseFont.CAPHEIGHT, fontSize);
		Float padding = 5f;
		String [] employee;
		LinkedHashMap<String,Integer> sum = new LinkedHashMap<String,Integer>();
		int tmpHead = 1;
		int h=0;
		String filter = "";
		if(chkgas.equals("0")){
		
		if(!employeeid.equals("")){
		
		filter = "t.employeeid = '"+employeeid+"' and t.dateid between '"+setStart+"' and '"+setEnd+"'";
		}
		else{
		filter = "t.dateid between '"+setStart+"' and '"+setEnd+"'";
		}
		}
		else{
			if(!employeeid.equals("")){
		filter = "t.employeeid = '"+employeeid+"' and t.dateid between '"+setStart+"' and '"+setEnd+"' and t.gas not in('0.00')";
		
		}
		else{
			filter = "t.dateid between '"+setStart+"' and '"+setEnd+"' and t.gas not in('0.00')";
		}
		
		}
		
			PdfPTable detail5 = new PdfPTable(6);
			detail5.setWidthPercentage(100);
			PdfPCell cellDetail5;
		String sql = "select BU2,EDESC from MEMPLOYEE as m inner join tmcustomer as t on m.EMPLOYEEID = t.EMPLOYEEID inner join MBU2 bu2 on m.bu2 = bu2.bu2id where "+filter+" group by BU2,bu2.edesc";
		DataSet ds = new DataSet(sql,screen.getUProfile().get("dbname"),"MEMPLOYEE");
		ds.initConnection(screen.getUProfile());	
		while(ds.next()){
		
			String sql3 = "select bu3id,edesc from mbu3 where parent ='"+ds.getString("bu2")+"'";
			DataSet ds2 = new DataSet(sql3,screen.getUProfile().get("dbname"),"MBU3");
			ds2.initConnection(screen.getUProfile());
			while(ds2.next()){
			//cellDetail5 = new PdfPCell(new Phrase(sql,fontH));
			cellDetail5 = new PdfPCell(new Phrase(ds.getString("bu2")+" : "+ds.getString("edesc"),fontH));
			cellDetail5.setPadding(padding);
			cellDetail5.setPaddingTop(capHeight - fontSize + padding);
			cellDetail5.setHorizontalAlignment(Element.ALIGN_LEFT);
			cellDetail5.setBorder(Rectangle.NO_BORDER);
			cellDetail5.setColspan(6);
			detail5.addCell(cellDetail5);

			cellDetail5 = new PdfPCell(new Phrase(ds2.getString("bu3id")+" : "+ds2.getString("edesc"),fontH));
			cellDetail5.setPadding(padding);
			cellDetail5.setPaddingTop(capHeight - fontSize + padding);
			cellDetail5.setHorizontalAlignment(Element.ALIGN_LEFT);
			cellDetail5.setBorder(Rectangle.NO_BORDER);
			cellDetail5.setColspan(6);
			detail5.addCell(cellDetail5);
			String sqlemp="";
			if(employeeid.equals("")){
			sqlemp = "select m.EMPLOYEEID,fname,lname,emp_position from MEMPLOYEE m inner join TMCUSTOMER t on m.EMPLOYEEID  = t.EMPLOYEEID where M.BU3 = '"+ds2.getString("bu3id")+"' group by m.EMPLOYEEID,fname,lname,emp_position";
			}
			else{
			sqlemp = "select m.EMPLOYEEID,fname,lname,emp_position from MEMPLOYEE m inner join TMCUSTOMER t on m.EMPLOYEEID  = t.EMPLOYEEID where M.BU3 = '"+ds2.getString("bu3id")+"' and m.employeeid = '"+employeeid+"' group by m.EMPLOYEEID,fname,lname,emp_position";
			}
			DataSet ds3 = new DataSet(sqlemp,screen.getUProfile().get("dbname"),"MEMPLOYEE");
			ds3.initConnection(screen.getUProfile());
			while(ds3.next()){
			String position ="";
			String pos = "select * from MPOSITION where POSITIONID = '"+ds3.getString("emp_position")+"'";
			DataSet dsp = new DataSet(pos,screen.getUProfile().get("dbname"),"MPOSITION");
			dsp.initConnection(screen.getUProfile());
			if(dsp.next()){
				position = dsp.getString("tdesc");
			}
			cellDetail5 = new PdfPCell(new Phrase(ds3.getString("employeeid")+"    "+ds3.getString("fname")+"  "+ds3.getString("lname")+"                                                                               "+position,fontH));
			cellDetail5.setPadding(padding);
			cellDetail5.setPaddingTop(capHeight - fontSize + padding);
			cellDetail5.setHorizontalAlignment(Element.ALIGN_LEFT);
			cellDetail5.setBorder(Rectangle.NO_BORDER);
			cellDetail5.setColspan(6);
			detail5.addCell(cellDetail5);
			String sqltm = "select * from tmcustomer where employeeid = '"+ds3.getString("employeeid")+"' and dateid between '"+setStart+"' and '"+setEnd+"' and workplace in ('1')";
			DataSet ds4 = new DataSet(sqltm,screen.getUProfile().get("dbname"),"TMCUSTOMER");
			ds4.initConnection(screen.getUProfile());
			
			while(ds4.next()){
			
			cellDetail5 = new PdfPCell(new Phrase(ds4.getString("dateid"),font));
			cellDetail5.setPadding(padding);
			cellDetail5.setPaddingTop(capHeight - fontSize + padding);
			cellDetail5.setHorizontalAlignment(Element.ALIGN_CENTER);
			cellDetail5.setBorder(Rectangle.NO_BORDER);
			detail5.addCell(cellDetail5);
			cellDetail5 = new PdfPCell(new Phrase(ds4.getString("c_tm_bg")+" - "+ds4.getString("c_tm_en"),font));
			cellDetail5.setPadding(padding);
			cellDetail5.setPaddingTop(capHeight - fontSize + padding);
			cellDetail5.setHorizontalAlignment(Element.ALIGN_CENTER);
			cellDetail5.setBorder(Rectangle.NO_BORDER);
			detail5.addCell(cellDetail5);
			cellDetail5 = new PdfPCell(new Phrase(ds4.getString("con_place"),font));
			cellDetail5.setPadding(padding);
			cellDetail5.setPaddingTop(capHeight - fontSize + padding);
			cellDetail5.setHorizontalAlignment(Element.ALIGN_LEFT);
			cellDetail5.setBorder(Rectangle.NO_BORDER);
			detail5.addCell(cellDetail5);
			cellDetail5 = new PdfPCell(new Phrase(ds4.getString("p_visti"),font));
			cellDetail5.setPadding(padding);
			cellDetail5.setPaddingTop(capHeight - fontSize + padding);
			cellDetail5.setHorizontalAlignment(Element.ALIGN_LEFT);
			cellDetail5.setBorder(Rectangle.NO_BORDER);
			detail5.addCell(cellDetail5);
			cellDetail5 = new PdfPCell(new Phrase(ds4.getString("con_province"),font));
			cellDetail5.setPadding(padding);
			cellDetail5.setPaddingTop(capHeight - fontSize + padding);
			cellDetail5.setHorizontalAlignment(Element.ALIGN_LEFT);
			cellDetail5.setBorder(Rectangle.NO_BORDER);
			detail5.addCell(cellDetail5);
			count = count +  Double.parseDouble(ds4.getString("gas"));
			cellDetail5 = new PdfPCell(new Phrase(ds4.getString("gas"),font));
			cellDetail5.setPadding(padding);
			cellDetail5.setPaddingTop(capHeight - fontSize + padding);
			cellDetail5.setHorizontalAlignment(Element.ALIGN_RIGHT);
			cellDetail5.setBorder(Rectangle.NO_BORDER);
			detail5.addCell(cellDetail5);
			}
			
			int j = 0;
			while(j<3){
				if(j==0 || j==2){
					cellDetail5 = new PdfPCell(new Phrase("__________________",fontH));
					

				}
				else{
				if(lang.equals("tha")){
				cellDetail5 = new PdfPCell(new Phrase("รวม              "+df.format(count)+"    บาท",font));
				}
				else{
				cellDetail5 = new PdfPCell(new Phrase("Total    "+df.format(count)+"   Bath",font));
				
				}
				}
				cellDetail5.setPadding(padding);
				cellDetail5.setPaddingBottom(capHeight - fontSize + padding);
				cellDetail5.setHorizontalAlignment(Element.ALIGN_RIGHT);
				cellDetail5.setBorder(Rectangle.NO_BORDER);
				cellDetail5.setColspan(6);
				detail5.addCell(cellDetail5);
				j++;
		}
			document.newPage();
			//document.add(new Paragraph("test"));
			
			count = 0.00;
		
			}
			
			}
			
			
			
				
			//document.add(new Paragraph("test"));
			//document.add(new Paragraph("test"));
			
			
			//document.add(detail5);
			document.newPage();
			
			//ล่างสุด
			tmpHead++;
			
			
			
		
			
		getHeaderTable(i, n,font,fontHead,date_start,date_end,lang).writeSelectedRows(0, -1, 36, 550, stamper.getOverContent(i));	
		}
		document.add(detail5);
			
			
		
		if(tmpHead==1){
			Paragraph p = new Paragraph("ไม่พบข้อมูล",fontHead);
		    p.setAlignment(Element.ALIGN_CENTER);
		    document.add(p);
		}
		document.close();
		OutputStream os = response.getOutputStream();
  		// Create a reader
        PdfReader reader = new PdfReader(baos.toByteArray());
        // Create a stamper
        PdfStamper stamper = new PdfStamper(reader,baos);
        // Loop over the pages and add a header to each page
        int n = reader.getNumberOfPages();
        for (int i = 1; i <= n; i++) {
        	getHeaderTable(i, n,font,fontHead,date_start,date_end,lang).writeSelectedRows(0, -1, 36, 550, stamper.getOverContent(i));
        	
        }

		
        // Close the stamper
        stamper.close();
        reader.close();
        
	  	response.setHeader("Expires", "0");
	    response.setHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0");
	    response.setHeader("Pragma", "public");
	    // setting the content type
	    response.setContentType("application/pdf");
	    // the contentlength
	    response.setContentLength(baos.size());
	    // write ByteArrayOutputStream to the ServletOutputStream
	      
	    baos.writeTo(os);
	   
	    os.flush();
	    os.close();
	
	%>
	<%!
	private  PdfPTable getHeaderTable(int x, int y,Font font,Font fontHead,String date_start,String date_end,String lang) {
		fontHead.setStyle(1);
		font.setSize(15);
		DecimalFormat two = new DecimalFormat("00");
			ReportUDF rf = new ReportUDF();
			Phrase content = new Phrase("Blah blah blah", font);
			Float fontSize = content.getFont().getSize();
			Float capHeight = content.getFont().getBaseFont().getFontDescriptor(BaseFont.CAPHEIGHT, fontSize);
			Float padding = 5f;
			PdfPTable table = new PdfPTable(6);
        PdfPCell pdfcell;
        table.setTotalWidth(770);
        //table.setWidthPercentage(100);
        table.setLockedWidth(true);
        //table.getDefaultCell().setFixedHeight(1);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
        if(lang.equals("tha")){
        pdfcell = new PdfPCell(new Phrase("รายงานตารางแผนเข้าพบลูกค้าประจำเดือน", fontHead));
        }
        else{
        	pdfcell = new PdfPCell(new Phrase("Plan visit to customer monthly", fontHead));	
        }
        pdfcell.setHorizontalAlignment(Element.ALIGN_CENTER);
        pdfcell.setBorder(Rectangle.NO_BORDER);
        pdfcell.setPaddingTop(-30);
        pdfcell.setColspan(9);
        table.addCell(pdfcell);
        if(lang.equals("tha")){
        pdfcell = new PdfPCell(new Phrase("\nตั้งแต่วันที่"+" "+getthaimont(date_start)+" - "+getthaimont(date_end),font));
        }
        else{
        	 pdfcell = new PdfPCell(new Phrase("\n"+" "+geteng(date_start)+" - "+geteng(date_end),font));	
        }
        
        pdfcell.setHorizontalAlignment(Element.ALIGN_CENTER);
        pdfcell.setBorder(Rectangle.NO_BORDER);
        pdfcell.setPaddingTop(-5);
        pdfcell.setColspan(6);
        table.addCell(pdfcell);
        if(lang.equals("tha")){
        pdfcell = new PdfPCell(new Phrase("\nวันที่",font));
        }
        else{
        	pdfcell = new PdfPCell(new Phrase("\nDate",font));
        }
        pdfcell.setHorizontalAlignment(Element.ALIGN_CENTER);
        pdfcell.setBorder(Rectangle.NO_BORDER);
        pdfcell.setPaddingTop(-5);
        table.addCell(pdfcell);
        if(lang.equals("tha")){
        pdfcell = new PdfPCell(new Phrase("\nเวลา",font));
        }
        else{
        	pdfcell = new PdfPCell(new Phrase("\nTime",font));	
        }
        pdfcell.setHorizontalAlignment(Element.ALIGN_CENTER);
        pdfcell.setBorder(Rectangle.NO_BORDER);
        pdfcell.setPaddingTop(-5);
        table.addCell(pdfcell);
        if(lang.equals("tha")){
        pdfcell = new PdfPCell(new Phrase("\nสถานที่ติดต่อ",font));
        }
        else{
        pdfcell = new PdfPCell(new Phrase("\nLocation",font));	
        }
        pdfcell.setHorizontalAlignment(Element.ALIGN_CENTER);
        pdfcell.setBorder(Rectangle.NO_BORDER);
        pdfcell.setPaddingTop(-5);
        table.addCell(pdfcell);
        if(lang.equals("tha")){
        pdfcell = new PdfPCell(new Phrase("\nเหตุการเข้าพบ",font));
        }
        else{
        	pdfcell = new PdfPCell(new Phrase("\nSubject to visit",font));	
        }
        pdfcell.setHorizontalAlignment(Element.ALIGN_CENTER);
        pdfcell.setBorder(Rectangle.NO_BORDER);
        pdfcell.setPaddingTop(-5);
        table.addCell(pdfcell);
        if(lang.equals("tha")){
        pdfcell = new PdfPCell(new Phrase("\nจังหวัด",font));
        }
        else{
        	pdfcell = new PdfPCell(new Phrase("\nProvince",font));	
        }
        pdfcell.setHorizontalAlignment(Element.ALIGN_CENTER);
        pdfcell.setBorder(Rectangle.NO_BORDER);
        pdfcell.setPaddingTop(-5);
        table.addCell(pdfcell);
        if(lang.equals("tha")){
        pdfcell = new PdfPCell(new Phrase("\nเงินช่วยเหลือค่าพาหนะ",font));
        }
        else{
        pdfcell = new PdfPCell(new Phrase("\nGasFee",font));
        }
        pdfcell.setHorizontalAlignment(Element.ALIGN_CENTER);
        pdfcell.setBorder(Rectangle.NO_BORDER);
        pdfcell.setPaddingTop(-5);
        table.addCell(pdfcell);
        return table;
		
	}
	private String  getthaimont(String a){
		CscCalendar cs = new CscCalendar();
		CscCalendar cs1 = new CscCalendar(cs.getDate()+" "+cs.getThaiMonth()+" "+cs.getYear());
					cs1  = new CscCalendar(a);
		return cs1.setCscCalendar(a).getThaiFullDDMMYYYY();
	}
	private String  geteng(String a){
		CscCalendar cs = new CscCalendar();
		CscCalendar cs1 = new CscCalendar(cs.getDate()+" "+cs.getThaiMonth()+" "+cs.getYear());
					cs1  = new CscCalendar(a);
		return cs1.setCscCalendar(a).getEngFull();
	}
	
	private String  getdat(String a){
		CscCalendar cs = new CscCalendar();
		return cs.setCscCalendar(a).getDDMMYYYY();
	}
	%>
	</body>
</html>