using System;
using System.Collections;
using System.Configuration;
using System.Data;
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.Data.OracleClient;
using System.Linq;
using SingleRateRequestMsgProcessor;
using EjadaMQProcessor;
using System.IO;
using Microsoft.Office.Interop.Excel;
using _Excel = Microsoft.Office.Interop.Excel;
using System.Collections.Generic;

public partial class SettlSearch : System.Web.UI.Page
{
    public string selectedCardScheme, selectedfdate;
    public int selected_RC_code;
    public decimal dPageTotal;

    public void SetReCodeAndCS()
    {
        if (Request.QueryString["cs"] != "" && Request.QueryString["fdate"] != "")
        {
            selectedCardScheme = Request.QueryString["cs"] as string;
            selectedfdate = Request.QueryString["fdate"] as String;
        }
        else if (Request.QueryString["cs"] != "")
        {
            selectedCardScheme = Request.QueryString["cs"] as string;
        }
        if (selectedCardScheme == "Amex")
        {
            lblTitle.Text = "Amex Settlements";
            selected_RC_code = 12;
        }
        else if (selectedCardScheme == "MCacq")
        {
            lblTitle.Text = "MasterCard Acquirer";
            selected_RC_code = 11;
        }
        else if (selectedCardScheme == "Maestro") // MDS
        {
            lblTitle.Text = "Maestro Settlements";
            selected_RC_code = 7;
        }
        else if (selectedCardScheme == "Visa")
        {
            selected_RC_code = 15;
            lblTitle.Text = "Visa Settlements";
        }
        // For Card Scheme Billing Changes
        else if (selectedCardScheme == "VISA_BILL_M" || selectedCardScheme == "VISA_BILL_Q")
        {
            selected_RC_code = 15;
            lblTitle.Text = "Visa Billing Settlements";
            btnReprocess.Visible = false;
        }
        else if (selectedCardScheme == "MC_BILL") // MDS
        {
            lblTitle.Text = "MasterCard Settlements";
            selected_RC_code = 11;
            btnReprocess.Visible = false;
        }
        else
        {
            //Response.Redirect("../Business/default.aspx?err=1");
            Session.Clear();
            Response.Redirect("../Security/LoginPage.aspx");
        }



    }
    protected void Page_Load(object sender, EventArgs e)
    {
        SetReCodeAndCS();
        if (!IsPostBack)
        {
            SecurityAgent.AuthenticateArchive();

            if (selectedCardScheme == "Visa")
            {
                loadProducts(selected_RC_code);//visa rc_code
                loadCurrency();
            }
            if (selectedCardScheme == "MCacq")
            {
                loadProducts(selected_RC_code);//visa rc_code
            }
            if (selectedCardScheme == "VISA_BILL_M")
            {
                ddlProducts.SelectedValue = "20";
                dt_SettleDate.date = Helper.convertDate(selectedfdate.ToString());
                loadProducts(selected_RC_code);
                loadCurrency();

                this.Search();
            }
            if (selectedCardScheme == "VISA_BILL_Q")
            {
                ddlProducts.SelectedValue = "21";
                dt_SettleDate.date = Helper.convertDate(selectedfdate.ToString());
                loadProducts(selected_RC_code);
                loadCurrency();

                this.Search();
            }
            if (selectedCardScheme == "MC_BILL")
            {
                ddlProducts.SelectedValue = "22";
                dt_SettleDate.date = Helper.convertDate(selectedfdate.ToString());
                loadProducts(selected_RC_code);

                this.Search();
            }
        }

    }
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[7].Visible = false;
            e.Row.Cells[8].Visible = false;

