using System;
using System.Data;
using System.Configuration;
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.Net.Mail;
using System.Data.SqlClient;
using System.Net;
using System.IO;
using System.Net.Sockets;
using System.Xml;
using System.Text.RegularExpressions;
using System.Threading;
using System.Collections.Specialized;

public class CommonFunction
{
    DataSet ds;
    string ActualStatus,Availablebalance;
	public CommonFunction()
	{		
	}
    public static void ClearControlValues(Control Container)
    {
        try
        {
            foreach (Control ctrl in Container.Controls)
            {
                if (ctrl.GetType() == typeof(TextBox))
                    ((TextBox)ctrl).Text = "";
                if (ctrl.GetType() == typeof(DropDownList))
                    ((DropDownList)ctrl).SelectedIndex = -1;
                if (ctrl.GetType() == typeof(CheckBox))
                    ((CheckBox)ctrl).Checked = false;
                if (ctrl.GetType() == typeof(RadioButtonList))
                    ((RadioButtonList)ctrl).SelectedIndex = -1;
                //if (ctrl.GetType() == typeof(Label))
                //    ((Label)ctrl).Text = "";
                //if (ctrl.GetType() == typeof(DateTimePicker))
                //    ((DateTimePicker)ctrl).Text = "";

                if (ctrl.Controls.Count > 0)
                    ClearControlValues(ctrl);
            }
        }
        catch (Exception ex)
        {
            
        }
    }

    public static void SendMailmsg(string body, string msgto, string msgcc, string msgfrom, string sub)
    {
        try
        {
            MailMessage message = new MailMessage();
            message.Body = body;
            message.IsBodyHtml = true;
            message.To.Add(msgto);
            if (!String.IsNullOrEmpty(msgcc))
                message.CC.Add(msgcc);
            message.From = new System.Net.Mail.MailAddress(msgfrom);
            message.Subject = sub;
            message.Priority = MailPriority.High;
            SmtpClient SmtpMail = new SmtpClient();
            {
                SmtpMail.Host = "smtp.gmail.com";
                SmtpMail.Port = 587;
                SmtpMail.EnableSsl = true;
                SmtpMail.UseDefaultCredentials = true;
                SmtpMail.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                SmtpMail.Credentials = new System.Net.NetworkCredential("accounts@orangepay.in", "Qd74va#7");
                SmtpMail.Send(message);
            }
            message = null;
        }
        catch (Exception ex)
        {            
        }
    }
    
