using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.OracleClient;
using System.Text;

public partial class Security_Users : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            pnlGrid.Visible = false;
            pnlControls.Visible = false;
            pnlPassword.Visible = false;
            
        }
        lblError.Text = "";
    }

    private void getUsers()
    {
        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 = "sec_user_maintain.get_sec_user";

            oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_user_id", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_user_name", 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.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;


            if (txtSearchUserID.Text.Trim().Length == 0)
                oracom.Parameters["p_user_id"].Value = OracleString.Null;
            else
                oracom.Parameters["p_user_id"].Value = txtSearchUserID.Text.Trim();

            if (txtSearchUserName.Text.Trim().Length == 0)
                oracom.Parameters["p_user_name"].Value = OracleString.Null;
            else
                oracom.Parameters["p_user_name"].Value = txtSearchUserName.Text.Trim();

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

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

            oracon.Close();

            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
            if (ex.Message.Contains("ORA-24338: statement handle not executed"))
            {
                GridView1.DataSource = null;
                GridView1.DataBind();
                lblError.Text = "No Data Found";
            }
        }
    }

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

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

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

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "SEC_GROUP_MAINTAIN.Get_Sec_Group";

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

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

        oracon.Close();

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

        //chkBoxGroups.SelectedIndex = 0;
    }

    private bool deleteUser(string UserID, ref string error)
    {
        //if (Request["x"] == null || Request["y"] == null)
        //{
        //    Response.End();
        //}
        
        string DBConnection = Helper.dbConnection();

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

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

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "sec_user_maintain.delete_sec_user";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_uid", 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_uid"].Value =UserID;
        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 GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
      

        if (e.CommandName.Equals("d"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string Uid = GridView1.DataKeys[index].Value.ToString();
            string error = "";
            bool temp = deleteUser(Uid, ref error);
            if (temp)
            {
                lblError.ForeColor = System.Drawing.Color.DarkGreen;
                lblError.Text = "User Deleted";
            }
            else
            {
                lblError.Text = error;
            }
            getUsers();
        }
        else if (e.CommandName.Equals("u"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string Uid = GridView1.DataKeys[index].Value.ToString();
            ViewState["mode"] = "u";
            pnlControls.Visible = true;
            pnlGrid.Enabled = false;

            ViewState["uid"] = Uid;
            //put the data in the controls
            txtUserID.Text = GridView1.Rows[index].Cells[1].Text;
            txtUserName.Text = GridView1.Rows[index].Cells[2].Text;

            //txtPass1.Attributes.Add("value", GridView1.Rows[index].Cells[3].Text);
            //txtPass2.Attributes.Add("value", GridView1.Rows[index].Cells[3].Text);

            //chkBoxGroups.SelectedValue = GridView1.Rows[index].Cells[6].Text;
            var multipleGroupIDs = GetUserGroups(txtUserID.Text).Split(':'); ;// GridView1.Rows[index].Cells[6].Text.Split(':');

           
            foreach (var gid in multipleGroupIDs)
                chkBoxGroups.SelectedValue = gid;
            
            foreach (var gid in multipleGroupIDs)
            foreach (ListItem item in chkBoxGroups.Items)
            {
                if (gid.Equals(item.Value)) // Equal 
                    item.Selected = true;
            }

            int status = int.Parse(GridView1.Rows[index].Cells[13].Text);
            if (status == 1)
                rdActive.Checked = true;
            else
                rdInActive.Checked = true;

            //txtPass1.Enabled = false;
            //txtPass2.Enabled = false;
            txtUserID.Enabled = false;

            string super = GridView1.Rows[index].Cells[12].Text;

            if (super == "1")
                chkSuper.Checked = true;
            else
                chkSuper.Checked = false;

        }
        else if (e.CommandName.Equals("r"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string Uid = GridView1.DataKeys[index].Value.ToString();
            ViewState["mode"] = "u";
            pnlPassword.Visible = true;
            pnlGrid.Enabled = false;

            ViewState["uid"] = Uid;
            //put the data in the controls
        }
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        ViewState["mode"] = "a";
        pnlControls.Visible = true;
        pnlGrid.Enabled = false;
        pnl_filters.Enabled = false;
        getGroups();
        clearControls();

        //txtPass1.Enabled = true;
        //txtPass2.Enabled = true;
        txtUserID.Enabled = true;
       
    }
    
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        ViewState["mode"] = null;
        ViewState["uid"] = null;
        pnlControls.Visible = false;
        pnlGrid.Enabled = true;
        pnl_filters.Enabled = true;
        clearControls();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            string mode = ViewState["mode"].ToString();
            string error = "";
            if (mode.Equals("a"))
            {
                bool saved = addUser(ref error);
                if (saved)
                {
                    lblError.ForeColor = System.Drawing.Color.DarkGreen;
                    lblError.Text = "User Data Saved";
                }
                else
                {
                    lblError.Text = error;
                }
            }
            else if (mode.Equals("u"))
            {
                string Uid = ViewState["uid"].ToString();
                bool saved = updateUser(ref error);
                if (saved)
                {
                    lblError.ForeColor = System.Drawing.Color.DarkGreen;
                    lblError.Text = "User Data Saved";
                }
                else
                {
                    lblError.Text = error;
                }
            }
            getUsers();
            ViewState["mode"] = null;
            ViewState["uid"] = null;
            pnlControls.Visible = false;
            pnlGrid.Enabled = true;
            pnl_filters.Enabled = true;
            pnlGrid.Visible = true;
            clearControls();
        }
        catch (Exception ex)
        {
        }
    }

    protected void GridView1_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[3].Visible = false;
            e.Row.Cells[4].Visible = false;
            e.Row.Cells[5].Visible = false;
            e.Row.Cells[6].Visible = false;
            e.Row.Cells[12].Visible = false;
            e.Row.Cells[13].Visible = false;
           // e.Row.Cells[9].Visible = false; Delete
            e.Row.Cells[11].Visible = false;
            
        }
        
    }

    private bool addUser(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 = "sec_user_maintain.create_sec_user";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_user_id", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_user_name", OracleType.VarChar).Direction = ParameterDirection.Input;        
        oracom.Parameters.Add("p_super_user", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_status", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_USER_TEL_NO", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_TEL_EXTEN", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_gid", 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_user_id"].Value = txtUserID.Text.ToUpper();
        oracom.Parameters["p_user_name"].Value = txtUserName.Text;
        oracom.Parameters["p_USER_TEL_NO"].Value = USER_TEL_NO.Text;
        oracom.Parameters["p_TEL_EXTEN"].Value = TEL_EXTEN.Text;

        // IRFAN_MOD 170205

        string multipleGroupIDs = "";

        foreach (ListItem item in chkBoxGroups.Items)
            if (item.Selected)
                multipleGroupIDs = item.Value + "," + multipleGroupIDs;


        oracom.Parameters["p_gid"].Value = multipleGroupIDs.Substring(0, multipleGroupIDs.Length - 1);


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

        if (chkSuper.Checked)
            oracom.Parameters["p_super_user"].Value = "1";
        else
            oracom.Parameters["p_super_user"].Value = "0";

        if (rdActive .Checked)
            oracom.Parameters["p_status"].Value = "1";
        else
            oracom.Parameters["p_status"].Value = "0";


        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 updateUser(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 = "SEC_USER_MAINTAIN.Update_Sec_User";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_user_name", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_super_user", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_USER_TEL_NO", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_TEL_EXTEN", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_gid", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_status", 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;

        string Uid = ViewState["uid"].ToString();
        oracom.Parameters["p_uid"].Value = int.Parse (Uid);
        oracom.Parameters["p_user_name"].Value = txtUserName.Text;
        oracom.Parameters["p_USER_TEL_NO"].Value = USER_TEL_NO.Text;
        oracom.Parameters["p_TEL_EXTEN"].Value = TEL_EXTEN.Text;
        int status;
        if (rdActive.Checked)
            status = 1;
        else
            status = 0;

        if(chkSuper.Checked)
            oracom.Parameters["p_super_user"].Value = 1;
        else
            oracom.Parameters["p_super_user"].Value = 0;

        oracom.Parameters["p_status"].Value = status;
        // IRFAN_MOD 170205
      
        string multipleGroupIDs="";

        foreach (ListItem item in chkBoxGroups.Items)
             if (item.Selected)
                 multipleGroupIDs = item.Value + "," + multipleGroupIDs;


        oracom.Parameters["p_gid"].Value = multipleGroupIDs.Substring(0, multipleGroupIDs.Length - 1);


        // Ends

        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 void clearControls()
    {
        //txtPass1.Text = "";
        //txtPass2.Text = "";
        //txtPass1.Attributes["value"] = "";
        //txtPass2.Attributes["value"] = "";
        txtUserID.Text = "";
        txtUserName.Text = "";
        
        chkBoxGroups.SelectedIndex = 0;
        chkSuper.Checked = false;
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        getUsers();
    }

    protected void Button4_Click(object sender, EventArgs e)
    {
        string error = "";
        bool saved = ChangePassword(ref error);
        if (saved)
        {
            pnlPassword.Visible = false;
            pnlGrid.Enabled = true;
            lblError.ForeColor = System.Drawing.Color.DarkGreen;
            lblError.Text = "Password changed Succesfully. ";
        }
        else
        {
            lblError.Text = error;
        }
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        pnlPassword.Visible = false;
        pnlGrid.Enabled = true;
    }
    private string GetUserGroups(string p_user_id)
    {
        string DBConnection = Helper.dbConnection();

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

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

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "SEC_USER_MAINTAIN.get_sec_multiGroups";

        oracom.Parameters.Add("p_user_id", OracleType.VarChar).Direction = ParameterDirection.Input;
         oracom.Parameters.Add("p_Multi_Groups", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

         oracom.Parameters["p_user_id"].Value = p_user_id;
     
        oracom.ExecuteNonQuery();
        oracon.Close();
        string v_Multi_Groups = oracom.Parameters["p_Multi_Groups"].Value.ToString();
        
        return v_Multi_Groups;
    }
    private bool ChangePassword(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 = "SEC_USER_MAINTAIN.Reset_Password";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_user_id", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_new_pass", 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_user_id"].Value = ViewState["uid"].ToString();
        oracom.Parameters["p_new_pass"].Value = Helper.DecPassword(TextBox1.Text);

        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 btnSearch_Click(object sender, EventArgs e)
    {
        pnlGrid.Visible = true;
        getGroups();
        getUsers();
    }
}