            e.Row.Cells[10].Visible = false;

        }
    }
    protected void GridView3_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[6].Visible = false;
        }
    }
    protected void GridViewVAT_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[7].Visible = false;
            e.Row.Cells[8].Visible = false;

            e.Row.Cells[10].Visible = false;

        }
    }
    private void loadCurrency()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        if (ddlProducts.SelectedValue == "17")
            oracom.CommandText = "CS_SETTL_INFO_EDITOR.get_Currency_lookup_Fees";
        else
            oracom.CommandText = "CS_SETTL_INFO_EDITOR.get_Currency_lookup";

        oracom.Parameters.Add("p_output_cur", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlCurrency.DataSource = ds;
        ddlCurrency.DataBind();

        oracon.Close();
    }

    private void loadProducts(int cs_RC_Code)
    {

        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        if (selectedCardScheme == "VISA_BILL_M" || selectedCardScheme == "VISA_BILL_Q" || selectedCardScheme == "MC_BILL")
            oracom.CommandText = "CS_SETTL_INFO_EDITOR.Get_CS_Product_Lookup";
        else
            oracom.CommandText = "CS_SETTL_INFO_EDITOR.get_product_lookup";

        oracom.Parameters.Add("p_cs_Rc_Code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_output_cur", OracleType.Cursor).Direction = ParameterDirection.Output;

        oracom.Parameters["p_cs_Rc_Code"].Value = cs_RC_Code;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlProducts.DataSource = ds;
        ddlProducts.DataBind();

        oracon.Close();
    }

    private void load_CS_Events(int cs_RC_Code)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INFO_EDITOR.get_cs_Event";

        oracom.Parameters.Add("p_product", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_currency", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_cs_Rc_Code", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_output_cur", OracleType.Cursor).Direction = ParameterDirection.Output;


        oracom.Parameters["p_cs_Rc_Code"].Value = cs_RC_Code;

        if (ddlProducts.SelectedIndex != -1)
            oracom.Parameters["p_product"].Value = ddlProducts.SelectedValue;
        else
            oracom.Parameters["p_product"].Value = OracleNumber.Null;

        if (Helper.IsMultiCurrencyProduct_CS(ddlProducts.SelectedValue))
            oracom.Parameters["p_currency"].Value = ddlCurrency.SelectedValue;
        else
            oracom.Parameters["p_currency"].Value = OracleString.Null;


        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddl_CS_EventList.DataSource = ds;
        ddl_CS_EventList.DataBind();

        ddlAccountFee.DataSource = ds;
        ddlAccountFee.DataBind();

        oracon.Close();
    }

    protected void ButtonSearch_Click(object sender, EventArgs e)
    {
        try
        {
            this.Search();
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex);
            lblError.Text = "Exception: Please Refer to application Log";
        }
    }

    public void Search()
    {
        try
        {
            ExceptionUtility.LogEvent_Errors(0, "", "ButtonSearch_Click", "Start Search");

            lblError.Text = ""; Lbl_MannualDif.Text = ""; lbl_CR_DR_Diff.Text = "";
            pnlAddMannualDiff.Visible = false; int FileNumber = 0;
            PanelMcAcq.Enabled = true; PanelMcAcq.Visible = false; pnlBR.Visible = false; pnlResult.Visible = false;
            pnlAddFee.Visible = false;
            pnlUploadFees.Visible = false;
            pnlResultFees.Visible = false;
            pnlUploadFees.Visible = false;

            if (ddlProducts.SelectedValue == "17")
            {
                btnGenSumReport.Visible = false;
                load_CS_Events(selected_RC_code);
                //pnlUploadFees.Visible = true;
                //pnlResultFees.Visible = true;
                loadResultFees();
            }
            else
            {
                btnGenSumReport.Visible = true;
                if ((selectedCardScheme == "Visa" || selectedCardScheme == "MCacq") && ddlProducts.SelectedIndex == -1)
                    lblError.Text = "Please Choose the product";
                else if (dt_SettleDate.date.Length == 0)
                    lblError.Text = "Please Choose the date";
                else
                {
                    load_CS_Events(selected_RC_code); // For add mannual screen

                    string status = getFileStatusandFileNumber(out FileNumber);

                    if (selectedCardScheme == "MC_BILL" && status == "0")
                    {
                        lblError.Text = processVatEntrie();
                        pnlResult.Visible = true;
                        loadResult(500, 1);
                    }
                    else if (selectedCardScheme == "VISA_BILL_M" || selectedCardScheme == "VISA_BILL_Q")
                    {
                        pnlResult.Visible = true;
                        loadResult(500, 1);
                    }
                    else if (selectedCardScheme == "VISA_BILL_M" || selectedCardScheme == "VISA_BILL_Q" && status == "5")
                    {
                        pnlResult.Visible = true;
                        loadResult(500, 1);
                    }
                    if (selectedCardScheme == "MCacq" && status == "0") // status to be decided
                    {
                        PanelMcAcq.Visible = true;
                        Get_MCACQ_ManualGLEntry(FileNumber);
                    }
                    else if (status == "1")
                    {
                        pnlResult.Visible = true;
                        // pnlBR.Visible = false;
                        loadResult(500, 1);
                    }
                    else if (status == "5")
                    {
                        Button3.Enabled = false;
                        Button3.ForeColor = System.Drawing.Color.Orange;

                        lblError.Text = "Settlement entries generation is in Progress";
                        if (selectedCardScheme == "Visa")
                        {
                            DataSet ds = getCurrencies();
                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                ExceptionUtility.LogEvent_Errors(0, "", "ButtonSearch_Click", selectedCardScheme + " - Generating the Settlement entries for Currency : " + ds.Tables[0].Rows[i]["CARDSCHEME_CURR_NAME"].ToString());
                                callMQ(ds.Tables[0].Rows[i]["CARDSCHEME_CURR_NAME"].ToString(), ds.Tables[0].Rows[i]["EXCHG_ACCOUNT_NUMBER"].ToString());
                            }
                        }

                        lblError.Text = processVatEntrie();
                        Button3.Enabled = true;
                        Button3.ForeColor = System.Drawing.Color.DarkBlue;

                        if (lblError.Text.Equals("Successful"))
                            lblError.Text = "";
                        else
                            return;


                        pnlResult.Visible = true;
                        //   pnlBR.Visible = false;
                        loadResult(500, 1);
                    }
                    else if (status == "9")
                    {
                        lblError.Text = "Files not loaded";
                        // pnlResult.Visible = true;
                        //   pnlBR.Visible = false;
                        //  loadResult(500, 1);
                    }

                }

                ExceptionUtility.LogEvent_Errors(0, "", "ButtonSearch_Click", "End Search");
            }
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex); ;
            lblError.Text = "Exception: Please Refer to application Log";
        }
    }

    private void Get_MCACQ_ManualGLEntry(int FileNumber)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INFO_EDITOR.Get_MCACQ_ManualGLEntry";

        oracom.Parameters.Add("p_cs_Rc_Code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Product", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_File_Number", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_page_size", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_page_num", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_total_pages", OracleType.Number).Direction = ParameterDirection.Output;


        oracom.Parameters["p_cs_Rc_Code"].Value = selected_RC_code;
        oracom.Parameters["P_File_Number"].Value = FileNumber;
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        if (ddlProducts.SelectedIndex != -1)
            oracom.Parameters["P_Product"].Value = ddlProducts.SelectedValue;
        else
            oracom.Parameters["P_Product"].Value = OracleNumber.Null;

        oracom.Parameters["p_page_size"].Value = 10;
        oracom.Parameters["p_page_num"].Value = 1;
        oracom.Parameters["p_lang"].Value = "EN";


        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        int nop = int.Parse(oracom.Parameters["p_total_pages"].Value.ToString());
        oracon.Close();


        gvMcAcq.DataSource = ds;
        gvMcAcq.DataBind();


    }

    private void loadResult(int pageSize, int pageNumber)
    {
        loadResult(pageSize, pageNumber, "E");
        loadResult(pageSize, pageNumber, "V");
    }

    private void loadResult(int pageSize, int pageNumber, string VAT_ENT_FLAG)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INFO_EDITOR.Get_CS_Settl";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_product", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_currency", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_page_size", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_page_num", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        // V VAT or E Entry 
        oracom.Parameters.Add("p_Evnt_Code", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_total_pages", OracleType.Number).Direction = ParameterDirection.Output;

        oracom.Parameters.Add("p_cs_Rc_Code", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters["p_cs_Rc_Code"].Value = selected_RC_code;




        oracom.Parameters["p_Evnt_Code"].Value = VAT_ENT_FLAG;


        if (ddlProducts.SelectedIndex != -1)
            oracom.Parameters["p_product"].Value = ddlProducts.SelectedValue;
        else
            oracom.Parameters["p_product"].Value = OracleNumber.Null;

        if (Helper.IsMultiCurrencyProduct_CS(ddlProducts.SelectedValue))
            oracom.Parameters["p_currency"].Value = ddlCurrency.SelectedValue;
        else
            oracom.Parameters["p_currency"].Value = OracleString.Null;

        //2017019
        string date = dt_SettleDate.date;
        //if (date[6] == '0')
        //    date = date.Remove(6, 1);
        oracom.Parameters["p_date"].Value = date;

        oracom.Parameters["p_page_size"].Value = pageSize;
        oracom.Parameters["p_page_num"].Value = pageNumber;
        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        int nop = int.Parse(oracom.Parameters["p_total_pages"].Value.ToString());
        oracon.Close();

        if (VAT_ENT_FLAG == "E")
        {
            GridView1.DataSource = ds;
            GridView1.DataBind();

            //Calculate Sum and display in Footer Row
            Session["File_Number"] = "";
            Session["CS_GL_CODE"] = "";

            if (ds.Tables[0].Rows.Count > 0)
            {
                decimal drTotal = ds.Tables[0].AsEnumerable().Sum(row => row.Field<decimal>("DbAmt"));
                decimal crTotal = ds.Tables[0].AsEnumerable().Sum(row => row.Field<decimal>("CRAmt"));
                GridView1.FooterRow.Cells[4].Text = "Total";
                GridView1.FooterRow.Cells[5].HorizontalAlign = HorizontalAlign.Right;
                GridView1.FooterRow.Cells[5].Text = drTotal.ToString("N2");
                GridView1.FooterRow.Cells[6].HorizontalAlign = HorizontalAlign.Right;
                GridView1.FooterRow.Cells[6].Text = crTotal.ToString("N2");

                lbl_CR_DR_Diff.Text = (crTotal - drTotal).ToString("N2");

                lbl_File_Number.Text = ds.Tables[0].Rows[0]["File_Number"].ToString();
                lbl_Status.Text = ds.Tables[0].Rows[0]["CS_GL_CODE"].ToString();

                ViewState["status"] = ds.Tables[0].Rows[0]["CS_GL_Code"].ToString();
                //.ro=Cells[6].Visible = false;

                GridView1.FooterRow.Cells[7].Visible = false;
                GridView1.FooterRow.Cells[8].Visible = false;
                GridView1.FooterRow.Cells[10].Visible = false;
            }
        }
        else// if (VAT_ENT_FLAG == "V") V or Full Event Code
        {
            GridViewVAT.DataSource = ds;
            GridViewVAT.DataBind();

            if (ds.Tables[0].Rows.Count > 0)
            {
                ViewState["status"] = ds.Tables[0].Rows[0]["CS_GL_Code"].ToString();

                GridViewVAT.FooterRow.Cells[7].Visible = false;
                GridViewVAT.FooterRow.Cells[8].Visible = false;
                GridViewVAT.FooterRow.Cells[10].Visible = false;
            }
        }
    }

    private void loadResultFees()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INFO_EDITOR.GET_SwiftFees_SETTL";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Prd_id", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_currency", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_page_size", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_page_num", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_total_pages", OracleType.Number).Direction = ParameterDirection.Output;


        oracom.Parameters["P_Prd_id"].Value = ddlProducts.SelectedValue;
        oracom.Parameters["p_currency"].Value = ddlCurrency.SelectedValue;

        //2017019
        string date = dt_SettleDate.date;
        //if (date[6] == '0')
        //    date = date.Remove(6, 1);
        oracom.Parameters["p_date"].Value = date;

        oracom.Parameters["p_page_size"].Value = 10;
        oracom.Parameters["p_page_num"].Value = 1;
        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        oracon.Close();

        string a = oracom.Parameters["p_res_code"].Value.ToString();
        string error = oracom.Parameters["p_res_msg"].Value.ToString();
        GridView3.DataSource = ds;
        GridView3.DataBind();
        pnlResultFees.Visible = true;
        if (a == "0")
        {
            lbl_File_Number.Text = ds.Tables[0].Rows[0]["File_Number"].ToString();
            lbl_Status.Text = ds.Tables[0].Rows[0]["CS_GL_CODE"].ToString();
        }
        else
        {
            lblError.Text = error;
            pnlUploadFees.Visible = true;
        }
    }

    protected void GridViewVAT_RowCommand(object sender, GridViewCommandEventArgs e)
    {

        Lbl_MannualDif.Text = "";
        if (e.CommandName.Equals("v"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = GridViewVAT.DataKeys[index].Value.ToString();

            lbl_Detail.Text = GridViewVAT.Rows[index].Cells[0].Text.ToString();
            pnlBR.Visible = true;
            Page.SetFocus(lbl_Detail.ClientID);

            //pnlBR.Enabled = false;
            ViewState["rowID"] = rowID;

            string evnt_code = GridViewVAT.Rows[index].Cells[7].Text.ToString();
            ViewState["evnt_code"] = evnt_code;

            loadDetails(rowID, evnt_code, Helper.gridSize(), 1);

            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "scrollWin()", true);
        }
    }

    protected void gvMcAcq_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[1].Visible = false;
        }
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {

        Lbl_MannualDif.Text = "";
        if (e.CommandName.Equals("v"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = GridView1.DataKeys[index].Value.ToString();

            lbl_Detail.Text = GridView1.Rows[index].Cells[0].Text.ToString();
            pnlBR.Visible = true;
            Page.SetFocus(lbl_Detail.ClientID);

            //pnlBR.Enabled = false;
            ViewState["rowID"] = rowID;

            string evnt_code = GridView1.Rows[index].Cells[7].Text.ToString();
            ViewState["evnt_code"] = evnt_code;

            loadDetails(rowID, evnt_code, Helper.gridSize(), 1);

            //   loadResult(500, 1, evnt_code);
            rowBttn.Visible = false;

            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "scrollWin()", true);

        }
        else if (e.CommandName.Equals("d"))
        {


            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = GridView1.DataKeys[index].Value.ToString();

            string evnt_code = GridView1.Rows[index].Cells[7].Text.ToString();
            int file_no = Convert.ToInt16(GridView1.Rows[index].Cells[8].Text);

            string error = ""; ;

            string status_flag = GridView1.Rows[index].Cells[9].Text.ToString();
            string editable_flag = GridView1.Rows[index].Cells[10].Text.ToString();

            if (status_flag.Substring(0, 6).ToLower().Equals("cancel") || status_flag.ToLower().Equals("entered"))
            {
                if (editable_flag.ToUpper().Equals("Y"))
                {
                    bool saved = Delete_CS_Entry(evnt_code, file_no, ref error);

                    if (saved)
                    {
                        Lbl_MannualDif.Text = "Successfuly deleted Entry";
                        loadResult(500, 1); ;
                    }
                    else
                    {
                        Lbl_MannualDif.Text = error;
                    }
                }
                else
                    Lbl_MannualDif.Text = "Deletion Failed - Auto Entry cannot be  deleted";
            }
            else
                Lbl_MannualDif.Text = "Deletion Failed - Entry can be deleted only when status is Entered/Caneled";
        }

    }
    private bool Delete_CS_Entry(string event_code, int File_no, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INFO_EDITOR.Delete_SettlEntry";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_File_no", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_event_code", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Product", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_cs_Rc_Code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_CST_CODE", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();
        oracom.Parameters["p_File_no"].Value = Convert.ToDecimal(File_no);
        oracom.Parameters["p_event_code"].Value = event_code;
        oracom.Parameters["P_CST_CODE"].Value = OracleString.Null;
        oracom.Parameters["p_cs_Rc_Code"].Value = selected_RC_code;
        if (ddlProducts.SelectedIndex != -1)
            oracom.Parameters["p_product"].Value = ddlProducts.SelectedValue;
        else
            oracom.Parameters["p_product"].Value = OracleNumber.Null;
        //oracom.Parameters["P_Product"].Value = ddlProducts.SelectedValue; 

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    private void loadDetails(string rowID, string evnt_code, int pageSize, int pageNumber)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INFO_EDITOR.get_cs_settl_trans";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_csr_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_page_size", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_page_num", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_evnt_code", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_total_pages", OracleType.Number).Direction = ParameterDirection.Output;


        oracom.Parameters["p_csr_code"].Value = rowID;

        oracom.Parameters["p_page_size"].Value = pageSize;
        oracom.Parameters["p_page_num"].Value = pageNumber;
        oracom.Parameters["p_lang"].Value = "EN";

        oracom.Parameters["p_evnt_code"].Value = evnt_code;

        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        int nop = int.Parse(oracom.Parameters["p_total_pages"].Value.ToString());
        oracon.Close();

        GridView2.DataSource = ds;
        GridView2.DataBind();
        if (pageNumber == 1)
        {
            ddlPages2.Items.Clear();
            for (int i = 1; i <= nop; i++)
            {
                ddlPages2.Items.Add(i.ToString());
            }
        }
    }

    protected void ddlPages2_SelectedIndexChanged(object sender, EventArgs e)
    {
        string rowID = ViewState["rowID"].ToString();
        string evnt_code = ViewState["evnt_code"].ToString();
        loadDetails(rowID, evnt_code, Helper.gridSize(), int.Parse(ddlPages2.SelectedValue));
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        pnlBR.Visible = false;
        rowBttn.Visible = true;
        //pnlResult.Enabled = true;
        loadResult(500, 1, "V");
    }


    private bool Approval_Reject_GenerateGl(string settleDate, int file_number, string status)
    {

        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INFO_EDITOR.SubmitForApprvl";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_product", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_currency", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_status", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_file_number", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters.Add("p_cs_Rc_Code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters["p_cs_Rc_Code"].Value = selected_RC_code;


        oracom.Parameters["p_status"].Value = status;


        if (ddlProducts.SelectedIndex != -1)
            oracom.Parameters["p_product"].Value = ddlProducts.SelectedValue;
        else
            oracom.Parameters["p_product"].Value = OracleNumber.Null;

        if (Helper.IsMultiCurrencyProduct_CS(ddlProducts.SelectedValue))
            oracom.Parameters["p_currency"].Value = ddlCurrency.SelectedValue;
        else
            oracom.Parameters["p_currency"].Value = OracleString.Null;




        oracom.Parameters["p_file_number"].Value = file_number;
        oracom.Parameters["p_date"].Value = "20" + settleDate;
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        OracleDataAdapter da = new OracleDataAdapter(oracom);


        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();

        if (a == "0")
        {
            lblError.ForeColor = System.Drawing.Color.DarkGreen;
            lblError.Text = oracom.Parameters["p_res_msg"].Value.ToString();
            return true;
        }
        else
        {
            lblError.Text = oracom.Parameters["p_res_msg"].Value.ToString();
            return false;
        }

    }
    protected void ShowMannualGL(string event_code)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INFO_EDITOR.get_cs_Event_Details";

        oracom.Parameters.Add("P_Evnt_code", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_output_cur", OracleType.Cursor).Direction = ParameterDirection.Output;


        oracom.Parameters["P_Evnt_code"].Value = event_code;


        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        oracon.Close();

        lbl_Narr.Text = lbl_FromAcct.Text = lbl_ToAcct.Text = lbl_Sett_Curr.Text = "";

        if (ds.Tables[0].Rows.Count >= 1)
        {
            lbl_Narr.Text = ds.Tables[0].Rows[0]["Narrative"].ToString();
            lbl_FromAcct.Text = ds.Tables[0].Rows[0]["From_Account"].ToString();
            lbl_ToAcct.Text = ds.Tables[0].Rows[0]["To_Account"].ToString();
            lbl_Sett_Curr.Text = ds.Tables[0].Rows[0]["Settl_Currency"].ToString();
        }
    }

    bool SaveMannualDifference(string Evnt_code, decimal Amount, string Amount_Sign, int File_Nmber, string Settl_Date)
    {

        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INFO_EDITOR.AddManualGLEntry";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Product", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Evnt_code", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Amt", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Amt_Sign", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_File_Number", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Settl_Date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Swift_RefNum", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters.Add("p_cs_Rc_Code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters["p_cs_Rc_Code"].Value = selected_RC_code;


        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        if (ddlProducts.SelectedIndex != -1)
            oracom.Parameters["p_product"].Value = Convert.ToInt32(ddlProducts.SelectedValue);
        else
            oracom.Parameters["p_product"].Value = OracleNumber.Null;

        oracom.Parameters["P_Swift_RefNum"].Value = txtRefNum.Text;
        oracom.Parameters["P_Evnt_code"].Value = Evnt_code;
        oracom.Parameters["P_Amt"].Value = Amount;
        oracom.Parameters["P_Amt_Sign"].Value = Amount_Sign;
        oracom.Parameters["p_file_number"].Value = File_Nmber;
        oracom.Parameters["P_Settl_Date"].Value = Settl_Date;



        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();

        if (a == "0")
        {
            Lbl_MannualDif.Text = oracom.Parameters["p_res_msg"].Value.ToString();
            return true;
        }
        else
        {
            Lbl_MannualDif.Text = "Failed to Complete Request.";
            return false;
        }
    }
    protected void btnSavePost_Click(object sender, EventArgs e)
    {
        Decimal Amount = 0;
        if (!Decimal.TryParse(txtAmount.Text.ToString(), out Amount) || Amount <= 0)
        {
            Lbl_MannualDif.Text = "Enter Valid Amount";
            return;
        }
        Lbl_MannualDif.Text = "";

        if (SaveMannualDifference(ddl_CS_EventList.SelectedValue,
                  Convert.ToDecimal(txtAmount.Text),
               ddlGLtype.SelectedValue,
              Convert.ToInt32(lbl_File_Number.Text),
              dt_SettleDate.date
              ))
        {
            btnSavePost.Enabled = false;
            pnlAddMannualDiff.Visible = false;
            loadResult(500, 1); ;

        }
        //   SaveMannualDifference(ddl_CS_EventList.Selev File_Number ,)
    }
    protected void btnCancelPost_Click(object sender, EventArgs e)
    {
        pnlAddMannualDiff.Visible = false;
        btnSavePost.Enabled = true;
    }
    protected void ButtonSubmitForApproval_Click(object sender, EventArgs e)
    {
        ExceptionUtility.LogEvent_Errors(0, "", "ButtonSubmitForApproval_Click", "Start");

        int File_Number = Convert.ToInt32(lbl_File_Number.Text);

        Approval_Reject_GenerateGl(dt_SettleDate.date, File_Number, "001");
        loadResult(500, 1); ;
        //  bttn_Approval.Enabled = false;
        ExceptionUtility.LogEvent_Errors(0, "", "ButtonSubmitForApproval_Click", "End");
    }//

    protected void btnReprocess_Click(object sender, EventArgs e)
    {
        try
        {
            ExceptionUtility.LogEvent_Errors(0, "", "btnReprocess_Click", "Start");

            if (selectedCardScheme == "Visa")
            {
                DataSet ds1 = getCurrencies();
                for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
                {
                    callMQ(ds1.Tables[0].Rows[i]["CARDSCHEME_CURR_NAME"].ToString(), ds1.Tables[0].Rows[i]["EXCHG_ACCOUNT_NUMBER"].ToString());
                }
            }

            string DBConnection = Helper.dbConnection();

            OracleConnection oracon = new OracleConnection(DBConnection);
            oracon.Open();

            OracleCommand oracom = new OracleCommand();
            oracom.Connection = oracon;

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "CS_SETTL_INTERFACE.REPROCESS_SETTLEMENT_ENTRIES";

            oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("P_Product", OracleType.Number).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_Currency", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("P_Settl_Date", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_Status", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;

            oracom.Parameters.Add("p_Rsp", OracleType.VarChar, 2500).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 25000).Direction = ParameterDirection.Output;

            oracom.Parameters.Add("p_cs_Rc_Code", OracleType.Number).Direction = ParameterDirection.Input;

            oracom.Parameters["p_cs_Rc_Code"].Value = selected_RC_code;

            oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

            // oracom.Parameters["p_Currency"].Value = ddlCurrency.SelectedValue;
            oracom.Parameters["P_Settl_Date"].Value = dt_SettleDate.date;
            oracom.Parameters["p_Status"].Value = ViewState["status"].ToString();
            oracom.Parameters["p_lang"].Value = "en";


            if (ddlProducts.SelectedIndex != -1)
                oracom.Parameters["p_product"].Value = ddlProducts.SelectedValue;
            else
                oracom.Parameters["p_product"].Value = OracleNumber.Null;

            if (Helper.IsMultiCurrencyProduct_CS(ddlProducts.SelectedValue))
                oracom.Parameters["p_currency"].Value = ddlCurrency.SelectedValue;
            else
                oracom.Parameters["p_currency"].Value = OracleString.Null;

            oracom.ExecuteNonQuery();
            oracon.Close();
            string a = oracom.Parameters["p_res_code"].Value.ToString();

            if (a == "0")
            {
                if (selectedCardScheme == "Visa")
                {
                    loadProducts(selected_RC_code);//visa rc_code
                    loadCurrency();
                }
                load_CS_Events(selected_RC_code);//visa rc_code

                Lbl_MannualDif.Text = oracom.Parameters["p_res_msg"].Value.ToString();
            }
            else
            {
                Lbl_MannualDif.Text = "Failed to Complete Requeset: " + oracom.Parameters["p_res_msg"].Value.ToString(); ;
            }


            ExceptionUtility.LogEvent_Errors(0, "", "btnReprocess_Click", "End");
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex); ;
            lblError.Text = "Exception: Please Refer to application Log";
        }
    }//

    protected void bttn_AddDiff_Click(object sender, EventArgs e)
    {
        try
        {

            ExceptionUtility.LogEvent_Errors(0, "", "bttn_AddDiff_Click", "Start");

            pnlAddMannualDiff.Visible = true;
            btnSavePost.Enabled = true;
            Lbl_MannualDif.Text = "";

            ShowMannualGL(ddl_CS_EventList.SelectedValue);

            ExceptionUtility.LogEvent_Errors(0, "", "bttn_AddDiff_Click", "End");
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex); ;
            lblError.Text = "Exception: Please Refer to application Log";
        }

    }

    protected void ButtonRejectForApproval_Click(object sender, EventArgs e)
    {
        ExceptionUtility.LogEvent_Errors(0, "", "ButtonRejectForApproval_Click", "Start");

        int File_Number = Convert.ToInt32(lbl_File_Number.Text);

        Approval_Reject_GenerateGl(dt_SettleDate.date, File_Number, "008");
        loadResult(500, 1); ;

        ExceptionUtility.LogEvent_Errors(0, "", "ButtonRejectForApproval_Click", "End");

        //  bttn_Reject.Enabled=false;
    }
    protected void bttn_ApproveAndCreateGL(object sender, EventArgs e)
    {
        ExceptionUtility.LogEvent_Errors(0, "", "bttn_ApproveAndCreateGL", "Start");

        int File_Number = Convert.ToInt32(lbl_File_Number.Text);

        Approval_Reject_GenerateGl(dt_SettleDate.date, File_Number, "002");
        loadResult(500, 1);

        //Session["ApproveAndCreateGL"] = "Y";
        //if (ddlProducts.SelectedValue == "2" || ddlProducts.SelectedValue == "7" || ddlProducts.SelectedValue == "9")
        //{
        //    ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window", "window.open('GLPosting.aspx?product=" + ddlProducts.SelectedValue + "&currency=" + ddlCurrency.SelectedValue + "&date=" + dt_SettleDate.date + "','Redirect')", true);
        //}
        //else
        //{
        //    ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window", "window.open('GLPosting.aspx?product=" + ddlProducts.SelectedValue + "&date=" + dt_SettleDate.date + "','Redirect')", true);
        //}

        ExceptionUtility.LogEvent_Errors(0, "", "bttn_ApproveAndCreateGL", "End");
    }
    protected void ddl_CS_EventList_SelectedIndexChanged(object sender, EventArgs e)
    {
        ShowMannualGL(ddl_CS_EventList.SelectedValue);
    }
    protected void btnGenDtlReport_Click(object sender, EventArgs e)
    {
        ExceptionUtility.LogEvent_Errors(0, "", "btnGenDtlReport_Click", "Start");


        string p1 = "20" + dt_SettleDate.date;
        string p2 = ddlProducts.SelectedValue;
        string p3 = "";

        if (Helper.IsMultiCurrencyProduct_CS(ddlProducts.SelectedValue))
            p3 = ddlCurrency.SelectedValue;
        string rpt = "10011";
        if (ddlProducts.SelectedValue == "17")
            rpt = "10012";
        string UrlString1 = "rpt="+ rpt +"&p1=" + p1 + "&p2=" + p2 + "&p3=" + p3 + "&p4=" + selected_RC_code + "&p5=" + selectedCardScheme;
        ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                "window.open('../Reports/Default.aspx?" + UrlString1 + "','Report')", true);

        ExceptionUtility.LogEvent_Errors(0, "", "btnGenDtlReport_Click", "End");
    }


    protected void btnGenSumReport_Click(object sender, EventArgs e)
    {
        string p1 = "20" + dt_SettleDate.date;

        string UrlString1 = "rpt=1003&p1=" + p1;
        ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                "window.open('../Reports/Default.aspx?" + UrlString1 + "','Report')", true);
    }

    protected void btnMCSumReport_Click(object sender, EventArgs e)
    {
        string p1 = dt_SettleDate.date;
        string p2 = ViewState["filenumber"].ToString();

        string UrlString1 = "rpt=1007&p1=" + p1 + "&p2=" + p2;
        ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                "window.open('../Reports/Default.aspx?" + UrlString1 + "','Report')", true);
    }

    string getFileStatusandFileNumber(out int fileNumber)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INTERFACE.ChkFileProcessStatus";

        oracom.Parameters.Add("P_FILE_DATE", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("P_Product", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("P_PrcStatus", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("P_FileNumber", OracleType.Number).Direction = ParameterDirection.Output;

        oracom.Parameters.Add("P_Cs_Rc_Code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters["p_cs_Rc_Code"].Value = selected_RC_code;

        if (ddlProducts.SelectedIndex != -1)
            oracom.Parameters["P_Product"].Value = ddlProducts.SelectedValue;
        else
            oracom.Parameters["p_product"].Value = OracleNumber.Null;

        oracom.Parameters["P_FILE_DATE"].Value = dt_SettleDate.date;

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["P_PrcStatus"].Value.ToString();

        fileNumber = Convert.ToInt32(oracom.Parameters["P_FileNumber"].Value);
        ViewState["filenumber"] = fileNumber.ToString();

        return a;
    }//

    void callMQ(string currency, string account)
    {
        ExceptionUtility.LogEvent_Errors(0, "", "callMQ", "Start");

        string result, msgRecieved, respCode;
        string strQMgrName = ConfigurationManager.AppSettings["QMgrName"];
        string timeOut = ConfigurationManager.AppSettings["TimeOut"];
        string strSendQName = ConfigurationManager.AppSettings["SendQName"];
        string strRecieveQName = ConfigurationManager.AppSettings["RecieveQName"];
        string strChannel = ConfigurationManager.AppSettings["Channel"];
        string strHost = ConfigurationManager.AppSettings["Host"];
        string strPort = ConfigurationManager.AppSettings["Port"];
        string strUser = DecryptLibrary.DecryptLibrary.DecryptData(ConfigurationManager.AppSettings["UserName"]);
        string strPwd = DecryptLibrary.DecryptLibrary.DecryptData(ConfigurationManager.AppSettings["Password"]);
        string strCon = DecryptLibrary.DecryptLibrary.DecryptData(ConfigurationSettings.AppSettings["DBConnection"]);
        string strMWLog = ConfigurationManager.AppSettings["MWLOG"];
        string BuySellCurrency = ConfigurationManager.AppSettings["ExchgRateCurFlg"];

        SingleRateRequestMsgProcessorCls SingleRateRequestMsgProObj;

        string UID_SID = Session["uid"] as string + HttpContext.Current.Session.SessionID;
        EjadaMQProcessorCls EjadaMQProcessorObj = new EjadaMQProcessorCls(strQMgrName, strSendQName, strRecieveQName, strChannel, strHost, strPort, strUser, strPwd, strMWLog, UID_SID);

        //instantiate Object
        SingleRateRequestMsgProObj = new SingleRateRequestMsgProcessorCls(strCon, strMWLog);

        //Build the outgoing messagez
        string strOutGoingMsg = SingleRateRequestMsgProObj.BuildMsg("SAIB  ", BuySellCurrency, "SAR", currency, "100", "123456", account);
        //string strOutGoingMsg = SingleRateRequestMsgProObj.BuildMsg("SAIB  ", "S", "SAR", "USD", "100", "123456", account);

        //MQ Call to Send Receive
        string strIncomingMsg = EjadaMQProcessorObj.ProcessMessage(strOutGoingMsg, "60000", false);

        //Parse the incoming message
        string strAmtChg, strAmtTot, strXchgSel, strUseSel, strXchgBuy, strUseBuy, strAmtVat;
        string strRspCode = SingleRateRequestMsgProObj.ParseRespCode(strIncomingMsg, out strAmtChg, out strAmtTot, out strXchgSel, out strUseSel, out strXchgBuy, out strUseBuy, out strAmtVat);

        ExceptionUtility.LogEvent_Errors(0, "", "callMQ", "MQ Response:" + strRspCode);

        //lblError.Text = strIncomingMsg + " : " + strAmtChg+ " - " + strAmtTot+ " - " + strXchgSel+ " - " + strUseSel+ " - " + strXchgBuy+ " - " + strUseBuy + " - " + strAmtVat +  " - " + strXchgSel + " - " + strXchgBuy;
        updateExchangeRate(currency, strXchgSel, strXchgBuy);

        ExceptionUtility.LogEvent_Errors(0, "", "callMQ", "End");


    }
    DataSet getCurrencies()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INTERFACE.Get_All_Curr_Rec";

        oracom.Parameters.Add("P_Curr_Rec", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        return ds;
    }

    void updateExchangeRate(string Currency, string sellRate, string buyRate)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INTERFACE.UpdtExChgRate";

        oracom.Parameters.Add("P_CurCode", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_sellRate", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_buyRate", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("P_FLAG", OracleType.Number).Direction = ParameterDirection.Output;

        oracom.Parameters["P_CurCode"].Value = Currency;
        oracom.Parameters["P_sellRate"].Value = sellRate;
        oracom.Parameters["P_buyRate"].Value = buyRate;

        oracom.ExecuteNonQuery();
        oracon.Close();
    }

    // void process_McAcq_SettleAmt( int filenumber, string cycle, out string  settl_amt )

    string process_McAcq_SettleAmt(int filenumber, string cycle)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INTERFACE.PROCESS_SetMCACQ_SettlAmt";

        oracom.Parameters.Add("P_FILE_NUMBER", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("P_CS_RC_Code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Product", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Settl_CycleNo", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("P_Status", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("P_RSP", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["P_FILE_NUMBER"].Value = filenumber;
        oracom.Parameters["P_Settl_CycleNo"].Value = cycle;
        oracom.Parameters["P_CS_RC_Code"].Value = 11;


        if (ddlProducts.SelectedIndex != -1)
            oracom.Parameters["P_Product"].Value = ddlProducts.SelectedValue;
        else
            oracom.Parameters["P_Product"].Value = OracleNumber.Null;

        oracom.ExecuteNonQuery();
        oracon.Close();
        string status = oracom.Parameters["P_Status"].Value.ToString();
        string response = "";
        response = oracom.Parameters["P_RSP"].Value.ToString();
        // lblError.ForeColor = System.Drawing.Color.Red;
        // lblError.Text = "Not processed";

        lblError.ForeColor = System.Drawing.Color.DarkGreen;
        lblError.Text = "Processed";

        return response;

        // lblError.Text = "\n" + lblError.Text + cycle + " : " + oracom.Parameters["P_RSP"].Value.ToString() + "\n";
    }


    string processVatEntrie()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INTERFACE.process_cs_settlement_entries";

        oracom.Parameters.Add("P_FILE_NUMBER", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_cs_Rc_Code", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("P_Product", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("P_RSP", OracleType.VarChar, 2500).Direction = ParameterDirection.Output;

        oracom.Parameters["P_FILE_NUMBER"].Value = Convert.ToInt32(ViewState["filenumber"]);
        oracom.Parameters["p_cs_Rc_Code"].Value = selected_RC_code;

        if (ddlProducts.SelectedIndex != -1)
            oracom.Parameters["P_Product"].Value = ddlProducts.SelectedValue;
        else
            oracom.Parameters["p_product"].Value = OracleNumber.Null;


        oracom.ExecuteNonQuery();
        oracon.Close();

        string response = oracom.Parameters["P_RSP"].Value.ToString();
        return response;

    }
    protected void bttn_ProcessdMcAcqSettlementCycle(object sender, EventArgs e)
    {
        int fileNumber = 0; string rsp = "";
        string cycle = ""; ;

        for (int iLoop = 0; iLoop < gvMcAcq.Rows.Count; iLoop++)
        {
            if ((gvMcAcq.Rows[iLoop].Cells[0].FindControl("chkRow") as System.Web.UI.WebControls.CheckBox).Checked)
            {
                fileNumber = Convert.ToInt32(gvMcAcq.Rows[iLoop].Cells[1].Text);
                cycle = gvMcAcq.Rows[iLoop].Cells[3].Text;

                rsp = process_McAcq_SettleAmt(fileNumber, cycle);

                // lblError.Text = rsp.Substring(0, 3);

                if (rsp.Substring(0, 3).Equals("Exp"))
                {
                    gvMcAcq.Rows[iLoop].Cells[5].ForeColor = System.Drawing.Color.Red;
                    rsp = rsp.Replace("Exp", "");
                }
                else
                {
                    gvMcAcq.Rows[iLoop].Cells[5].ForeColor = System.Drawing.Color.Green;
                }
                gvMcAcq.Rows[iLoop].Cells[5].Text = rsp;
            }

        }
        PanelMcAcq.Enabled = false;



    }
    protected void btnGenAmexSumReport_Click(object sender, EventArgs e)
    {

        string p1 = "12";
        string p2 = "";
        string p3 = dt_SettleDate.date;
        string p4 = Session["uid"].ToString();

        ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                  "window.open('../Reports/Default.aspx?rpt=10432&p1=" + p1 + "&p3=" + p3 + "&p4=" + p4 + "','Report')", true);

    }
    protected void btnGenMDSSumReport_Click(object sender, EventArgs e)
    {



        string p1 = "7";
        string p2 = "";
        string p3 = dt_SettleDate.date;
        string p4 = Session["uid"].ToString();

        ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                  "window.open('../Reports/Default.aspx?rpt=10433&p1=" + p1 + "&p3=" + p3 + "&p4=" + p4 + "','Report')", true);

    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string error = "";
        if (FileUpload1.HasFile)
        {
            string str = FileUpload1.FileName;
            char ch = '.';
            int freq = 0;
            foreach (char c in str)
            {
                if (c == ch)
                {
                    freq++;
                }
            }
            if (freq > 1)
            {
                lblError.Text = "File contains more than one extension";
                return;
            }

            var fileExt = System.IO.Path.GetExtension(FileUpload1.FileName).Substring(1);
            if (!fileExt.ToLower().Equals("csv"))
            {
                lblError.Text = "File extension not supported";
                return;
            }
            string onlyfileName = FileUpload1.FileName.Replace(" ", "");
            string uploadPath = Server.MapPath("../UploadedFiles") + "\\";
            string fileName = uploadPath + onlyfileName;
            string newName = fileName.Substring(0, fileName.Length - 4)+ "_processed.csv";
            if (!File.Exists(fileName))
            {
                try
                {
                    FileUpload1.SaveAs(fileName);
                    lblError.ForeColor = System.Drawing.Color.DarkGreen;
                    lblError.Text = "File uploaded!";
                    FileUpload1.FileContent.Close();
                }
                catch (Exception ex)
                {
                    lblError.Text = ex.Message;
                }
                finally
                {
                    FileUpload1.PostedFile.InputStream.Dispose();
                }
            }
            else
                lblError.Text = "File already uploaded!";
            //System.Threading.Thread.Sleep(int.Parse(ConfigurationManager.AppSettings["Sleep"]));
            ViewState["filename"] = fileName;
            //lblError.Text = excelParsing(fileName);
        }
        else
            lblError.Text = "Please choose a file";
    }

    protected void btnUpload1_Click(object sender, EventArgs e)
    {
        try
        {
            if (ViewState["filename"] != null)
            {
                lblError.Text = excelParsing(ViewState["filename"].ToString());
                string newName = ViewState["filename"].ToString().Substring(0, ViewState["filename"].ToString().Length - 4) + "_processed.csv";
                System.IO.File.Move(ViewState["filename"].ToString(), newName);

                if(lblError.Text == "File Processing Completed")
                {
                    this.Search();
                }
            }
            else
                lblError.Text = "Please choose a file";
        }
        catch(Exception ex)
        {
            lblError.Text = ex.Message;
        }
    }

    public string excelParsing(string fullpath)
    {
        using (var reader = new StreamReader(fullpath))
        {
            
            string error = "", fileNumber = "";
            string date = "", data = "";
            string currency = "";
            string fee = "";
            string nar = "";
            int rowCount = 0;
            string fileDate = "";

            var firstLine = reader.ReadLine();
            while (!reader.EndOfStream)
            {

                var line = reader.ReadLine();
                var values = line.Split(',');

                DateTime d = DateTime.Parse(values[0]);
                fileDate = d.ToString("yyMMdd");
                if (rowCount == 0)
                {
                    
                    bool start = startFeesJob(fileDate, ref error, ref fileNumber);
                    if (!start)
                    {
                        data = error;
                        return data;
                    }
                }
                currency = values[1].ToString();
                fee = values[2].ToString();
                nar = values[3].ToString();
                //data += "Row " + rowCount.ToString() + "-> date: " + fileDate + " , Currency : " + currency + " , fee : " + fee + " , narrative : " + nar + "<br>";
                bool insert = insertFee(fileDate, decimal.Parse(fee), currency, nar, fileNumber, ref error);
                if (!insert)
                    data += error + "<br>";
                rowCount++;
            }
            bool end = endFeesJob(fileDate, ref error, fileNumber, rowCount);
            if (!end)
            {
                data += error+"<br>";
                return data;
            }
            data += "File Processing Completed";
            return data;
        }
    }

    private bool startFeesJob(string date, ref string error, ref string fileNumber)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INFO_EDITOR.Log_SWIFT_FEES";

        oracom.Parameters.Add("P_Current_Uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_File_Date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Oper_Type", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_FileNumber", OracleType.Number).Direction = ParameterDirection.InputOutput;
        oracom.Parameters.Add("P_RecCnt", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();
        oracom.Parameters["P_FileNumber"].Value = OracleNumber.Null;
        oracom.Parameters["P_File_Date"].Value = date;
        oracom.Parameters["P_RecCnt"].Value = OracleNumber.Null;
        oracom.Parameters["P_Oper_Type"].Value = 1;
        oracom.Parameters["P_Lang"].Value = "en";




        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        fileNumber = oracom.Parameters["P_FileNumber"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    private bool endFeesJob(string date, ref string error, string fileNumber, int rowCount)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INFO_EDITOR.Log_SWIFT_FEES";

        oracom.Parameters.Add("P_Current_Uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_File_Date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Oper_Type", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_FileNumber", OracleType.Number).Direction = ParameterDirection.InputOutput;
        oracom.Parameters.Add("P_RecCnt", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();
        oracom.Parameters["P_FileNumber"].Value = fileNumber;
        oracom.Parameters["P_File_Date"].Value = date;
        oracom.Parameters["P_RecCnt"].Value = rowCount;
        oracom.Parameters["P_Oper_Type"].Value = 2;
        oracom.Parameters["P_Lang"].Value = "en";




        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    private bool insertFee(string date, decimal fee, string currency, string nar, string fileNumber, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INFO_EDITOR.Process_SWIFT_FEES";

        oracom.Parameters.Add("P_Current_Uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_File_Date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_FileNumber", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Swift_Curr", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Swift_Fees", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Swift_RefNum", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Amt_Sign", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Lang", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();
        oracom.Parameters["P_File_Date"].Value = date;
        oracom.Parameters["P_FileNumber"].Value = fileNumber;

        oracom.Parameters["P_Swift_Curr"].Value = currency;
        oracom.Parameters["P_Swift_Fees"].Value = fee;
        oracom.Parameters["P_Swift_RefNum"].Value = nar;
        oracom.Parameters["P_Amt_Sign"].Value = "DB";
        oracom.Parameters["P_Lang"].Value = "en";




        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }
    protected void ddlProducts_SelectedIndexChanged(object sender, EventArgs e)
    {
        loadCurrency();
    }
    protected void ddlAccountFee_SelectedIndexChanged(object sender, EventArgs e)
    {
        ShowMannualGLFee(ddlAccountFee.SelectedValue);
    }
    protected void ShowMannualGLFee(string event_code)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INFO_EDITOR.get_cs_Event_Details";

        oracom.Parameters.Add("P_Evnt_code", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_output_cur", OracleType.Cursor).Direction = ParameterDirection.Output;


        oracom.Parameters["P_Evnt_code"].Value = event_code;


        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        oracon.Close();

        lblNarFee.Text = lblDBAccountFee.Text = lblCRAccountFee.Text = lblSettleCurFee.Text = "";

        if (ds.Tables[0].Rows.Count >= 1)
        {
            lblNarFee.Text = ds.Tables[0].Rows[0]["Narrative"].ToString();
            lblDBAccountFee.Text = ds.Tables[0].Rows[0]["From_Account"].ToString();
            lblCRAccountFee.Text = ds.Tables[0].Rows[0]["To_Account"].ToString();
            lblSettleCurFee.Text = ds.Tables[0].Rows[0]["Settl_Currency"].ToString();

        }

    }
    protected void Button7_Click(object sender, EventArgs e)
    {
        try
        {

            ExceptionUtility.LogEvent_Errors(0, "", "bttn_AddDiff_Click", "Start");

            pnlAddFee.Visible = true;
            Button6.Enabled = true;
            Lbl_MannualDif.Text = "";

            ShowMannualGLFee(ddlAccountFee.SelectedValue);

            ExceptionUtility.LogEvent_Errors(0, "", "bttn_AddDiff_Click", "End");
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex); ;
            lblError.Text = "Exception: Please Refer to application Log";
        }
    }
    protected void Button6_Click(object sender, EventArgs e)
    {
        Decimal Amount = 0;
        if (!Decimal.TryParse(txtAmountFee.Text.ToString(), out Amount) || Amount <= 0)
        {
            lblError.Text = "Enter Valid Amount";
            return;
        }
        lblError.Text = "";

        if (SaveMannualDifferenceFee(ddlAccountFee.SelectedValue,
                  Convert.ToDecimal(txtAmountFee.Text),
               DropDownList2.SelectedValue,
              Convert.ToInt32(lbl_File_Number.Text),
              dt_SettleDate.date
              ))
        {
            Button6.Enabled = false;
            pnlAddFee.Visible = false;
            loadResultFees(); ;

        }
    }
    bool SaveMannualDifferenceFee(string Evnt_code, decimal Amount, string Amount_Sign, int File_Nmber, string Settl_Date)
    {

        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INFO_EDITOR.AddManualGLEntry";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Evnt_code", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Product", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_cs_Rc_Code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Amt", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Amt_Sign", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_File_Number", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Settl_Date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Swift_RefNum", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters.Add("p_cs_Rc_Code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters["p_cs_Rc_Code"].Value = selected_RC_code;


        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        if (ddlProducts.SelectedIndex != -1)
            oracom.Parameters["p_product"].Value = Convert.ToInt32(ddlProducts.SelectedValue);
        else
            oracom.Parameters["p_product"].Value = OracleNumber.Null;

        oracom.Parameters["P_Swift_RefNum"].Value = txtRefNum.Text;
        oracom.Parameters["P_Amt"].Value = Amount;
        oracom.Parameters["P_Amt_Sign"].Value = Amount_Sign;
        oracom.Parameters["p_file_number"].Value = File_Nmber;
        oracom.Parameters["P_Settl_Date"].Value = Settl_Date;
        oracom.Parameters["P_Evnt_code"].Value = ddlAccountFee.SelectedValue;



        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();

        if (a == "0")
        {
            lblError.ForeColor = System.Drawing.Color.DarkGreen;
            lblError.Text = oracom.Parameters["p_res_msg"].Value.ToString();
            return true;
        }
        else
        {
            lblError.Text = oracom.Parameters["p_res_msg"].Value.ToString();
            return false;
        }
    }
    protected void Button5_Click(object sender, EventArgs e)
    {
        pnlAddFee.Visible = false;
        Button6.Enabled = true;
    }
    protected void GridView3_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        Lbl_MannualDif.Text = "";
        if (e.CommandName.Equals("d"))
        {


            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = GridView3.DataKeys[index].Value.ToString();

            //string evnt_code = GridView1.Rows[index].Cells[7].Text.ToString();
            string file_no = GridView3.Rows[index].Cells[6].Text;

            string error = ""; ;

            string status_flag = GridView3.Rows[index].Cells[7].Text.ToString();
            //string editable_flag = GridView1.Rows[index].Cells[10].Text.ToString();

            if (status_flag.Substring(0, 6).ToLower().Equals("cancel") || status_flag.ToLower().Equals("entered"))
            {

                bool saved = Delete_Fee_Entry(rowID, file_no, ref error);

                    if (saved)
                    {
                        lblError.ForeColor = System.Drawing.Color.DarkGreen;
                        lblError.Text = "Successfuly deleted Entry";
                        loadResultFees(); 
                    }
                    else
                    {
                        lblError.Text = error;
                    }
            }
            else
                lblError.Text = "Deletion Failed - Entry can be deleted only when status is Entered/Caneled";
        }
    }
    private bool Delete_Fee_Entry(string cstCode, string File_no, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INFO_EDITOR.Delete_SettlEntry";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_Event_code", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Product", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_cs_Rc_Code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_CST_CODE", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_File_No", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();
        oracom.Parameters["p_File_no"].Value = File_no;
        oracom.Parameters["P_CST_CODE"].Value = cstCode;

        oracom.Parameters["p_Event_code"].Value = OracleString.Null;
        oracom.Parameters["p_cs_Rc_Code"].Value = selected_RC_code;
        oracom.Parameters["P_Product"].Value = ddlProducts.SelectedValue; 




        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }
    protected void Button8_Click(object sender, EventArgs e)
    {
        ExceptionUtility.LogEvent_Errors(0, "", "ButtonSubmitForApproval_Click", "Start");

        int File_Number = Convert.ToInt32(lbl_File_Number.Text);

        Approval_Reject_GenerateGlFee(dt_SettleDate.date, File_Number, "001");
        loadResultFees(); ;
        //  bttn_Approval.Enabled = false;
        ExceptionUtility.LogEvent_Errors(0, "", "ButtonSubmitForApproval_Click", "End");
    }

    private bool Approval_Reject_GenerateGlFee(string settleDate, int file_number, string status)
    {

        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "CS_SETTL_INFO_EDITOR.Swift_SubmitForApprvl";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_product", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_cs_Rc_Code", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_currency", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_status", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_File_Number", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_cs_Rc_Code"].Value = selected_RC_code;


        oracom.Parameters["p_status"].Value = status;


        if (ddlProducts.SelectedIndex != -1)
            oracom.Parameters["p_product"].Value = ddlProducts.SelectedValue;
        else
            oracom.Parameters["p_product"].Value = OracleNumber.Null;

        if (Helper.IsMultiCurrencyProduct_CS(ddlProducts.SelectedValue))
            oracom.Parameters["p_currency"].Value = ddlCurrency.SelectedValue;
        else
            oracom.Parameters["p_currency"].Value = OracleString.Null;




        oracom.Parameters["p_file_number"].Value = file_number;
        oracom.Parameters["p_date"].Value = settleDate;
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        OracleDataAdapter da = new OracleDataAdapter(oracom);


        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();

        if (a == "0")
        {
            lblError.ForeColor = System.Drawing.Color.DarkGreen;
            lblError.Text = oracom.Parameters["p_res_msg"].Value.ToString();
            return true;
        }
        else
        {
            lblError.Text = oracom.Parameters["p_res_msg"].Value.ToString();
            return false;
        }

    }
    protected void Button9_Click(object sender, EventArgs e)
    {
        ExceptionUtility.LogEvent_Errors(0, "", "ButtonSubmitForApproval_Click", "Start");

        int File_Number = Convert.ToInt32(lbl_File_Number.Text);

        Approval_Reject_GenerateGlFee(dt_SettleDate.date, File_Number, "002");
        loadResultFees(); ;
        //  bttn_Approval.Enabled = false;
        ExceptionUtility.LogEvent_Errors(0, "", "ButtonSubmitForApproval_Click", "End");
    }
    protected void Button10_Click(object sender, EventArgs e)
    {
        ExceptionUtility.LogEvent_Errors(0, "", "ButtonSubmitForApproval_Click", "Start");

        int File_Number = Convert.ToInt32(lbl_File_Number.Text);

        Approval_Reject_GenerateGlFee(dt_SettleDate.date, File_Number, "008");
        loadResultFees(); ;
        //  bttn_Approval.Enabled = false;
        ExceptionUtility.LogEvent_Errors(0, "", "ButtonSubmitForApproval_Click", "End");
    }
    protected void GridView3_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        GridView3.PageIndex = e.NewSelectedIndex;
        GridView3.DataBind(); 
    }
}