    public string GetUserStatus(string MobileNo)
    {
        SqlParameter[] paramGetStatus = new SqlParameter[] 
        { 
            new SqlParameter("@MobileNo",MobileNo)
        };
        DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "usp_GetUserStatus", paramGetStatus);
        if (ds.Tables[0].Rows.Count > 0)
        {
            ActualStatus = ds.Tables[0].Rows[0]["FLAGSMS"].ToString();
        }
        return ActualStatus;
    }
    public string userdetails(string agent_Id)
    {
        try
        {
            SqlParameter[] get_user_details = new SqlParameter[]
            {
                new SqlParameter("@LOGINID",agent_Id)
            };
            DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_getavailablebalance", get_user_details);           
            if (ds.Tables[0].Rows.Count > 0)
            {
                Availablebalance = ds.Tables[0].Rows[0]["balance"].ToString();
            }
        }
        catch (Exception ex)
        {
            string st = ex.Message;
        }
        return Availablebalance;
    }
    public void SendSMS(string MobileNo, string sms, string refrenceno, string AgMobileNo, string stringquery)
    {
        try
        {

            string CourentDate = DateTime.Now.ToShortDateString();
            int ServiceSMS = 0;
            string strUrl = "";
            SqlParameter[] param = new SqlParameter[]
            {
                new SqlParameter("@LoginId","")
            };
            DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "GetSmsServiceStatus", param);
            if (ds.Tables[0].Rows.Count > 0)
            {
                ServiceSMS = Convert.ToInt32(ds.Tables[0].Rows[0]["SMSService"]);
            }
            else
            {
                ServiceSMS = 0;
            }
            if (ServiceSMS == 1)
            {
                strUrl = "http://alerts.sinfini.com/api/web2sms.php?workingkey=A0c8f3938f877b4a46175dfa15e04b064&sender=RECHRG&to=" + MobileNo + "&message=" + sms + "";
            }
            else
            {
                //http://192.169.225.110/SMSAPIS.aspx?username=VENUS&password=12345&mobileno=8273533062&message=test%20sms&unicode=0&senderid=VENUSR
                strUrl = "http://sms.jharkhandwala.com/SMSAPIS.aspx?username=VENUS&password=12345&mobileno=" + MobileNo + "&message=" + sms + "&unicode=0" + "&senderid=VENUSR" + "";
            }
            //string strUrl = "http://alerts.sinfini.com/api/web2sms.php?workingkey=A0c8f3938f877b4a46175dfa15e04b064&sender=RECHRG&to=" + MobileNo + "&message=" + sms + "";
            WebRequest request = HttpWebRequest.Create(strUrl);
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream s = (Stream)response.GetResponseStream();
            StreamReader readStream = new StreamReader(s);
            string dataString = readStream.ReadToEnd();
            response.Close();
            s.Close();
            readStream.Close();
            SqlParameter[] url = new SqlParameter[]
            {
                new SqlParameter("@RefNumber",refrenceno),
                new SqlParameter("@SentMessage",sms),
                new SqlParameter ("@SMSResponce",dataString),
            };
            SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "usp_Responcegeturl", url);
        }
        catch (Exception ex)
        {
           // CommonFunction.writeToLogFile(Convert.ToString(ex));            
        }
    }

    public void SendSMSByAdmin(string MobileNo, string sms, string refumber, string loginid)
    {
        try
        {
            int ServiceSMS=0;
            string strUrl = "";
            SqlParameter[] param = new SqlParameter[]
            {
                new SqlParameter("@LoginId",loginid)
            };
            DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "GetSmsServiceStatus", param);
            if (ds.Tables[0].Rows.Count > 0)
            {
                ServiceSMS = Convert.ToInt32(ds.Tables[0].Rows[0]["SMSService"]);
            }
            else
            {
                ServiceSMS = 0;
            }
            if (ServiceSMS == 5)
            {
                strUrl = "http://alerts.sinfini.com/api/web2sms.php?workingkey=A0c8f3938f877b4a46175dfa15e04b064&sender=RECHRG&to=" + MobileNo + "&message=" + sms + "";
            }
            else
            {
                 strUrl ="http://bhashsms.com/api/sendmsg.php?user=9835482910&pass=9835482910&sender=OrgPay&phone="+ MobileNo + "&text="+ sms + "&priority=ndnd&stype=normal";
            }
            //WebRequest request = HttpWebRequest.Create(strUrl);
            //request.Method = "GET";
           // HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //Stream s = (Stream)response.GetResponseStream();
            //StreamReader readStream = new StreamReader(s);
            //string dataString = readStream.ReadToEnd();
            //response.Close();
            //s.Close();
            //readStream.Close();
        
            SqlParameter[] paramSaveSms = new SqlParameter[] 
            {
                new SqlParameter("@Sms",sms),
                new SqlParameter("@UserId",loginid),
                new SqlParameter ("@RefNumber",refumber),
                new SqlParameter ("@SMSResponce",""),

            };
            SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "usp_InsertSmsUsedByAdmin", paramSaveSms);
        }
        catch (Exception ex)
        {
           // CommonFunction.writeToLogFile(Convert.ToString(ex));
        }
    }

    public static string eGenAPIRechargeGetStatus(string RefNumber)
    {
      
        string strUrl = "http://venusrecharge.co.in/TransactionStatus.aspx?authkey=10001&authpass=Test@123&OrderNo=&Merchantrefno="+RefNumber+"&ServiceType=MR";
        WebRequest request = HttpWebRequest.Create(strUrl);
        request.Method = "GET";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream s = (Stream)response.GetResponseStream();
        StreamReader readStream = new StreamReader(s);
        string dataString = readStream.ReadToEnd();
        response.Close();
        s.Close();
        readStream.Close();
        return dataString;
    }

    public void UpdateUserStatus(string AgMobileNo)
    {
        try
        {
            SqlParameter[] url = new SqlParameter[]
            {
                new SqlParameter("@AgMobileNo",AgMobileNo),
            };
            SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "usp_UpdateStatusForSMS", url);
        }
        catch (Exception ex)
        {
            CommonFunction.writeToLogFile(Convert.ToString(ex));
        }
    }

    public static void writeToLogFile(string logMessage)
    {
        string strLogMessage = string.Empty;
        string strLogFile = HttpContext.Current.Server.MapPath("../ErrorLog/Logfile.txt");

        StreamWriter swLog;
        strLogMessage = string.Format("{0}: {1}", DateTime.Now, logMessage);
        if (!File.Exists(strLogFile))
        {
            swLog = new StreamWriter(strLogFile);
        }
        else
        {
            swLog = File.AppendText(strLogFile);
        }
        swLog.WriteLine(strLogMessage);
        swLog.WriteLine();
        swLog.Close();
    }

    public static void writeToLogFileMApps(string logMessage)
    {
        string strLogMessage = string.Empty;
        string strLogFile = HttpContext.Current.Server.MapPath("../MobilePortal/Test/MobileAppserror.txt");
        StreamWriter swLog;
        strLogMessage = string.Format("{0}: {1}", DateTime.Now, logMessage);
        if (!File.Exists(strLogFile))
        {
            swLog = new StreamWriter(strLogFile);
        }
        else
        {
            swLog = File.AppendText(strLogFile);
        }
        swLog.WriteLine(strLogMessage);
        swLog.WriteLine();
        swLog.Close();
    }

    public static int InsertTransactionWithPendingStatus(string WLID, string Ipaddress, string RefNo, string AgentId, string Type, string Operator, string OperatotId, string Circle, string MobileNo, string Amount, string VendorTxnId, string ServiceVendor, string PortalName, string ServiceName)
    {
        SqlParameter[] InsertWithPendingStatusParam = new SqlParameter[]
        {
            new SqlParameter("@WLID",Convert.ToInt64(WLID)),
            new SqlParameter("@IPAddress",Ipaddress),
            new SqlParameter("@ReferenceNumber",RefNo),
            new SqlParameter("@AgentID",Convert.ToInt64(AgentId)),
            new SqlParameter("@Type",Type.ToString()),
            new SqlParameter("@Operater",Operator),
            new SqlParameter("@operatorID",Convert.ToInt32(OperatotId)),
            new SqlParameter("@Circle",Circle),
            new SqlParameter("@Mobileno",Convert.ToString(MobileNo)),
            new SqlParameter("@Amount",Convert.ToDecimal(Amount)),
            new SqlParameter("@cptransactionid",VendorTxnId),
            new SqlParameter("@ServiceVendor",ServiceVendor),
            new SqlParameter("@PortalName",PortalName),
            new SqlParameter("@SERVICE_NAME",ServiceName),
            new SqlParameter("@ErrorMessage",SqlDbType.Int)
        };
        InsertWithPendingStatusParam[14].Direction = ParameterDirection.Output;
        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "Insert_Mobile_DTH_Bill_With_Pending_Status", InsertWithPendingStatusParam);
        int result = Convert.ToInt32(InsertWithPendingStatusParam[14].Value);
        return result;
    }

    public static int InsertTransactionWithPendingStatusSMS(string WLID, string Ipaddress, string RefNo, string AgentId, string Type, string Operator, string OperatotId, string Circle, string MobileNo, string Amount, string ServiceCharge, string VendorTxnId, string ServiceVendor, string PortalName, string ServiceName)
    {
        SqlParameter[] InsertWithPendingStatusParam = new SqlParameter[]
        {
            new SqlParameter("@WLID",WLID),
            new SqlParameter("@IPAddress",Ipaddress),
            new SqlParameter("@ReferenceNumber",RefNo),
            new SqlParameter("@AgentID",Convert.ToInt64(AgentId)),
            new SqlParameter("@Type",Type.ToString()),
            new SqlParameter("@Operater",Operator),
            new SqlParameter("@operatorID",OperatotId),
            new SqlParameter("@Circle",Circle),
            new SqlParameter("@Mobileno",Convert.ToInt64(MobileNo)),
            new SqlParameter("@Amount",Convert.ToDecimal(Amount)),
            new SqlParameter("@ServiceCharge",Convert.ToDecimal(ServiceCharge)),
            new SqlParameter("@cptransactionid",VendorTxnId),
            new SqlParameter("@ServiceVendor",ServiceVendor),
            new SqlParameter("@PortalName",PortalName),
            new SqlParameter("@SERVICE_NAME",ServiceName),
            new SqlParameter("@ErrorMessage",SqlDbType.Int)
        };
        InsertWithPendingStatusParam[15].Direction = ParameterDirection.Output;
        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "Insert_Mobile_DTH_Bill_With_Pending_Status_SMS", InsertWithPendingStatusParam);
        int result = Convert.ToInt32(InsertWithPendingStatusParam[15].Value);
        return result;
    }

    public static string ChackBalanceeGenAPI()
    {
        string strUrl = "http://venusrecharge.co.in/Balance.aspx?authkey=10021&authpass=OrangePay@123&service=recharge";
        WebRequest request = HttpWebRequest.Create(strUrl);
        request.Method = "GET";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream s = (Stream)response.GetResponseStream();
        StreamReader readStream = new StreamReader(s);
        string dataString = readStream.ReadToEnd();
        response.Close();
        s.Close();
        readStream.Close();
        string bal = "0";
        DataSet ds = new DataSet();
        if (!(dataString.Contains("error") || dataString.Contains("Error")))
        {
            ds.ReadXml(new StringReader(dataString));
            if (ds.Tables["Response"].Rows.Count > 0)
            {
                bal= Convert.ToString(ds.Tables[0].Rows[0]["Balance"]);
            }
        }
        else
        {
            bal= "0";
        }

        return bal; 
        
    }
    public static string ChackBalanceIWTAPI()
    {
        
            return "0";
        
    }

    public static string CheckBalExcel()
    {
         return "0";
       
    }
    public static string CheckBalApiWorld()
    {
         return "0";
        
    }
   
 public static string eGenAPIRecharge(string service, string operatorCode, string ServiceCode, string accountNumber, string amount, string clientTranId, string CoustomerMobNo, string loginid)
    {
        string strUrl = "http://venusrecharge.co.in/Transaction.aspx?authkey=10021&authpass=OrangePay@123&mobile=" + accountNumber + "&amount=" + amount + "&opcode=" + operatorCode + "&Merchantrefno=" + clientTranId + "&ServiceType=" + ServiceCode;
        vendorinputoutputResponce(loginid, clientTranId, strUrl, "", service);
        WebRequest request = HttpWebRequest.Create(strUrl);
        request.Method = "GET";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream s = (Stream)response.GetResponseStream();
        StreamReader readStream = new StreamReader(s);
        string dataString = readStream.ReadToEnd();
        response.Close();
        s.Close();
        readStream.Close();
        vendorinputoutputResponce(loginid, clientTranId, "", dataString, service);
        return dataString;
    }


    public static string eGenAPIPostPaidRecharge(string service, string operatorCode, string circleCode, string mlAccountNumber, string userAccountNumber, string type, string stdCode, string amount, string clientTranId, string CoustomerMobNo, string loginid)
    {
        
        return "";
    }


    public static string ExcelApiRecharge(string Loginid, string reseller_id, string reseller_pass, string denomination, string mobilenumber, string operatorid, string meroid, string circleid, string voucher, string servicename)
    {
        return "";
    }

    public static string IWTApiRecharge(string Loginid, string denomination, string mobilenumber, string operatorid, string meroid, string circleid, string voucher, string servicename)
    {
        
        return "";
    }

    public static string ExcelRechargeGetReResponse(string RefNo,string OdrID)
    {
        return "";
    }    

    public static string ApiWorldRecharge(string Loginid, string reseller_id, string servicetype, string denomination, string mobilenumber, string operatorid, string meroid, string circleid, string voucher, string servicename)
    {
        return "";
    }

    public static void vendorinputoutputResponce(string Loginid, string txnid, string inputrequest, string outputresponce, string servicename)
    {
        SqlParameter[] insertinputoutputvendor = new SqlParameter[]
        {
            new SqlParameter("@Loginid",Loginid),
            new SqlParameter("@referenceno",txnid),
            new SqlParameter("@inputrequest",inputrequest),
            new SqlParameter("@outputresponce",outputresponce),
            new SqlParameter("@servicename",servicename)
        }; SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_vendor_inputoutput_Responce", insertinputoutputvendor);
    }

    public static string  FN_GetOperatorId(string RSMsg)
    {
        string[] abc = RSMsg.Split('=');
        string auth = Convert.ToString(abc.GetValue(5));
        string[] xyz = auth.Split('T');
        string AUTHCODE = Convert.ToString(xyz.GetValue(0));
                
        return AUTHCODE;
    }

    public static bool IsNumeric(string strToCheck)
    {
        return Regex.IsMatch(strToCheck, "^\\d+(\\.\\d+)?$");
    }

    public static string FN_GetDTHSerialNo(string RSMsg)
    {
        string[] PIN = RSMsg.Split('=');
        string PIN_SERIAL= Convert.ToString(PIN.GetValue(8));
        string[] pin1 = PIN_SERIAL.Split('E');
        string PIN_SERIAL1 = Convert.ToString(pin1.GetValue(0));
                  
        return PIN_SERIAL1;
    }

    public static string FN_GetDTHPinNo(string RSMsg)
    {
        string[] PINV = RSMsg.Split('=');
        string PIN_VALUE = Convert.ToString(PINV.GetValue(7));
        string[] PINV1 = PIN_VALUE.Split('P');
        string PIN_VALUE1 = Convert.ToString(PINV1.GetValue(0));
       
        return PIN_VALUE1;
    }

    public static DataSet GetWhitelabelDetails(string url, string pageid)
    {
        DataSet ds;
        try
        {
            if (pageid != "0")
            {
                SqlParameter[] check_DomainName = new SqlParameter[]
                {
                    new SqlParameter("@DomainName",url),
                    new SqlParameter("@Pageid",pageid)
                };

                ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "usp_GetWhiteLabelDetails_WhiteLabel", check_DomainName);
            }
            else
            {
                SqlParameter[] check_DomainName = new SqlParameter[]
                {
                    new SqlParameter("@DomainName",url),
                    new SqlParameter("@Pageid",pageid)
                };

                ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "usp_GetWhiteLabelDetails_WhiteLabel", check_DomainName);
            }
            return ds;
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}
