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 NCBEAI.Adapters.Transport;
using System.Xml;
using System.Diagnostics;
using MscllnsFundXferMsgGenerator;
using EjadaMQProcessor;
using InternalFundsTransferMsgProcessor;


public partial class Business_GLPosting : System.Web.UI.Page
{
    public int SuccessCount = 0;
    public int totalCount = 0, psdate;
    public string pproduct, pcurrency;
    protected void Page_Load(object sender, EventArgs e)
    {
        btnSavePost.Attributes.Add("onclick", "this.disabled=true;" + ClientScript.GetPostBackEventReference(btnSavePost, null) + ";");

        if (!IsPostBack)
        {
            pnlResult.Visible = false;
            pnlControls.Visible = false;
            pnlPost.Visible = true;
          
            loadCurrency();
            loadChannels();
            loadEvents();
            loadAccType();
            loadBranches();
            loadATMTypes();
            loadChannelTypes();
            channelsRow.Visible = false;
            ATMNoRow.Visible = false;
            ATMTypeRow.Visible = false;
            BranchRow.Visible = false;
            POSRow.Visible = false;
            ClaimRow.Visible = false;
            ClaimRow2.Visible = false;
            ClaimSamaApprovedRow.Visible = false;
            btnPostAll.Visible = false;
            btnGenReport.Visible = false;
            pnlPost.Visible = false;
            btnSavePost.Attributes.Add("onclick", "this.disabled=true;" + GetPostBackEventReference(btnSavePost).ToString());

            ///////// To Enable Claims Only
            rdClaims_CheckedChanged(sender, e);
            ///
        }
     
        lblError.Text = "";

        //pnlPost.Visible = true;

        if (Session["PostAllSamaClaim"] == "Y")
        {
            Session["PostAllSamaClaim"] = "Y";
            //= "170607";
            Button1_Click(sender, e);
            BtnSelectedApproved_Click(sender, e);
        }
        Session["PostAllSamaClaim"] = "N";

        if (Request.QueryString["product"] != null && Request.QueryString["date"] != null)
        {
            try
            {
                pproduct = Request.QueryString["product"] as string;
                psdate = Convert.ToInt32(Request.QueryString["date"] as string);

                psdate = psdate - 1;

                rdCSSett.Checked = true;
                this.rdCS_Sett_CC();

                rdVisaSett.Checked = true;
                load_CS_Products();

                ddlProducts.SelectedValue = pproduct;

                if (pproduct == "2" || pproduct == "7" || pproduct == "9")
                {
                    pcurrency = Request.QueryString["currency"] as string;
                    ddlCurrency.SelectedValue = pcurrency;
                }

                DatePicker1.date = Helper.convertDate(psdate.ToString());

                this.Search();
                BtnSelectedApproved_Click(sender, e);
            }
            catch(Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }
    }

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

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

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

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "LOOKUP_GETTER.Get_Recon_Channels";

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

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

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


        ddlChannels.Items.Insert(0, "------ Channels ------");
        oracon.Close();
    }

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

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

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

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "LOOKUP_GETTER.Get_Recon_Events";

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

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

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

