using System;
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 SettlProcessor;
using System.Configuration;

public partial class MMonthlySettlement : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            pnl_result.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 = Helper.getDate(txtsdate.Text);
        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)
    {
        ExceptionUtility.LogEvent_Errors(0, "", "btnGenReport_Click", "Start");

        string p1 = Helper.getDate(txtsdate.Text);

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

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

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

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

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

        if (txtsdate.Text != "")
        {
            this.Get_MADA_FileInfo();
        }
        else
        {
            this.Clear();
            Notifications.showMessage("Please Enter the Transaction Date", this, Notifications.errorMessage, false);
        }

        ExceptionUtility.LogEvent_Errors(0, "", "btnSearch_Click", "End Search");
    }

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

    public void Clear()
    {
        GV_Settlement.DataSource = null;
        GV_Settlement.DataBind();

        GV_TicketEntry.DataSource = null;
        GV_TicketEntry.DataBind();

        pnl_result.Visible = false;
        pnlResult_TicketEntry.Visible = false;
    }

    protected void btn_Generate_Click(object sender, EventArgs e)
    {
        Lbl_URC_Message.Text = "Are you sure you want to Process ?";
        Notifications.showModal("UR-confirmation-modal-xl", this);
    }

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

        this.loadMTicketEntry(500, 1);
        this.loadResult(500, 1);

        pnl_result.Visible = true;
        pnlResult_TicketEntry.Visible = true;

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

    protected void btn_clear_Click(object sender, EventArgs e)
    {
        //his.clearResultControls();
        txtsdate.Text = "";
        pnl_result.Visible = false;
        pnlResult_TicketEntry.Visible = false;
        //this.pnl_searchCriteria.Enabled = true;

        GV_Settlement.DataSource = null;
        GV_Settlement.DataBind();

        GV_TicketEntry.DataSource = null;
        GV_TicketEntry.DataBind();
    }

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

    protected void GV_TicketEntry_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 GV_Settlement_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[0].Visible = false;
            e.Row.Cells[1].Visible = false;
        }
    }

    protected void GV_Settlement_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.Cells[6].Text != "Entered")
            {
                btn_Generate.Visible = false;
                Generate.Visible = false;

                this.loadMTicketEntry(500, 1);
                pnlResult_TicketEntry.Visible = true;
            }
            else if (e.Row.Cells[6].Text == "Entered")
            {
                btn_Generate.Visible = true;
                Generate.Visible = true;
            }

            if (e.Row.Cells[6].Text == "PROCESSED")
            {
                e.Row.Cells[6].ForeColor = System.Drawing.Color.Green;
            }
            else if (e.Row.Cells[6].Text == "N" || e.Row.Cells[6].Text == "NOT PROCESSED")
            {
                e.Row.Cells[6].ForeColor = System.Drawing.Color.Red;
            }

            if (e.Row.Cells[5].Text.Contains("-"))
            {
                e.Row.Cells[5].ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                e.Row.Cells[5].ForeColor = System.Drawing.Color.Green;
            }

            if (e.Row.Cells[5].Text == "Amount")
            {
                e.Row.Cells[5].ForeColor = System.Drawing.Color.Black;
            }
        }
    }

    protected void ButtonGenerateGL_Click(object sender, EventArgs e)
    {
        string strRespMsg = "";
        string p1 = Helper.getDate(txtsdate.Text);
        //string logFile = ConfigurationManager.AppSettings["ErrorLog"].ToString();
        string p2 = DateTime.ParseExact(p1, "yyMMdd", null).ToString("yyMMdd");
        SettlFileGenerator sl = new SettlFileGenerator();
        sl.Gen_Settl(ConfigurationManager.AppSettings["Gen_settle_location"].ToString(), "MADA", p2, out strRespMsg);

    }

    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;
    }

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

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

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

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MADA_PDF_Loader_Processor.GET_MM_FileInfo";

        oracom.Parameters.Add("P_FILE_DATE", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_FILE_NUMBER", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("P_RSP", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["P_FILE_DATE"].Value = Helper.getDate(txtsdate.Text);

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

        if (oracom.Parameters["P_RSP"].Value.ToString() != "")
        {
            lbl_FSResponse.Text = oracom.Parameters["P_RSP"].Value.ToString();
            if (lbl_FSResponse.Text == "Successful")
            {
                this.loadResult(50, 1);
            }
            else
            {
                Notifications.showMessage(lbl_FSResponse.Text, this, Notifications.errorMessage, false);
            }
        }
    }

    private void loadResult(int pageSize, int pageNumber)
    {
        ExceptionUtility.LogEvent_Errors(0, "", "loadResult", "Start");

        try
        {
            string DBConnection = Helper.dbConnection();

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

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

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "MADA_PDF_Loader_Processor.Get_MM_Settl_Summary";

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

            oracom.Parameters["p_date"].Value = Helper.getDate(txtsdate.Text);

            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();
            oracom.Parameters["p_Evnt_Code"].Value = OracleString.Null;

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

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

            if(lbl_FSResponse.Text == "Successful")
            {
                if(ds.Tables[0].Rows.Count > 0)
                {
                    GV_Settlement.DataSource = ds;
                    GV_Settlement.DataBind();

                    pnl_result.Visible = true;

                    decimal Settl_Total = ds.Tables[0].AsEnumerable().Sum(row => row.Field<decimal>("SETTL_AMOUNT"));
                    GV_Settlement.FooterRow.Cells[2].Text = "Total";
                    GV_Settlement.FooterRow.Cells[3].HorizontalAlign = HorizontalAlign.Right;
                    GV_Settlement.FooterRow.Cells[3].Text = Settl_Total.ToString("N2");

                    GV_Settlement.FooterRow.Cells[2].Font.Bold = true;
                    GV_Settlement.FooterRow.Cells[3].Font.Bold = true;

                    GV_Settlement.FooterRow.Cells[5].Visible = false;
                    GV_Settlement.FooterRow.Cells[6].Visible = false;
                }
                else
                {
                    Notifications.showMessage("No Data Found", this, Notifications.errorMessage, false);
                }
            }
            else
            {
                GV_Settlement.DataSource = null;
                GV_Settlement.DataBind();

                GV_TicketEntry.DataSource = null;
                GV_TicketEntry.DataBind();

                pnl_result.Visible = false;
                pnlResult_TicketEntry.Visible = false;

                Notifications.showMessage("Pdf File is not Processed", this, Notifications.errorMessage, false);
            } 
        }
        catch(Exception ex)
        {
            ExceptionUtility.LogException(ex);
            Notifications.showMessage(ex.Message, this, Notifications.errorMessage, false);
        }

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

    private void loadMTicketEntry(int pageSize, int pageNumber)
    {
        //ExceptionUtility.LogEvent_Errors(0, "", "loadMTicketEntry", "Start");

        try
        {
            string DBConnection = Helper.dbConnection();

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

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

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "MADA_PDF_Loader_Processor.GET_MM_SETTL_ENTRY";

            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_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 = Helper.getDate(txtsdate.Text);

            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();

            GV_TicketEntry.DataSource = ds;
            GV_TicketEntry.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"));
                GV_TicketEntry.FooterRow.Cells[2].Text = "Total";
                GV_TicketEntry.FooterRow.Cells[3].HorizontalAlign = HorizontalAlign.Right;
                GV_TicketEntry.FooterRow.Cells[3].Text = drTotal.ToString("N2");
                GV_TicketEntry.FooterRow.Cells[4].HorizontalAlign = HorizontalAlign.Right;
                GV_TicketEntry.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();
            }
        }
        catch(Exception ex)
        {
            ExceptionUtility.LogException(ex);
            Notifications.showMessage(ex.Message, this, Notifications.errorMessage, false);
        }

        //ExceptionUtility.LogEvent_Errors(0, "", "loadMTicketEntry", "End");
    }

    protected void GV_TicketEntry_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("d"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = GV_TicketEntry.DataKeys[index].Value.ToString();

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

            string error = ""; ;

            string status_flag = GV_TicketEntry.Rows[index].Cells[9].Text.ToString();
            string editable_flag = GV_TicketEntry.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)
                    {
                        loadMTicketEntry(500, 1);
                        Notifications.showMessage("Successfuly deleted Entry", this, Notifications.successMessage, false);
                    }
                    else
                    {
                        Notifications.showMessage(error, this, Notifications.errorMessage, false);
                    }
                }
                else Notifications.showMessage("Deletion Failed - Auto Entry cannot be  deleted", this, Notifications.errorMessage, false);
            }
            else Notifications.showMessage("Deletion Failed - Entry can be deleted only when status is Entered/Caneled", this, Notifications.errorMessage, false);
        }
    }

    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")
        {
            Notifications.showMessage(oracom.Parameters["p_res_msg"].Value.ToString(), this, Notifications.errorMessage, false);
            return true;
        }
        else
        {
            Notifications.showMessage(oracom.Parameters["p_res_msg"].Value.ToString(), this, Notifications.errorMessage, false);
            return false;
        }
    }

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

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

        if (Approval_Reject_GenerateGl(Helper.getDate(txtsdate.Text), File_Number, "001"))
        {
            loadMTicketEntry(500, 1);
            loadResult(500, 1);
        }

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

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

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

        if (Approval_Reject_GenerateGl(Helper.getDate(txtsdate.Text), File_Number, "008"))
        {
            loadMTicketEntry(500, 1);
            loadResult(500, 1);
        }

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

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

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

        if (Approval_Reject_GenerateGl(Helper.getDate(txtsdate.Text), File_Number, "002"))
        {
            loadMTicketEntry(500, 1);
            loadResult(500, 1);
        }

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