using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OracleClient;
using System.Data;
using System.Configuration;
using System.Security.Cryptography;
using EjadaCSGenParser;
using EjadaCSLoader;
using EjadaFileLoaderLicenceVerifier;
using System.Data.OleDb;
using System.Text.RegularExpressions;

public partial class Business_DiscoveryDailySettlement : System.Web.UI.Page
{
    public string JobName = "LOAD_MADADGN_WIN";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            this.pnl_result.Visible = false;
            this.btn_print.Visible = false;
            tlfFilesArea.Visible = false;
        }
    }

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

    public void Search()
    {
        if (dtp_filter_sttlDate.date != "")
        {
            if (Get_Sama_Summary() == 0)
            {
                Lbl_FileName.Visible = false;
                FileUpload1.Visible = false;
                btnUpload.Visible = false;

                Get_SPAN_Ticket_Entry();
                Get_TLF_Amounts();
                // loadCountries();
            }
            else
            {
                this.pnl_result.Visible = false;
                this.pnlResult_TicketEntry.Visible = false;
                this.pnlResult_VAT.Visible = false;
                tlfFilesArea.Visible = false;
            }
        }
        else
        {
            lbl_error.Text = "Please Enter the Transaction Date";
        }
    }

    protected double Get_Sama_Summary()
    {
        string settmelentDate = dtp_filter_sttlDate.date;
        string errorMsg = "";

        double resCode = -1;

        Dictionary<string, double> results = this.searchSamaFiles(settmelentDate, ref errorMsg);

        resCode = results["p_res_code"];

        if (resCode == 0)
        {
            this.pnl_result.Visible = true;
            if (rdATM.Checked)
            {
                this.lblgccpdfdebit.Text = results["P_PDF_ATMISS_Settl_Amt"].ToString("N2");
                this.lblgccpdfcredit.Text = results["P_PDF_ATMACQ_Settl_Amt"].ToString("N2");
                this.lblgccbankdebit.Text = results["P_Switch_ATMISS_Settl_Amt"].ToString("N2");
                this.lblgccbankcredit.Text = results["P_Switch_ATMACQ_Settl_Amt"].ToString("N2");

                this.lbldebitdiff.Text = results["P_DGN_ATM_ISS_DIFF_Amt"].ToString("N2");
                this.lblcreditdiff.Text = results["P_DGN_ATM_ACQ_DIFF_Amt"].ToString("N2");

                this.lblgccpdftotal.Text = results["P_NET_PDF_ATM_CR_DR_AMT"].ToString("N2");
                this.lblgccbanktotal.Text = results["P_NET_Switch_ATM_CR_DR_AMT"].ToString("N2");
                this.lblnetdiff.Text = results["P_NET_ATM_DIFF_PDF_SWITCH_AMT"].ToString("N2");
            }
            else
            {
                this.lblgccpdfdebit.Text = results["P_PDF_POSISS_Settl_Amt"].ToString("N2");
                this.lblgccpdfcredit.Text = results["P_PDF_POSACQ_Settl_Amt"].ToString("N2");
                this.lblgccbankdebit.Text = results["P_Switch_POSISS_Settl_Amt"].ToString("N2");
                this.lblgccbankcredit.Text = results["P_Switch_POSACQ_Settl_Amt"].ToString("N2");

                this.lbldebitdiff.Text = results["P_DGN_POS_ISS_DIFF_Amt"].ToString("N2");
                this.lblcreditdiff.Text = results["P_DGN_POS_ACQ_DIFF_Amt"].ToString("N2");

                this.lblgccpdftotal.Text = results["P_NET_PDF_POS_CR_DR_AMT"].ToString("N2");
                this.lblgccbanktotal.Text = results["P_NET_Switch_POS_CR_DR_AMT"].ToString("N2");
                this.lblnetdiff.Text = results["P_NET_POS_DIFF_PDF_SWITCH_AMT"].ToString("N2");
            }
        }
        else
        {
            lbl_error.Text = errorMsg;
        }

        if (resCode == 265)
        {
            Lbl_FileName.Visible = true;
            FileUpload1.Visible = true;
            btnUpload.Visible = true;

            Lbl_FileName.Text = "Choose File:";
        }
        else
        {
            Lbl_FileName.Text = "";

            Lbl_FileName.Visible = false;
            FileUpload1.Visible = false;
            btnUpload.Visible = false;
        }

        return resCode;
    }

    private Dictionary<string, double> searchSamaFiles(string settlementDate, ref string errorMsg)
    {
        Dictionary<string, double> resultParams = new Dictionary<string, double>();
        int resCode;

        string DBConnection = Helper.dbConnection();

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

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

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "SAMA_SETTL_OPERATIONS.GET_DGN_SETTL_PDF_AMOUNTS";

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

        oracom.Parameters.Add("p_settl_date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_Product_Id", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("P_Switch_ATMACQ_Settl_Amt", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("P_Switch_ATMISS_Settl_Amt", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("P_Switch_POSACQ_Settl_Amt", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("P_Switch_POSISS_Settl_Amt", OracleType.Number).Direction = ParameterDirection.Output;

        oracom.Parameters.Add("P_PDF_ATMACQ_Settl_Amt", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("P_PDF_ATMISS_Settl_Amt", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("P_PDF_POSACQ_Settl_Amt", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("P_PDF_POSISS_Settl_Amt", OracleType.Number).Direction = ParameterDirection.Output;

        oracom.Parameters.Add("P_DGN_ATM_ACQ_DIFF_Amt", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("P_DGN_ATM_ISS_DIFF_Amt", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("P_DGN_POS_ACQ_DIFF_Amt", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("P_DGN_POS_ISS_DIFF_Amt", OracleType.Number).Direction = ParameterDirection.Output;

        oracom.Parameters.Add("P_NET_PDF_ATM_CR_DR_AMT", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("P_NET_Switch_ATM_CR_DR_AMT", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("P_NET_ATM_DIFF_PDF_SWITCH_AMT", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("P_NET_PDF_POS_CR_DR_AMT", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("P_NET_Switch_POS_CR_DR_AMT", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("P_NET_POS_DIFF_PDF_SWITCH_AMT", OracleType.Number).Direction = ParameterDirection.Output;

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


        // 

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

        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString(); ;
        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_settl_date"].Value = settlementDate;
        oracom.Parameters["P_Product_Id"].Value = rdATM.Checked ? 1 : 2;

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

        oracon.Close();

        ViewState["mode"] = oracom.Parameters["p_status"].Value.ToString();
        /*
            0 - New
            1 - Posted
        */

        errorMsg = oracom.Parameters["p_res_msg"].Value.ToString();
        resCode = int.Parse(oracom.Parameters["p_res_code"].Value.ToString());

        resultParams.Add("p_res_code", resCode);

        if (resCode == 0)
        {
            resultParams.Add("P_Switch_ATMACQ_Settl_Amt", double.Parse(oracom.Parameters["P_Switch_ATMACQ_Settl_Amt"].Value.ToString()));
            resultParams.Add("P_Switch_ATMISS_Settl_Amt", double.Parse(oracom.Parameters["P_Switch_ATMISS_Settl_Amt"].Value.ToString()));
            resultParams.Add("P_Switch_POSACQ_Settl_Amt", double.Parse(oracom.Parameters["P_Switch_POSACQ_Settl_Amt"].Value.ToString()));
            resultParams.Add("P_Switch_POSISS_Settl_Amt", double.Parse(oracom.Parameters["P_Switch_POSISS_Settl_Amt"].Value.ToString()));

            resultParams.Add("P_PDF_ATMACQ_Settl_Amt", double.Parse(oracom.Parameters["P_PDF_ATMACQ_Settl_Amt"].Value.ToString()));
            resultParams.Add("P_PDF_ATMISS_Settl_Amt", double.Parse(oracom.Parameters["P_PDF_ATMISS_Settl_Amt"].Value.ToString()));
            resultParams.Add("P_PDF_POSACQ_Settl_Amt", double.Parse(oracom.Parameters["P_PDF_POSACQ_Settl_Amt"].Value.ToString()));
            resultParams.Add("P_PDF_POSISS_Settl_Amt", double.Parse(oracom.Parameters["P_PDF_POSISS_Settl_Amt"].Value.ToString()));

            resultParams.Add("P_DGN_ATM_ACQ_DIFF_Amt", double.Parse(oracom.Parameters["P_DGN_ATM_ACQ_DIFF_Amt"].Value.ToString()));
            resultParams.Add("P_DGN_ATM_ISS_DIFF_Amt", double.Parse(oracom.Parameters["P_DGN_ATM_ISS_DIFF_Amt"].Value.ToString()));
            resultParams.Add("P_DGN_POS_ACQ_DIFF_Amt", double.Parse(oracom.Parameters["P_DGN_POS_ACQ_DIFF_Amt"].Value.ToString()));
            resultParams.Add("P_DGN_POS_ISS_DIFF_Amt", double.Parse(oracom.Parameters["P_DGN_POS_ISS_DIFF_Amt"].Value.ToString()));

            resultParams.Add("P_NET_PDF_ATM_CR_DR_AMT", double.Parse(oracom.Parameters["P_NET_PDF_ATM_CR_DR_AMT"].Value.ToString()));
            resultParams.Add("P_NET_Switch_ATM_CR_DR_AMT", double.Parse(oracom.Parameters["P_NET_Switch_ATM_CR_DR_AMT"].Value.ToString()));
            resultParams.Add("P_NET_ATM_DIFF_PDF_SWITCH_AMT", double.Parse(oracom.Parameters["P_NET_ATM_DIFF_PDF_SWITCH_AMT"].Value.ToString()));
            resultParams.Add("P_NET_PDF_POS_CR_DR_AMT", double.Parse(oracom.Parameters["P_NET_PDF_POS_CR_DR_AMT"].Value.ToString()));
            resultParams.Add("P_NET_Switch_POS_CR_DR_AMT", double.Parse(oracom.Parameters["P_NET_Switch_POS_CR_DR_AMT"].Value.ToString()));
            resultParams.Add("P_NET_POS_DIFF_PDF_SWITCH_AMT", double.Parse(oracom.Parameters["P_NET_POS_DIFF_PDF_SWITCH_AMT"].Value.ToString()));
        }

        return resultParams;
    }

    private void Get_TLF_Amounts()
    {
        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_SUMMARY_INQUIRER.DGN_TLF_GL_TOTALS";

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

        oracom.Parameters["p_settle_date"].Value = dtp_filter_sttlDate.date;
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();
        oracom.Parameters["P_Product_Id"].Value = rdATM.Checked ? 1 : 2;

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

        decimal debitTotal = 0, creditTotal = 0;
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            if (rdPOS.Checked)  /// POS ISSUER and POS ACQ
            {
                if (dr["re_code"].ToString() == "45")
                    debitTotal += Convert.ToDecimal(dr["tot_amount"]);
                if (dr["re_code"].ToString() == "42")
                    creditTotal += Convert.ToDecimal(dr["tot_amount"]);
            }
            else   // ATM ISSUER AND ATM ATM ACQ
            {
                if (dr["re_code"].ToString() == "44")
                    debitTotal += Convert.ToDecimal(dr["tot_amount"]);
                if (dr["re_code"].ToString() == "41")
                    creditTotal += Convert.ToDecimal(dr["tot_amount"]);
            }
            //33 34 35
        }

        //LabelTLF01.Text =(tranAmount_ReCode10).ToString("N2");
        // LabelTLF02.Text =(tranAmount_ReCode5).ToString("N2");
        // LabelTLF03.Text =(tranAmount_ReCode14+tranAmount_ReCode8).ToString("N2");
        // LabelTLF04.Text = (tranAmount_ReCode17 + tranAmount_ReCode8).ToString("N2");
        // 33 34 35 IRFAN_MOD 190929 CR
        LabelTLF05.Text = creditTotal.ToString("N2");
        LabelTLF06.Text = debitTotal.ToString("N2");

        LabelTLFTotal.Text = (creditTotal - debitTotal).ToString("N2");
        tlfFilesArea.Visible = true;
        pnlResult_TicketEntry.Visible = true;
    }

    void Get_SPAN_Ticket_Entry()
    {
        pnlResult_TicketEntry.Visible = true;
        pnlResult_VAT.Visible = true;
        loadResult(50, 1);
    }

    private void loadResult(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 = "SAMA_SETTL_OPERATIONS.GET_DGN_SETTL";

        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_Prd_id", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_page_size", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_page_num", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_total_pages", OracleType.Number).Direction = ParameterDirection.Output;

        //    date = date.Remove(6, 1);

        oracom.Parameters["p_date"].Value = dtp_filter_sttlDate.date;
        oracom.Parameters["P_Prd_id"].Value = rdATM.Checked ? 24 : 25;

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

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

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

        string strExpr = "Event_name not like '%VAT%'";
        string strExpr1 = "Event_name like '%VAT%'";
        //string strSort = "";
        ds.Tables[0].DefaultView.RowFilter = strExpr;

        GridView1.DataSource = ds.Tables[0];//.Select(strExpr);
        GridView1.DataBind();

        ds.Tables[0].DefaultView.RowFilter = strExpr1;
        GridView3.DataSource = ds.Tables[0];//.Select(strExpr);
        GridView3.DataBind();

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

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

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

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

            if (GridView1.Rows.Count > 0)
            {
                GridView1.FooterRow.Cells[7].Visible = false;
                GridView1.FooterRow.Cells[8].Visible = false;
            }

            if (GridView3.Rows.Count > 0)
            {
                GridView3.FooterRow.Cells[7].Visible = false;
                GridView3.FooterRow.Cells[8].Visible = false;
            }
        }
    }

    private void setParam(int ID, string newValue)
    {
        string DBConnection = Helper.dbConnection();

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

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

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "SYSTEM_PARAM_EDITOR.edit_parameter";

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

        oracom.Parameters.Add("p_param_id", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_new_value", 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_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.Parameters["p_param_id"].Value = ID;

        oracom.Parameters["p_new_value"].Value = newValue;

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

    protected void btnClaimReport_Click(object sender, EventArgs e)
    {
        string p1 = dtp_filter_sttlDate.date;
        string p2 = DateTime.ParseExact(p1, "yyMMdd", null).AddDays(1).ToString("yyMMdd");

        setParam(310, p1);
        setParam(311, p2);

        string UrlString1 = "rpt=1004&p1=" + p1 + "&p2=" + p2;
        ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                "window.open('../Reports/Default.aspx?" + UrlString1 + "','Report')", true);
    }
    protected void btnGenReport_Click(object sender, EventArgs e)
    {
        string p1 = dtp_filter_sttlDate.date;
        string p2;

        if (rdATM.Checked)
        {
            p2 = "24";
        }
        else
        {
            p2 = "25";
        }

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

        //if (rdATM.Checked)
        //{
        //    string UrlString1 = "rpt=9001&p1=" + p1;
        //    ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
        //            "window.open('../Reports/Default.aspx?" + UrlString1 + "','Report')", true);
        //}
        //else
        //{
        //    string UrlString1 = "rpt=9002&p1=" + p1;
        //    ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
        //            "window.open('../Reports/Default.aspx?" + UrlString1 + "','Report')", true);
        //}
    }

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

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

    private string getNumber(string amount)
    {
        return amount.Replace(",", "");
    }

    public void Clear()
    {
        lbl_error.Text = "";

        GridView1.DataSource = null;
        GridView1.DataBind();
        this.pnl_result.Visible = false;

        GridView3.DataSource = null;
        GridView3.DataBind();
        this.pnlResult_VAT.Visible = false;
    }

    protected void btn_clear_Click(object sender, EventArgs e)
    {
        dtp_filter_sttlDate.date = "";
        this.Clear();
    }

    //private void clearResultControls()
    //{
    //    this.txt_creditATM_amount.Text = "";
    //    this.txt_debitATM_amount.Text = "";
    //    this.txt_creditPOS_amount.Text = "";
    //    this.txt_debitPOS_amount.Text = "";
    //    this.txt_creditATM_GCC_amount.Text = "";
    //    this.txt_debitATM_GCC_amount.Text = "";

    //    this.lbl_creditATM_difference.Text = "";
    //    this.lbl_creditATM_GCC_difference.Text = "";
    //    this.lbl_creditATM_GCC_SamaAmount.Text = "";
    //    this.lbl_creditATM_SamaAmount.Text = "";
    //    this.lbl_creditPOS_difference.Text = "";
    //    this.lbl_creditPOS_SamaAmount.Text = "";
    //    this.lbl_debitATM_difference.Text = "";
    //    this.lbl_debitATM_GCC_difference.Text = "";
    //    this.lbl_debitATM_GCC_SamaAmount.Text = "";
    //    this.lbl_debitATM_SamaAmount.Text = "";
    //    this.lbl_debitPOS_difference.Text = "";
    //    this.lbl_debitPOS_SamaAmount.Text = "";

    //}

    //private void clearManualControls()
    //{
    //    this.txt_creditATM_amount.Text = "";
    //    this.txt_debitATM_amount.Text = "";
    //    this.txt_creditPOS_amount.Text = "";
    //    this.txt_debitPOS_amount.Text = "";
    //    this.txt_creditATM_GCC_amount.Text = "";
    //    this.txt_debitATM_GCC_amount.Text = "";
    //}



    protected void btn_print_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
            "window.open('../Reports/Default.aspx?rpt=222&p1=" + dtp_filter_sttlDate.date + "&p2=" + Session["uid"].ToString() + "','Report')", true);

    }

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

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

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

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

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

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

        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();
        oracom.Parameters["p_File_no"].Value = Convert.ToDecimal(File_no);
        oracom.Parameters["p_event_code"].Value = event_code;

        oracom.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 GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {

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


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

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

            string error = ""; ;

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

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

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

    private bool Approval_Reject_GenerateGl(string settleDate, int file_number, string status)
    {
        string DBConnection = Helper.dbConnection();

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

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

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "SAMA_SETTL_OPERATIONS.SUBMITFORAPRVL";

        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_status", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_file_number", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

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

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

        OracleDataAdapter da = new OracleDataAdapter(oracom);


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

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

    protected void ButtonSubmitForApproval_Click(object sender, EventArgs e)
    {
        int File_Number = Convert.ToInt32(lbl_File_Number.Text);

        if (Approval_Reject_GenerateGl(dtp_filter_sttlDate.date, File_Number, "001"))
            loadResult(500, 1); ;
        //  bttn_Approval.Enabled = false;
    }//
    protected void ButtonRejectForApproval_Click(object sender, EventArgs e)
    {
        int File_Number = Convert.ToInt32(lbl_File_Number.Text);

        if (Approval_Reject_GenerateGl(dtp_filter_sttlDate.date, File_Number, "008"))
            loadResult(500, 1); ;
        //  bttn_Reject.Enabled=false;
    }
    protected void bttn_ApproveAndCreateGL(object sender, EventArgs e)
    {
        int File_Number = Convert.ToInt32(lbl_File_Number.Text);

        if (Approval_Reject_GenerateGl(dtp_filter_sttlDate.date, File_Number, "002"))
            loadResult(500, 1); ;
    }

    public string GetCSName(string job_name)
    {
        DataTable dtRes = new DataTable();
        try
        {
            string DBConnection = Helper.dbConnection();

            OracleConnection oracon = new OracleConnection(DBConnection);

            OracleCommand oraCom = new OracleCommand();
            oraCom.CommandText = "select * from application_jobs where job_name ='" + JobName + "'";
            oraCom.Connection = oracon;
            OracleDataAdapter da = new OracleDataAdapter(oraCom);

            da.Fill(dtRes);
            if (dtRes.Rows.Count > 0 && dtRes.Rows[0]["LOAD_TYPE"] as string == "DLL")
                return dtRes.Rows[0]["directroy"] as string;
            else return "DBJOB";
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex);
            lbl_error.Text = ex.Message;
            return "EXCEPTION";
        }
    }

    public string GetXmlPath(string job_name)
    {
        DataTable dtRes = new DataTable();
        try
        {
            string DBConnection = Helper.dbConnection();

            OracleConnection oracon = new OracleConnection(DBConnection);

            OracleCommand oraCom = new OracleCommand();
            oraCom.CommandText = "select * from application_jobs where job_name ='" + JobName + "'";
            oraCom.Connection = oracon;
            OracleDataAdapter da = new OracleDataAdapter(oraCom);

            da.Fill(dtRes);
            if (dtRes.Rows.Count > 0 && dtRes.Rows[0]["LOAD_TYPE"] as string == "DLL")
                return dtRes.Rows[0]["XML_DIRECTORY"] as string;
            else return "DBJOB";
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex);
            lbl_error.Text = ex.Message;
            return "EXCEPTION";
        }
    }

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

        if (dtp_filter_sttlDate.date != "")
        {
            if(rdATM.Checked || rdPOS.Checked)
            {
                if (FileUpload1.HasFile)
                {
                    try
                    {
                        string error = "";
                        string[] validFileTypes = { "pdf" }; //, "gif", "png", "jpg", "jpeg", "doc", "xls" };
                        string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
                        bool isValidFile = false;
                        int count = FileUpload1.FileName.Split('.').Length;
                        if (count > 2)
                        {
                            lbl_error.Text = "Uploaded file has more than one extension. Please check the file and upload again";
                        }
                        for (int i = 0; i < validFileTypes.Length; i++)
                        {
                            if (ext == "." + validFileTypes[i])
                            {
                                isValidFile = true;
                                break;
                            }
                        }
                        if (!isValidFile)
                        {
                            lbl_error.Text = "Invalid File. Please upload a File with extension " + string.Join(" / ", validFileTypes);
                        }
                        else
                        {
                            this.loadFiles();
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionUtility.LogException(ex);
                        lbl_error.Text = ex.Message;
                    }
                }
                else
                {
                    lbl_error.Text = "Please Choose a File";
                }
            }
            else
            {
                lbl_error.Text = "Please Choose the ATM / POS";
            }
        }
        else
        {
            lbl_error.Text = "Please Choose the Settlement Date";
        }

        ExceptionUtility.LogEvent_Errors(0, "", "btnUpload_Click", "End File Loading");
    }

    private void loadFiles()
    {
        string CSName = GetCSName(JobName);
        string xmlpath = GetXmlPath(JobName);
        ExceptionUtility.LogEvent_Errors(0, "", "btnUpload_Click", "Load '" + CSName + "' File");

        string FilePath = ConfigurationSettings.AppSettings["CSLoader_Files"] + "\\" + xmlpath + "\\";
        FileUpload1.SaveAs(FilePath + FileUpload1.PostedFile.FileName);

        string strRespMsg = ""; //this will hold the response message details

        if (CSName.Length > 1)
        {
            try
            {
                EJCSLoader objEJCSLoader = new EJCSLoader();
                ExceptionUtility.LogEvent_Errors(0, "", "btnStart_Click", "Before dll Call");

                objEJCSLoader.Load_CS(ConfigurationSettings.AppSettings["CSLoader"], dtp_filter_sttlDate.date, CSName, out strRespMsg);

                if (strRespMsg == "Process Completed Successfully!!")
                {
                    lbl_error.ForeColor = System.Drawing.Color.DarkGreen;
                    lbl_error.Text = strRespMsg;

                    this.Search();
                }
                else
                {
                    lbl_error.Text = strRespMsg;
                }

                ExceptionUtility.LogEvent_Errors(0, "", "btnStart_Click", "dll Call Response " + strRespMsg);
            }
            catch (Exception ex)
            {
                ExceptionUtility.LogException(ex);
                lbl_error.Text = "Exception: Please Refer to application Log";
            }
        }
        else
        {
            lbl_error.Text = "Failed to find relevent Job";
        }

        ExceptionUtility.LogEvent_Errors(0, "", "btnUpload_Click", "End '" + CSName + "' File");
    }
}