using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Data.SqlClient;
using CrystalDecisions.CrystalReports.Engine;
using System.Globalization;
using System.Collections.Generic;
using System.Diagnostics;
using CrystalDecisions.Shared;

public partial class CrystalRptPage : System.Web.UI.Page
{
    static string constr = ConfigurationManager.ConnectionStrings["CON"].ToString();
    static string PathUrl = HttpContext.Current.Server.MapPath(".");
    static string logPath = HttpContext.Current.Request.PhysicalApplicationPath + "GaneshIAS";
    static string fromMail = ConfigurationManager.AppSettings.Get("FROM_MAIL");
    static string fromPwd = ConfigurationManager.AppSettings.Get("FROM_PWD");
    static string ccMail = ConfigurationManager.AppSettings.Get("CC_MAIL");
    static string Smtp = ConfigurationManager.AppSettings.Get("SMTP");

    DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            try{

        SqlConnection connection = new SqlConnection();
       SqlCommand command =new SqlCommand();
                connection=GetConnection();
                command.Connection=connection;
        string Name = Session["Name"].ToString();
        string Mobile = Session["Mobile"].ToString();
        string Email = Session["Email"].ToString();
        string FileUpload = Session["Uploadimage"].ToString();
        int Langid = Convert.ToInt16(Session["session_id"].ToString());
           command.CommandType=CommandType.Text;

           command.CommandText = "SELECT Id, CommercialUse, UsId, Branch, Name, FName, FOccu, MName, MOccu, [address], paddress, FileUpload, Grad , Pgrad, OQuali, YearG, YearP, YearO, InstG, InstP, InstO, Religion, Catagory, Main1, Main2, Hob, Strength, Weekness, KnowAbtInst, Email, Place, [Date], EndDate, Telephone, Mobile, TotalAttempt, Attempt1, Attempt2, PercenG, PercenP, PercenO FROM T_IAS_Application where Name = '" + Name + "' and Mobile = '" + Mobile + "'";

        
       
        SqlDataAdapter adapter = new SqlDataAdapter(command);

        //Customer _Customer = new Customer();

        DataSet dataset = new DataSet();

        adapter.Fill(dataset, "T_IAS_Application");
        
        ReportDocument CustomerReport = new ReportDocument();

        if (Langid == 0)
        {
            CustomerReport.Load(Server.MapPath("Application.rpt"));

        }
        else
        {
            CustomerReport.Load(Server.MapPath("Application_Tamil.rpt"));
        }


        CustomerReport.SetDataSource(dataset.Tables["T_IAS_Application"]);


        CrystalReportViewer1.ReportSource = CustomerReport;

        CrystalReportViewer1.DataBind();
        CrystalReportViewer1.SeparatePages = false;

               //Similarly you can export Crystal Reports to PDF

        ExportOptions exo = new ExportOptions();
        DiskFileDestinationOptions destinationURL = new DiskFileDestinationOptions();
        PdfRtfWordFormatOptions formatOptionPDF = new PdfRtfWordFormatOptions();
        destinationURL.DiskFileName = PathUrl + @"\Application_PDF\" + Name + "_" + "report.pdf";
        exo.ExportDestinationType = ExportDestinationType.DiskFile;
        exo.ExportFormatType = ExportFormatType.PortableDocFormat;
        exo.ExportDestinationOptions = destinationURL;
        exo.ExportFormatOptions = formatOptionPDF;
        CustomerReport.Export(exo);

        string message = "Dear " + Name + ",<br /><br /> Thank you for your Interest with Us.";
        message = message + "<br /><br />";
        SendNotification(Email, "Application Stored Successfull - By GaneshIAS Academy", message, Name);



        
            }
            catch(Exception es)
            {
            }
        }
    }

    


    public void SendNotification(string ToMail, string Subject, string Message, string UName)
    {
        SendNotifyMail(ToMail, Message, Subject, UName);
    }

    public void SaveLog(string logstr, string path)
    {
        //string serverpath = HttpContext.Current.Request.PhysicalApplicationPath + "LOG";   //local path
        string serverpath = HttpContext.Current.Request.PhysicalApplicationPath + "safl\\LOG";   //server path
        StreamWriter sw = new StreamWriter(serverpath + "\\LOG.Log", true);
        sw.WriteLine("[" + DateTime.Now.ToString() + "] - " + logstr);
        sw.Flush();
        sw.Close();
        sw = null;
    }

   
    public void SendNotifyMail(string tomail, string Message, string Subject, string UName)
    {
        try
        {
            //HitzSmtpMail.HitzMail.Mail objMail = new HitzSmtpMail.HitzMail.Mail();
            //objMail.FromName = "MGM-SAFL";
            //objMail.FromEmailId = fromMail;
            //objMail.MailTo = tomail.Split(',');
            //objMail.Subject = Subject;
            //objMail.Message = MessageTemplate(Message, Subject, UName, Pwd);
            //objMail.SmtpServer = Smtp;
            //objMail.SmtpPort = 25;
            //objMail.SmtpUserName = fromMail;
            //objMail.SmtpPassword = fromPwd;
            //objMail.SmtpSSLEnabled = true;
            //objMail.SendAsyncMode = true;
            //objMail.SendMail();

            MailMessage oMail = new MailMessage();
            oMail.From = new MailAddress(fromMail, "GaneshIAS Academy");
            oMail.Sender = new MailAddress(fromMail);
            oMail.To.Add(tomail);
            //oMail.CC.Add(ccMail);
            oMail.Subject = Subject;
            oMail.IsBodyHtml = true;
            oMail.Body = MessageTemplate(Message, Subject, UName);
            SmtpClient oSmtp = new SmtpClient(Smtp);
            oSmtp.Port = 26;
            oMail.Attachments.Add(new Attachment(Server.MapPath(@"Application_PDF\" + UName + "_" + "report.pdf")));
            oSmtp.Credentials = new NetworkCredential(fromMail, fromPwd);
            oSmtp.Send(oMail);
        }
        catch (Exception e)
        {
            // SaveLog("ERR: SendNotifyMail()-> " + e.Message.ToString(), logPath);
        }
    }

    private static string MessageTemplate(string Msg, string subject, string UName)
    //private static string MessageTemplate(string Msg, string subject)
    {
        string str = "";
        str = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
        str = str + "<html xmlns=\"http://www.w3.org/1999/xhtml\">";
        str = str + "<head id='Head1' runat='server'>";
        str = str + "<title>GaneshIAS Academy Registration</title>";
        str = str + "<style rel='stylesheet' type='text/css'>";
        str = str + "body {margin:0px auto; background:#4eb9c6;}";
        str = str + "#divmain{width:500px; margin:0px auto; text-align:center; height:auto; background:#fafafa;}";
        str = str + "#divTopWrapper{float:left; width:500px; height:300px;  background:#fafafa; border-bottom:solid 1px #cdcdcd;}";
        str = str + "#divTopInnerLeft{float:left; width:150px; height:50px;}";
        str = str + "#divFooterWrapper{float:left; width:500px; height:20px; background:#27313b;color:white;text-align:right;font-size:10px;font-family:arial;}";
        str = str + "</style>";
        str = str + "</head>";
        str = str + "<body>";
        str = str + "<div id='divmain'>";
        str = str + "<div id='divTopWrapper'>";
        str = str + "<div id='divTopInnerLeft'><img src='http://www.ganeshias.com/images/gan-logo1.png' width='90px' height='80px' alt='GaneshIAS Academy' /></div>";
        str = str + "<hr style='float:left;width:499px;height:1px;background-color:Black;' />";
        str = str + "<div style='float:left;height:200px;width:499px;font-family:Verdana;font-weight:bold;text-align:left;'><br />";
        str = str + "<p align='left' style='margin-left:10px;'>" + subject + "</p><br />";
        str = str + "<p align='left' style='margin-left:10px;'>" + Msg + "</p>";
        str = str + "<p align='left' style='margin-left:10px;'>User Name: " + UName + "</p>";
        str = str + "<p align='left' style='margin-left:10px;color: rgb(147,3,3);font-size:10px;'>Regards, <br />GaneshIAS Academy<br /><a href='www.ganeshias.com'>www.ganeshias.com</a> </p>";
        str = str + "</div>";
        str = str + "</div>";
        str = str + "</div>";
        str = str + "</body>";
        str = str + "</html>";
        return str;

    }
    public static void ShowAlertMessage(string message)
    {
        Page page = HttpContext.Current.CurrentHandler as Page;
        if (page != null)
        {
            //string message = "Please check your mail for the further Details!";
            page.ClientScript.RegisterStartupScript(typeof(Page), "alert", "<script language=JavaScript>alert('" + (message) + "');</script>");

        }
    }

    private SqlConnection GetConnection()
    {
        SqlConnection con = new SqlConnection();
        if (constr != "")
        {
            con.ConnectionString = constr;
            con.Open();
            return con;
        }
        else
        { return null; }
    }
    protected void btn_Close_Click(object sender, EventArgs e)
    {
        Response.Redirect("index.aspx");
       
    }
    
}
