//using OccuCare.Core.SessionHelper;
using Microsoft.Reporting.WebForms;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;

namespace OccuCare.Report.Pages
{
    public partial class DefaultReport : System.Web.UI.Page
    {
        public static string DefaultOrgId = "9999";
        private static clConn objC
        {
            get
            {
                return new clConn();
            }
            set { }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
                DefaultOrgId = Request.QueryString["OrgId"];
                SecuritySession.OrgId = Decode1(DefaultOrgId);
                string ReportDetailId = Decode1(Request.QueryString["ReportDetailId"]);
                objC.errorlog("ReportDetailId-" + ReportDetailId);
                objC.errorlog("SecuritySession.OrgId-" + SecuritySession.OrgId);
                if (!string.IsNullOrEmpty(ReportDetailId))
                {
                    ReportDetail ReportDetailData = new ReportDetail();

                    string sql = "Select ReportDetailData from sCommon.tReportDetail where Id = @rReportDetailid";

                    object objResult = objC.pQueryScalarSQL(sql,
                        objC.GetSqlParam("@rReportDetailid", SqlDbType.Int, ReportDetailId)
                        );
                    objC.errorlog("objResult-");
                    objC.errorlog(Convert.ToString(objResult));
                    ReportDetailData = JsonConvert.DeserializeObject<ReportDetail>(Convert.ToString(objResult));
                    ReportSession.ReportDetail = ReportDetailData;

                    String userData = String.Empty;
                    String userID = ReportDetailData.PrintedBy.ToString();
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                                                        1, // Ticket version
                                                        userID, // Username to be associated with this ticket
                                                        DateTime.Now, // Date/time issued
                                                        DateTime.Now.AddSeconds(300), // Date/time to expire
                                                        true, // "true" for a persistent user cookie (could be a checkbox on form)
                                                        userData, // User-data (the roles from this user record in our database)
                                                        FormsAuthentication.FormsCookiePath); // Path cookie is valid for

                    // Hash the cookie for transport over the wire
                    string hash = FormsAuthentication.Encrypt(ticket);
                    HttpCookie cookie = new HttpCookie(
                                                FormsAuthentication.FormsCookieName, // Name of auth cookie (it's the name specified in web.config)
                                                hash); // Hashed ticket

                    Response.Cookies.Add(cookie);

                    InvokeReport(ReportDetailData);
                }
            }
            catch (Exception ex)
            {                
                objC.errorlog("error-" + ex.Message);
                throw ex;
            }
        }

        public void InvokeReport(ReportDetail reportDetailData)
        {
            PageController _page = new PageController();
            string ImagePath = Directory.GetCurrentDirectory() + @"../Images/Report_Logo.jpg";
            if (!File.Exists(ImagePath))
            {
                ImagePath = Directory.GetCurrentDirectory() + @"../../Images/Report_Logo.jpg";
            }
            if (!File.Exists(ImagePath))
            {
                ImagePath = Directory.GetCurrentDirectory() + @"../../../Images/Report_Logo.jpg";
            }
            if (!File.Exists(ImagePath))
            {
                ImagePath = Directory.GetCurrentDirectory() + @"../../../../Images/Report_Logo.jpg";
            }
            //reportDetailData.Logo = ImagePath;
            RDLCReportHelper.InvokeReport(reportDetailData);

            //IMessageBox _MessageBox = null;
            //if (page.Master != null)
            //    _MessageBox = (IMessageBox)page.Master.FindControl("MainMessageBoxControl");
            if (SecuritySession.OrgId == null)
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Session Timeout');window.close();", true);
                //_MessageBox.Show("No Records found for the selected criteria", MessageType.Error);
                return;
            }
            if (reportDetailData.DataSet == null)
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('No Records found for the selected criteria');window.close();", true);
                //_MessageBox.Show("No Records found for the selected criteria", MessageType.Error);
                return;
            }
            if (reportDetailData.DataSet.Tables[0].Rows.Count == 0)
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('No Records found for the selected criteria');window.close();", true);
                //_MessageBox.Show("No Records found for the selected criteria", MessageType.Error);
                return;
            }
            //iReportController.ManipulateData(reportDetailData);
            ReportSession.ReportDetail = reportDetailData;
            int position = ReportSession.ReportDetail.ReportLocationPath.LastIndexOf('\\');

            //string ReportLocationPath = ReportSession.ReportDetail.ReportLocationPath.Substring(0, position + 1) + ReportSession.ReportDetail.OrgId + "\\" + ReportSession.ReportDetail.ReportLocationPath.Substring(position + 1);
            string ReportLocationPath = ReportSession.ReportDetail.ReportLocationPath.Substring(position + 1);

            if (File.Exists(Server.MapPath(ReportLocationPath.Replace("~", ""))))
            {
                ReportSession.ReportDetail.ReportLocationPath = ReportLocationPath.Replace("~", "");
            }

            if (reportDetailData.ViewMode == "PDF")
            {
                reportDetailData.IsPDF = true;
            }
            else if (reportDetailData.ViewMode == "Screen")
            {
                reportDetailData.IsPDF = false;
            }
            if (!reportDetailData.issendmail)
            {
                if (reportDetailData.PrintMode == "Save PDF")
                {
                    ExportToPDF(reportDetailData);
                    return;
                }
                else if (reportDetailData.IsPDF || reportDetailData.PrintMode == "PDF")
                {
                    PrintToPDF(reportDetailData, _page);
                    return;
                }
                else
                {
                    PrintToViewer(reportDetailData, _page);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(reportDetailData.HealthCardCompanyEmail))
                {
                    bool isOPDReport = false;
                    if (reportDetailData.HealthCardCompanyEmail.Contains(','))
                    {
                        HttpContext.Current.Session["HealthCardCompanyEmail"] = reportDetailData.HealthCardCompanyEmail.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)[0];
                        isOPDReport = true;
                    }
                    else
                    {
                        HttpContext.Current.Session["HealthCardCompanyEmail"] = reportDetailData.HealthCardCompanyEmail;
                        HttpContext.Current.Session["UserId"] = reportDetailData.UserId != 0 ? reportDetailData.UserId.ToString() : "1";
                    }

                    MailPDF(isOPDReport);
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "Close", "window.close()", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "window.close();", true);
                }
            }
        }

        private void PrintToViewer(ReportDetail reportDetailData, PageController page)
        {
            string ReportViewerPath = reportDetailData.ReportViewerPath;
            if (string.IsNullOrEmpty(ReportViewerPath))
            {
                ReportViewerPath = "../Pages/DefaultReportViewer.aspx";
            }
            if (!File.Exists(page.Server.MapPath(ReportViewerPath)))
            {
                ReportViewerPath = "../../Common/Report/DefaultReportViewer.aspx";
            }
            //if (!File.Exists(page.Server.MapPath(ReportViewerPath)))
            //{
            //    ReportViewerPath = "../../../Common/Report/DefaultReportViewer.aspx";
            //}
            Response.Redirect("~/Pages/Common/Report/DefaultReportViewer.aspx", false);
            ScriptManager.RegisterStartupScript(page, page.GetType(), "OPEN_WINDOW", "openReportWin('" + ReportViewerPath + "', '', 'dialogWidth:550px;dialogHeight:550px');", true);
        }

        public static void MailPDF(bool isOPDReport)
        {
            Warning[] warnings;
            string[] streamIds;
            string mimeType = string.Empty;
            string encoding = string.Empty;
            string extension = "pdf";

            //ReportGlobalSettingsHelper rptGlobalSettingsHelper = new ReportGlobalSettingsHelper();
            ReportViewer viewer = new ReportViewer();
            viewer.ProcessingMode = ProcessingMode.Local;

            ReportDataSource ReportInfoDatasource = new ReportDataSource("ReportInfo", ReportSession.ReportDetail.SubReport[0].DataSet.Tables[0]);
            viewer.LocalReport.DataSources.Clear();
            viewer.LocalReport.DataSources.Add(ReportInfoDatasource);

            ReportDataSource datasource = new ReportDataSource(ReportSession.ReportDetail.DataSetName, ReportSession.ReportDetail.DataSet.Tables[0]);
            RDLCSubReportProcessing subReport = new RDLCSubReportProcessing(DefaultOrgId);
            subReport.AddSubReportDataSource(ReportInfoDatasource, viewer);
            viewer.LocalReport.DataSources.Add(datasource);

            if (ReportSession.ReportDetail.DataSetName2 != null && ReportSession.ReportDetail.DataSet2 != null)
            {
                ReportDataSource datasource1 = new ReportDataSource(ReportSession.ReportDetail.DataSetName2, ReportSession.ReportDetail.DataSet2.Tables[0]);
                viewer.LocalReport.DataSources.Add(datasource1);
            }

            viewer.LocalReport.ReportPath = HttpContext.Current.Server.MapPath(ReportSession.ReportDetail.ReportLocationPath);
            if (isOPDReport)
                viewer.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(LocalReport_SubreportProcessing14);
            else
                viewer.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(LocalReport_SubreportProcessing13);



            string deviceInfo = null;

            if (ReportSession.ReportDetail.PaperSize == "Legal")
                deviceInfo = @"<DeviceInfo><OutputFormat>PDF</OutputFormat><PageWidth>8.5in</PageWidth><PageHeight>14in</PageHeight></DeviceInfo>";

            byte[] bytes = viewer.LocalReport.Render("PDF", deviceInfo, out mimeType, out encoding, out extension, out streamIds, out warnings);

            string savepath;
            savepath = HttpContext.Current.Server.MapPath("~/ReportPDF");
            string ReportName = ReportSession.ReportDetail.CustomFileName;

            Guid UniqueID = Guid.NewGuid();
            FileStream fs;
            string FileMapPath;

            fs = new FileStream(Path.Combine(savepath, UniqueID + ".pdf"), FileMode.OpenOrCreate);
            fs.Write(bytes, 0, bytes.Length);
            fs.Close();
            FileMapPath = savepath + @"\" + UniqueID + ".pdf";
            string filepath = @"..\" + FileMapPath.Substring(System.Web.HttpContext.Current.Request.PhysicalApplicationPath.Length).Replace("\\", "/");
            clConn obj = new clConn();

            int Id = 1;
            int MailTypeId = 1;
            if (GetUserConfigurationValue("alert.emailprovider").ToString() != null)
            {
                if (GetUserConfigurationValue("alert.emailprovider").ToString() == "smtp")
                {
                    Id = 1;
                    MailTypeId = 1;
                }
                else
                {
                    Id = 2;
                    MailTypeId = 2;
                }
            }

            String sqlQuery = "select SMTPPort,FromMail,SendPassword,SMTPServer,isnull(APIKey,'') as APIKey,isnull(SecretKey,'') as SecretKey from sAlert.tEmailConfiguration where OrgId=@rOrgId and MailTypeId=@rMailTypeId and Id = @rId";

            DataSet Ds = obj.QueryDataReader(sqlQuery,
                obj.GetSqlParam("@rOrgId", SqlDbType.Int, 4, SecuritySession.OrgId),
                obj.GetSqlParam("@rMailTypeId", SqlDbType.Int, 4, MailTypeId.ToString()),
                obj.GetSqlParam("@rId", SqlDbType.Int, 4, Id.ToString())
                );

            int SMTPPort = int.Parse(Ds.Tables[0].Rows[0]["SMTPPort"].ToString());
            string FromMail = Ds.Tables[0].Rows[0]["FromMail"].ToString();
            string SendPassword = Ds.Tables[0].Rows[0]["SendPassword"].ToString();
            string SMTPServer = Ds.Tables[0].Rows[0]["SMTPServer"].ToString();
            string APIKey = Ds.Tables[0].Rows[0]["APIKey"].ToString();
            string SecretKey = Ds.Tables[0].Rows[0]["SecretKey"].ToString();

            String sqlQuery1 = "select Isnull(Template,'') Template,Isnull(MailSubject,'') MailSubject From sAlert.tEventTemplate where OrgId=@rOrgId and AlertModeId=@rAlertModeId and EventId =@rEventId ";
            string Message = "Your Health Card Report";
            string Subject = "Your Health Card Report";
            string queryString = "";
            queryString += "select EM.FirstName + ' ' + EM.LastName as EmployeeName,(select top 1 FirstName + ' ' + LastName from sHrm.tEmployeeMaster where Id = EX.DoctorEmployeeId) as DoctorName";
            queryString += " from sExamination.tExamination EX";
            queryString += " INNER JOIN sHrm.tEmployeeMaster EM on EX.ParticipantSourceId = EM.Id";
            queryString += " where EX.Id =" + Convert.ToInt64(ReportSession.ReportDetail.SProc[0].Parameters[1].Value);

            DataSet dataSet = obj.QueryDataReader(queryString);
            string _message = string.Empty;
            if (dataSet != null && dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
                _message = "Hello " + Convert.ToString(dataSet.Tables[0].Rows[0]["EmployeeName"]) + ", Please check the medicine details in the attached OPD Prescription Report which was assigned by Dr " + Convert.ToString(dataSet.Tables[0].Rows[0]["DoctorName"]) + " in your today's OPD";

            DataSet Ds1 = obj.QueryDataReader(sqlQuery1,
                obj.GetSqlParam("@rOrgId", SqlDbType.Int, 4, SecuritySession.OrgId),
                obj.GetSqlParam("@rAlertModeId", SqlDbType.Int, 4, "1"),
                obj.GetSqlParam("@rEventId", SqlDbType.Int, 4, "1")
                );

            if (Ds1 != null && Ds1.Tables.Count > 0 && Ds1.Tables[0].Rows.Count > 0)
            {
                Message = Ds1.Tables[0].Rows[0]["Template"].ToString();
                Subject = Ds1.Tables[0].Rows[0]["MailSubject"].ToString();
            }
            //obj.CreateEmailLog(ds1, 0, "", "Custom", 9, SecuritySession.OrgId, SecuritySession.UserId);
            obj.SendExternalEmail(Id, HttpContext.Current.Session["HealthCardCompanyEmail"].ToString(), FromMail, isOPDReport ? "Opd Prescription Report" : Subject, isOPDReport ? _message : Message, "", "", filepath, APIKey, SecretKey, SMTPPort, SMTPServer, SendPassword);
            objC.CreateEmailLog(HttpContext.Current.Session["HealthCardCompanyEmail"].ToString(), Message, Subject, "Custom", 1, Convert.ToInt32(SecuritySession.OrgId), HttpContext.Current.Session["UserId"] != null ? HttpContext.Current.Session["UserId"].ToString() : "1");
            HttpContext.Current.Session["HealthCardCompanyEmail"] = null;
            HttpContext.Current.Session["UserId"] = null;
        }
        public static void LocalReport_SubreportProcessing14(object sender, SubreportProcessingEventArgs e)
        {
            string ExaminationIdText;
            //string Code = "";
            string PolicyId;
            string IncidentId;
            string PermitNumber;
            ReportPDF reportPDF = new ReportPDF();
            switch (e.ReportPath)
            {
                case "EmploymentDetail":
                    ExaminationIdText = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("Employment", reportPDF.FetchHealthCardEmployment(ExaminationIdText)));
                    break;
                case "HealthCardFullGeneralSub":
                    ExaminationIdText = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("HealthCardFull_General", FetchHealthCardGeneral(ExaminationIdText)));
                    break;
                case "HealthCardFullGeneralSub_New2":
                    ExaminationIdText = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("HealthCardFull_General", FetchHealthCardGeneral(ExaminationIdText)));
                    break;
                case "HealthCardFullTestSub":
                    ExaminationIdText = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("HealthCardFull_Test", FetchHealthCardFullTestSub(ExaminationIdText)));
                    break;
                case "PulmanaryResult":
                    ExaminationIdText = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("PulmonaryResult", FetchPulmonaryResult(ExaminationIdText)));
                    break;
                case "AudiometryTest":
                    ExaminationIdText = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("Audiometry", FetchAudiometry(ExaminationIdText)));
                    break;
                case "HealthCardFullGeneralSub_Filter":
                    ExaminationIdText = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("HealthCardFull_General", FetchHealthCardGeneral(ExaminationIdText)));
                    break;
                case "ClaimStatus":
                    PolicyId = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("ClaimStatus", reportPDF.FetchClaimStatus(PolicyId)));
                    break;
                case "ClaimRelationship":
                    PolicyId = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("ClaimRelationship", reportPDF.FetchClaimRelationship(PolicyId)));
                    break;
                case "ClaimCare":
                    PolicyId = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("ClaimCare", reportPDF.FetchClaimCare(PolicyId)));
                    break;
                case "ClaimTopHospitals":
                    PolicyId = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("ClaimTopHospitals", reportPDF.FetchClaimTopHospitals(PolicyId)));
                    break;
                case "ClaimTopAilments":
                    PolicyId = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("ClaimTopAilments", reportPDF.FetchClaimTopAilments(PolicyId)));
                    break;
                case "ClaimTreatment":
                    PolicyId = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("ClaimTreatment", reportPDF.FetchClaimTreatment(PolicyId)));
                    break;
                case "ClaimTopAilmentCare":
                    PolicyId = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("ClaimTopAilmentCare", reportPDF.FetchClaimTopAilmentCare(PolicyId)));
                    break;
                case "ClaimTopAilmentRelationship":
                    PolicyId = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("ClaimTopAilmentRelationship", reportPDF.FetchClaimTopAilmentRelationship(PolicyId)));
                    break;
                case "ApproversList":
                    PermitNumber = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("ApproversList", reportPDF.FetchPermitNumber(PermitNumber)));
                    break;
                case "IncidentTeamFormation":
                    IncidentId = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("IncidentTeamFormation", reportPDF.CFTFromation(IncidentId)));
                    break;
                case "InitialProblemDescription":
                    IncidentId = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("InitialProblemDescription", reportPDF.ProblemDescription(IncidentId)));
                    break;
                case "ContainmentAction":
                    IncidentId = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("ContainmentAction", reportPDF.ContainmentAction(IncidentId)));
                    break;
                case "RootCauseInvestigation":
                    IncidentId = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("RootCauseInvestigation", reportPDF.RootCauseInvestigation(IncidentId)));
                    break;
                case "RootCauseValidation":
                    IncidentId = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("RootCauseValidation", reportPDF.RootCauseValidation(IncidentId)));
                    break;
                case "IncidentCorrectiveAction":
                    IncidentId = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("IncidentCorrectiveAction", reportPDF.IncidentCorrectiveAction(IncidentId)));
                    break;
                case "CorrectiveActionValidation":
                    IncidentId = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("CorrectiveActionValidation", reportPDF.CorrectiveActionValidation(IncidentId)));
                    break;
                case "PreventOccurrence":
                    IncidentId = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("PreventOccurrence", reportPDF.PreventOccurrence(IncidentId)));
                    break;
                case "TeamRecognition":
                    IncidentId = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("TeamRecognition", reportPDF.TeamRecognition(IncidentId)));
                    break;

            }
        }
        public static void LocalReport_SubreportProcessing13(object sender, SubreportProcessingEventArgs e)
        {
            string ExaminationIdText;
            switch (e.ReportPath)
            {
                case "HealthCardFullGeneralSub":
                    ExaminationIdText = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("HealthCardFull_General", FetchHealthCardGeneral(ExaminationIdText)));
                    break;
                case "HealthCardFullGeneralSub_New2":
                    ExaminationIdText = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("HealthCardFull_General", FetchHealthCardGeneral(ExaminationIdText)));
                    break;
                case "HealthCardFullTestSub":
                    ExaminationIdText = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("HealthCardFull_Test", FetchHealthCardFullTestSub(ExaminationIdText)));
                    break;
                case "PulmanaryResult":
                    ExaminationIdText = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("PulmonaryResult", FetchPulmonaryResult(ExaminationIdText)));
                    break;
                case "AudiometryTest":
                    ExaminationIdText = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("Audiometry", FetchAudiometry(ExaminationIdText)));
                    break;
                case "HealthCardFullGeneralSub_Filter":
                    ExaminationIdText = e.Parameters[0].Values[0].ToString();
                    e.DataSources.Add(new ReportDataSource("HealthCardFull_General", FetchHealthCardGeneral(ExaminationIdText)));
                    break;
            }
        }

        private static DataTable FetchHealthCardGeneral(string ExaminationIdText)
        {
            DataSet ds = new DataSet();
            string sql = "sExamination.pRptGetHealthCardSubGeneralParameters";

            ds = objC.QuerySQL(sql,
                objC.GetSqlParam("@rExaminationId", SqlDbType.BigInt, ExaminationIdText)
                );

            return ds.Tables[0];
        }

        private static DataTable FetchHealthCardFullTestSub(string ExaminationIdText)
        {
            DataSet ds = new DataSet();
            string sql = "sExamination.pRptGetHealthCardSubTestsParameters";

            ds = objC.QuerySQL(sql,
                objC.GetSqlParam("@rExaminationId", SqlDbType.BigInt, ExaminationIdText)
                );

            return ds.Tables[0];
        }

        private static DataTable FetchPulmonaryResult(string ExaminationIdText)
        {
            DataSet ds = new DataSet();
            string sql = "sExamination.pRptPulmonaryResult";

            ds = objC.QuerySQL(sql,
                objC.GetSqlParam("@rExaminationId", SqlDbType.BigInt, ExaminationIdText)
                );

            return ds.Tables[0];
        }

        private static DataTable FetchAudiometry(string ExaminationIdText)
        {
            DataSet ds = new DataSet();
            string sql = "sExamination.pRptAudiometrytest";

            ds = objC.QuerySQL(sql,
                objC.GetSqlParam("@rExaminationId", SqlDbType.BigInt, ExaminationIdText)
                );

            return ds.Tables[0];
        }

        private void PrintToPDF(ReportDetail reportDetailData, PageController page)
        {

            string ReportViewerPath = reportDetailData.ReportViewerPath;
            if (string.IsNullOrEmpty(ReportViewerPath))
            {
                ReportViewerPath = "../Common/Report/ReportPDF.aspx";
            }
            if (!File.Exists(page.Server.MapPath(ReportViewerPath)))
            {
                ReportViewerPath = "../../Common/Report/ReportPDF.aspx";
            }
            //if (!File.Exists(page.Server.MapPath(ReportViewerPath)))
            //{
            //    ReportViewerPath = "../../../Common/Report/ReportPDF.aspx";
            //}
            Response.Redirect("~/Pages/Common/Report/ReportPDF.aspx", false);
            ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "OPEN_WINDOW", "openReportWin('" + ReportViewerPath + "', '', 'dialogWidth:550px;dialogHeight:550px');", true);
        }
        private static string PrintToPDF(ReportDetail reportDetailData, PageController page, PageController opage)
        {

            string ReportViewerPath = reportDetailData.ReportViewerPath;
            if (string.IsNullOrEmpty(ReportViewerPath))
            {
                ReportViewerPath = "../Common/Report/ReportPDF.aspx";
            }
            if (!File.Exists(page.Server.MapPath(ReportViewerPath)))
            {
                ReportViewerPath = "../../Common/Report/ReportPDF.aspx";
            }
            if (!File.Exists(page.Server.MapPath(ReportViewerPath)))
            {
                ReportViewerPath = "../../../Common/Report/ReportPDF.aspx";
            }
            return ReportViewerPath;
            //ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "OPEN_WINDOW", "openReportWin('" + ReportViewerPath + "', '', 'dialogWidth:550px;dialogHeight:550px');", true);
        }

        public static void CreatePDF(PageController page)
        {
            Warning[] warnings;
            string[] streamIds;
            string mimeType = string.Empty;
            string encoding = string.Empty;
            string extension = "pdf";

            //ReportGlobalSettingsHelper rptGlobalSettingsHelper = new ReportGlobalSettingsHelper();
            ReportViewer viewer = new ReportViewer();
            viewer.ProcessingMode = ProcessingMode.Local;

            ReportDataSource ReportInfoDatasource = new ReportDataSource("ReportInfo", ReportSession.ReportDetail.SubReport[0].DataSet.Tables[0]);
            viewer.LocalReport.DataSources.Clear();
            viewer.LocalReport.DataSources.Add(ReportInfoDatasource);

            ReportDataSource datasource = new ReportDataSource(ReportSession.ReportDetail.DataSetName, ReportSession.ReportDetail.DataSet.Tables[0]);
            RDLCSubReportProcessing subReport = new RDLCSubReportProcessing(DefaultOrgId);
            subReport.AddSubReportDataSource(ReportInfoDatasource, viewer);
            viewer.LocalReport.DataSources.Add(datasource);

            if (ReportSession.ReportDetail.DataSetName2 != null && ReportSession.ReportDetail.DataSet2 != null)
            {
                ReportDataSource datasource1 = new ReportDataSource(ReportSession.ReportDetail.DataSetName2, ReportSession.ReportDetail.DataSet2.Tables[0]);
                viewer.LocalReport.DataSources.Add(datasource1);
            }

            viewer.LocalReport.ReportPath = page.Server.MapPath(ReportSession.ReportDetail.ReportLocationPath);
            viewer.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(LocalReport_SubreportProcessing);

            string deviceInfo = null;

            if (ReportSession.ReportDetail.PaperSize == "Legal")
                deviceInfo = @"<DeviceInfo><OutputFormat>PDF</OutputFormat><PageWidth>8.5in</PageWidth><PageHeight>14in</PageHeight></DeviceInfo>";

            byte[] bytes = viewer.LocalReport.Render("PDF", deviceInfo, out mimeType, out encoding, out extension, out streamIds, out warnings);

            string savepath;
            string ReportName = ReportSession.ReportDetail.CustomFileName;
            if (ReportSession.ReportDetail.IsCustomFile)
            {
                if (!string.IsNullOrEmpty(ReportSession.ReportDetail.CustomFolderName))
                    savepath = page.Server.MapPath("~/ReportPDF/" + ReportSession.ReportDetail.CustomFolderName);
                else
                    savepath = page.Server.MapPath("~/ReportPDF");
            }
            else if (!string.IsNullOrEmpty(ReportSession.ReportDetail.CustomFileName))
            {
                savepath = page.Server.MapPath("~/ReportPDF/TempReportForMail");
            }
            else
            {
                savepath = page.Server.MapPath("~/ReportPDF");
            }
            if (!Directory.Exists(savepath))
            {
                Directory.CreateDirectory(savepath);
                DirectoryInfo dir1 = new DirectoryInfo(savepath);
                System.Security.Principal.WindowsIdentity self = System.Security.Principal.WindowsIdentity.GetCurrent();
                DirectorySecurity ds = dir1.GetAccessControl();
                ds.AddAccessRule(new FileSystemAccessRule(self.Name,
                FileSystemRights.FullControl,
                InheritanceFlags.ObjectInherit |
                InheritanceFlags.ContainerInherit,
                PropagationFlags.None,
                AccessControlType.Allow));
                dir1.SetAccessControl(ds);
            }
            Guid UniqueID = Guid.NewGuid();
            FileStream fs;
            string FileMapPath;
            if (ReportSession.ReportDetail.IsCustomFile)
            {
                fs = new FileStream(Path.Combine(savepath, ReportSession.ReportDetail.CustomFileName + ".pdf"), FileMode.OpenOrCreate);
                fs.Write(bytes, 0, bytes.Length);
                fs.Close();
            }
            else if (!string.IsNullOrEmpty(ReportSession.ReportDetail.CustomFileName))
            {
                if (File.Exists(Path.Combine(savepath, ReportSession.ReportDetail.CustomFileName + ".pdf")))
                {
                    fs = new FileStream(Path.Combine(savepath, ReportSession.ReportDetail.CustomFileName + ".pdf"), FileMode.Open, FileAccess.Read);
                }
                else
                {
                    fs = new FileStream(Path.Combine(savepath, ReportSession.ReportDetail.CustomFileName + ".pdf"), FileMode.CreateNew);
                    fs.Write(bytes, 0, bytes.Length);
                }
                fs.Close();

                FileMapPath = savepath + @"\" + ReportSession.ReportDetail.CustomFileName + ".pdf";
                string filepath = @"..\..\..\" + FileMapPath.Substring(System.Web.HttpContext.Current.Request.PhysicalApplicationPath.Length).Replace("\\", "/");
                System.Web.HttpContext.Current.Response.Redirect(filepath, false);

                if (!string.IsNullOrEmpty(ReportSession.ReportDetail.CustomFileName))
                {
                    System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
                    SmtpClient SmtpServer = new SmtpClient();
                    mail.From = new MailAddress("dev@occucare.co.in");
                    mail.To.Add("rajeshwar.rathod@vidyalayaschoolsoftware.com");
                    mail.Subject = "Test Mail - 1";
                    mail.Body = "mail with attachment";

                    System.Net.Mail.Attachment attachment;
                    attachment = new System.Net.Mail.Attachment(page.Server.MapPath("~/ReportPDF/TempReportForMail/" + ReportSession.ReportDetail.CustomFileName + ".pdf"));

                    mail.Attachments.Add(attachment);
                    SmtpServer.Host = "smtp.zoho.com";
                    SmtpServer.Port = 587;

                    SmtpServer.UseDefaultCredentials = false;
                    SmtpServer.Credentials = new System.Net.NetworkCredential("dev@occucare.co.in", "zoho@12345");
                    SmtpServer.EnableSsl = true;

                    SmtpServer.Send(mail);
                }
            }
            else
            {
                fs = new FileStream(Path.Combine(savepath, UniqueID + ".pdf"), FileMode.OpenOrCreate);
                fs.Write(bytes, 0, bytes.Length);
                fs.Close();
                FileMapPath = savepath + @"\" + UniqueID + ".pdf";
                string filepath = @"..\..\..\" + FileMapPath.Substring(System.Web.HttpContext.Current.Request.PhysicalApplicationPath.Length).Replace("\\", "/");
                System.Web.HttpContext.Current.Response.Redirect(filepath, false);
                if (System.Web.HttpContext.Current.Session["HealthCardCompanyEmail"] != null)
                {
                    if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Session["HealthCardCompanyEmail"].ToString()))
                    {
                        try
                        {
                            clConn obj = new clConn();

                            int Id = 0;
                            int MailTypeId = 0;
                            //if (ConfigurationHelper.GetUserConfigurationValue("Alert.EMailProvider").ToString() != null)
                            //{
                            //    if (ConfigurationHelper.GetUserConfigurationValue("Alert.EMailProvider").ToString() == "smtp")
                            //    {
                            //        Id = 1;
                            //        MailTypeId = 1;
                            //    }
                            //    else
                            //    {
                            //        Id = 2;
                            //        MailTypeId = 2;
                            //    }
                            //}
                            //else
                            //{
                            //    Id = 1;
                            //    MailTypeId = 1;
                            //}

                            String sqlQuery = "select SMTPPort,FromMail,SendPassword,SMTPServer,isnull(APIKey,'') as APIKey,isnull(SecretKey,'') as SecretKey from sAlert.tEmailConfiguration where OrgId=@rOrgId and MailTypeId=@rMailTypeId and Id = @rId";

                            DataSet Ds = obj.QueryDataReader(sqlQuery,
                                obj.GetSqlParam("@rOrgId", SqlDbType.Int, 4, ConfigurationManager.AppSettings["DefaultOrgId"].ToString()),
                                obj.GetSqlParam("@rMailTypeId", SqlDbType.Int, 4, MailTypeId.ToString()),
                                obj.GetSqlParam("@rId", SqlDbType.Int, 4, Id.ToString())
                                );

                            int SMTPPort = int.Parse(Ds.Tables[0].Rows[0]["SMTPPort"].ToString());
                            string FromMail = Ds.Tables[0].Rows[0]["FromMail"].ToString();
                            string SendPassword = Ds.Tables[0].Rows[0]["SendPassword"].ToString();
                            string SMTPServer = Ds.Tables[0].Rows[0]["SMTPServer"].ToString();
                            string APIKey = Ds.Tables[0].Rows[0]["APIKey"].ToString();
                            string SecretKey = Ds.Tables[0].Rows[0]["SecretKey"].ToString();

                            //objC.SendExternalEmail(Session["HealthCardCompanyEmail"].ToString(), "Health Card", "Health Card", "", "", filepath);
                            objC.CreateEmailLog(HttpContext.Current.Session["HealthCardCompanyEmail"].ToString(), "Your Health Card Report", "Your Health Card Report", "Custom", 1, Convert.ToInt32(ConfigurationManager.AppSettings["DefaultOrgId"].ToString()), HttpContext.Current.Session["UserId"] != null ? HttpContext.Current.Session["UserId"].ToString() : "1");
                            obj.SendExternalEmail(Id, System.Web.HttpContext.Current.Session["HealthCardCompanyEmail"].ToString(), FromMail, "Your Health Card Report", "Your Health Card Report", "", "", filepath, APIKey, SecretKey, SMTPPort, SMTPServer, SendPassword);
                            System.Web.HttpContext.Current.Session["HealthCardCompanyEmail"] = null;
                            HttpContext.Current.Session["UserId"] = null;
                        }
                        catch
                        {
                            System.Web.HttpContext.Current.Session["HealthCardCompanyEmail"] = null;
                            HttpContext.Current.Session["UserId"] = null;
                        }
                    }
                }
            }
        }

        private static void ExportToPDF(ReportDetail reportDetailData)
        {
            Warning[] warnings;
            string[] streamIds;
            string mimeType = string.Empty;
            string encoding = string.Empty;
            string extension = "pdf";
            //ReportGlobalSettingsHelper rptGlobalSettingsHelper = new ReportGlobalSettingsHelper();
            ReportViewer viewer = new ReportViewer();
            viewer.ProcessingMode = ProcessingMode.Local;
            ReportDataSource ReportInfoDatasource = new ReportDataSource("ReportInfo", ReportSession.ReportDetail.SubReport[0].DataSet.Tables[0]);
            viewer.LocalReport.DataSources.Clear();
            viewer.LocalReport.DataSources.Add(ReportInfoDatasource);
            ReportDataSource datasource = new ReportDataSource(ReportSession.ReportDetail.DataSetName, ReportSession.ReportDetail.DataSet.Tables[0]);
            RDLCSubReportProcessing subReport = new RDLCSubReportProcessing(DefaultOrgId);
            subReport.AddSubReportDataSource(ReportInfoDatasource, viewer);
            viewer.LocalReport.DataSources.Add(datasource);
            viewer.LocalReport.ReportPath = HttpContext.Current.Server.MapPath(ReportSession.ReportDetail.ReportLocationPath);
            viewer.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(LocalReport_SubreportProcessing);
            string deviceInfo = null;
            if (ReportSession.ReportDetail.PaperSize == "Legal")
                deviceInfo = @"<DeviceInfo>
                <OutputFormat>PDF</OutputFormat>
                <PageWidth>8.5in</PageWidth>
                <PageHeight>14in</PageHeight> 
            </DeviceInfo>";
            byte[] bytes = viewer.LocalReport.Render("PDF", deviceInfo, out mimeType, out encoding, out extension, out streamIds, out warnings);
            string savepath;
            if (ReportSession.ReportDetail.IsCustomFile)
            {
                savepath = HttpContext.Current.Server.MapPath("~/ReportPDF/" + ReportSession.ReportDetail.CustomFolderName);
            }
            else
            {
                savepath = HttpContext.Current.Server.MapPath("~/ReportPDF");
            }
            if (!Directory.Exists(savepath))
            {
                Directory.CreateDirectory(savepath);
                DirectoryInfo dir1 = new DirectoryInfo(savepath);
                System.Security.Principal.WindowsIdentity self = System.Security.Principal.WindowsIdentity.GetCurrent();
                DirectorySecurity ds = dir1.GetAccessControl();
                ds.AddAccessRule(new FileSystemAccessRule(self.Name,
                FileSystemRights.FullControl,
                InheritanceFlags.ObjectInherit |
                InheritanceFlags.ContainerInherit,
                PropagationFlags.None,
                AccessControlType.Allow));
                dir1.SetAccessControl(ds);
            }
            Guid UniqueID = Guid.NewGuid();
            FileStream fs;
            string FileMapPath;
            if (ReportSession.ReportDetail.IsCustomFile)
            {
                fs = new FileStream(Path.Combine(savepath, ReportSession.ReportDetail.CustomFileName + ".pdf"), FileMode.OpenOrCreate);
                fs.Write(bytes, 0, bytes.Length);
                fs.Close();
            }
            else
            {
                fs = new FileStream(Path.Combine(savepath, ReportSession.ReportDetail.CustomFileName + ".pdf"), FileMode.OpenOrCreate);
                fs.Write(bytes, 0, bytes.Length);
                fs.Close();
                FileMapPath = savepath + @"\" + ReportSession.ReportDetail.CustomFileName + ".pdf";
                string filepath = @"..\..\..\" + FileMapPath.Substring(System.Web.HttpContext.Current.Request.PhysicalApplicationPath.Length).Replace("\\", "/");
            }
        }

        public static void LocalReport_SubreportProcessing(object sender, SubreportProcessingEventArgs e)
        {
            RDLCSubReportProcessing subReport = new RDLCSubReportProcessing(DefaultOrgId);
            subReport.LocalReportSubreportProcessing(sender, e);
        }

        private static void PrintRdlcDirectPrint(ReportDetail reportDetailData, PageController page)
        {
            //ReportGlobalSettingsHelper rptGlobalSettingsHelper = new ReportGlobalSettingsHelper();
            LocalReport report = new LocalReport();
            report.ReportPath = page.Server.MapPath(ReportSession.ReportDetail.ReportLocationPath);
            report.DataSources.Add(new ReportDataSource("FeeReceipt", reportDetailData.DataSet.Tables[0]));
            Print();
        }
        private static int m_currentPageIndex;
        private static IList<Stream> m_streams;

        private static void Print()
        {
            if (m_streams == null || m_streams.Count == 0)
                throw new Exception("Error: no stream to print.");

            PrintDocument printDoc = new PrintDocument();
            printDoc.PrinterSettings.PrinterName = @"\\LAB-PC6\HP LaserJet P1007";
            if (!printDoc.PrinterSettings.IsValid)
            {
                throw new Exception("Error: cannot find the default printer.");
            }
            else
            {
                printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
                m_currentPageIndex = 0;
                printDoc.Print();
            }
        }

        private static void PrintPage(object sender, PrintPageEventArgs ev)
        {
            Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]);

            // Adjust rectangular area with printer margins.
            Rectangle adjustedRect = new Rectangle(
                ev.PageBounds.Left - (int)ev.PageSettings.HardMarginX,
                ev.PageBounds.Top - (int)ev.PageSettings.HardMarginY,
                ev.PageBounds.Width,
                ev.PageBounds.Height);

            // Draw a white background for the report
            ev.Graphics.FillRectangle(Brushes.White, adjustedRect);

            // Draw the report content
            ev.Graphics.DrawImage(pageImage, adjustedRect);

            // Prepare for the next page. Make sure we haven't hit the end.
            m_currentPageIndex++;
            ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
        }

        public static string Decode(string cipherText)
        {
            if (cipherText != null)
            {
                string s = "O((uC4r3";
                UTF8Encoding utF8Encoding = new UTF8Encoding();
                MD5CryptoServiceProvider cryptoServiceProvider1 = new MD5CryptoServiceProvider();
                byte[] hash = cryptoServiceProvider1.ComputeHash(utF8Encoding.GetBytes(s));
                cipherText = cipherText.ToUpper();
                for (int i = 0; i < cipherText.Length; i += 3)
                {
                    cipherText = cipherText.Insert(i + 2, "-");
                }
                cipherText = cipherText.Remove(cipherText.Length - 1);
                TripleDESCryptoServiceProvider cryptoServiceProvider2 = new TripleDESCryptoServiceProvider();
                cryptoServiceProvider2.Key = hash;
                cryptoServiceProvider2.Mode = CipherMode.ECB;
                cryptoServiceProvider2.Padding = PaddingMode.PKCS7;
                //byte[] inputBuffer = Convert.FromBase64String(cipherText);
                String[] arr = cipherText.Split('-');
                byte[] inputBuffer = new byte[arr.Length];
                for (int i = 0; i < arr.Length; i++)
                    inputBuffer[i] = Convert.ToByte(arr[i], 16);
                // byte[] inputBuffer = Convert.FromBase64String(cipherText);
                byte[] bytes;
                try
                {
                    bytes = cryptoServiceProvider2.CreateDecryptor().TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
                }
                finally
                {
                    cryptoServiceProvider2.Clear();
                    cryptoServiceProvider1.Clear();
                }
                return utF8Encoding.GetString(bytes);
            }
            return null;
        }

        public static string Decode1(string cipherText)
        {
            if (cipherText != null)
            {
                int numberChars = cipherText.Length;
                byte[] bytes = new byte[numberChars / 2];
                for (int i = 0; i < numberChars; i += 2)
                {
                    bytes[i / 2] = Convert.ToByte(cipherText.Substring(i, 2), 16);
                }
                return System.Text.Encoding.Unicode.GetString(bytes);
            }
            return null;
        }

        public static string GetUserConfigurationValue(string key)
        {
            clConn obj = new clConn();
            string value = "";
            try
            {
                string q = " SELECT Top 1 ISNULL(CS.ItemValue,CM.ItemValue) AS ItemValue FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS " +
                    "ON CS.ConfigurationId = CM.Id   Where ItemKey =  '" + key + "' ";
                value = obj.pQueryScalarSQL(q).ToString();
            }
            catch
            {
                value = "";
            }
            return value;

        }
    }
}