        ddlEvents.Items.Insert(0, "------ Events ------");
        ddlEvents.Items.Insert(1, new ListItem("ALL Events", "-1"));
        oracon.Close();
    }

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

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

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

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "LOOKUP_GETTER.Get_Post_Acct_Type";

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

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

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

        oracon.Close();
    }

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

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

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

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "LOOKUP_GETTER.Get_Branches";

        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_branches", OracleType.Cursor).Direction = ParameterDirection.Output;

        oracom.Parameters["p_lang"].Value = "EN";

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

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

        ddlBranch.Items.Insert(0, "------ Branches ------");
        oracon.Close();
    }

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

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

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

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "LOOKUP_GETTER.Get_ATM_Types";

        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_types", OracleType.Cursor).Direction = ParameterDirection.Output;

        oracom.Parameters["p_lang"].Value = "EN";

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

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

        ddlATMType.Items.Insert(0, "------ ATM Type ------");
        oracon.Close();
    }

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

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

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

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "LOOKUP_GETTER.Get_Channel_Types";

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

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

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

        ddlType.Items.Insert(0, "------- ALL -------");
        oracon.Close();
    }

    private void loadResult(string ChannelID, string EventID, string BranchID, string Approved, string Posted, string Declined, 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 = "GL_POSTING_APPROVER.Get_GL_Entities";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_re_code", 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_cs_type", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_rc_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_branch", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_atm_no", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_atm_type", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_client_num", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_term_id", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_claim_id", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_card_no", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_trace_id", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_approved", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_posted", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_decline", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_date", OracleType.VarChar, 250).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_acct_type", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_ch_type", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_claim_src", 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;

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

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

        if (ChannelID.Length != 0)
            oracom.Parameters["p_rc_code"].Value = ChannelID;
        else
        {
            if (rdAmexSett.Checked)
                oracom.Parameters["p_rc_code"].Value = 12;
            else if (rdVisaSett.Checked)
                oracom.Parameters["p_rc_code"].Value = 15;
            else if (rdMcAcq.Checked)
                oracom.Parameters["p_rc_code"].Value = 11;
            else if (rdMaestro.Checked)
                oracom.Parameters["p_rc_code"].Value = 7;
            else if (rdDiscover.Checked)
                oracom.Parameters["p_rc_code"].Value = 20;
            else if (rdMadaMonthly.Checked)
                oracom.Parameters["p_rc_code"].Value = 16;
            else if (rdCSBilling.Checked)
            {
                if (ddlProducts.SelectedValue == "20" || ddlProducts.SelectedValue == "21")
                {
                    oracom.Parameters["p_rc_code"].Value = 15;
                }
                else if (ddlProducts.SelectedValue == "22")
                {
                    oracom.Parameters["p_rc_code"].Value = 11;
                }
            }
            else
                oracom.Parameters["p_rc_code"].Value = OracleNumber.Null;
        }
        if (EventID.Length != 0)
        {
            oracom.Parameters["p_re_code"].Value = EventID;
        }
        else
        {
            oracom.Parameters["p_re_code"].Value = OracleNumber.Null;
        }

        if (BranchID.Length != 0)
            oracom.Parameters["p_branch"].Value = BranchID;
        else
            oracom.Parameters["p_branch"].Value = OracleString.Null;

        if (ddlATMType.SelectedIndex != 0)
            oracom.Parameters["p_atm_type"].Value = ddlATMType.SelectedValue;
        else
            oracom.Parameters["p_atm_type"].Value = OracleString.Null;

        if (rdEvent.Checked)
        {
            if (ddlType.SelectedIndex == 0)
                oracom.Parameters["p_ch_type"].Value = OracleNumber.Null;
            else
                oracom.Parameters["p_ch_type"].Value = ddlType.SelectedValue;
        }

        if (rdChannel.Checked)
            oracom.Parameters["p_ch_type"].Value = "3";
        if (rdATM.Checked)
            oracom.Parameters["p_ch_type"].Value = "5";
        if (rdPOSSET.Checked)
            oracom.Parameters["p_ch_type"].Value = "6";
        //if (rdPOSRENT.Checked)
        //    oracom.Parameters["p_ch_type"].Value = "7";
        if (rdClaims.Checked)
            oracom.Parameters["p_ch_type"].Value = "8";

        if (rdCSSett.Checked)
        {
            oracom.Parameters["p_ch_type"].Value = "9";
        }

        if (rdClaims.Checked)
        {
            oracom.Parameters["p_card_no"].Value = txtCardNo.Text;
            oracom.Parameters["p_trace_id"].Value = txtTraceID.Text;
            oracom.Parameters["p_claim_id"].Value = txtClaimID.Text;
        }
        else
        {
            oracom.Parameters["p_card_no"].Value = OracleString.Null;
            oracom.Parameters["p_trace_id"].Value = OracleString.Null;
            oracom.Parameters["p_claim_id"].Value = OracleString.Null;
        }

        if (txtClientNo.Text.Length > 0)
            oracom.Parameters["p_client_num"].Value = txtClientNo.Text;
        else
            oracom.Parameters["p_client_num"].Value = OracleNumber.Null;

        if (txtTerminalID.Text.Length > 0)
            oracom.Parameters["p_term_id"].Value = txtTerminalID.Text;
        else
            oracom.Parameters["p_term_id"].Value = OracleString.Null;

        if (rdATMClaim.Checked)
            oracom.Parameters["p_claim_src"].Value = "1";
        else if (rdPOSClaim.Checked)
            oracom.Parameters["p_claim_src"].Value = "2";
        else
            oracom.Parameters["p_claim_src"].Value = "3";

        oracom.Parameters["p_acct_type"].Value = ddlAccType.SelectedValue;
        oracom.Parameters["p_atm_no"].Value = txtATMnumber.Text;
        oracom.Parameters["p_approved"].Value = Approved;
        oracom.Parameters["p_posted"].Value = Posted;
        oracom.Parameters["p_decline"].Value = Declined;

        if (Session["PostAllSamaClaim"] == "Y")
            oracom.Parameters["p_date"].Value = DateTime.Today.ToString("yyMMdd");
        else
            oracom.Parameters["p_date"].Value = DatePicker1.date;

        if (Session["PostAllSamaClaim"] == "Y")
            oracom.Parameters["p_current_uid"].Value = "999"; // System user while posting Sama Auto Claims
        else
            oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

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

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

        GridView1.PageSize = pageSize; // GridSize need to be updated for autoposting 

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

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

    public void Search()
    {
        txtATMnumber.Text = txtATMnumber.Text.Trim();
        txtClientNo.Text = txtClientNo.Text.Trim();
        txtTerminalID.Text = txtTerminalID.Text.Trim();
        txtCardNo.Text = txtCardNo.Text.Trim();
        txtTraceID.Text = txtTraceID.Text.Trim();
        txtClaimID.Text = txtClaimID.Text.Trim();

        pnlResult.Visible = false;

        if (ddlChannels.SelectedIndex == 0 && rdChannel.Checked)
            lblError.Text = "You must choose a Channel";
        else if (ddlEvents.SelectedIndex == 0 && rdEvent.Checked)
            lblError.Text = "You must choose an Event";
        //else if (DatePicker1.date.Length == 0 && rdPOSRENT.Checked)
        //    lblError.Text = "You must enter Date";
        //else if (DatePicker1.date.Length == 0 &&  txtClaimID .Text .Length ==0)
        //    lblError.Text = "You must enter either approved date or claim id";
        else if (rdClaims.Checked)
        {
            if (DatePicker1.date.Length == 0 && txtClaimID.Text.Length == 0 && Session["PostAllSamaClaim"] != "Y")
                lblError.Text = "You must enter either approved date or claim id";
            else
                getSetup();

        }
        else if (!rdClaims.Checked)
        {
            if (DatePicker1.date.Length == 0)
                lblError.Text = "You must enter date";
            else
                getSetup();
        }
        else
            getSetup();


        // btnPostAll.Visible = rdATM.Checked || rdClaims.Checked || rdChannel.Checked || rdEvent.Checked || rdPOSSET.Checked;
        //if (chkPosted.Checked)
        //    btnPostAll.Visible = false;
        //else
        //    btnPostAll.Visible = true;

        //if (btnPostAll.Visible)
        //    btnGenReport.Visible = true;
        //else
        //   

        pnlControls.Visible = false;
        pnlPost.Visible = false;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        this.Search();
    }

    private void getSetup()
    {

        string channelID = "", EventID = "", BranchID = "", approved = "", posted = "", declined = "";

        if (ddlChannels.SelectedIndex > 0)
            channelID = ddlChannels.SelectedValue;
        if (ddlEvents.SelectedIndex > 0)
            EventID = ddlEvents.SelectedValue;
        if (ddlBranch.SelectedIndex > 0)
            BranchID = ddlBranch.SelectedValue;

        if (chkApproved.Checked)
            approved = "1";
        else
            approved = "0";
        if (chkPosted.Checked)
            posted = "1";
        else
            posted = "0";

        if (chkDeclined.Checked)
            declined = "1";
        else
            declined = "0";
        pnlResult.Visible = true;
        pnlControls.Visible = false;
        pnlResult.Enabled = true;

        GridView1.Columns[11].Visible = true;
        GridView1.Columns[12].Visible = true;

        if (rdATM.Checked)
        {
            GridView1.Columns[4].Visible = false;
            GridView1.Columns[5].Visible = true;
        }
        else
        {
            GridView1.Columns[5].Visible = false;
            GridView1.Columns[4].Visible = true;
        }
        if (Session["PostAllSamaClaim"] == "Y" || chkSamaApproved.Checked)
            loadResult(channelID, EventID, BranchID, "9", posted, declined, 2000, 1);
        else
            loadResult(channelID, EventID, BranchID, approved, posted, declined, Helper.gridSize("GlPage"), 1);

        if (!rdEvent.Checked)
        {
            GridView1.Columns[11].Visible = false;
            GridView1.Columns[12].Visible = false;
        }

        if (rdPOSSET.Checked)
        {
            if (txtClientNo.Text.Length == 0)
            {
                btnApproveAll.Visible = true;
                //btnPostAll.Visible = true;
            }
            else
            {
                btnApproveAll.Visible = false;
                //btnPostAll.Visible = false;
            }
        }
        else
        {
            btnApproveAll.Visible = false;
            //btnPostAll.Visible = false;
        }
    }

    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        string channelID = "", EventID = "", BranchID = "", approved = "", posted = "", declined = "";

        if (ddlChannels.SelectedIndex > 0)
            channelID = ddlChannels.SelectedValue;
        if (ddlEvents.SelectedIndex > 0)
            EventID = ddlEvents.SelectedValue;
        if (ddlBranch.SelectedIndex > 0)
            BranchID = ddlBranch.SelectedValue;

        if (chkApproved.Checked)
            approved = "1";
        else
            approved = "0";
        if (chkPosted.Checked)
            posted = "1";
        else
            posted = "0";
        if (chkDeclined.Checked)
            declined = "1";
        else
            declined = "0";

        if (Session["PostAllSamaClaim"] == "Y" || chkSamaApproved.Checked)
            loadResult(channelID, EventID, BranchID, "9", posted, declined, Helper.gridSize("GlPage"), int.Parse(ddlPages.SelectedValue));
        else
            loadResult(channelID, EventID, BranchID, approved, posted, declined, Helper.gridSize("GlPage"), int.Parse(ddlPages.SelectedValue));

        pnlControls.Visible = false;
        pnlPost.Visible = false;
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("a"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = GridView1.DataKeys[index].Value.ToString();
            ViewState["index"] = index;
            //can't approve a declined claim
            string declined = GridView1.Rows[index].Cells[8].Text.ToString();
            string approved = GridView1.Rows[index].Cells[7].Text.ToString();
            string error = "";
            if (declined.ToLower().Equals("no"))
            {
                if (!approved.ToLower().Equals("yes"))
                {
                    bool saved = Approve(rowID, ref error);
                    if (saved)
                    {
                        lblError.ForeColor = System.Drawing.Color.DarkGreen;
                        lblError.Text = "Entity Approved";
                    }
                    else
                    {
                        lblError.Text = error;
                    }
                }
                else
                {
                    lblError.Text = "Entry is already approved";
                }
            }
            else
            {
                lblError.Text = "Cannot approve a declined entry";
            }
        }
        else if (e.CommandName.Equals("d"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = GridView1.DataKeys[index].Value.ToString();
            string error = "";
            //can't post a claim until it's approved
            string approved = GridView1.Rows[index].Cells[8].Text.ToString();
            string declined = GridView1.Rows[index].Cells[9].Text.ToString();
            if (approved.ToLower().Equals("no"))
            {
                if (!declined.ToLower().Equals("yes"))
                {
                    bool saved = Decline(rowID, ref error);
                    if (saved)
                    {
                        lblError.ForeColor = System.Drawing.Color.DarkGreen;
                        lblError.Text = "Entity Declined";
                    }
                    else
                    {
                        lblError.Text = error;
                    }
                }
                else
                {
                    lblError.Text = "Entry already declined";
                }
            }
            else
            {
                lblError.Text = "Cannot decline an approved entry";
            }
        }
        else if (e.CommandName.Equals("p"))
        {
            if (rdCSSett.Enabled)
            {
                lbl_Card.Visible = false;
                txtPostingCardNumber.Visible = false;
            }
            else
            {
                lbl_Card.Visible = true;
                txtPostingCardNumber.Visible = true;
            }
            // pnlPost.Visible = true;
            //string strReqMsg = MscllnsFundXferMsgGenObj.GenReqMsg(txtCardNo .Text  , txtSettlementAcc .Text  , txtAmount .Text , "SAR",txtAccount.Text , "", "", "", "");


            //if (rdATM.Checked || rdATMClaim.Checked || rdChannel.Checked)
            //    lblError.Text = "Post is not allowed for single transaction" +
            //    Environment.NewLine + "Please press POST All to do the posting";
            //else
            //    lblError.Text = " Posting is not allowed for the transaction";

            pnlResult.Enabled = false;
            int index = int.Parse(e.CommandArgument.ToString());
            ViewState["index"] = index;
            string account = GridView1.Rows[index].Cells[3].Text.ToString();
            string amount = GridView1.Rows[index].Cells[10].Text.ToString();

            amount = (Math.Round(double.Parse(amount), 2) + 0.0001).ToString();
            amount = amount.Substring(0, amount.Length - 2); ;
            ////can't post a claim until it's approved
            string approved = GridView1.Rows[index].Cells[8].Text.ToString().Replace("&nbsp;", "");
            string posted = GridView1.Rows[index].Cells[7].Text.ToString().Replace("&nbsp;", "");
            string cashacc = GridView1.Rows[index].Cells[30].Text.ToString().Replace("&nbsp;", "");
            string cardNumber = GridView1.Rows[index].Cells[36].Text.ToString().Replace("&nbsp;", "");
            string glDesc = GridView1.Rows[index].Cells[33].Text.ToString().Replace("&nbsp;", "");
            
            string sarAmount = GridView1.Rows[index].Cells[39].Text.ToString().Replace("&nbsp;", "");
            sarAmount = (Math.Round(double.Parse(sarAmount), 2)+0.0001).ToString();
            sarAmount = sarAmount.Substring(0, sarAmount.Length - 2);
            
            
            string drCurrencyCode = GridView1.Rows[index].Cells[40].Text.ToString().Replace("&nbsp;", "");
            string crCurrencyCode = GridView1.Rows[index].Cells[41].Text.ToString().Replace("&nbsp;", "");

            //

            ViewState["uniq_ID"] = GridView1.Rows[index].Cells[37].Text.ToString();
            if (approved.ToLower().Equals("yes") && posted.ToLower().Equals("no"))
            {
                string rowID = GridView1.DataKeys[index].Value.ToString();
                string trans_type = GridView1.Rows[index].Cells[6].Text.ToString();
                string error = "";
                if (Can_Post(rowID, ref error))
                {
                    // IRFAN_MOD on KG Confirmation
                    txtDrCurrency.Text = drCurrencyCode;                //
                    txtCrCuurency.Text = crCurrencyCode;                //
                    // //

                    txtAccount.Text = account;
                    txtAmount.Text = amount;
                    txtAmountSAR.Text = sarAmount;

                    txtSettlementAcc.Text = cashacc;
                    txtPostingCardNumber.Text = cardNumber;
                    txtGLDesc.Text = glDesc;
                    if (!trans_type.Equals("&nbsp;"))
                        lblGLType.Text = trans_type;
                    else
                        lblGLType.Text = "";

                    pnlPost.Visible = true;
                }
                else
                    lblError.Text = error;
            }
            else
            {
                if (posted.ToLower().Equals("yes"))
                    lblError.Text = "Cannot post an already posted entry";
                if (approved.ToLower().Equals("no"))
                    lblError.Text = "Cannot post an entry until it is approved";
            }
        }
        else if (e.CommandName.Equals("print"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = GridView1.DataKeys[index].Value.ToString();

            ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
            "window.open('PrintGL.aspx?id=" + rowID + "','Report')", true);
        }
        else if (e.CommandName.Equals("v"))
        {
            pnlControls.Visible = true;
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = GridView1.DataKeys[index].Value.ToString();
            string eventID = GridView1.Rows[index].Cells[2].Text.ToString();
            string channelID = GridView1.Rows[index].Cells[1].Text.ToString();
            string account = GridView1.Rows[index].Cells[3].Text.ToString();
            string settleAccount = GridView1.Rows[index].Cells[30].Text.ToString();
            string trans_type = GridView1.Rows[index].Cells[6].Text.ToString();
            string posted = GridView1.Rows[index].Cells[7].Text.ToString();
            string approved = GridView1.Rows[index].Cells[8].Text.ToString();
            string declined = GridView1.Rows[index].Cells[9].Text.ToString();
            string amount = GridView1.Rows[index].Cells[10].Text.ToString();
            string record_date = GridView1.Rows[index].Cells[18].Text.ToString();
            string posting_for_date = GridView1.Rows[index].Cells[19].Text.ToString();
            string post_date = GridView1.Rows[index].Cells[20].Text.ToString();
            string approve_date = GridView1.Rows[index].Cells[21].Text.ToString();
            string file_number = GridView1.Rows[index].Cells[22].Text.ToString();
            string re_code = GridView1.Rows[index].Cells[23].Text.ToString();
            string rc_code = GridView1.Rows[index].Cells[24].Text.ToString();
            string decline_date = GridView1.Rows[index].Cells[25].Text.ToString();
            string journal = GridView1.Rows[index].Cells[26].Text.ToString();
            string postedby = GridView1.Rows[index].Cells[27].Text.ToString();
            string approvedby = GridView1.Rows[index].Cells[28].Text.ToString();
            string declinedby = GridView1.Rows[index].Cells[29].Text.ToString();
            string cashacc = GridView1.Rows[index].Cells[30].Text.ToString();
            string glDesc = GridView1.Rows[index].Cells[33].Text.ToString();
            string gridDesc = GridView1.Rows[index].Cells[34].Text.ToString();
            string MW_Resp = GridView1.Rows[index].Cells[38].Text.ToString();
            string amountSAR = GridView1.Rows[index].Cells[39].Text.ToString();

            if (!MW_Resp.Equals("&nbsp;"))
            {

                if (MW_Resp.Length > 150)
                    MW_Resp = MW_Resp.Substring(0, 150) + "</br>" + MW_Resp.Substring(201);
                if (MW_Resp.Length > 300)
                    MW_Resp = MW_Resp.Substring(0, 300) + "</br>" + MW_Resp.Substring(301);

                lbl_MW_Resp.Text = MW_Resp;
            }
            else
                lbl_MW_Resp.Text = "";

            if (!record_date.Equals("&nbsp;"))
                Label1.Text = record_date;
            else
                Label1.Text = "";

            if (!gridDesc.Equals("&nbsp;"))
                Label21.Text = gridDesc;
            else
                Label21.Text = "";

            if (!posting_for_date.Equals("&nbsp;"))
                Label2.Text = posting_for_date;
            else
                Label2.Text = "";

            if (!account.Equals("&nbsp;"))
                Label3.Text = account;
            else
                Label3.Text = "";

            if (!settleAccount.Equals("&nbsp;"))
                Label4.Text = settleAccount;
            else
                Label4.Text = "";

            if (!trans_type.Equals("&nbsp;"))
                Label15.Text = trans_type;
            else
                Label15.Text = "";
            if (!posted.Equals("&nbsp;"))
                Label5.Text = posted;
            else
                Label5.Text = "";
            if (!post_date.Equals("&nbsp;"))
                Label6.Text = post_date;
            else
                Label6.Text = "";
            if (!approved.Equals("&nbsp;"))
                Label7.Text = approved;
            else
                Label7.Text = "";
            if (!approve_date.Equals("&nbsp;"))
                Label8.Text = approve_date;
            else
                Label8.Text = "";
            if (!amount.Equals("&nbsp;"))
                Label9.Text = amount;
            else
                Label9.Text = "";

            if (!amountSAR.Equals("&nbsp;"))
                lblSarAmount.Text = amountSAR;
            else
                lblSarAmount.Text = "";

            if (!file_number.Equals("&nbsp;"))
                Label10.Text = file_number;
            else
                Label10.Text = "";
            if (!eventID.Equals("&nbsp;"))
                Label11.Text = eventID;
            else
                Label11.Text = "";
            if (!channelID.Equals("&nbsp;"))
                Label12.Text = channelID;
            else
                Label12.Text = "";
            if (!declined.Equals("&nbsp;"))
                Label16.Text = declined;
            else
                Label16.Text = "";
            if (!decline_date.Equals("&nbsp;"))
                Label17.Text = decline_date;
            else
                Label17.Text = "";
            if (!journal.Equals("&nbsp;"))
                Label14.Text = journal;
            else
                Label14.Text = "";
            if (!postedby.Equals("&nbsp;"))
                Label13.Text = postedby;
            else
                Label13.Text = "";
            if (!approvedby.Equals("&nbsp;"))
                Label18.Text = approvedby;
            else
                Label18.Text = "";
            if (!declinedby.Equals("&nbsp;"))
                Label19.Text = declinedby;
            else
                Label19.Text = "";
            if (!glDesc.Equals("&nbsp;"))
                Label20.Text = glDesc;
            else
                Label20.Text = "";
            if (rdATM.Checked && chkPosted.Checked)
            {
                if (!cashacc.Equals("&nbsp;"))
                    lblCashAcc.Text = cashacc;
                cashaccrow.Visible = true;
            }
            else
                cashaccrow.Visible = false;

            return;
        }
        else if (e.CommandName.Equals("r"))
        {
            if (!rdClaims.Checked)
            {
                int index = int.Parse(e.CommandArgument.ToString());
                string rowID = GridView1.DataKeys[index].Value.ToString();
                string error = "", error1 = "";
                if (Can_Reset(rowID, ref error1))
                {
                    bool saved = Reset(rowID, ref error);
                    if (saved)
                    {
                        lblError.ForeColor = System.Drawing.Color.DarkGreen;
                        lblError.Text = "Entity Reset Successful";
                    }
                    else
                    {
                        lblError.Text = error;
                    }
                }
                else
                    lblError.Text = error1;
            }
            else
            {
                //IJR --> 04-04-2012 
                /* Change the way to handle the claims reset,
                 * When user want to Reset the Claim following actions will be taken:
                 * 1- Claim to be reseted in the claim table as 000 (Entered)
                 * 2- Delete from the GL posting table
                 * Re- Load the data in the Grid View to eliminate the rested claim
                */



                int index = int.Parse(e.CommandArgument.ToString());
                string rowID = GridView1.DataKeys[index].Value.ToString();
                string error = "", error1 = "";
                if (Can_Reset(rowID, ref error1))
                {
                    bool saved = Reset_Claim(rowID, ref error);
                    if (saved)
                    {
                        lblError.ForeColor = System.Drawing.Color.DarkGreen;
                        lblError.Text = "Entity Reset Successful";

                    }
                    else
                    {
                        lblError.Text = error;
                    }
                }
                else
                    lblError.Text = error1;

            }
        }

        if (!e.CommandName.Equals("p"))
        {
            if (ddlChannels.SelectedIndex == 0 && rdChannel.Checked)
                lblError.Text = "You must choose a Channel";
            else if (ddlEvents.SelectedIndex == 0 && rdEvent.Checked)
                lblError.Text = "You must choose an Event";
            else
                getSetup();
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        pnlControls.Visible = false;
    }

    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow)
        {
            for (int i = 18; i <= 31; i++)
                e.Row.Cells[i].Visible = false;
            e.Row.Cells[6].Visible = false;
            //e.Row.Cells[4].Visible = false;

            e.Row.Cells[33].Visible = false;
            e.Row.Cells[34].Visible = false;
            e.Row.Cells[35].Visible = false;
            e.Row.Cells[36].Visible = false;
            e.Row.Cells[37].Visible = false;
            e.Row.Cells[38].Visible = false;
            e.Row.Cells[39].Visible = false; // SAR_AMT

            e.Row.Cells[40].Visible = false; // Dr Currency
            e.Row.Cells[41].Visible = false; // Cr Currency

            if (rdCSSett.Checked)
            {
                e.Row.Cells[1].Visible = false;
                e.Row.Cells[2].Visible = false;

                e.Row.Cells[15].Visible = false;
                e.Row.Cells[16].Visible = false;

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

            }
        }
    }

    private bool Approve(string index, 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 = "GL_POSTING_APPROVER.Approve_GL_Entity";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_gpe_code", 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["p_gpe_code"].Value = index;

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

        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 Decline(string index, 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 = "GL_POSTING_APPROVER.Decline_GL_Entity";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_gpe_code", 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["p_gpe_code"].Value = index;

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

        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 Post(string index, string SettleAcct, string Desc, 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 = "GL_POSTING_APPROVER.Post_GL_Entity";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_gpe_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_mw_journal_ref", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_mw_resp", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_settle_acct", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_gl_desc", 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_gpe_code"].Value = index;
        if (ViewState["p_mw_journal_ref"] != null)
            oracom.Parameters["p_mw_journal_ref"].Value = ViewState["JID"].ToString();
        else
            oracom.Parameters["p_mw_journal_ref"].Value = OracleString.Null;
        //if (ViewState["p_mw_journal_ref"] != null)

        if (ViewState["MESSAGE"] != null) // IRFAN_MOD
            oracom.Parameters["p_mw_resp"].Value = ViewState["MESSAGE"].ToString();
        else
            oracom.Parameters["p_mw_resp"].Value = OracleString.Null;

        oracom.Parameters["p_settle_acct"].Value = SettleAcct;
        oracom.Parameters["p_gl_desc"].Value = Desc;

        oracom.Parameters["p_lang"].Value = "EN";

        if (Session["PostAllSamaClaim"] == "Y")
            oracom.Parameters["p_current_uid"].Value = "999"; // System user while posting Sama Auto Claims
        else
            oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        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 PostBegin(string index, 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 = "GL_POSTING_APPROVER.begin_post_gl";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_gpe_code", 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["p_gpe_code"].Value = index;

        oracom.Parameters["p_lang"].Value = "EN";


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

        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 PostFailed(string index, string SettleAcct, string Desc, 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 = "GL_POSTING_APPROVER.post_gl_failed";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_gpe_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_mw_resp", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_settle_acct", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_gl_desc", 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_gpe_code"].Value = index;
        oracom.Parameters["p_mw_resp"].Value = ViewState["MESSAGE"].ToString();
        oracom.Parameters["p_settle_acct"].Value = SettleAcct;
        oracom.Parameters["p_gl_desc"].Value = Desc;

        oracom.Parameters["p_lang"].Value = "EN";
        if (Session["PostAllSamaClaim"] == "Y")
            oracom.Parameters["p_current_uid"].Value = "999";
        else
            oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        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 Reset(string index, 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 = "GL_POSTING_APPROVER.Reset_GL_Entity";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_gpe_code", 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["p_gpe_code"].Value = index;

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

        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 Reset_Claim(string index, 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 = "GL_POSTING_APPROVER.reset_claim";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_gpe_code", 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["p_gpe_code"].Value = index;

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

        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 postGL(string Type, string Account, string Amount, string Desc)
    {
        string Directory = ConfigurationSettings.AppSettings["MWCertificate"];
        string XmlMessage = "";
        string XmlResponse = "";
        string TransportVia = "I";
        string TransportMethod = "Synch";
        string LangItem = "1";

        //NCBEAI.Adapters.Transport.Message Request = new Message(Directory);

        //if (Type.Equals("Cr"))
        //{
        //    XmlMessage = "<AccID>" + Account + "</AccID><Amount>" + Amount + "</Amount><Description>" + Desc + "</Description><VoucherNo></VoucherNo><Currency>SAR</Currency><BaseAmount>" + Amount + "</BaseAmount><ReferenceNo></ReferenceNo><Override>Y</Override>";
        //    Request.TCod = "AccountCredit";
        //    int finalError = Request.PrepareMessage(XmlMessage, LangItem, Directory, TransportVia, TransportMethod, out XmlResponse);
        //}
        //else
        //{
        //    XmlMessage = "<AccID>" + Account + "</AccID><Amount>" + Amount + "</Amount><Description>" + Desc + "</Description><VoucherNo></VoucherNo><Currency>SAR</Currency><BaseAmount>" + Amount + "</BaseAmount><ReferenceNo></ReferenceNo><Override>Y</Override><Retry>N</Retry>";
        //    Request.TCod = "AccountDebit";
        //    int finalError = Request.PrepareMessage(XmlMessage, LangItem, Directory, TransportVia, TransportMethod, out XmlResponse);
        //}

        //log the transaction request
        Helper.writeMWLog("Request (" + DateTime.Now + "): " + XmlMessage);

        if (XmlResponse.Contains("OK"))
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(XmlResponse);
            XmlNode node = doc.SelectSingleNode("/OK");
            string temp = node.Attributes["Journal"].InnerText;
            ViewState["JID"] = temp;
            ViewState["MESSAGE"] = "successful";
            //log the transaction response
            Helper.writeMWLog("Response (" + DateTime.Now + "): " + XmlResponse);
            return true;
        }
        else if (XmlResponse.Contains("ERR"))
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(XmlResponse);
            XmlNode node = doc.SelectSingleNode("/ERR");
            string temp = node.Attributes["Desc"].InnerText;
            string temp1 = node.Attributes["NativeErr"].InnerText;
            string temp2 = node.Attributes["NativeDesc"].InnerText;

            ViewState["MESSAGE"] = temp + " " + temp1 + " " + temp2;
            //log the transaction response
            Helper.writeMWLog("Response (" + DateTime.Now + "): " + XmlResponse);
            return false;
        }



        return false;
    }

    private bool postGLTR(string Type, string Account, string settleAcc, string Amount, string Desc)
    {
        string Directory = ConfigurationSettings.AppSettings["MWCertificate"];
        string XmlMessage = "";
        string XmlResponse = "";
        string TransportVia = "I";
        string TransportMethod = "Synch";
        string LangItem = "1";

        //NCBEAI.Adapters.Transport.Message Request = new Message(Directory);

        //if (Type.Equals("Dr"))
        //{
        //    XmlMessage      = "<FromAccID>" + Account + "</FromAccID><ToAccID>" + settleAcc +
        //                      "</ToAccID><FromAmount>" + Amount + "</FromAmount><Desc>"
        //                      + Desc + "</Desc>";
        //    Request.TCod    = "AccountTransfer";
        //    int finalError  = Request.PrepareMessage(XmlMessage, LangItem, Directory, TransportVia, TransportMethod, out XmlResponse);
        //}
        //else
        //{
        //    XmlMessage = "<AccountTransfer><FromAccID>" + settleAcc + "</FromAccID><ToAccID>" + Account +
        //                   "</ToAccID><FromAmount>" + Amount + "</FromAmount><PurposeOfTransfer>" + Desc + "</PurposeOfTransfer></AccountTransfer>";
        //    Request.TCod = "AccountTransfer";
        //    int finalError = Request.PrepareMessage(XmlMessage, LangItem, Directory, TransportVia, TransportMethod, out XmlResponse);
        //}

        //log the transaction request
        Helper.writeMWLog("Request (" + DateTime.Now + "): " + XmlMessage);

        if (XmlResponse.Contains("OK"))
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(XmlResponse);
            XmlNode node = doc.SelectSingleNode("/OK");
            string temp = node.Attributes["Journal"].InnerText;
            ViewState["JID"] = temp;
            ViewState["MESSAGE"] = "successful";
            //log the transaction response
            Helper.writeMWLog("Response (" + DateTime.Now + "): " + XmlResponse);
            return true;
        }
        else if (XmlResponse.Contains("ERR"))
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(XmlResponse);
            XmlNode node = doc.SelectSingleNode("/ERR");
            string temp = node.Attributes["System"].InnerText + " - " + node.Attributes["NativeErr"].InnerText +
                          " : " + node.Attributes["Desc"].InnerText + " ( " + node.Attributes["NativeDesc"].InnerText + " ) ";
            ViewState["MESSAGE"] = temp;
            //log the transaction response
            Helper.writeMWLog("Response (" + DateTime.Now + "): " + XmlResponse);
            return false;
        }

        return false;
    }
    private string InternalFundTransfer(ref string error)
    {
        try
        {
            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 BuySellFlag = ConfigurationManager.AppSettings["FndTrnfrExchgRateFlg"];

            /* Start Code Added by Sathish on 24th August 2017
            Currency code was hardcode pervisoly it has been changed to dynamic */
            string strDrCurrCode = txtDrCurrency.Text;// ConfigurationManager.AppSettings[txtAccount.Text.Substring(10, 3)];
            string strCrCurrCode = txtCrCuurency.Text;//ConfigurationManager.AppSettings[txtSettlementAcc.Text.Substring(10, 3)];

            if (String.IsNullOrEmpty(strDrCurrCode)) strDrCurrCode = "SAR";
            if (String.IsNullOrEmpty(strCrCurrCode)) strCrCurrCode = "SAR";

            /*End */


            InternalFundsTransferMsgProcessorCls InFundsXferMsgProObj = new InternalFundsTransferMsgProcessorCls(strCon, strMWLog);
            //result= InFundsXferMsgProObj.BuildMsg("000256", "0101000256001", "0101012400001", "00000000001000", "SAR", "9982                               ", "Fund Transfer for the Registration ", "AF788A5E");
            //result = InFundsXferMsgProObj.BuildMsg(txtAccount.Text .Substring (4,6) , txtAccount.Text, txtSettlementAcc.Text, txtAmount.Text.Replace(".","") , "SAR", txtGLDesc.Text , "" , "AF788A5E      ");
            /* Changed by Sathish on 24th August 2017 */
            //result = InFundsXferMsgProObj.BuildMsg(txtAccount.Text.Substring(4, 6), txtAccount.Text, txtSettlementAcc.Text, txtAmount.Text.Replace(".", ""), "SAR", txtGLDesc.Text, "", ViewState["uniq_ID"].ToString());

            string mqDesc1 = txtGLDesc.Text, mqDesc2 = "".PadLeft(35, ' ');

            if (txtGLDesc.Text.Length > 35)
            {
                mqDesc1 = txtGLDesc.Text.Substring(0, 35);
                mqDesc2 = txtGLDesc.Text.Substring(35);
            }
            // Condition was comments on October 3 by Sathish as this is handled in the declaration.
            /*      else /* Else condition was added by sathish on 26 September 2017 
                  {
                      mqDesc1 = txtGLDesc.Text;
                      mqDesc2 = mqDesc2.PadLeft(35, ' ');
                  }
                  */

            result = InFundsXferMsgProObj.BuildMsg(txtAccount.Text.Substring(4, 6), txtAccount.Text, txtSettlementAcc.Text, txtAmount.Text.Replace(".", ""), txtAmountSAR.Text.Replace(".", ""), strDrCurrCode, strCrCurrCode, mqDesc1, mqDesc2, BuySellFlag);

            Helper.writeMWLog("Result:" + result);

            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);
            Helper.writeMWLog("QMgrName :" + strQMgrName + ", SendQName : " + strSendQName + ", RecieveQName : " + strRecieveQName + ", Channel: " + strHost + ", Port: " + strPort + ",User: " + strUser);//+ ",Password :" + strPwd);
            msgRecieved = EjadaMQProcessorObj.ProcessMessage(result, timeOut, false);
            Helper.writeMWLog("Message Recieved :" + msgRecieved);
            respCode = InFundsXferMsgProObj.ParseRespCode(msgRecieved);
            Helper.writeMWLog("Response Code :" + respCode);
            //Helper.writeMWLog ("MsgRecieved: "
            string respCode2 = "";
            if (!respCode.Trim().Equals("000"))
            {
                result = InFundsXferMsgProObj.BuildDoubtMsg();
                msgRecieved = EjadaMQProcessorObj.ProcessMessage(result, timeOut, true);
                Helper.writeMWLog(" Doubt Message Recieved :" + msgRecieved);
                respCode2 = InFundsXferMsgProObj.ParseRespCodeDoubt(msgRecieved);
                Helper.writeMWLog("Doubt Response Code :" + respCode2); // not to write respCode2 in database ,as requested by yousif
            }
            ViewState["JID"] = null;
            //irfan_mod 170517 starts 
            if (!result.Equals("000"))
            {
                ViewState["MESSAGE"] = respCode.Trim();
                error = "Posting Failed. Check MW Response";
            }
            else
            {
                respCode = respCode2; // In case of sucess write the 2nd response, as requested by yousif
                ViewState["MESSAGE"] = "Successfull without Reference Number";
                error = "Successful";

            }
            // irfan_mod 170517 Ends

            return respCode.Trim();
        }
        catch (Exception ex)
        {
            Helper.writeMWLog("Exception:   " + ex.Message);
            ViewState["JID"] = null;
            ViewState["MESSAGE"] = "Failed..";
            return ex.Message;
        }
    }
    //private string TransferFund(ref string error)
    //{
    //    try
    //    {
    //        string ftSendQ = ConfigurationManager.AppSettings["FundTransferReq"];
    //        string ftRecvQ = ConfigurationManager.AppSettings["FundTransferResp"];


    //        MscllnsFundXferMsgGen MscllnsFundXferMsgGenObj = new MscllnsFundXferMsgGen();
    //        // string strReqMsg = MscllnsFundXferMsgGenObj.GenReqMsg("68200010069000", "12312", "SAR", "68200010069001", "12312", "SAR", "", "Cr");

    //        string Format_amount = (Convert.ToDouble(txtAmount.Text)).ToString();
    //        string strReqMsg = MscllnsFundXferMsgGenObj.GenReqMsg(txtPostingCardNumber.Text, txtSettlementAcc.Text, Format_amount, "SAR", txtAccount.Text, "", "", "", "", txtGLDesc.Text, txtGLDesc.Text);
    //      // string strReqMsg = MscllnsFundXferMsgGenObj.GenReqMsg("4323280000447565", "SAR1001200050001", "132", "SAR", "68200010069000", "", "", "", "","Ref123","Ref123");

    //        Helper.writeMWLog("strReqMsg : " + strReqMsg);

    //        //EjadaMQProcessorCls EjadaMQProcessorObj = new EjadaMQProcessorCls(ConfigurationManager.AppSettings["QMgrName"], ConfigurationManager.AppSettings["CardInqReq"], ConfigurationManager.AppSettings["RecQName"], txtCardNo .Text);
    //        EjadaMQProcessorCls EjadaMQProcessorObj = new EjadaMQProcessorCls(ConfigurationManager.AppSettings["QMgrName"], ftSendQ, ftRecvQ, "4323260002531152");
    //        string RecvMsg = EjadaMQProcessorObj.ProcessMessage(strReqMsg, ConfigurationManager.AppSettings["TimeOut"]);
    //        Helper.writeMWLog("RecvMsg :" + RecvMsg);

    //        // txtRecvMsg.Text=  "<?xml version=\"1.0\" encoding=\"UTF-8\"?><MscllnsFundXferRs><MsgRsHdr><StatusCode>I000000</StatusCode><RqUID>RCNS29052014000089</RqUID><SPRefNum>FT0810257H98</SPRefNum><MsgRecDt>2014-05-29T16:46:00</MsgRecDt></MsgRsHdr><Body><AmtDebited><Amt>20.00</Amt><AmtLcl>20.00</AmtLcl></AmtDebited><AmtCredited><Amt>20.00</Amt><AmtLcl>20.00</AmtLcl></AmtCredited><StmtEntryId>169518789760384.02#1-2</StmtEntryId></Body></MscllnsFundXferRs>";
    //        string SPRefNo;

    //        string result = MscllnsFundXferMsgGenObj.ParseResMsgXMLBased(RecvMsg, out SPRefNo);
    //        //Helper.writeMWLog("result : " + result);
    //        //Helper.writeMWLog("Reference No : "+SPRefNo );
    //        error = SPRefNo;
    //        return result;
    //        //txtMsgParsed.Text = result + "  " + SPRefNo;
    //    }
    //    catch (Exception ex)
    //    {
    //        Helper.writeMWLog("Exception:   " + ex.Message);
    //        return ex.Message;
    //    }
    //}

    protected void btnSavePost_Click(object sender, EventArgs e)
    {
        if (ViewState["PostAll"] as string != "Y") // Single post
            lblError.Text = "";

        lblError.Visible = true;
        string error = "";
        int index = int.Parse(ViewState["index"].ToString());
        string rowID = GridView1.DataKeys[index].Value.ToString();
        //string SettleAcc=GridView1.Rows[index].Cells[4].Text .ToString ();
        //string Desc=GridView1 .Rows[index].Cells[5].Text .ToString ();
        string SettleAcc = txtSettlementAcc.Text;
        string Desc = txtGLDesc.Text;
          bool beginPost = PostBegin(rowID, ref error);
        if (beginPost)
        {
            string result = InternalFundTransfer(ref error);
            if (!result.Equals("000"))
            {
                lblError.Text += error + " - GPE_CODE: " + rowID + " - GL Desc. " + txtGLDesc.Text + "</br>"; ;  //irfan_mod 170203
                bool failed = PostFailed(rowID, SettleAcc, Desc, ref error);
                if (!failed)
                {
                    lblError.Text += error + " - GPE_CODE: " + rowID + " - GL Desc. " + txtGLDesc.Text + "</br>";  //  //irfan_mod 170203
                }
            }

            else
            {
                bool saved = Post(rowID, SettleAcc, Desc, ref error);
                if (saved)
                {
                    if (ViewState["PostAll"] as string != "Y") // Single post
                        getSetup();
                    pnlPost.Visible = false;
                    lblError.ForeColor = System.Drawing.Color.DarkGreen;
                    lblError.Text += "Posted Successfully - GPE_CODE: " + rowID + " - GL Desc. " + txtGLDesc.Text + "</br>";
                    SuccessCount++;
                }
                else
                    lblError.Text += error + "- GPE_CODE:" + rowID + " - GL Desc. " + txtGLDesc.Text + "</br>";
                //lblError.Text = "Success";
            }
        }
        else
            lblError.Text += error + "- GPE_CODE:" + rowID + " - GL Desc. " + txtGLDesc.Text + "</br>";

    }

    protected void btnCancelPost_Click(object sender, EventArgs e)
    {
        pnlResult.Enabled = true;
        pnlPost.Visible = false;
    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    protected void rdEvent_CheckedChanged(object sender, EventArgs e)
    {
        productRow.Visible = false;
        CSRow.Visible = false;

        pnlResult.Visible = false;
        pnlControls.Visible = false;

        channelsRow.Visible = false;
        ATMNoRow.Visible = false;
        ATMTypeRow.Visible = false;
        BranchRow.Visible = false;
        POSRow.Visible = false;
        ClaimRow.Visible = false;
        ClaimRow2.Visible = false;
        ClaimSamaApprovedRow.Visible = false;

        eventsRow.Visible = true;
        AccTypeRow.Visible = true;

        ddlEvents.SelectedIndex = 0;
        ddlChannels.SelectedIndex = 0;
        ddlATMType.SelectedIndex = 0;
        ddlBranch.SelectedIndex = 0;
        txtATMnumber.Text = "";
        txtClientNo.Text = "";
        txtCardNo.Text = "";
        txtTraceID.Text = "";
        txtTerminalID.Text = "";
    }

    protected void rdChannel_CheckedChanged(object sender, EventArgs e)
    {
        lbl_Date.Text = "Date";
        productRow.Visible = false;
        CSRow.Visible = false;

        productRow.Visible = false;
        pnlResult.Visible = false;
        pnlControls.Visible = false;

        ATMNoRow.Visible = false;
        ATMTypeRow.Visible = false;
        eventsRow.Visible = false;
        BranchRow.Visible = false;
        POSRow.Visible = false;
        ClaimRow.Visible = false;
        ClaimRow2.Visible = false;
        ClaimSamaApprovedRow.Visible = false;

        channelsRow.Visible = true;
        AccTypeRow.Visible = true;

        ddlEvents.SelectedIndex = 0;
        ddlChannels.SelectedIndex = 0;
        ddlATMType.SelectedIndex = 0;
        ddlBranch.SelectedIndex = 0;
        txtATMnumber.Text = "";
        txtClientNo.Text = "";
        txtCardNo.Text = "";
        txtTraceID.Text = "";
        txtTerminalID.Text = "";
    }

    protected void rdATM_CheckedChanged(object sender, EventArgs e)
    {
        lbl_Date.Text = "Replenishment Date";
        productRow.Visible = false;
        CSRow.Visible = false;

        pnlResult.Visible = false;
        pnlControls.Visible = false;

        eventsRow.Visible = false;
        channelsRow.Visible = false;
        AccTypeRow.Visible = false;
        POSRow.Visible = false;
        ClaimRow.Visible = false;
        ClaimRow2.Visible = false;

        ATMNoRow.Visible = true;
        ATMTypeRow.Visible = true;
        BranchRow.Visible = true;

        ddlEvents.SelectedIndex = 0;
        ddlChannels.SelectedIndex = 0;
        ddlATMType.SelectedIndex = 0;
        ddlBranch.SelectedIndex = 0;
        txtATMnumber.Text = "";
        txtClientNo.Text = "";
        txtCardNo.Text = "";
        txtTraceID.Text = "";
        txtTerminalID.Text = "";
    }

    protected void rdPOSSET_CheckedChanged(object sender, EventArgs e)
    {
        productRow.Visible = false;
        CSRow.Visible = false;

        pnlResult.Visible = false;
        pnlControls.Visible = false;

        eventsRow.Visible = false;
        channelsRow.Visible = false;
        AccTypeRow.Visible = false;

        ATMNoRow.Visible = false;
        ATMTypeRow.Visible = false;
        BranchRow.Visible = false;
        ClaimRow.Visible = false;
        ClaimRow2.Visible = false;
        ClaimSamaApprovedRow.Visible = false;
        POSRow.Visible = true;

        ddlEvents.SelectedIndex = 0;
        ddlChannels.SelectedIndex = 0;
        ddlATMType.SelectedIndex = 0;
        ddlBranch.SelectedIndex = 0;
        txtATMnumber.Text = "";
        txtClientNo.Text = "";
        txtCardNo.Text = "";
        txtTraceID.Text = "";
        txtTerminalID.Text = "";
    }

    protected void rdPOSRENT_CheckedChanged(object sender, EventArgs e)
    {
        productRow.Visible = false;
        CSRow.Visible = false;

        eventsRow.Visible = false;
        channelsRow.Visible = false;
        AccTypeRow.Visible = false;

        ATMNoRow.Visible = false;
        ATMTypeRow.Visible = false;
        BranchRow.Visible = false;
        ClaimRow.Visible = false;
        ClaimRow2.Visible = false;
        ClaimSamaApprovedRow.Visible = false;
        POSRow.Visible = true;

        ddlEvents.SelectedIndex = 0;
        ddlChannels.SelectedIndex = 0;
        ddlATMType.SelectedIndex = 0;
        ddlBranch.SelectedIndex = 0;
        txtATMnumber.Text = "";
        txtClientNo.Text = "";
        txtCardNo.Text = "";
        txtTraceID.Text = "";
        txtTerminalID.Text = "";
    }

    protected void rdClaims_CheckedChanged(object sender, EventArgs e)
    {
        lbl_Date.Text = "Approved Date";
        productRow.Visible = false;
        CSRow.Visible = false;

        pnlResult.Visible = false;
        pnlControls.Visible = false;

        eventsRow.Visible = false;
        channelsRow.Visible = false;
        AccTypeRow.Visible = false;

        ATMNoRow.Visible = false;
        ATMTypeRow.Visible = false;
        BranchRow.Visible = false;
        POSRow.Visible = false;

        ClaimRow.Visible = true;
        ClaimRow2.Visible = true;
        ClaimSamaApprovedRow.Visible = true;

        ddlEvents.SelectedIndex = 0;
        ddlChannels.SelectedIndex = 0;
        ddlATMType.SelectedIndex = 0;
        ddlBranch.SelectedIndex = 0;
        txtATMnumber.Text = "";
        txtClientNo.Text = "";
        txtCardNo.Text = "";
        txtTraceID.Text = "";
        txtTerminalID.Text = "";

        chkApproved.Checked = true;
    }
    protected void rdCS_Sett_CheckedChanged(object sender, EventArgs e)
    {
        this.rdCS_Sett_CC();
    }

    public void rdCS_Sett_CC()
    {
        lbl_Date.Text = "Settlement Date";

        pnlResult.Visible = false;
        pnlControls.Visible = false;

        eventsRow.Visible = false;
        channelsRow.Visible = false;
        AccTypeRow.Visible = false;
        POSRow.Visible = false;
        ClaimRow.Visible = false;
        ClaimRow2.Visible = false;

        ATMNoRow.Visible = false;
        ATMTypeRow.Visible = false;
        BranchRow.Visible = false;
        ATMNoRow.Visible = false;
        ATMTypeRow.Visible = false;
        BranchRow.Visible = false;
        POSRow.Visible = false;

        ClaimRow.Visible = false;
        ClaimRow2.Visible = false;
        ClaimSamaApprovedRow.Visible = false;

        CSRow.Visible = true;
        productRow.Visible = true;

        //ddlProducts.SelectedIndex = 0;

        chkApproved.Checked = true;
    }

    private bool Can_Post(string index, 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 = "GL_POSTING_APPROVER.Can_Post";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_gpe_code", 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["p_gpe_code"].Value = index;

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

        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 Can_Reset(string index, 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 = "GL_POSTING_APPROVER.Can_Reset";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_gpe_code", 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["p_gpe_code"].Value = index;

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

        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 btnApproveAll_Click(object sender, EventArgs e)
    {
        string error = "";
        bool saved = ApproveAll(ref error);
        if (saved)
        {
            lblError.ForeColor = System.Drawing.Color.DarkGreen;
            lblError.Text = "Approve Successful";
            getSetup();
        }
        else
        {
            lblError.Text = error;
        }
    }

    protected void btnPostAll_Click(object sender, EventArgs e)
    {
        string error = "";
        bool saved = PostAll(ref error);
        if (saved)
        {
            lblError.ForeColor = System.Drawing.Color.DarkGreen;
            lblError.Text = "Post Successful";
            getSetup();
            btnPostAll.Visible = false;
            btnGenReport.Visible = false;
        }
        else
        {
            lblError.Text = error;
        }
    }

    private bool ApproveAll(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 = "GL_POSTING_APPROVER.Approve_All";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_ch_type", 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["p_date"].Value = DatePicker1.date;

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

        if (rdPOSSET.Checked)
            oracom.Parameters["p_ch_type"].Value = "6";
        //if (rdPOSRENT.Checked)
        //    oracom.Parameters["p_ch_type"].Value = "7";

        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 PostAll(ref string error)
    {
        //IJR 
        //New Code --> for Offline posting, this will use the procedure name
        //GENERATE_GL_FILE.GW56_files for posting the results 
        //the result file will be on the specified path inside the procedure called OUTPUT
        //This will depend on the channel type : 
        //3	channel Gl
        //5	ATM GL
        //8	claims

        string DBConnection = Helper.dbConnection();
        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

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

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "GENERATE_GL_FILE.GW56_files";



        oracom.Parameters.Add("p_file_dir", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_channel_type", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("v_res", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

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

        if (rdClaims.Checked)
            oracom.Parameters["p_channel_type"].Value = 8;
        else if (rdATM.Checked)
            oracom.Parameters["p_channel_type"].Value = 5;
        else if (rdChannel.Checked)
            oracom.Parameters["p_channel_type"].Value = 3;


        else if (rdEvent.Checked)
            oracom.Parameters["p_channel_type"].Value = 2;

        else if (rdPOSSET.Checked)
            oracom.Parameters["p_channel_type"].Value = 6;
        //OUTPUT is a directory  defined inside the DB Directories
        oracom.Parameters["p_file_dir"].Value = "OUTPUT";


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


        string a = oracom.Parameters["v_res"].Value.ToString();
        //error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "Successful")
            return true;
        else
            return false;

        /*Previous 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 = "GL_POSTING_APPROVER.Post_All";

        //oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        //oracom.Parameters.Add("p_date", OracleType.VarChar).Direction = ParameterDirection.Input;
        //oracom.Parameters.Add("p_ch_type", 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["p_date"].Value = DatePicker1.date;

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

        //if (rdPOSSET.Checked)
        //    oracom.Parameters["p_ch_type"].Value = "6";
        //if (rdPOSRENT.Checked)
        //    oracom.Parameters["p_ch_type"].Value = "7";

        //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 btnGenReport_Click(object sender, EventArgs e)
    {

        string p1 = DatePicker1.date;
        string p2 = "";

        if (rdClaims.Checked)
            p2 = "8";
        else if (rdATM.Checked)
            p2 = "5";
        else if (rdChannel.Checked)
            p2 = "3";
        else if (rdEvent.Checked)
            p2 = "2";
        else if (rdPOSSET.Checked)
            p2 = "6";


        string UrlString = "rpt=503&p1=" + p1 + "&p2=" + p2;

        ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
            "window.open('../Reports/Default.aspx?" + UrlString + "','Report')", true);


    }
    protected void ddlEvents_SelectedIndexChanged(object sender, EventArgs e)
    {
        pnlResult.Visible = false;
        pnlControls.Visible = false;
    }
    protected void ddlChannels_SelectedIndexChanged(object sender, EventArgs e)
    {
        pnlResult.Visible = false;
        pnlControls.Visible = false;
    }


    protected void BtnSelectedApproved_Click(object sender, EventArgs e)
    {
        if (GridView1.Rows.Count < 1)
        {
            lblError.Text = "There is no Claim to post, use Search button to load Claim";
            return;
        }

        SuccessCount = 0;
        totalCount = 0;
        bool isChecked = false;
        foreach (GridViewRow row in GridView1.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);
                if (chkRow.Checked || Session["PostAllSamaClaim"] == "Y" || Session["ApproveAndCreateGL"] == "Y")
                {
                    isChecked = true;
                    totalCount++;
                }
            }
        }
        if (!isChecked)
        {
            lblError.Text = "There is no selected Claim to post, Kindly select one or more claims";
            return;
        }

        ViewState["PostAll"] = "Y";
        // Button1_Click(sender, e);

        int index = 0;

        ///Start posting
        for (int iLoop = 0; iLoop < GridView1.Rows.Count; iLoop++)
        {
            lblError.Text = "";
            CheckBox chkRow = (GridView1.Rows[iLoop].Cells[0].FindControl("chkRow") as CheckBox);

            if (chkRow.Checked || Session["PostAllSamaClaim"] == "Y" || Session["ApproveAndCreateGL"] == "Y") // Posted only seleced
            {
                index = iLoop;

                ViewState["index"] = index;
                string account = GridView1.Rows[index].Cells[3].Text.ToString();
                string amount = GridView1.Rows[index].Cells[10].Text.ToString();
                //amount = amount.Remove(amount.Length - 1);
               // amount = Math.Round(Convert.ToDecimal(amount), 2).ToString(); // IRFAN_MOD
                amount = (Math.Round(double.Parse(amount), 2) + 0.0001).ToString();
                amount = amount.Substring(0, amount.Length - 2); 
                ////can't post a claim until it's approved
               
            
                string approved = GridView1.Rows[index].Cells[8].Text.ToString().Replace("&nbsp;", "");
                string posted = GridView1.Rows[index].Cells[7].Text.ToString().Replace("&nbsp;", "");
                string cashacc = GridView1.Rows[index].Cells[30].Text.ToString().Replace("&nbsp;", "");
                string cardNumber = GridView1.Rows[index].Cells[36].Text.ToString().Replace("&nbsp;", "");
                string glDesc = GridView1.Rows[index].Cells[33].Text.ToString().Replace("&nbsp;", "");
                ViewState["uniq_ID"] = GridView1.Rows[index].Cells[37].Text.ToString();

                string sarAmount = GridView1.Rows[index].Cells[39].Text.ToString().Replace("&nbsp;", ""); //IRFAN_MOD FIX 191126
                //sarAmount = Math.Round(decimal.Parse(sarAmount), 2).ToString();
                sarAmount = (Math.Round(double.Parse(sarAmount), 2) + 0.0001).ToString();
                sarAmount = sarAmount.Substring(0, sarAmount.Length - 2);

                string drCurrencyCode = GridView1.Rows[index].Cells[40].Text.ToString().Replace("&nbsp;", "");   
                string crCurrencyCode = GridView1.Rows[index].Cells[41].Text.ToString().Replace("&nbsp;", "");

                if (approved.ToLower().Equals("yes") && posted.ToLower().Equals("no"))
                {
                    string rowID = GridView1.DataKeys[index].Value.ToString();
                    string trans_type = GridView1.Rows[index].Cells[6].Text.ToString();
                    string error = "";
                    if (Can_Post(rowID, ref error))
                    {
                        // IRFAN_MOD on KG Confirmation
                        txtDrCurrency.Text = drCurrencyCode;                //
                        txtCrCuurency.Text = crCurrencyCode;                //
                        // //
                        
                        txtAccount.Text = account;
                        txtAmount.Text = amount;

                        txtAmountSAR.Text = sarAmount; // IRFAN_MOD FIX 191126

                        txtSettlementAcc.Text = cashacc;
                        txtPostingCardNumber.Text = cardNumber;
                        txtGLDesc.Text = glDesc;
                        if (!trans_type.Equals("&nbsp;"))
                            lblGLType.Text = trans_type;
                        else
                            lblGLType.Text = "";

                        //POST
                        btnSavePost_Click(sender, e);
                    }
                    else
                        lblError.Text = lblError.Text + error + "- GPE CODE" + rowID; ;
                }
                else
                {
                    if (posted.ToLower().Equals("yes"))
                        lblError.Text = lblError.Text + "Cannot post an already posted entry - GPE CODE" + index;
                    if (approved.ToLower().Equals("no"))
                        lblError.Text = lblError.Text + "Cannot post an entry until it is approved - GPE CODE" + index;
                }
                System.Threading.Thread.Sleep(3000);
            }// Post only checked
        }
        //End posting

        getSetup(); //Search
        lblError.Text = lblError.Text + "<br/>Total GL Entries (" + totalCount + ") Posted ("
            + SuccessCount + ") Rejected (" + (totalCount - SuccessCount) + ")";
        // lblError.Text = "Number of Claims which are not posted -- " + GridView1.Rows.Count;

        //for (int i = 0; i < GridView1.Columns.Count; i++)
        //    if (GridView1.Columns[i].HeaderText == "MW Resp.")
        //        GridView1.Columns[i].Visible = true;

        ViewState["PostAll"] = "N";
    }

    private void load_CS_Products()
    {
        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_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;

        if (rdVisaSett.Checked)
            oracom.Parameters["p_cs_Rc_Code"].Value = 15;
        else if (rdAmexSett.Checked)
            oracom.Parameters["p_cs_Rc_Code"].Value = 12;
        else if (rdMcAcq.Checked)
            oracom.Parameters["p_cs_Rc_Code"].Value = 11;
        else if (rdMaestro.Checked)
            oracom.Parameters["p_cs_Rc_Code"].Value = 7;
        else if (rdDiscover.Checked)
            oracom.Parameters["p_cs_Rc_Code"].Value = 20;
        else if(rdMadaMonthly.Checked)
            oracom.Parameters["p_cs_Rc_Code"].Value = 16;
        else
            oracom.Parameters["p_cs_Rc_Code"].Value = 0;

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

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

        oracon.Close();
    }

    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;
        oracom.CommandText = "VISA_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();
    }

    protected void rdcsGrp_CheckedChanged(object sender, EventArgs e)
    {
        load_CS_Products();
    }

    private void LoadCardScheme()
    {
        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_CSBILL_Product_Lookup";

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

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

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

        oracon.Close();
    }

    protected void rdCSBilling_CheckedChanged(object sender, EventArgs e)
    {
        LoadCardScheme();
    }
}
